Decompiled source of BetterTames v0.0.4

plugins/BetterTames.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BetterTames.ConfigSynchronization;
using BetterTames.DistanceTeleport;
using BetterTames.MakeCommandable;
using BetterTames.PetProtection;
using BetterTames.Utils;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Valheim.BetterTames")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Atlas Playbook v0.4.1")]
[assembly: AssemblyProduct("Valheim.BetterTames")]
[assembly: AssemblyCopyright("Copyright © Atlas Playbook v0.4.1 2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("c7a9c4aa-0b32-47f7-a590-a68e94a2511e")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace BetterTames
{
	public static class DistanceTeleportLogic
	{
		private static readonly int groundLayerMask = LayerMask.GetMask(new string[7] { "Default", "static_solid", "Default_small", "piece", "terrain", "blocker", "vehicle" });

		public const float TELEPORT_CHECK_INTERVAL = 5f;

		public static void ExecuteTeleportBehindPlayer(Character characterToTeleport, GameObject followTarget)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Unknown result type (might be due to invalid IL or missing references)
			//IL_032b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Expected O, but got Unknown
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			ZNetView component = ((Component)characterToTeleport).GetComponent<ZNetView>();
			ZDO zDO = component.GetZDO();
			Vector3 position = followTarget.transform.position;
			Quaternion rotation = followTarget.transform.rotation;
			BetterTamesPlugin.LogIfDebug("Attempting teleport for " + characterToTeleport.m_name + ".", DebugFeature.TeleportFollow);
			if (position.y > 1000f)
			{
				BetterTamesPlugin.LogIfDebug($"Player Y position {position.y:F1} is > 1000. Preventing pet teleport.", DebugFeature.TeleportFollow);
				return;
			}
			Vector3 val = rotation * Vector3.forward;
			Vector3 val2 = rotation * Vector3.right;
			float num = 1f;
			CapsuleCollider component2 = ((Component)characterToTeleport).GetComponent<CapsuleCollider>();
			if ((Object)(object)component2 != (Object)null)
			{
				num = component2.radius * Mathf.Max(((Component)characterToTeleport).transform.localScale.x, ((Component)characterToTeleport).transform.localScale.z);
			}
			else
			{
				Collider component3 = ((Component)characterToTeleport).GetComponent<Collider>();
				if ((Object)(object)component3 != (Object)null)
				{
					Bounds bounds = component3.bounds;
					float x = ((Bounds)(ref bounds)).extents.x;
					bounds = component3.bounds;
					num = Mathf.Max(x, ((Bounds)(ref bounds)).extents.z);
				}
			}
			float num2 = Mathf.Max(8f, num + 0.5f);
			float num3 = num2 + 3f;
			float num4 = Mathf.Max(10f, num * 1.5f);
			float num5 = Random.Range(num2, num3);
			float num6 = Random.Range((0f - num4) / 2f, num4 / 2f);
			try
			{
				if (zDO != null && zDO.GetBool("isRecoveringFromStun", false))
				{
					BetterTamesPlugin.LogIfDebug("Pet " + characterToTeleport.m_name + " is in pet-protection stun phase — increasing teleport distance by 30f.", DebugFeature.TeleportFollow);
					num5 += 30f;
				}
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"Exception while checking stun flag for {characterToTeleport.m_name}: {arg}", DebugFeature.TeleportFollow);
			}
			Vector3 val3 = -val * num5;
			Vector3 val4 = val2 * num6;
			Vector3 val5 = position + val3 + val4;
			RaycastHit val6 = default(RaycastHit);
			if (Physics.Raycast(val5 + Vector3.up * 5f, Vector3.down, ref val6, 10f, groundLayerMask))
			{
				val5.y = ((RaycastHit)(ref val6)).point.y + 1f;
			}
			else
			{
				val5.y = position.y;
				BetterTamesPlugin.LogIfDebug("No ground found via Raycast for auto-teleport of " + characterToTeleport.m_name + ", using target Y position.", DebugFeature.TeleportFollow);
			}
			Quaternion rotation2 = ((!(((Vector3)(ref val)).sqrMagnitude < 1E-06f)) ? Quaternion.LookRotation(((Vector3)(ref val)).normalized) : rotation);
			rotation2 = ((Quaternion)(ref rotation2)).normalized;
			((Component)characterToTeleport).transform.position = val5;
			((Component)characterToTeleport).transform.rotation = rotation2;
			zDO.SetPosition(val5);
			zDO.SetRotation(rotation2);
			Rigidbody component4 = ((Component)characterToTeleport).GetComponent<Rigidbody>();
			if ((Object)(object)component4 != (Object)null)
			{
				component4.WakeUp();
			}
			BetterTamesPlugin.LogIfDebug($"Teleported {characterToTeleport.m_name} to {val5} (behind followTarget). Sending RPC.", DebugFeature.TeleportFollow);
			ZPackage val7 = new ZPackage();
			val7.Write(val5);
			val7.Write(((Quaternion)(ref rotation2)).normalized);
			string text = $"{((ZDOID)(ref zDO.m_uid)).UserID}:{((ZDOID)(ref zDO.m_uid)).ID}";
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "BT_TeleportSync", new object[2] { text, val7 });
		}

		public static bool CheckDistanceAndTeleport(Character tame)
		{
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			BetterTames.ConfigSynchronization.ConfigSync configInstance = BetterTamesPlugin.ConfigInstance;
			if (configInstance == null || !(configInstance.Tames.TeleportFollowEnabled?.Value).GetValueOrDefault())
			{
				return false;
			}
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return false;
			}
			ZNetView component = ((Component)tame).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return false;
			}
			ZDO zDO = component.GetZDO();
			if (zDO == null)
			{
				return false;
			}
			if (!tame.IsTamed())
			{
				return false;
			}
			GameObject followTarget = ((Component)tame).GetComponent<MonsterAI>().GetFollowTarget();
			if ((Object)(object)followTarget == (Object)null)
			{
				return false;
			}
			Vector3 position = ((Component)tame).transform.position;
			Vector3 position2 = followTarget.transform.position;
			MonsterAI component2 = ((Component)tame).GetComponent<MonsterAI>();
			Character targetCreature = ((BaseAI)component2).GetTargetCreature();
			StaticTarget staticTarget = component2.GetStaticTarget();
			bool flag = ((Object)(object)targetCreature != (Object)null && BaseAI.IsEnemy(tame, targetCreature)) || (Object)(object)staticTarget != (Object)null;
			if (Vector3.Distance(position, position2) < 5f && !flag)
			{
				((BaseAI)component2).StopMoving();
			}
			if (!component.IsOwner())
			{
				return false;
			}
			float num = Mathf.Max((float)BetterTamesPlugin.ConfigInstance.Tames.TeleportOnDistanceMaxRange.Value, 10f);
			Vector3 val = position - position2;
			float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
			float num2 = num * num;
			if (sqrMagnitude <= num2)
			{
				BetterTamesPlugin.LogIfDebug($"Distance check for {tame.m_name}: {Mathf.Sqrt(sqrMagnitude):F1}m < {num}m threshold. No teleport.", DebugFeature.TeleportFollow);
				return false;
			}
			BetterTamesPlugin.LogIfDebug($"DistanceSqr {sqrMagnitude:F1} > {num2:F1}. Attempting teleport for {tame.m_name}.", DebugFeature.TeleportFollow);
			ExecuteTeleportBehindPlayer(tame, followTarget);
			return true;
		}

		public static List<Vector3> CalculateDistributedSpawnPositions(Vector3 playerPos, Quaternion playerRot, int petCount)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: 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)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>();
			if (petCount == 0)
			{
				return list;
			}
			float num = 3f;
			float num2 = 120f;
			float num3 = 0.2f;
			float num5 = default(float);
			for (int i = 0; i < petCount; i++)
			{
				float num4 = ((petCount > 1) ? ((0f - num2) / 2f + (float)i * (num2 / (float)(petCount - 1))) : 0f);
				Vector3 val = Quaternion.Euler(0f, num4, 0f) * (playerRot * Vector3.back);
				Vector3 val2 = playerPos + val * num;
				if (ZoneSystem.instance.FindFloor(val2 + Vector3.up * 2f, ref num5))
				{
					val2.y = num5 + num3;
				}
				list.Add(val2);
			}
			return list;
		}
	}
	[HarmonyPatch]
	internal static class InitializationPatches
	{
		private static bool _zNetReadyCalled;

		private static bool _localPlayerReadyCalled;

		public static void ResetInitializationFlags()
		{
			BetterTamesPlugin.LogIfDebug("Resetting initialization flags.");
			_zNetReadyCalled = false;
			_localPlayerReadyCalled = false;
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		[HarmonyPostfix]
		private static void ZNet_Awake_Postfix(ZNet __instance)
		{
			if (_zNetReadyCalled || (Object)(object)ZNet.instance != (Object)(object)__instance)
			{
				return;
			}
			BetterTamesPlugin.LogIfDebug("ZNet.Awake postfix triggered. Calling OnZNetReady...");
			try
			{
				BetterTamesPlugin.OnZNetReady();
				_zNetReadyCalled = true;
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"Error in OnZNetReady from ZNet_Awake_Postfix: {arg}");
			}
		}

		[HarmonyPatch(typeof(Player), "SetLocalPlayer")]
		[HarmonyPostfix]
		private static void Player_SetLocalPlayer_Postfix()
		{
			if (_localPlayerReadyCalled || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return;
			}
			BetterTamesPlugin.LogIfDebug("Player.SetLocalPlayer postfix triggered for " + Player.m_localPlayer.GetPlayerName() + ". Calling OnLocalPlayerReady...");
			try
			{
				BetterTamesPlugin.OnLocalPlayerReady();
				_localPlayerReadyCalled = true;
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"Error in OnLocalPlayerReady from Player_SetLocalPlayer_Postfix: {arg}");
			}
		}
	}
	public enum DebugFeature
	{
		MakeCommandable,
		TeleportFollow,
		PetProtection,
		Initialization
	}
	[BepInPlugin("Koro.bettertames", "BetterTames", "0.0.4")]
	public class BetterTamesPlugin : BaseUnityPlugin
	{
		public const string PluginId = "Koro.bettertames";

		public const string PluginName = "BetterTames";

		public const string PluginVersion = "0.0.4";

		public const string RPC_REQUEST_PET_PROTECTION = "BT_RequestPetProtection";

		public const string RPC_PET_PROTECTION_SYNC = "BT_PetProtectionSync";

		public const string RPC_TELEPORT_SYNC = "BT_TeleportSync";

		public const string RPC_PREPARE_PETS_FOR_TELEPORT = "BT_PreparePetsForTeleport";

		public const string RPC_RECREATE_PETS_AT_DESTINATION = "BT_RecreatePetsAtDest";

		public const string RPC_REQUEST_MERCY_KILL = "BT_RequestMercyKill";

		public const string RPC_NOTIFY_MERCY_KILL = "BetterTames_NotifyMercyKill";

		public static ServerSync.ConfigSync _configSync;

		private readonly Harmony _harmony = new Harmony("Koro.bettertames");

		private static bool _corePatchesAppliedSession;

		private Coroutine _petMonitorCoroutine;

		public static BetterTamesPlugin Instance { get; private set; }

		public static BetterTames.ConfigSynchronization.ConfigSync ConfigInstance { get; private set; }

		private void Awake()
		{
			Instance = this;
			_configSync = new ServerSync.ConfigSync("Koro.bettertames")
			{
				DisplayName = "BetterTames",
				CurrentVersion = "0.0.4",
				MinimumRequiredVersion = "0.0.4",
				ModRequired = true
			};
			ConfigInstance = new BetterTames.ConfigSynchronization.ConfigSync(this);
			LogIfDebug("AWAKE: Config instances initialized.");
			ConfigInstance.Tames.PetProtectionExceptionPrefabs.SettingChanged += OnExceptionPrefabsSettingChanged;
			ApplyInitialPatches();
		}

		private void OnDestroy()
		{
			LogIfDebug("OnDestroy called. Unpatching Harmony...");
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			try
			{
				if (_petMonitorCoroutine != null && (Object)(object)Player.m_localPlayer != (Object)null)
				{
					((MonoBehaviour)Player.m_localPlayer).StopCoroutine(_petMonitorCoroutine);
					_petMonitorCoroutine = null;
					LogIfDebug("Stopped PlayerPetMonitor coroutine on destroy.", DebugFeature.TeleportFollow);
				}
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)$"Failed stopping PlayerPetMonitor coroutine: {arg}");
			}
		}

		public static void OnZNetReady()
		{
			LogIfDebug("ZNet is ready. Registering RPCs...");
			RPCManager.RegisterRPCs();
			LogIfDebug($"RPC registration completed. ZRoutedRpc instance active: {ZRoutedRpc.instance != null}");
		}

		public static void OnLocalPlayerReady()
		{
			LogIfDebug("Local player is ready.");
			PetProtectionPatch.Initialize();
			if (!_corePatchesAppliedSession)
			{
				ApplyCorePatches();
				_corePatchesAppliedSession = true;
			}
		}

		private void ApplyInitialPatches()
		{
			try
			{
				LogIfDebug("Applying initial patches (Initialization & PetProtection)...");
				_harmony.PatchAll(typeof(PetProtectionPatch));
				_harmony.PatchAll(typeof(InitializationPatches));
				_harmony.PatchAll(typeof(EnemyHud_TestShow_Patch));
				LogIfDebug("Initial patches applied.");
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"CRITICAL ERROR applying initial patches: {arg}");
			}
		}

		private static void ApplyCorePatches()
		{
			try
			{
				if ((Object)(object)Player.m_localPlayer != (Object)null)
				{
					Instance._petMonitorCoroutine = ((MonoBehaviour)Player.m_localPlayer).StartCoroutine(PlayerPetMonitor.MonitorRoutine());
					LogIfDebug("Started PlayerPetMonitor coroutine on local player.", DebugFeature.TeleportFollow);
				}
				else
				{
					LogIfDebug("Player.m_localPlayer was null when attempting to start PlayerPetMonitor.", DebugFeature.TeleportFollow);
				}
				LogIfDebug("Applying core feature patches...");
				Instance._harmony.PatchAll(typeof(MakeCommandablePatch));
				Instance._harmony.PatchAll(typeof(StunBehaviorPatches));
				Instance._harmony.PatchAll(typeof(ButcherKnifePatch));
				LogIfDebug("Core feature patches applied.");
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)Instance).Logger.LogError((object)$"Exception during core patching: {arg}");
			}
		}

		private void OnExceptionPrefabsSettingChanged(object sender, EventArgs e)
		{
			PetProtectionPatch.UpdateExceptionPrefabs(ConfigInstance.Tames.PetProtectionExceptionPrefabs.Value);
		}

		public static void LogIfDebug(string message, DebugFeature feature = DebugFeature.Initialization)
		{
			if (ConfigInstance != null && feature switch
			{
				DebugFeature.MakeCommandable => ConfigInstance.Tames.DebugMakeCommandable.Value, 
				DebugFeature.TeleportFollow => ConfigInstance.Tames.DebugTeleportFollow.Value, 
				DebugFeature.PetProtection => ConfigInstance.Tames.DebugPetProtection.Value, 
				DebugFeature.Initialization => true, 
				_ => false, 
			})
			{
				((BaseUnityPlugin)Instance).Logger.LogInfo((object)$"[{feature}] {message}");
			}
		}
	}
}
namespace BetterTames.Utils
{
	public static class RPCHelper
	{
		public static bool Ready => ZRoutedRpc.instance != null && (Object)(object)ZNet.instance != (Object)null;

		public static void RegisterServer<T1>(string rpcName, Action<long, T1> handler)
		{
			if (!Ready || !ZNet.instance.IsServer())
			{
				return;
			}
			try
			{
				ZRoutedRpc.instance.Register<T1>(rpcName, handler);
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"RegisterServer failed for {rpcName}: {arg}");
			}
		}

		public static void RegisterClient<T1>(string rpcName, Action<long, T1> handler)
		{
			if (!Ready || ZNet.instance.IsServer())
			{
				return;
			}
			try
			{
				ZRoutedRpc.instance.Register<T1>(rpcName, handler);
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"RegisterClient failed for {rpcName}: {arg}");
			}
		}

		public static void RegisterClient<T1, T2>(string rpcName, Action<long, T1, T2> handler)
		{
			if (!Ready || ZNet.instance.IsServer())
			{
				return;
			}
			try
			{
				ZRoutedRpc.instance.Register<T1, T2>(rpcName, handler);
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"RegisterClient failed for {rpcName}: {arg}");
			}
		}

		public static void RegisterClient<T1, T2, T3>(string rpcName, Action<long, T1, T2, T3> handler)
		{
			if (!Ready || ZNet.instance.IsServer())
			{
				return;
			}
			try
			{
				ZRoutedRpc.instance.Register<T1, T2, T3>(rpcName, handler);
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"RegisterClient failed for {rpcName}: {arg}");
			}
		}

		public static ZDOID ParseZDOID(string zdoID_str)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(zdoID_str))
			{
				return ZDOID.None;
			}
			string[] array = zdoID_str.Split(new char[1] { ':' });
			if (array.Length != 2)
			{
				return ZDOID.None;
			}
			if (long.TryParse(array[0], out var result) && uint.TryParse(array[1], out var result2))
			{
				return new ZDOID(result, result2);
			}
			return ZDOID.None;
		}

		public static string ZDOIDToString(ZDOID zdoid)
		{
			if (((ZDOID)(ref zdoid)).IsNone())
			{
				return string.Empty;
			}
			return $"{((ZDOID)(ref zdoid)).UserID}:{((ZDOID)(ref zdoid)).ID}";
		}

		public static ZPackage CreateTeleportPackage(Vector3 pos, Quaternion rot)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			val.Write(pos);
			val.Write(rot);
			return val;
		}

		public static bool TryReadTeleportPackage(ZPackage pkg, out Vector3 pos, out Quaternion rot)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			pos = Vector3.zero;
			rot = Quaternion.identity;
			try
			{
				pos = pkg.ReadVector3();
				rot = pkg.ReadQuaternion();
				return true;
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"TryReadTeleportPackage failed: {arg}", DebugFeature.TeleportFollow);
				return false;
			}
		}
	}
	public static class RPCManager
	{
		private static readonly Dictionary<ZDOID, List<ZDOID>> serverPetTeleportCache = new Dictionary<ZDOID, List<ZDOID>>();

		public static void RegisterRPCs()
		{
			BetterTamesPlugin.LogIfDebug("Registering RPCs...");
			RPCHelper.RegisterClient<ZDOID>("BT_RequestMercyKill", RPC_RequestMercyKill_Server);
			RPCHelper.RegisterClient<string>("BetterTames_NotifyMercyKill", RPC_NotifyMercyKill_Client);
			RPCHelper.RegisterClient<string, ZPackage>("BT_TeleportSync", RPC_TeleportSync_Client);
		}

		private static void RPC_RequestMercyKill_Server(long sender, ZDOID targetZDOID)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer())
			{
				return;
			}
			BetterTamesPlugin.LogIfDebug($"RPC_MercyKill_AllClients triggered for ZDOID: {targetZDOID} from sender: {sender}", DebugFeature.PetProtection);
			ZDO zDO = ZDOMan.instance.GetZDO(targetZDOID);
			if (zDO == null)
			{
				BetterTamesPlugin.LogIfDebug($"ZDO for ZDOID {targetZDOID} not found. Cannot process MercyKill.", DebugFeature.PetProtection);
				return;
			}
			GameObject val = ZNetScene.instance.FindInstance(targetZDOID);
			if ((Object)(object)val == (Object)null)
			{
				BetterTamesPlugin.LogIfDebug($"GameObject for ZDOID {targetZDOID} not found, but ZDO exists. Setting flag via ZDO.", DebugFeature.PetProtection);
			}
			else
			{
				BetterTamesPlugin.LogIfDebug($"Found GameObject for ZDOID {targetZDOID}.", DebugFeature.PetProtection);
			}
			zDO.Set("BT_MercyKill", true);
			BetterTamesPlugin.LogIfDebug($"BT_MercyKill flag set for ZDOID {targetZDOID} via ZDO. Pet protection bypassed on next damage.", DebugFeature.PetProtection);
			try
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "BetterTames_NotifyMercyKill", new object[1] { ((object)(ZDOID)(ref targetZDOID)).ToString() });
				BetterTamesPlugin.LogIfDebug($"NotifyMercyKill broadcast sent for ZDOID {targetZDOID}.", DebugFeature.PetProtection);
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"Exception while broadcasting NotifyMercyKill: {arg}", DebugFeature.PetProtection);
			}
		}

		private static void RPC_NotifyMercyKill_Client(long sender, string targetZDOID_str)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer())
				{
					return;
				}
				ZDOID val = ParseZDOID(targetZDOID_str);
				if (((ZDOID)(ref val)).IsNone())
				{
					return;
				}
				ZDO zDO = ZDOMan.instance.GetZDO(val);
				if (zDO == null)
				{
					return;
				}
				zDO.Set("BT_MercyKill", true);
				BetterTamesPlugin.LogIfDebug(string.Format("Client received NotifyMercyKill for ZDOID {0}. Local BT_MercyKill = {1}", val, zDO.GetBool("BT_MercyKill", false)), DebugFeature.PetProtection);
				try
				{
					if (!zDO.IsValid() || !zDO.IsOwner())
					{
						return;
					}
					BetterTamesPlugin.LogIfDebug($"This client is owner for ZDOID {val}. Attempting local owner-side kill.", DebugFeature.PetProtection);
					ZNetView val2 = ZNetScene.instance.FindInstance(zDO);
					if ((Object)(object)val2 != (Object)null)
					{
						Character component = ((Component)val2).GetComponent<Character>();
						if ((Object)(object)component != (Object)null)
						{
							component.SetHealth(0f);
							BetterTamesPlugin.LogIfDebug($"Owner performed local Kill() for {component.m_name} (ZDOID: {val}).", DebugFeature.PetProtection);
						}
						else
						{
							BetterTamesPlugin.LogIfDebug($"Owner: found ZNetView but no Character component for ZDOID {val}.", DebugFeature.PetProtection);
						}
					}
					else
					{
						BetterTamesPlugin.LogIfDebug($"Owner: no instance found for ZDOID {val} when trying to perform local kill.", DebugFeature.PetProtection);
					}
				}
				catch (Exception arg)
				{
					BetterTamesPlugin.LogIfDebug($"Exception while attempting owner local kill in RPC_NotifyMercyKill_Client: {arg}", DebugFeature.PetProtection);
				}
			}
			catch (Exception arg2)
			{
				BetterTamesPlugin.LogIfDebug($"Exception in RPC_NotifyMercyKill_Client: {arg2}", DebugFeature.PetProtection);
			}
		}

		private static void RPC_TeleportSync_Client(long sender, string zdoID_str, ZPackage pkg)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer())
				{
					return;
				}
				ZDOID val = ParseZDOID(zdoID_str);
				if (((ZDOID)(ref val)).IsNone())
				{
					return;
				}
				ZDO zDO = ZDOMan.instance.GetZDO(val);
				if (zDO == null || !zDO.IsValid())
				{
					return;
				}
				Vector3 position = pkg.ReadVector3();
				Quaternion val2 = pkg.ReadQuaternion();
				val2 = ((Quaternion)(ref val2)).normalized;
				if (float.IsNaN(val2.x) || float.IsNaN(val2.y) || float.IsNaN(val2.z) || float.IsNaN(val2.w))
				{
					BetterTamesPlugin.LogIfDebug("RPC_TeleportSync_Client: received invalid rotation quaternion, ignoring rotation.", DebugFeature.TeleportFollow);
					val2 = Quaternion.identity;
				}
				ZNetView val3 = ZNetScene.instance.FindInstance(zDO);
				if ((Object)(object)val3 != (Object)null)
				{
					Character component = ((Component)val3).GetComponent<Character>();
					if ((Object)(object)component != (Object)null && !component.IsTeleporting())
					{
						((Component)val3).transform.position = position;
						((Component)val3).transform.rotation = val2;
					}
				}
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"Exception in RPC_TeleportSync_Client: {arg}", DebugFeature.TeleportFollow);
			}
		}

		private static ZDOID ParseZDOID(string zdoID_str)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(zdoID_str))
			{
				return ZDOID.None;
			}
			string[] array = zdoID_str.Split(new char[1] { ':' });
			if (array.Length != 2)
			{
				return ZDOID.None;
			}
			if (long.TryParse(array[0], out var result) && uint.TryParse(array[1], out var result2))
			{
				return new ZDOID(result, result2);
			}
			return ZDOID.None;
		}
	}
}
namespace BetterTames.PetProtection
{
	[HarmonyPatch(typeof(Character), "Damage")]
	public static class ButcherKnifePatch
	{
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		public static bool Prefix(Character __instance, HitData hit)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			BetterTamesPlugin.LogIfDebug("ButcherKnifePatch Prefix called for character: " + (((Object)(object)__instance != (Object)null) ? __instance.m_name : "null"), DebugFeature.PetProtection);
			if (CheckButcherKnifeBypass(__instance, hit))
			{
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if ((Object)(object)component != (Object)null && component.IsValid())
				{
					ZDOID uid = component.GetZDO().m_uid;
					BetterTamesPlugin.LogIfDebug($"Butcher Knife used on {__instance.m_name} (ZDOID: {uid}). IsOwner: {component.IsOwner()}", DebugFeature.PetProtection);
					if (component.IsOwner())
					{
						BetterTamesPlugin.LogIfDebug("Owner setting BT_MercyKill flag for " + __instance.m_name + " locally.", DebugFeature.PetProtection);
						component.GetZDO().Set("BT_MercyKill", true);
						return true;
					}
					BetterTamesPlugin.LogIfDebug($"Non-owner sending MercyKill RPC for ZDOID: {uid} to server and ALLOWING local damage.", DebugFeature.PetProtection);
					try
					{
						ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "BT_RequestMercyKill", new object[1] { uid });
						BetterTamesPlugin.LogIfDebug($"MercyKill RPC sent to server for ZDOID: {uid}. Local damage allowed.", DebugFeature.PetProtection);
					}
					catch (Exception arg)
					{
						BetterTamesPlugin.LogIfDebug($"Exception while sending MercyKill RPC from non-owner: {arg}", DebugFeature.PetProtection);
					}
					return true;
				}
				BetterTamesPlugin.LogIfDebug("ZNetView is null or invalid, cannot process MercyKill.", DebugFeature.PetProtection);
			}
			return true;
		}

		private static bool CheckButcherKnifeBypass(Character character, HitData hit)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			BetterTamesPlugin.LogIfDebug("Checking ButcherKnife bypass conditions...", DebugFeature.PetProtection);
			Character attacker = hit.GetAttacker();
			BetterTamesPlugin.LogIfDebug($"Attacker: {(Object)(object)attacker != (Object)null}, IsPlayer: {attacker != null && attacker.IsPlayer()}", DebugFeature.PetProtection);
			if ((Object)(object)attacker != (Object)null && attacker.IsPlayer())
			{
				Player val = (Player)attacker;
				ItemData currentWeapon = ((Humanoid)val).GetCurrentWeapon();
				BetterTamesPlugin.LogIfDebug(string.Format("CurrentWeapon: {0}, Name: {1}", currentWeapon != null, ((currentWeapon != null) ? ((Object)currentWeapon.m_dropPrefab).name : null) ?? "null"), DebugFeature.PetProtection);
				if (currentWeapon != null && ((Object)currentWeapon.m_dropPrefab).name == "KnifeButcher")
				{
					BetterTamesPlugin.LogIfDebug($"IsTamed check for {character.m_name}: {character.IsTamed()}", DebugFeature.PetProtection);
					if (character.IsTamed())
					{
						BetterTamesPlugin.LogIfDebug("Butcher Knife used on tamed animal. Bypassing pet protection.", DebugFeature.PetProtection);
						return true;
					}
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(EnemyHud), "TestShow")]
	public static class EnemyHud_TestShow_Patch
	{
		[HarmonyPostfix]
		public static void HideKnockedOutHud(Character c, ref bool __result)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: 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)
			if (!__result || (Object)(object)c == (Object)null || !c.IsTamed())
			{
				return;
			}
			ZNetView component = ((Component)c).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid())
			{
				ZDOID uid = component.GetZDO().m_uid;
				if (PetProtectionPatch.IsPetKnockedOut(uid) || PetProtectionPatch.IsTransformedToWisp(uid))
				{
					__result = false;
				}
			}
		}
	}
	[HarmonyPatch]
	public static class PetProtectionPatch
	{
		private static readonly HashSet<string> s_exceptionPrefabs = new HashSet<string>();

		private static readonly Dictionary<ZDOID, GameObject> s_wispInstances = new Dictionary<ZDOID, GameObject>();

		private static GameObject wispPrefab;

		public static bool IsPetKnockedOut(ZDOID petId)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return s_wispInstances.ContainsKey(petId);
		}

		public static bool IsTransformedToWisp(ZDOID petId)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = ZDOMan.instance.GetZDO(petId);
			return zDO != null && zDO.GetBool("BT_TransformedToWisp", false);
		}

		public static void Initialize()
		{
			wispPrefab = ZNetScene.instance.GetPrefab("LuredWisp");
			BetterTamesPlugin.LogIfDebug("Stunned Pets get Transformed into: " + (object)wispPrefab, DebugFeature.PetProtection);
			if ((Object)(object)wispPrefab != (Object)null)
			{
				BetterTamesPlugin.LogIfDebug("LuredWisp prefab cached successfully.", DebugFeature.PetProtection);
			}
			else
			{
				BetterTamesPlugin.LogIfDebug("ERROR: Could not cache LuredWisp prefab!", DebugFeature.PetProtection);
			}
		}

		public static void UpdateExceptionPrefabs(string exceptionPrefabString)
		{
			s_exceptionPrefabs.Clear();
			if (!string.IsNullOrWhiteSpace(exceptionPrefabString))
			{
				string[] array = exceptionPrefabString.Split(new char[1] { ',' });
				string[] array2 = array;
				foreach (string text in array2)
				{
					s_exceptionPrefabs.Add(text.Trim().ToLowerInvariant());
				}
			}
		}

		private static bool ShouldApplyPetProtection(Character character)
		{
			if ((Object)(object)character == (Object)null || !character.IsTamed())
			{
				return false;
			}
			ZNetView component = ((Component)character).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return false;
			}
			string item = ((Object)ZNetScene.instance.GetPrefab(component.GetZDO().GetPrefab())).name.ToLowerInvariant();
			return !s_exceptionPrefabs.Contains(item);
		}

		[HarmonyPatch(typeof(Character), "ApplyDamage")]
		[HarmonyPrefix]
		public static bool ApplyDamagePrefix(Character __instance, HitData hit)
		{
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Expected O, but got Unknown
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return true;
			}
			ZDO zDO = component.GetZDO();
			try
			{
				if ((Object)(object)ZNet.instance != (Object)null && component.IsOwner())
				{
					Character attacker = hit.GetAttacker();
					if ((Object)(object)attacker != (Object)null && attacker.IsPlayer())
					{
						Player val = (Player)attacker;
						ItemData currentWeapon = ((Humanoid)val).GetCurrentWeapon();
						if (currentWeapon != null && (Object)(object)currentWeapon.m_dropPrefab != (Object)null && string.Equals(((Object)currentWeapon.m_dropPrefab).name, "KnifeButcher", StringComparison.OrdinalIgnoreCase))
						{
							BetterTamesPlugin.LogIfDebug("Zonehost Bypass for butcherknife hit on " + __instance.m_name + ". Bypassing PetProtection and allowing damage.", DebugFeature.PetProtection);
							return true;
						}
					}
				}
				else
				{
					BetterTamesPlugin.LogIfDebug("Not a server-owner or Zonehost butcherknife hit, proceeding with normal checks.", DebugFeature.PetProtection);
					if (zDO != null && zDO.GetBool("BT_MercyKill", false))
					{
						BetterTamesPlugin.LogIfDebug($"{__instance.m_name} marked for MercyKill (ZDOID: {zDO.m_uid}). Bypassing pet protection. Initial Health: {__instance.GetHealth()}, Hit Damage: {hit.GetTotalDamage()}", DebugFeature.PetProtection);
						zDO.Set("BT_MercyKill", false);
						return true;
					}
				}
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"Exception in server-bypass butcherknife check: {arg}", DebugFeature.PetProtection);
			}
			if (!BetterTamesPlugin.ConfigInstance.Tames.PetProtectionEnabled.Value || !ShouldApplyPetProtection(__instance))
			{
				return true;
			}
			if (!component.IsOwner())
			{
				if (__instance.GetHealth() <= hit.GetTotalDamage())
				{
					try
					{
						Character attacker2 = hit.GetAttacker();
						if ((Object)(object)attacker2 != (Object)null && attacker2.IsPlayer())
						{
							Player val2 = (Player)attacker2;
							ItemData currentWeapon2 = ((Humanoid)val2).GetCurrentWeapon();
							if (currentWeapon2 != null && (Object)(object)currentWeapon2.m_dropPrefab != (Object)null && string.Equals(((Object)currentWeapon2.m_dropPrefab).name, "KnifeButcher", StringComparison.OrdinalIgnoreCase))
							{
								BetterTamesPlugin.LogIfDebug($"Non-owner detected lethal butcherknife hit on {__instance.m_name}. Sending MercyKill request to server for ZDOID: {zDO.m_uid}", DebugFeature.PetProtection);
								ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "BT_RequestMercyKill", new object[1] { zDO.m_uid });
								return false;
							}
						}
					}
					catch (Exception arg2)
					{
						BetterTamesPlugin.LogIfDebug($"Exception while sending MercyKill request from non-owner: {arg2}", DebugFeature.PetProtection);
					}
				}
				return true;
			}
			if (zDO.GetBool("isRecoveringFromStun", false))
			{
				return false;
			}
			if (__instance.GetHealth() > hit.GetTotalDamage())
			{
				return true;
			}
			ApplyWispTransform(__instance, component, zDO);
			return false;
		}

		[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
		[HarmonyPostfix]
		public static void KnockoutTimerPostfix(MonsterAI __instance)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsOwner())
			{
				return;
			}
			ZDO zDO = component.GetZDO();
			if (!zDO.GetBool("isRecoveringFromStun", false))
			{
				return;
			}
			if (s_wispInstances.TryGetValue(zDO.m_uid, out var value) && (Object)(object)value != (Object)null)
			{
				Character component2 = value.GetComponent<Character>();
				MonsterAI component3 = ((Component)__instance).GetComponent<MonsterAI>();
				if ((Object)(object)component2 != (Object)null && (Object)(object)component3 != (Object)null)
				{
					GameObject followTarget = component3.GetFollowTarget();
					Player val = ((followTarget != null) ? followTarget.GetComponent<Player>() : null);
					if ((Object)(object)val != (Object)null)
					{
						BetterTamesPlugin.LogIfDebug("Teleporting wisp to player.", DebugFeature.PetProtection);
						DistanceTeleportLogic.ExecuteTeleportBehindPlayer((Character)(object)val, followTarget);
					}
				}
			}
			float @float = zDO.GetFloat("BT_RevivalTimestamp", 0f);
			if (@float > 0f && ZNet.instance.GetTimeSeconds() >= (double)@float)
			{
				Character component4 = ((Component)__instance).GetComponent<Character>();
				if ((Object)(object)component4 != (Object)null)
				{
					RevertWispTransform(component4, component, zDO);
				}
			}
		}

		private static void ApplyWispTransform(Character character, ZNetView nview, ZDO zdo)
		{
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			zdo.Set("isRecoveringFromStun", true);
			zdo.Set(ZDOVars.s_health, 1f);
			float num = (float)ZNet.instance.GetTimeSeconds() + (float)BetterTamesPlugin.ConfigInstance.Tames.PetProtectionStunDuration.Value;
			zdo.Set("BT_RevivalTimestamp", num);
			if ((Object)(object)EnemyHud.instance != (Object)null)
			{
				EnemyHud.instance.RemoveCharacterHud(character);
			}
			float num2 = (float)ZNet.instance.GetTimeSeconds() + 2f;
			zdo.Set("BT_WispTeleportTimestamp", num2);
			zdo.Set("BT_TransformedToWisp", true);
			SetRenderersVisible(character, visible: false);
			if (!((Object)(object)wispPrefab != (Object)null))
			{
				return;
			}
			GameObject val = Object.Instantiate<GameObject>(wispPrefab, ((Component)character).transform.position, Quaternion.identity);
			try
			{
				Collider[] componentsInChildren = val.GetComponentsInChildren<Collider>(true);
				int num3 = 0;
				Collider[] array = componentsInChildren;
				foreach (Collider val2 in array)
				{
					if ((Object)(object)val2 != (Object)null && val2.enabled)
					{
						val2.enabled = false;
						num3++;
					}
				}
				Rigidbody[] componentsInChildren2 = val.GetComponentsInChildren<Rigidbody>(true);
				Rigidbody[] array2 = componentsInChildren2;
				foreach (Rigidbody val3 in array2)
				{
					if ((Object)(object)val3 != (Object)null)
					{
						val3.isKinematic = true;
					}
				}
				BetterTamesPlugin.LogIfDebug($"Wisp instance created. Disabled {num3} colliders on wisp.", DebugFeature.PetProtection);
			}
			catch (Exception arg)
			{
				BetterTamesPlugin.LogIfDebug($"Exception while disabling colliders on wisp: {arg}", DebugFeature.PetProtection);
			}
			MonsterAI component = ((Component)character).GetComponent<MonsterAI>();
			GameObject followTarget = component.GetFollowTarget();
			Player val4 = ((followTarget != null) ? followTarget.GetComponent<Player>() : null);
			if ((Object)(object)val4 != (Object)null)
			{
				BetterTamesPlugin.LogIfDebug("Teleporting Soul to player.", DebugFeature.PetProtection);
				DistanceTeleportLogic.ExecuteTeleportBehindPlayer(character, followTarget);
			}
			s_wispInstances[zdo.m_uid] = val;
		}

		private static void RevertWispTransform(Character character, ZNetView nview, ZDO zdo)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			BetterTamesPlugin.LogIfDebug("Reverting " + character.m_name + " from wisp form.", DebugFeature.PetProtection);
			if (s_wispInstances.TryGetValue(zdo.m_uid, out var value))
			{
				if ((Object)(object)value != (Object)null)
				{
					Object.Destroy((Object)(object)value);
				}
				s_wispInstances.Remove(zdo.m_uid);
			}
			SetRenderersVisible(character, visible: true);
			zdo.Set("BT_TransformedToWisp", false);
			zdo.Set("isRecoveringFromStun", false);
			zdo.Set("BT_RevivalTimestamp", 0f);
			float maxHealth = character.GetMaxHealth();
			float num = BetterTamesPlugin.ConfigInstance.Tames.PetProtectionHealPercentage.Value;
			float num2 = Mathf.Clamp(maxHealth * (num / 100f), 1f, maxHealth);
			zdo.Set(ZDOVars.s_health, num2);
		}

		private static void SetRenderersVisible(Character character, bool visible)
		{
			Collider[] componentsInChildren = ((Component)character).GetComponentsInChildren<Collider>();
			foreach (Collider val in componentsInChildren)
			{
				val.enabled = visible;
			}
			Renderer[] componentsInChildren2 = ((Component)character).GetComponentsInChildren<Renderer>();
			foreach (Renderer val2 in componentsInChildren2)
			{
				val2.enabled = visible;
			}
		}
	}
	[HarmonyPatch]
	public static class StunBehaviorPatches
	{
		[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
		[HarmonyPrefix]
		public static bool PreventAIUpdateWhenStunned(MonsterAI __instance)
		{
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return true;
			}
			SyncRenderersWithZDO(__instance);
			ZDO zDO = component.GetZDO();
			if (zDO == null || !zDO.GetBool("isRecoveringFromStun", false))
			{
				return true;
			}
			((BaseAI)__instance).StopMoving();
			Character component2 = ((Component)__instance).GetComponent<Character>();
			if ((Object)(object)component2 != (Object)null)
			{
				ZSyncAnimation zAnim = component2.GetZAnim();
				if (zAnim != null)
				{
					zAnim.SetBool("sleeping", true);
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(Humanoid), "StartAttack")]
		[HarmonyPrefix]
		public static bool PreventAttackWhenStunned_Humanoid(Humanoid __instance)
		{
			if (!((Character)__instance).IsTamed())
			{
				return true;
			}
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid() && component.GetZDO().GetBool("isRecoveringFromStun", false))
			{
				return false;
			}
			return true;
		}

		private static void SyncRenderersWithZDO(MonsterAI ai)
		{
			if ((Object)(object)ai == (Object)null)
			{
				return;
			}
			ZNetView component = ((Component)ai).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return;
			}
			ZDO zDO = component.GetZDO();
			if (zDO == null)
			{
				return;
			}
			bool @bool = zDO.GetBool("BT_TransformedToWisp", false);
			Character component2 = ((Component)ai).GetComponent<Character>();
			if ((Object)(object)component2 == (Object)null)
			{
				return;
			}
			bool flag = !@bool;
			bool flag2 = false;
			Renderer[] componentsInChildren = ((Component)component2).GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null && val.enabled)
				{
					flag2 = true;
					break;
				}
			}
			if (flag2 != flag)
			{
				ApplyRendererVisibility(component2, flag);
			}
		}

		private static void ApplyRendererVisibility(Character character, bool visible)
		{
			if ((Object)(object)character == (Object)null)
			{
				return;
			}
			Collider[] componentsInChildren = ((Component)character).GetComponentsInChildren<Collider>(true);
			foreach (Collider val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null)
				{
					val.enabled = visible;
				}
			}
			Renderer[] componentsInChildren2 = ((Component)character).GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val2 in componentsInChildren2)
			{
				if ((Object)(object)val2 != (Object)null)
				{
					val2.enabled = visible;
				}
			}
		}
	}
}
namespace BetterTames.MakeCommandable
{
	[HarmonyPatch(typeof(Tameable), "Interact")]
	public static class MakeCommandablePatch
	{
		[HarmonyPatch(typeof(Player), "TeleportTo")]
		public static class Player_TeleportTo_Patch
		{
			[HarmonyPostfix]
			public static void Postfix(Player __instance)
			{
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
				{
					return;
				}
				int value = BetterTamesPlugin.ConfigInstance.Tames.MaxFollowingPets.Value;
				if (value == -1)
				{
					return;
				}
				string playerName = __instance.GetPlayerName();
				float num = 50f;
				List<Character> list = new List<Character>();
				Collider[] array = Physics.OverlapSphere(((Component)__instance).transform.position, num);
				foreach (Collider val in array)
				{
					Character component = ((Component)val).GetComponent<Character>();
					if ((Object)(object)component != (Object)null && component.IsTamed())
					{
						ZNetView component2 = ((Component)component).GetComponent<ZNetView>();
						if (((component2 != null) ? component2.GetZDO().GetString(ZDOVars.s_follow, "") : null) == playerName)
						{
							list.Add(component);
						}
					}
				}
				if (list.Count <= value)
				{
					return;
				}
				((Character)__instance).Message((MessageType)2, "Begleiter-Limit am Ankunftsort überschritten.", 0, (Sprite)null);
				List<Character> list2 = list.OrderByDescending((Character c) => Vector3.Distance(((Component)__instance).transform.position, ((Component)c).transform.position)).ToList();
				int num2 = list2.Count - value;
				for (int j = 0; j < num2; j++)
				{
					MonsterAI component3 = ((Component)list2[j]).GetComponent<MonsterAI>();
					if (component3 != null)
					{
						component3.SetFollowTarget((GameObject)null);
					}
				}
			}
		}

		[HarmonyPrefix]
		public static bool Prefix(Tameable __instance, Humanoid user, bool hold, bool alt, ref bool __result)
		{
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			if (hold || alt)
			{
				return true;
			}
			Character component = ((Component)__instance).GetComponent<Character>();
			if ((Object)(object)component == (Object)null || !component.IsTamed())
			{
				return true;
			}
			Player val = (Player)(object)((user is Player) ? user : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val != (Object)(object)Player.m_localPlayer)
			{
				return true;
			}
			MonsterAI component2 = ((Component)__instance).GetComponent<MonsterAI>();
			if ((Object)(object)component2 != (Object)null && (Object)(object)component2.GetFollowTarget() == (Object)null)
			{
				int value = BetterTamesPlugin.ConfigInstance.Tames.MaxFollowingPets.Value;
				if (value != -1)
				{
					int num = 0;
					string playerName = val.GetPlayerName();
					float num2 = 64f;
					Collider[] array = Physics.OverlapSphere(((Component)val).transform.position, num2);
					foreach (Collider val2 in array)
					{
						Character component3 = ((Component)val2).GetComponent<Character>();
						if ((Object)(object)component3 != (Object)null && component3.IsTamed())
						{
							ZNetView component4 = ((Component)component3).GetComponent<ZNetView>();
							if (((component4 != null) ? component4.GetZDO().GetString(ZDOVars.s_follow, "") : null) == playerName)
							{
								num++;
							}
						}
					}
					if (num >= value)
					{
						((Character)user).Message((MessageType)2, "Zu viele Begleiter in deiner Nähe folgen dir bereits. Maximal erlaubt: " + value, 0, (Sprite)null);
						__result = true;
						return false;
					}
				}
			}
			__instance.Command(user, true);
			string text = (((Object)(object)component2 != (Object)null && (Object)(object)component2.GetFollowTarget() != (Object)null) ? "Follow" : "Stay");
			BetterTamesPlugin.LogIfDebug("Command issued to " + __instance.GetHoverName() + ": " + text, DebugFeature.MakeCommandable);
			__result = true;
			return false;
		}
	}
}
namespace BetterTames.ConfigSynchronization
{
	public class ConfigSync
	{
		public class TamesConfig
		{
			private const string SectionGeneral = "1. General";

			private const string SectionMakeCommandable = "2. MakeCommandable";

			private const string SectionTeleportFollow = "3. TeleportFollow";

			private const string SectionPetProtection = "4. PetProtection";

			private const string SectionTaming = "5. Taming";

			public ConfigEntry<bool> ServerConfigLocked { get; private set; }

			public ConfigEntry<bool> DebugMakeCommandable { get; private set; }

			public ConfigEntry<int> MaxFollowingPets { get; private set; }

			public ConfigEntry<bool> TeleportFollowEnabled { get; private set; }

			public ConfigEntry<int> TeleportOnDistanceMaxRange { get; private set; }

			public ConfigEntry<bool> DebugTeleportFollow { get; private set; }

			public ConfigEntry<bool> PetProtectionEnabled { get; private set; }

			public ConfigEntry<int> PetProtectionStunDuration { get; private set; }

			public ConfigEntry<int> PetProtectionHealPercentage { get; private set; }

			public ConfigEntry<string> PetProtectionExceptionPrefabs { get; private set; }

			public ConfigEntry<bool> DebugPetProtection { get; private set; }

			public TamesConfig(ConfigFile cfg)
			{
				//IL_0056: Unknown result type (might be due to invalid IL or missing references)
				//IL_0060: Expected O, but got Unknown
				//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ce: Expected O, but got Unknown
				//IL_0134: Unknown result type (might be due to invalid IL or missing references)
				//IL_013e: Expected O, but got Unknown
				//IL_0165: Unknown result type (might be due to invalid IL or missing references)
				//IL_016f: Expected O, but got Unknown
				ServerConfigLocked = cfg.Bind<bool>("1. General", "Lock Configuration", true, "If true on the server, this configuration file will be locked and synced to clients.");
				BetterTamesPlugin._configSync.AddLockingConfigEntry<bool>(ServerConfigLocked);
				MaxFollowingPets = BindAndSync(cfg, "2. MakeCommandable", "Max Following Pets", 5, new ConfigDescription("Maximum number of pets that can follow a player at the same time. -1 to disable.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-1, 20), Array.Empty<object>()));
				DebugMakeCommandable = BindAndSync(cfg, "2. MakeCommandable", "Debug Logging", defaultValue: false, "Enables debug logging for this feature.");
				TeleportFollowEnabled = BindAndSync(cfg, "3. TeleportFollow", "Enable", defaultValue: true, "Enables pets to teleport to the player if they get too far or the player uses a portal/teleports.");
				TeleportOnDistanceMaxRange = BindAndSync(cfg, "3. TeleportFollow", "Max Distance For AutoTeleport", 64, new ConfigDescription("Maximum distance a pet can be from its owner before it attempts to teleport (if not in combat).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(20, 64), Array.Empty<object>()));
				DebugTeleportFollow = BindAndSync(cfg, "3. TeleportFollow", "Debug Logging", defaultValue: false, "Enables debug logging for teleport features.");
				PetProtectionEnabled = BindAndSync(cfg, "4. PetProtection", "Enable", defaultValue: true, "Prevents tamed creatures from dying by knocking them out instead. They recover after a set time.");
				PetProtectionStunDuration = BindAndSync(cfg, "4. PetProtection", "Stun Duration", 10, new ConfigDescription("How long the pet stays stunned/downed (seconds).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 300), Array.Empty<object>()));
				PetProtectionHealPercentage = BindAndSync(cfg, "4. PetProtection", "Heal After Stun Pct", 25, new ConfigDescription("Percentage of max HP the pet recovers after being downed. (0 = 1HP).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
				PetProtectionExceptionPrefabs = BindAndSync(cfg, "4. PetProtection", "Exception Prefabs", "SummonedGolem_TW,SummonedSurtling_TW,SummonedSeeker_TW,SummonedImp_TW,Troll_Summoned,Charred_Twitcher_Summoned,Skeleton_Friendly,JC_Skeleton,ArcticWolf_TW", "A comma-separated list of prefab names that should NOT receive pet protection.");
				DebugPetProtection = BindAndSync(cfg, "4. PetProtection", "Debug Logging", defaultValue: false, "Enables debug logging for this feature.");
			}

			private ConfigEntry<T> BindAndSync<T>(ConfigFile cfg, string section, string key, T defaultValue, string description)
			{
				ConfigEntry<T> val = cfg.Bind<T>(section, key, defaultValue, description);
				BetterTamesPlugin._configSync.AddConfigEntry<T>(val);
				return val;
			}

			private ConfigEntry<T> BindAndSync<T>(ConfigFile cfg, string section, string key, T defaultValue, ConfigDescription description)
			{
				ConfigEntry<T> val = cfg.Bind<T>(section, key, defaultValue, description);
				BetterTamesPlugin._configSync.AddConfigEntry<T>(val);
				return val;
			}
		}

		public TamesConfig Tames { get; private set; }

		public ConfigSync(BetterTamesPlugin pluginInstance)
		{
			Tames = new TamesConfig(((BaseUnityPlugin)pluginInstance).Config);
		}
	}
}
namespace BetterTames.DistanceTeleport
{
	public static class PlayerPetMonitor
	{
		[CompilerGenerated]
		private sealed class <MonitorRoutine>d__1 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			private List<Character> <allCharacters>5__1;

			private List<Character> <followingPets>5__2;

			private List<Character>.Enumerator <>s__3;

			private Character <character>5__4;

			private ZNetView <nview>5__5;

			private MonsterAI <ai>5__6;

			private List<Character>.Enumerator <>s__7;

			private Character <pet>5__8;

			private bool <teleported>5__9;

			private Exception <ex>5__10;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <MonitorRoutine>d__1(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<allCharacters>5__1 = null;
				<followingPets>5__2 = null;
				<>s__3 = default(List<Character>.Enumerator);
				<character>5__4 = null;
				<nview>5__5 = null;
				<ai>5__6 = null;
				<>s__7 = default(List<Character>.Enumerator);
				<pet>5__8 = null;
				<ex>5__10 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					break;
				case 1:
					<>1__state = -1;
					if ((Object)(object)Player.m_localPlayer == (Object)null)
					{
						BetterTamesPlugin.LogIfDebug("PlayerPetMonitor: Player.m_localPlayer == null, skipping this tick.", DebugFeature.TeleportFollow);
						break;
					}
					BetterTamesPlugin.LogIfDebug("PlayerPetMonitor: Starting scan for owned following pets.", DebugFeature.TeleportFollow);
					<allCharacters>5__1 = Character.GetAllCharacters();
					if (<allCharacters>5__1 == null || <allCharacters>5__1.Count == 0)
					{
						BetterTamesPlugin.LogIfDebug("PlayerPetMonitor: No characters found in the world. Skipping scan.", DebugFeature.TeleportFollow);
						break;
					}
					<followingPets>5__2 = new List<Character>();
					<>s__3 = <allCharacters>5__1.GetEnumerator();
					try
					{
						while (<>s__3.MoveNext())
						{
							<character>5__4 = <>s__3.Current;
							if ((Object)(object)<character>5__4 == (Object)null || !<character>5__4.IsTamed())
							{
								continue;
							}
							<nview>5__5 = ((Component)<character>5__4).GetComponent<ZNetView>();
							if (!((Object)(object)<nview>5__5 == (Object)null) && <nview>5__5.IsOwner())
							{
								<ai>5__6 = ((Component)<character>5__4).GetComponent<MonsterAI>();
								if ((Object)(object)<ai>5__6 != (Object)null && (Object)(object)<ai>5__6.GetFollowTarget() != (Object)null)
								{
									<followingPets>5__2.Add(<character>5__4);
								}
								<nview>5__5 = null;
								<ai>5__6 = null;
								<character>5__4 = null;
							}
						}
					}
					finally
					{
						((IDisposable)<>s__3).Dispose();
					}
					<>s__3 = default(List<Character>.Enumerator);
					BetterTamesPlugin.LogIfDebug($"PlayerPetMonitor: Found {<followingPets>5__2.Count} owned pets with follow targets.", DebugFeature.TeleportFollow);
					<>s__7 = <followingPets>5__2.GetEnumerator();
					try
					{
						while (<>s__7.MoveNext())
						{
							<pet>5__8 = <>s__7.Current;
							try
							{
								<teleported>5__9 = DistanceTeleportLogic.CheckDistanceAndTeleport(<pet>5__8);
								if (<teleported>5__9)
								{
									BetterTamesPlugin.LogIfDebug("PlayerPetMonitor: Teleport triggered for " + <pet>5__8.m_name + ".", DebugFeature.TeleportFollow);
								}
							}
							catch (Exception ex)
							{
								<ex>5__10 = ex;
								BetterTamesPlugin.LogIfDebug($"PlayerPetMonitor: Exception while checking/teleporting pet {<pet>5__8?.m_name}: {<ex>5__10}", DebugFeature.TeleportFollow);
							}
							<pet>5__8 = null;
						}
					}
					finally
					{
						((IDisposable)<>s__7).Dispose();
					}
					<>s__7 = default(List<Character>.Enumerator);
					<allCharacters>5__1 = null;
					<followingPets>5__2 = null;
					break;
				}
				<>2__current = (object)new WaitForSeconds(5f);
				<>1__state = 1;
				return true;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		private const float CheckInterval = 5f;

		[IteratorStateMachine(typeof(<MonitorRoutine>d__1))]
		public static IEnumerator MonitorRoutine()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <MonitorRoutine>d__1(0);
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 ServerSync
{
	[PublicAPI]
	public abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	public class SyncedConfigEntry<T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
			base..ctor();
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	public abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
		{
			Priority = priority;
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	public sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0)
			: base(configSync, identifier, typeof(T), priority)
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	public class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p)
							{
								string hostName = p.m_rpc.GetSocket().GetHostName();
								return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName }));
							}).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ZPlayFabSocket, ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
					((ZPlayFabSocket)this)..ctor();
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (!__instance.IsServer())
				{
					return;
				}
				BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket());
				AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket);
				object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
				ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
				if (val != null && (int)ZNet.m_onlineBackend > 0)
				{
					FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket");
					object? value = fieldInfo.GetValue(val);
					ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null);
					if (val2 != null)
					{
						typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId);
					}
					fieldInfo.SetValue(val, bufferingSocket);
				}
				if (__state == null)
				{
					__state = new Dictionary<Assembly, BufferingSocket>();
				}
				__state[Assembly.GetExecutingAssembly()] = bufferingSocket;
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZRpc rpc2 = rpc;
				ZNet __instance2 = __instance;
				Dictionary<Assembly, BufferingSocket> __state2 = __state;
				ZNetPeer peer;
				if (__instance2.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance2).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc2.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc2.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			ConfigEntry<T> configEntry2 = configEntry;
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry2);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry2.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			CustomSyncedValueBase customValue2 = customValue;
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue2);
			allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority));
			customValue2.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue2);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				ConfigFile val2 = null;
				bool saveOnConfigSet = false;
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					if (val2 == null)
					{
						val2 = configValue.Key.BaseConfig.ConfigFile;
						saveOnConfigSet = val2.SaveOnConfigSet;
						val2.SaveOnConfigSet = false;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				if (val2 != null)
				{
					val2.SaveOnConfigSet = saveOnConfigSet;
					val2.Save();
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			OwnConfigEntryBase config2 = config;
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			ConfigFile val = null;
			bool saveOnConfigSet = false;
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				if (val == null)
				{
					val = item.BaseConfig.ConfigFile;
					saveOnConfigSet = val.SaveOnConfigSet;
					val.SaveOnConfigSet = false;
				}
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			if (val != null)
			{
				val.SaveOnConfigSet = saveOnConfigSet;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZNetPeer peer2 = peer;
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer2.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer2.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer2.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout");
						peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer2);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list