Decompiled source of ControlCompanyModdedMonsters v1.0.1

BepInEx/plugins/ControlCompanyModdedMonsters/ControlCompanyModdedMonsters.dll

Decompiled 4 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ControlCompanyModdedMonsters.Adapters;
using ControlCompanyModdedMonsters.Core;
using ControlCompanyModdedMonsters.Patches;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Animations;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ControlCompanyModdedMonsters")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("ControlCompanyModdedMonsters")]
[assembly: AssemblyTitle("ControlCompanyModdedMonsters")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ControlCompanyModdedMonsters
{
	[BepInPlugin("ControlCompanyModdedMonsters", "ControlCompanyModdedMonsters", "1.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "ControlCompanyModdedMonsters";

		public const string PluginName = "ControlCompanyModdedMonsters";

		public const string PluginVersion = "1.0.1";

		public static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			PluginConfig.Bind(((BaseUnityPlugin)this).Config);
			if (!ControlCompanyBridge.Initialize())
			{
				Log.LogError((object)"ControlCompanyBridge initialization failed. Modded monster integration disabled.");
				return;
			}
			Harmony harmony = new Harmony("ControlCompanyModdedMonsters");
			ControlCompanyPatches.Apply(harmony);
			List<string> list = new List<string>();
			TryPatch("ImmortalSnail", () => SnailPatches.Apply(harmony), list);
			TryPatch("DontTouchMe", () => DontTouchMePatches.Apply(harmony), list);
			TryPatch("FacelessStalker (Slenderman)", () => SlendermanPatches.Apply(harmony), list);
			TryPatch("Herobrine", () => HerobrinePatches.Apply(harmony), list);
			Log.LogInfo((object)("ControlCompanyModdedMonsters v1.0.1 loaded. Bespoke adapters active: [" + string.Join(", ", list) + "]. Generic modded EnemyAI fallback: enabled."));
		}

		private static void TryPatch(string name, Func<bool> patchAction, List<string> activeAdapters)
		{
			try
			{
				if (patchAction())
				{
					activeAdapters.Add(name);
				}
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Failed to initialize adapter patches for {name}: {arg}");
			}
		}
	}
	public static class PluginConfig
	{
		public static ConfigEntry<bool> AutoAllowlistAllModdedEnemies { get; private set; }

		public static ConfigEntry<bool> AllowModdedEnemiesOutdoors { get; private set; }

		public static ConfigEntry<bool> EnsureAllModdedEnemiesOnEveryMoon { get; private set; }

		public static ConfigEntry<float> SnailWalkSpeed { get; private set; }

		public static ConfigEntry<float> SnailRunSpeed { get; private set; }

		public static ConfigEntry<bool> SnailKillAnyPlayerWhileControlled { get; private set; }

		public static ConfigEntry<float> DtmWalkSpeed { get; private set; }

		public static ConfigEntry<float> DtmRunSpeed { get; private set; }

		public static ConfigEntry<float> DtmSyncIntervalSeconds { get; private set; }

		public static ConfigEntry<float> SlenderWalkSpeed { get; private set; }

		public static ConfigEntry<float> SlenderRunSpeed { get; private set; }

		public static ConfigEntry<float> HerobrineWalkSpeed { get; private set; }

		public static ConfigEntry<float> HerobrineRunSpeed { get; private set; }

		public static ConfigEntry<bool> HerobrineVisibleToAllClientsWithAddon { get; private set; }

		public static void Bind(ConfigFile config)
		{
			AutoAllowlistAllModdedEnemies = config.Bind<bool>("General", "AutoAllowlistAllModdedEnemies", true, "Automatically allow all modded EnemyAI monsters in ControlCompany without requiring Extended Mode.");
			AllowModdedEnemiesOutdoors = config.Bind<bool>("General", "AllowModdedEnemiesOutdoors", true, "Include modded indoor enemies in the outdoor spawn list so you can spawn them outside too.");
			EnsureAllModdedEnemiesOnEveryMoon = config.Bind<bool>("General", "EnsureAllModdedEnemiesOnEveryMoon", true, "Ensure every loaded modded enemy (Immortal Snail, Don't Touch Me, Herobrine, Faceless Stalker, etc.) appears in ControlCompany on every moon.");
			SnailWalkSpeed = config.Bind<float>("ImmortalSnail", "WalkSpeed", 2.5f, "Walking speed when controlling the Immortal Snail.");
			SnailRunSpeed = config.Bind<float>("ImmortalSnail", "RunSpeed", 6.5f, "Sprinting speed when controlling the Immortal Snail.");
			SnailKillAnyPlayerWhileControlled = config.Bind<bool>("ImmortalSnail", "KillAnyPlayerWhileControlled", true, "Allow touching any living player (not only targetPlayer) to kill them while manually controlling the Immortal Snail.");
			DtmWalkSpeed = config.Bind<float>("DontTouchMe", "WalkSpeed", 4f, "Walking speed when controlling Don't Touch Me.");
			DtmRunSpeed = config.Bind<float>("DontTouchMe", "RunSpeed", 7.5f, "Sprinting speed when controlling Don't Touch Me.");
			DtmSyncIntervalSeconds = config.Bind<float>("DontTouchMe", "SyncIntervalSeconds", 0.15f, "How often (in seconds) position/disguise is synced to clients while moving Don't Touch Me.");
			SlenderWalkSpeed = config.Bind<float>("FacelessStalker", "WalkSpeed", 5f, "Walking speed when controlling the Faceless Stalker (Slenderman).");
			SlenderRunSpeed = config.Bind<float>("FacelessStalker", "RunSpeed", 12f, "Sprinting speed when controlling the Faceless Stalker (Slenderman) outside of Chase Mode.");
			HerobrineWalkSpeed = config.Bind<float>("Herobrine", "WalkSpeed", 5.3f, "Walking speed when controlling Herobrine.");
			HerobrineRunSpeed = config.Bind<float>("Herobrine", "RunSpeed", 8.5f, "Sprinting speed when controlling Herobrine.");
			HerobrineVisibleToAllClientsWithAddon = config.Bind<bool>("Herobrine", "VisibleToAllClientsWithAddon", true, "When friends also have this addon installed, keep host-controlled Herobrine visible and smoothly puppeted for all players.");
		}
	}
}
namespace ControlCompanyModdedMonsters.Patches
{
	public static class ControlCompanyPatches
	{
		public static void Apply(Harmony harmony)
		{
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyConfigurationType, "IsEnemyAllowlisted", new Type[1] { typeof(EnemyAI) }, (Type[])null), null, "IsEnemyAllowlistedPostfix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyConfigurationType, "GetEnemyAttributes", new Type[1] { typeof(EnemyAI) }, (Type[])null), null, "GetEnemyAttributesPostfix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyConfigurationType, "GetEnemyName", new Type[1] { typeof(EnemyAI) }, (Type[])null), null, "GetEnemyNamePostfix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.ControlCenterType, "StartOfRoundInitialization", (Type[])null, (Type[])null), null, "StartOfRoundInitializationPostfix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.ControlCenterType, "SpawnControllableEnemy", new Type[3]
			{
				ControlCompanyBridge.ControllableEnemyType,
				typeof(Vector3),
				typeof(Quaternion)
			}, (Type[])null), "SpawnControllableEnemyPrefix", null, "SpawnControllableEnemyFinalizer");
			PatchMethod(harmony, AccessTools.Method(typeof(EnemyAI), "ChangeOwnershipOfEnemy", new Type[1] { typeof(ulong) }, (Type[])null), "ChangeOwnershipOfEnemyPrefix");
			PatchMethod(harmony, AccessTools.Method(typeof(EnemyAI), "ChangeEnemyOwnerServerRpc", new Type[1] { typeof(ulong) }, (Type[])null), "ChangeEnemyOwnerServerRpcPrefix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyAIControllerType, "InitializeEnemyController", (Type[])null, (Type[])null), null, "InitializeEnemyControllerPostfix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyAIControllerType, "LateUpdate", (Type[])null, (Type[])null), null, "EnemyAILateUpdatePostfix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyAIControllerType, "Move", (Type[])null, (Type[])null), "EnemyAIMovePrefix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyAIControllerType, "CanControlEnemy", (Type[])null, (Type[])null), null, "CanControlEnemyPostfix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyAIControllerType, "ToggleAIControlTrue", (Type[])null, (Type[])null), null, "ToggleAIControlTruePostfix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyAIControllerType, "ToggleAIControlFalse", (Type[])null, (Type[])null), null, "ToggleAIControlFalsePostfix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyAIControllerType, "UseSecondarySkillAction", (Type[])null, (Type[])null), "UseSecondarySkillActionPrefix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyAIControllerType, "GetSecondarySkillName", (Type[])null, (Type[])null), "GetSecondarySkillNamePrefix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyControllerType, "UsePrimarySkillAction", (Type[])null, (Type[])null), "UsePrimarySkillActionPrefix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyControllerType, "ReleasePrimarySkillAction", (Type[])null, (Type[])null), "ReleasePrimarySkillActionPrefix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyControllerType, "ReleaseSecondarySkillAction", (Type[])null, (Type[])null), "ReleaseSecondarySkillActionPrefix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyControllerType, "GetPrimarySkillName", (Type[])null, (Type[])null), "GetPrimarySkillNamePrefix");
			PatchMethod(harmony, AccessTools.Method(ControlCompanyBridge.EnemyControllerType, "DestroyAndCleanUp", (Type[])null, (Type[])null), "DestroyAndCleanUpPrefix");
		}

		private static void PatchMethod(Harmony harmony, MethodBase target, string prefix = null, string postfix = null, string finalizer = null)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			if (target == null)
			{
				Plugin.Log.LogWarning((object)("Skipped patching missing target method (prefix=" + prefix + ", postfix=" + postfix + ")."));
			}
			else
			{
				harmony.Patch(target, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(ControlCompanyPatches), prefix, (Type[])null), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(ControlCompanyPatches), postfix, (Type[])null), (HarmonyMethod)null, (finalizer == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(ControlCompanyPatches), finalizer, (Type[])null), (HarmonyMethod)null);
			}
		}

		private static void IsEnemyAllowlistedPostfix(EnemyAI enemyAI, ref bool __result)
		{
			if (!__result && !((Object)(object)enemyAI == (Object)null))
			{
				Type type = ((object)enemyAI).GetType();
				if (AdapterFactory.HasCustomAdapter(type) || (PluginConfig.AutoAllowlistAllModdedEnemies.Value && AdapterFactory.IsModdedEnemyAI(type)))
				{
					__result = true;
				}
			}
		}

		private static void GetEnemyAttributesPostfix(EnemyAI enemyAI, ref object __result)
		{
			if (!((Object)(object)enemyAI == (Object)null) && AdapterFactory.TryBuildAttributes(((object)enemyAI).GetType(), out var attrs))
			{
				__result = attrs;
			}
		}

		private static void GetEnemyNamePostfix(EnemyAI enemyAI, ref string __result)
		{
			if (!((Object)(object)enemyAI == (Object)null) && AdapterFactory.TryGetDisplayName(((object)enemyAI).GetType(), out var name))
			{
				__result = name;
			}
		}

		private static void StartOfRoundInitializationPostfix(object __instance)
		{
			ControlledEnemyTracker.Clear();
			if (!PluginConfig.EnsureAllModdedEnemiesOnEveryMoon.Value || __instance == null)
			{
				return;
			}
			IList indoorEnemiesOfLevel = ControlCompanyBridge.GetIndoorEnemiesOfLevel(__instance);
			IList outdoorEnemiesOfLevel = ControlCompanyBridge.GetOutdoorEnemiesOfLevel(__instance);
			IList allIndoorEnemies = ControlCompanyBridge.GetAllIndoorEnemies(__instance);
			IList allOutdoorEnemies = ControlCompanyBridge.GetAllOutdoorEnemies(__instance);
			List<EnemyType> list = DiscoverLoadedModdedEnemyTypes();
			int num = 0;
			foreach (EnemyType item in list)
			{
				object obj = ControlCompanyBridge.CreateControllableEnemy(item);
				if (obj == null)
				{
					continue;
				}
				string name = ControlCompanyBridge.GetControllableEnemyName(obj) ?? item.enemyName;
				GameObject prefab = ControlCompanyBridge.GetControllableEnemyPrefab(obj) ?? item.enemyPrefab;
				if (item.isOutsideEnemy)
				{
					if (TryAddUniqueEnemy(outdoorEnemiesOfLevel, obj, name, prefab))
					{
						num++;
					}
					TryAddUniqueEnemy(allOutdoorEnemies, obj, name, prefab);
					TryAddUniqueEnemy(allIndoorEnemies, obj, name, prefab);
					continue;
				}
				if (TryAddUniqueEnemy(indoorEnemiesOfLevel, obj, name, prefab))
				{
					num++;
				}
				TryAddUniqueEnemy(allIndoorEnemies, obj, name, prefab);
				if (PluginConfig.AllowModdedEnemiesOutdoors.Value)
				{
					TryAddUniqueEnemy(outdoorEnemiesOfLevel, obj, name, prefab);
					TryAddUniqueEnemy(allOutdoorEnemies, obj, name, prefab);
				}
			}
			if (num > 0)
			{
				Plugin.Log.LogInfo((object)$"Registered {num} modded monster(s) into ControlCompany spawn lists.");
			}
		}

		private static List<EnemyType> DiscoverLoadedModdedEnemyTypes()
		{
			List<EnemyType> result = new List<EnemyType>();
			HashSet<GameObject> seenPrefabs = new HashSet<GameObject>();
			HashSet<GameObject> registeredNetworkPrefabs = CollectRegisteredNetworkPrefabs();
			if ((Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.levels != null)
			{
				SelectableLevel[] levels = StartOfRound.Instance.levels;
				foreach (SelectableLevel val in levels)
				{
					if ((Object)(object)val == (Object)null)
					{
						continue;
					}
					if (val.Enemies != null)
					{
						foreach (SpawnableEnemyWithRarity enemy in val.Enemies)
						{
							Consider(enemy?.enemyType);
						}
					}
					if (val.OutsideEnemies != null)
					{
						foreach (SpawnableEnemyWithRarity outsideEnemy in val.OutsideEnemies)
						{
							Consider(outsideEnemy?.enemyType);
						}
					}
					if (val.DaytimeEnemies == null)
					{
						continue;
					}
					foreach (SpawnableEnemyWithRarity daytimeEnemy in val.DaytimeEnemies)
					{
						Consider(daytimeEnemy?.enemyType);
					}
				}
			}
			EnemyType[] array = Resources.FindObjectsOfTypeAll<EnemyType>();
			for (int i = 0; i < array.Length; i++)
			{
				Consider(array[i]);
			}
			Consider(GetStaticEnemyType("DontTouchMe.Assets", "EnemyType", isProperty: false));
			Consider(GetStaticEnemyType("Kittenji.HerobrineMod.Plugin", "EnemyDef", isProperty: true));
			Consider(GetStaticEnemyType("SlendermanMod.Plugin", "SlendermanEnemy", isProperty: false));
			return result;
			void Consider(EnemyType et)
			{
				if (!((Object)(object)et == (Object)null) && !((Object)(object)et.enemyPrefab == (Object)null) && !seenPrefabs.Contains(et.enemyPrefab))
				{
					EnemyAI componentInChildren = et.enemyPrefab.GetComponentInChildren<EnemyAI>();
					if (!((Object)(object)componentInChildren == (Object)null) && AdapterFactory.IsModdedEnemyAI(((object)componentInChildren).GetType()) && !((Object)(object)et.enemyPrefab.GetComponent<NetworkObject>() == (Object)null) && (registeredNetworkPrefabs.Count <= 0 || registeredNetworkPrefabs.Contains(et.enemyPrefab)))
					{
						seenPrefabs.Add(et.enemyPrefab);
						result.Add(et);
					}
				}
			}
		}

		private static HashSet<GameObject> CollectRegisteredNetworkPrefabs()
		{
			HashSet<GameObject> hashSet = new HashSet<GameObject>();
			NetworkManager singleton = NetworkManager.Singleton;
			object obj;
			if (singleton == null)
			{
				obj = null;
			}
			else
			{
				NetworkConfig networkConfig = singleton.NetworkConfig;
				if (networkConfig == null)
				{
					obj = null;
				}
				else
				{
					NetworkPrefabs prefabs = networkConfig.Prefabs;
					obj = ((prefabs != null) ? prefabs.Prefabs : null);
				}
			}
			IReadOnlyList<NetworkPrefab> readOnlyList = (IReadOnlyList<NetworkPrefab>)obj;
			if (readOnlyList == null)
			{
				return hashSet;
			}
			foreach (NetworkPrefab item in readOnlyList)
			{
				if ((Object)(object)item?.Prefab != (Object)null)
				{
					hashSet.Add(item.Prefab);
				}
			}
			return hashSet;
		}

		private static EnemyType GetStaticEnemyType(string typeName, string memberName, bool isProperty)
		{
			try
			{
				Type type = AccessTools.TypeByName(typeName);
				if (type == null)
				{
					return null;
				}
				return (EnemyType)(isProperty ? /*isinst with value type is only supported in some contexts*/: /*isinst with value type is only supported in some contexts*/);
			}
			catch
			{
				return null;
			}
		}

		private static bool TryAddUniqueEnemy(IList list, object controllableEnemy, string name, GameObject prefab)
		{
			if (list == null || controllableEnemy == null)
			{
				return false;
			}
			foreach (object item in list)
			{
				if (item != null)
				{
					GameObject controllableEnemyPrefab = ControlCompanyBridge.GetControllableEnemyPrefab(item);
					if ((Object)(object)prefab != (Object)null && (Object)(object)controllableEnemyPrefab == (Object)(object)prefab)
					{
						return false;
					}
					string controllableEnemyName = ControlCompanyBridge.GetControllableEnemyName(item);
					if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(controllableEnemyName) && string.Equals(controllableEnemyName, name, StringComparison.OrdinalIgnoreCase))
					{
						return false;
					}
				}
			}
			list.Add(controllableEnemy);
			return true;
		}

		private static void SpawnControllableEnemyPrefix(Vector3 position, Quaternion rotation)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			ControlledEnemyTracker.IsSpawningFromControlCompany = true;
			ControlledEnemyTracker.LastRequestedSpawnPosition = position;
			ControlledEnemyTracker.LastRequestedSpawnRotation = rotation;
		}

		private static void SpawnControllableEnemyFinalizer()
		{
			ControlledEnemyTracker.IsSpawningFromControlCompany = false;
		}

		[HarmonyPriority(600)]
		private static bool ChangeOwnershipOfEnemyPrefix(EnemyAI __instance, ulong newOwnerClientId)
		{
			return ShouldAllowOwnershipChange(__instance, newOwnerClientId);
		}

		[HarmonyPriority(600)]
		private static bool ChangeEnemyOwnerServerRpcPrefix(EnemyAI __instance, ulong clientId)
		{
			return ShouldAllowOwnershipChange(__instance, clientId);
		}

		private static bool ShouldAllowOwnershipChange(EnemyAI instance, ulong newOwnerClientId)
		{
			if ((Object)(object)instance == (Object)null)
			{
				return true;
			}
			if (!ControlledEnemyTracker.TryGet(instance, out var adapter))
			{
				return true;
			}
			if (adapter.IsAIControlled || adapter.AllowOwnershipTransfer)
			{
				return true;
			}
			PlayerControllerB hostPlayer = ControlCompanyBridge.GetHostPlayer();
			if ((Object)(object)hostPlayer == (Object)null)
			{
				return true;
			}
			if (newOwnerClientId == hostPlayer.actualClientId)
			{
				return true;
			}
			return false;
		}

		private static void InitializeEnemyControllerPostfix(object __instance, GameObject enemyGameObject)
		{
			EnemyAI enemyAI = ControlCompanyBridge.GetEnemyAI(__instance);
			if (!((Object)(object)enemyAI == (Object)null))
			{
				AdapterFactory.CreateAdapter(enemyAI, __instance, enemyGameObject)?.OnInitialized();
			}
		}

		private static bool TryGetAdapter(object controller, out ModdedEnemyAdapter adapter)
		{
			Component val = (Component)((controller is Component) ? controller : null);
			if (val != null && val.TryGetComponent<ModdedEnemyAdapter>(ref adapter))
			{
				return true;
			}
			adapter = null;
			return false;
		}

		private static void EnemyAILateUpdatePostfix(object __instance)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				adapter.OnLateUpdate();
			}
		}

		private static bool EnemyAIMovePrefix(object __instance)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				return adapter.CanMove();
			}
			return true;
		}

		private static void CanControlEnemyPostfix(object __instance, ref bool __result)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				__result = adapter.CanControlEnemy(__result);
			}
		}

		private static void ToggleAIControlTruePostfix(object __instance)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				adapter.OnEnableAI();
			}
		}

		private static void ToggleAIControlFalsePostfix(object __instance)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				adapter.OnDisableAI();
			}
		}

		private static bool UsePrimarySkillActionPrefix(object __instance)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				adapter.OnPrimaryDown();
				return false;
			}
			return true;
		}

		private static bool ReleasePrimarySkillActionPrefix(object __instance)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				adapter.OnPrimaryUp();
				return false;
			}
			return true;
		}

		private static bool UseSecondarySkillActionPrefix(object __instance)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				adapter.OnSecondaryDown();
				return false;
			}
			return true;
		}

		private static bool ReleaseSecondarySkillActionPrefix(object __instance)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				adapter.OnSecondaryUp();
				return false;
			}
			return true;
		}

		private static bool GetPrimarySkillNamePrefix(object __instance, ref string __result)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				__result = adapter.GetPrimarySkillName();
				return false;
			}
			return true;
		}

		private static bool GetSecondarySkillNamePrefix(object __instance, ref string __result)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				__result = adapter.GetSecondarySkillName();
				return false;
			}
			return true;
		}

		private static void DestroyAndCleanUpPrefix(object __instance)
		{
			if (TryGetAdapter(__instance, out var adapter))
			{
				adapter.OnCleanUp();
			}
		}
	}
}
namespace ControlCompanyModdedMonsters.Core
{
	public static class ControlCompanyBridge
	{
		private static FieldInfo _ccInstanceField;

		private static FieldInfo _ccCurrentControlledEnemyField;

		private static FieldInfo _ccCurrentModeField;

		private static FieldInfo _ccIndoorEnemiesOfLevelField;

		private static FieldInfo _ccOutdoorEnemiesOfLevelField;

		private static FieldInfo _ccAllIndoorEnemiesField;

		private static FieldInfo _ccAllOutdoorEnemiesField;

		private static FieldInfo _ccIsGhostIndoorsField;

		private static MethodInfo _ccGetHostPlayerMethod;

		private static PropertyInfo _attrWalkSpeedProp;

		private static PropertyInfo _attrRunSpeedProp;

		private static PropertyInfo _attrPlayerControlsRotationProp;

		private static PropertyInfo _attrCamHeightProp;

		private static PropertyInfo _attrCamDistanceProp;

		private static PropertyInfo _attrEnemyNameProp;

		private static PropertyInfo _attrEnemyPositionOffsetProp;

		private static PropertyInfo _attrUseLerpRotationProp;

		private static MethodInfo _ceFromSpawnableEnemyMethod;

		private static PropertyInfo _ceEnemyNameProp;

		private static PropertyInfo _ceEnemyPrefabProp;

		private static PropertyInfo _ceAllowlistedProp;

		private static FieldInfo _ecEnemyGameObjectField;

		private static FieldInfo _ecIsAIControlledField;

		private static FieldInfo _ecControlEnemyRotationField;

		private static FieldInfo _ecControlEnemyMovementField;

		private static FieldInfo _eaicEnemyAIField;

		private static FieldInfo _eaicEnemyAIAgentField;

		private static FieldInfo _eaicOriginalAngularSpeedField;

		private static FieldInfo _eaicOriginalSpeedField;

		private static FieldInfo _cpcCharacterControllerField;

		private static PropertyInfo _cpcWalkSpeedProp;

		private static PropertyInfo _cpcRunSpeedProp;

		public static bool IsInitialized { get; private set; }

		public static Type ControlCenterType { get; private set; }

		public static Type EnemyConfigurationType { get; private set; }

		public static Type EnemyAttributesType { get; private set; }

		public static Type ControllableEnemyType { get; private set; }

		public static Type EnemyControllerType { get; private set; }

		public static Type EnemyAIControllerType { get; private set; }

		public static Type CustomPlayerControllerType { get; private set; }

		public static Type EnemyAIPatchType { get; private set; }

		public static bool Initialize()
		{
			if (IsInitialized)
			{
				return true;
			}
			ControlCenterType = AccessTools.TypeByName("ControlCompany.Core.ControlCenter");
			EnemyConfigurationType = AccessTools.TypeByName("ControlCompany.Core.Config.EnemyConfiguration");
			EnemyAttributesType = AccessTools.TypeByName("ControlCompany.Core.Config.EnemyAttributes");
			ControllableEnemyType = AccessTools.TypeByName("ControlCompany.Core.Enemy.ControllableEnemy");
			EnemyControllerType = AccessTools.TypeByName("ControlCompany.Core.EnemyController");
			EnemyAIControllerType = AccessTools.TypeByName("ControlCompany.Core.EnemyAIController");
			CustomPlayerControllerType = AccessTools.TypeByName("ControlCompany.Core.CustomPlayerController");
			EnemyAIPatchType = AccessTools.TypeByName("ControlCompany.Patches.EnemyAIPatch");
			if (ControlCenterType == null || EnemyConfigurationType == null || EnemyAttributesType == null || ControllableEnemyType == null || EnemyControllerType == null || EnemyAIControllerType == null || CustomPlayerControllerType == null)
			{
				Plugin.Log.LogError((object)"Failed to locate one or more ControlCompany core types.");
				return false;
			}
			_ccInstanceField = AccessTools.Field(ControlCenterType, "Instance");
			_ccCurrentControlledEnemyField = AccessTools.Field(ControlCenterType, "currentControlledEnemy");
			_ccCurrentModeField = AccessTools.Field(ControlCenterType, "currentMode");
			_ccIndoorEnemiesOfLevelField = AccessTools.Field(ControlCenterType, "indoorEnemiesOfLevel");
			_ccOutdoorEnemiesOfLevelField = AccessTools.Field(ControlCenterType, "outdoorEnemiesOfLevel");
			_ccAllIndoorEnemiesField = AccessTools.Field(ControlCenterType, "allIndoorEnemies");
			_ccAllOutdoorEnemiesField = AccessTools.Field(ControlCenterType, "allOutdoorEnemies");
			_ccIsGhostIndoorsField = AccessTools.Field(ControlCenterType, "isGhostIndoors");
			_ccGetHostPlayerMethod = AccessTools.Method(ControlCenterType, "GetHostPlayer", (Type[])null, (Type[])null);
			_attrWalkSpeedProp = AccessTools.Property(EnemyAttributesType, "WalkSpeed");
			_attrRunSpeedProp = AccessTools.Property(EnemyAttributesType, "RunSpeed");
			_attrPlayerControlsRotationProp = AccessTools.Property(EnemyAttributesType, "PlayerControlsRotation");
			_attrCamHeightProp = AccessTools.Property(EnemyAttributesType, "CamHeight");
			_attrCamDistanceProp = AccessTools.Property(EnemyAttributesType, "CamDistance");
			_attrEnemyNameProp = AccessTools.Property(EnemyAttributesType, "EnemyName");
			_attrEnemyPositionOffsetProp = AccessTools.Property(EnemyAttributesType, "EnemyPositionOffset");
			_attrUseLerpRotationProp = AccessTools.Property(EnemyAttributesType, "UseLerpRotation");
			_ceFromSpawnableEnemyMethod = AccessTools.Method(ControllableEnemyType, "FromSpawnableEnemy", new Type[1] { typeof(SpawnableEnemyWithRarity) }, (Type[])null);
			_ceEnemyNameProp = AccessTools.Property(ControllableEnemyType, "EnemyName");
			_ceEnemyPrefabProp = AccessTools.Property(ControllableEnemyType, "EnemyPrefab");
			_ceAllowlistedProp = AccessTools.Property(ControllableEnemyType, "Allowlisted");
			_ecEnemyGameObjectField = AccessTools.Field(EnemyControllerType, "enemyGameObject");
			_ecIsAIControlledField = AccessTools.Field(EnemyControllerType, "isAIControlled");
			_ecControlEnemyRotationField = AccessTools.Field(EnemyControllerType, "controlEnemyRotation");
			_ecControlEnemyMovementField = AccessTools.Field(EnemyControllerType, "controlEnemyMovement");
			_eaicEnemyAIField = AccessTools.Field(EnemyAIControllerType, "enemyAI");
			_eaicEnemyAIAgentField = AccessTools.Field(EnemyAIControllerType, "enemyAIAgent");
			_eaicOriginalAngularSpeedField = AccessTools.Field(EnemyAIControllerType, "originalAgentAngularSpeed");
			_eaicOriginalSpeedField = AccessTools.Field(EnemyAIControllerType, "originalAgentSpeed");
			_cpcCharacterControllerField = AccessTools.Field(CustomPlayerControllerType, "characterController");
			_cpcWalkSpeedProp = AccessTools.Property(CustomPlayerControllerType, "WalkSpeed");
			_cpcRunSpeedProp = AccessTools.Property(CustomPlayerControllerType, "RunSpeed");
			IsInitialized = _ccInstanceField != null && _attrWalkSpeedProp != null && _ceFromSpawnableEnemyMethod != null && _ecIsAIControlledField != null && _eaicEnemyAIField != null && _cpcCharacterControllerField != null;
			return IsInitialized;
		}

		public static object GetControlCenterInstance()
		{
			return _ccInstanceField?.GetValue(null);
		}

		public static object GetCurrentControlledEnemy()
		{
			object controlCenterInstance = GetControlCenterInstance();
			if (controlCenterInstance == null)
			{
				return null;
			}
			return _ccCurrentControlledEnemyField?.GetValue(controlCenterInstance);
		}

		public static int GetCurrentMode()
		{
			object controlCenterInstance = GetControlCenterInstance();
			if (controlCenterInstance == null || _ccCurrentModeField == null)
			{
				return 0;
			}
			return Convert.ToInt32(_ccCurrentModeField.GetValue(controlCenterInstance));
		}

		public static bool IsGhostIndoors()
		{
			object controlCenterInstance = GetControlCenterInstance();
			if (controlCenterInstance != null && _ccIsGhostIndoorsField != null)
			{
				return (bool)_ccIsGhostIndoorsField.GetValue(controlCenterInstance);
			}
			return false;
		}

		public static PlayerControllerB GetHostPlayer()
		{
			object controlCenterInstance = GetControlCenterInstance();
			if (controlCenterInstance == null)
			{
				return null;
			}
			object? obj = _ccGetHostPlayerMethod?.Invoke(controlCenterInstance, null);
			return (PlayerControllerB)((obj is PlayerControllerB) ? obj : null);
		}

		public static IList GetIndoorEnemiesOfLevel(object cc)
		{
			return _ccIndoorEnemiesOfLevelField?.GetValue(cc) as IList;
		}

		public static IList GetOutdoorEnemiesOfLevel(object cc)
		{
			return _ccOutdoorEnemiesOfLevelField?.GetValue(cc) as IList;
		}

		public static IList GetAllIndoorEnemies(object cc)
		{
			return _ccAllIndoorEnemiesField?.GetValue(cc) as IList;
		}

		public static IList GetAllOutdoorEnemies(object cc)
		{
			return _ccAllOutdoorEnemiesField?.GetValue(cc) as IList;
		}

		public static object CreateControllableEnemy(EnemyType enemyType)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			if ((Object)(object)enemyType == (Object)null || _ceFromSpawnableEnemyMethod == null)
			{
				return null;
			}
			SpawnableEnemyWithRarity val = new SpawnableEnemyWithRarity(enemyType, 1);
			object obj = _ceFromSpawnableEnemyMethod.Invoke(null, new object[1] { val });
			if (obj != null && _ceAllowlistedProp != null)
			{
				_ceAllowlistedProp.SetValue(obj, true);
			}
			return obj;
		}

		public static string GetControllableEnemyName(object ce)
		{
			return _ceEnemyNameProp?.GetValue(ce) as string;
		}

		public static GameObject GetControllableEnemyPrefab(object ce)
		{
			object? obj = _ceEnemyPrefabProp?.GetValue(ce);
			return (GameObject)((obj is GameObject) ? obj : null);
		}

		public static object CreateEnemyAttributes(string enemyName, float walkSpeed, float runSpeed, float camDistance = -3.5f, float camHeight = 2f, bool playerControlsRotation = true, bool useLerpRotation = true, Vector3? positionOffset = null)
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			object obj = Activator.CreateInstance(EnemyAttributesType);
			_attrEnemyNameProp?.SetValue(obj, enemyName);
			_attrWalkSpeedProp?.SetValue(obj, walkSpeed);
			_attrRunSpeedProp?.SetValue(obj, runSpeed);
			_attrCamDistanceProp?.SetValue(obj, camDistance);
			_attrCamHeightProp?.SetValue(obj, camHeight);
			_attrPlayerControlsRotationProp?.SetValue(obj, playerControlsRotation);
			_attrUseLerpRotationProp?.SetValue(obj, useLerpRotation);
			if (positionOffset.HasValue)
			{
				_attrEnemyPositionOffsetProp?.SetValue(obj, positionOffset.Value);
			}
			return obj;
		}

		public static EnemyAI GetEnemyAI(object controller)
		{
			if (controller == null || !EnemyAIControllerType.IsInstanceOfType(controller))
			{
				return null;
			}
			object? obj = _eaicEnemyAIField?.GetValue(controller);
			return (EnemyAI)((obj is EnemyAI) ? obj : null);
		}

		public static NavMeshAgent GetEnemyAIAgent(object controller)
		{
			if (controller == null || !EnemyAIControllerType.IsInstanceOfType(controller))
			{
				return null;
			}
			object? obj = _eaicEnemyAIAgentField?.GetValue(controller);
			return (NavMeshAgent)((obj is NavMeshAgent) ? obj : null);
		}

		public static float GetOriginalAgentSpeed(object controller)
		{
			if (controller == null || !(_eaicOriginalSpeedField != null))
			{
				return 5f;
			}
			return (float)_eaicOriginalSpeedField.GetValue(controller);
		}

		public static float GetOriginalAgentAngularSpeed(object controller)
		{
			if (controller == null || !(_eaicOriginalAngularSpeedField != null))
			{
				return 120f;
			}
			return (float)_eaicOriginalAngularSpeedField.GetValue(controller);
		}

		public static GameObject GetEnemyGameObject(object controller)
		{
			if (controller == null)
			{
				return null;
			}
			object? obj = _ecEnemyGameObjectField?.GetValue(controller);
			return (GameObject)((obj is GameObject) ? obj : null);
		}

		public static bool IsAIControlled(object controller)
		{
			if (controller != null && _ecIsAIControlledField != null)
			{
				return (bool)_ecIsAIControlledField.GetValue(controller);
			}
			return false;
		}

		public static void SetControlRotation(object controller, bool value)
		{
			_ecControlEnemyRotationField?.SetValue(controller, value);
		}

		public static void SetControlMovement(object controller, bool value)
		{
			_ecControlEnemyMovementField?.SetValue(controller, value);
		}

		public static void SetWalkRunSpeed(object controller, float walkSpeed, float runSpeed)
		{
			if (controller != null)
			{
				_cpcWalkSpeedProp?.SetValue(controller, walkSpeed);
				_cpcRunSpeedProp?.SetValue(controller, runSpeed);
			}
		}

		public static Vector3 GetControllerVelocity(object controller)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			CharacterController val = (CharacterController)((controller != null) ? /*isinst with value type is only supported in some contexts*/: null);
			if (!((Object)(object)val != (Object)null))
			{
				return Vector3.zero;
			}
			return val.velocity;
		}
	}
	public static class ControlledEnemyTracker
	{
		private static readonly Dictionary<int, ModdedEnemyAdapter> AdaptersByEnemyId = new Dictionary<int, ModdedEnemyAdapter>();

		private static readonly HashSet<int> StartedDuringSpawnIds = new HashSet<int>();

		public static bool IsSpawningFromControlCompany { get; set; }

		public static Vector3 LastRequestedSpawnPosition { get; set; }

		public static Quaternion LastRequestedSpawnRotation { get; set; }

		public static void Register(EnemyAI enemyAI, ModdedEnemyAdapter adapter)
		{
			if (!((Object)(object)enemyAI == (Object)null) && !((Object)(object)adapter == (Object)null))
			{
				AdaptersByEnemyId[((Object)enemyAI).GetInstanceID()] = adapter;
			}
		}

		public static void Unregister(EnemyAI enemyAI)
		{
			if (!((Object)(object)enemyAI == (Object)null))
			{
				int instanceID = ((Object)enemyAI).GetInstanceID();
				AdaptersByEnemyId.Remove(instanceID);
				StartedDuringSpawnIds.Remove(instanceID);
			}
		}

		public static void MarkStartedDuringSpawn(EnemyAI enemyAI)
		{
			if (!((Object)(object)enemyAI == (Object)null))
			{
				StartedDuringSpawnIds.Add(((Object)enemyAI).GetInstanceID());
			}
		}

		public static bool ConsumeStartedDuringSpawn(EnemyAI enemyAI)
		{
			if ((Object)(object)enemyAI == (Object)null)
			{
				return false;
			}
			return StartedDuringSpawnIds.Remove(((Object)enemyAI).GetInstanceID());
		}

		public static bool TryGet(EnemyAI enemyAI, out ModdedEnemyAdapter adapter)
		{
			if ((Object)(object)enemyAI == (Object)null)
			{
				adapter = null;
				return false;
			}
			if (AdaptersByEnemyId.TryGetValue(((Object)enemyAI).GetInstanceID(), out adapter))
			{
				return (Object)(object)adapter != (Object)null;
			}
			return false;
		}

		public static bool IsPlayerControlled(EnemyAI enemyAI)
		{
			if (TryGet(enemyAI, out var adapter))
			{
				return !adapter.IsAIControlled;
			}
			return false;
		}

		public static bool IsControlledOrSpawning(EnemyAI enemyAI)
		{
			if (!IsSpawningFromControlCompany)
			{
				return IsPlayerControlled(enemyAI);
			}
			return true;
		}

		public static void Clear()
		{
			AdaptersByEnemyId.Clear();
			StartedDuringSpawnIds.Clear();
			IsSpawningFromControlCompany = false;
		}
	}
	public static class EnemySyncHelper
	{
		private static readonly FieldInfo PreviousYRotationField = AccessTools.Field(typeof(EnemyAI), "previousYRotation");

		private static readonly FieldInfo TargetYRotationField = AccessTools.Field(typeof(EnemyAI), "targetYRotation");

		private static readonly MethodInfo UpdateEnemyRotationClientRpcMethod = AccessTools.Method(typeof(EnemyAI), "UpdateEnemyRotationClientRpc", new Type[1] { typeof(short) }, (Type[])null);

		public static void TickHostSync(EnemyAI enemyAI, ref float posSyncTimer, float posSyncInterval = 0.08f)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)enemyAI == (Object)null || !((NetworkBehaviour)enemyAI).IsOwner)
			{
				return;
			}
			enemyAI.ventAnimationFinished = true;
			posSyncTimer += Time.deltaTime;
			if (posSyncTimer >= posSyncInterval)
			{
				posSyncTimer = 0f;
				enemyAI.SyncPositionToClients();
			}
			if (!(PreviousYRotationField == null) && !(UpdateEnemyRotationClientRpcMethod == null))
			{
				float num = (float)PreviousYRotationField.GetValue(enemyAI);
				float y = ((Component)enemyAI).transform.eulerAngles.y;
				if (Mathf.Abs(num - y) > 6f)
				{
					PreviousYRotationField.SetValue(enemyAI, y);
					TargetYRotationField?.SetValue(enemyAI, y);
					UpdateEnemyRotationClientRpcMethod.Invoke(enemyAI, new object[1] { (short)Mathf.RoundToInt(y) });
				}
			}
		}

		public static void ForceSyncTransform(EnemyAI enemyAI)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)enemyAI == (Object)null) && ((NetworkBehaviour)enemyAI).IsOwner)
			{
				enemyAI.serverPosition = ((Component)enemyAI).transform.position;
				enemyAI.SyncPositionToClients();
				if (PreviousYRotationField != null && UpdateEnemyRotationClientRpcMethod != null)
				{
					float y = ((Component)enemyAI).transform.eulerAngles.y;
					PreviousYRotationField.SetValue(enemyAI, y);
					TargetYRotationField?.SetValue(enemyAI, y);
					UpdateEnemyRotationClientRpcMethod.Invoke(enemyAI, new object[1] { (short)Mathf.RoundToInt(y) });
				}
			}
		}

		public static PlayerControllerB FindNearestLivingPlayer(Vector3 origin, float maxRange, bool excludeHost = true)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || instance.allPlayerScripts == null)
			{
				return null;
			}
			PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
			PlayerControllerB result = null;
			float num = maxRange * maxRange;
			PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
			foreach (PlayerControllerB val2 in allPlayerScripts)
			{
				if (!((Object)(object)val2 == (Object)null) && val2.isPlayerControlled && !val2.isPlayerDead && (!excludeHost || !((Object)(object)val != (Object)null) || !((Object)(object)val2 == (Object)(object)val)))
				{
					Vector3 val3 = ((Component)val2).transform.position - origin;
					float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
					if (sqrMagnitude <= num)
					{
						num = sqrMagnitude;
						result = val2;
					}
				}
			}
			return result;
		}

		public static PlayerControllerB FindAnyLivingTargetPlayer(bool preferNonHost = true)
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || instance.allPlayerScripts == null)
			{
				return null;
			}
			PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
			PlayerControllerB result = null;
			PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
			foreach (PlayerControllerB val2 in allPlayerScripts)
			{
				if (!((Object)(object)val2 == (Object)null) && val2.isPlayerControlled && !val2.isPlayerDead)
				{
					if (!preferNonHost || !((Object)(object)val != (Object)null) || !((Object)(object)val2 == (Object)(object)val))
					{
						return val2;
					}
					result = val2;
				}
			}
			return result;
		}

		public static void KillPlayerHostSafe(PlayerControllerB target, Vector3 hitDirection)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)target == (Object)null) && !target.isPlayerDead)
			{
				PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
				if ((Object)(object)val != (Object)null && (Object)(object)target == (Object)(object)val)
				{
					target.KillPlayer(hitDirection, true, (CauseOfDeath)0, 0, default(Vector3), false);
				}
				else
				{
					target.DamagePlayerFromOtherClientServerRpc(999, hitDirection, -1);
				}
			}
		}

		public static void FreezeAgent(NavMeshAgent agent)
		{
			if (!((Object)(object)agent == (Object)null))
			{
				agent.speed = 0f;
				agent.angularSpeed = 0f;
				if (((Behaviour)agent).enabled && agent.isOnNavMesh)
				{
					agent.isStopped = true;
				}
				agent.updatePosition = false;
			}
		}

		public static void RestoreAgent(NavMeshAgent agent, Vector3 position, float speed, float angularSpeed)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)agent == (Object)null))
			{
				((Behaviour)agent).enabled = true;
				agent.updatePosition = true;
				agent.speed = speed;
				agent.angularSpeed = angularSpeed;
				if (agent.isOnNavMesh)
				{
					agent.Warp(position);
					agent.isStopped = false;
				}
			}
		}
	}
}
namespace ControlCompanyModdedMonsters.Adapters
{
	public static class AdapterFactory
	{
		private delegate ModdedEnemyAdapter AdapterCreator(GameObject controllerGo);

		private static readonly Dictionary<string, AdapterCreator> CreatorsByTypeName = new Dictionary<string, AdapterCreator>(StringComparer.Ordinal)
		{
			["ImmortalSnail.SnailAI"] = (GameObject go) => go.AddComponent<SnailAdapter>(),
			["DontTouchMe.DTMEntityAI"] = (GameObject go) => go.AddComponent<DontTouchMeAdapter>(),
			["SlendermanMod.SlendermanEnemyAI"] = (GameObject go) => go.AddComponent<SlendermanAdapter>(),
			["Kittenji.HerobrineMod.HerobrineAI"] = (GameObject go) => go.AddComponent<HerobrineAdapter>()
		};

		private static readonly Dictionary<string, Func<object>> AttributeBuildersByTypeName = new Dictionary<string, Func<object>>(StringComparer.Ordinal)
		{
			["ImmortalSnail.SnailAI"] = SnailAdapter.BuildAttributes,
			["DontTouchMe.DTMEntityAI"] = DontTouchMeAdapter.BuildAttributes,
			["SlendermanMod.SlendermanEnemyAI"] = SlendermanAdapter.BuildAttributes,
			["Kittenji.HerobrineMod.HerobrineAI"] = HerobrineAdapter.BuildAttributes
		};

		private static readonly Dictionary<string, string> DisplayNamesByTypeName = new Dictionary<string, string>(StringComparer.Ordinal)
		{
			["ImmortalSnail.SnailAI"] = "Immortal Snail",
			["DontTouchMe.DTMEntityAI"] = "Don't Touch Me",
			["SlendermanMod.SlendermanEnemyAI"] = "Faceless Stalker",
			["Kittenji.HerobrineMod.HerobrineAI"] = "Herobrine"
		};

		public static bool IsModdedEnemyAI(Type enemyType)
		{
			if (enemyType != null)
			{
				return enemyType.Assembly != typeof(EnemyAI).Assembly;
			}
			return false;
		}

		public static bool HasCustomAdapter(Type enemyType)
		{
			if (enemyType != null)
			{
				return CreatorsByTypeName.ContainsKey(enemyType.FullName ?? string.Empty);
			}
			return false;
		}

		public static bool TryGetDisplayName(Type enemyType, out string name)
		{
			if (enemyType != null && DisplayNamesByTypeName.TryGetValue(enemyType.FullName ?? string.Empty, out name))
			{
				return true;
			}
			name = null;
			return false;
		}

		public static bool TryBuildAttributes(Type enemyType, out object attrs)
		{
			if (enemyType != null && AttributeBuildersByTypeName.TryGetValue(enemyType.FullName ?? string.Empty, out var value))
			{
				attrs = value();
				return true;
			}
			attrs = null;
			return false;
		}

		public static ModdedEnemyAdapter CreateAdapter(EnemyAI enemyAI, object controller, GameObject enemyGameObject)
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: 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_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)enemyAI == (Object)null || controller == null)
			{
				return null;
			}
			Component val = (Component)((controller is Component) ? controller : null);
			if (val == null)
			{
				return null;
			}
			Type type = ((object)enemyAI).GetType();
			string key = type.FullName ?? string.Empty;
			ModdedEnemyAdapter moddedEnemyAdapter = null;
			if (CreatorsByTypeName.TryGetValue(key, out var value))
			{
				moddedEnemyAdapter = value(val.gameObject);
			}
			else if (IsModdedEnemyAI(type))
			{
				moddedEnemyAdapter = val.gameObject.AddComponent<GenericModdedEnemyAdapter>();
			}
			if ((Object)(object)moddedEnemyAdapter == (Object)null)
			{
				return null;
			}
			Vector3 spawnPosition = (ControlledEnemyTracker.IsSpawningFromControlCompany ? ControlledEnemyTracker.LastRequestedSpawnPosition : (((Object)(object)enemyGameObject != (Object)null) ? enemyGameObject.transform.position : ((Component)enemyAI).transform.position));
			Quaternion spawnRotation = (ControlledEnemyTracker.IsSpawningFromControlCompany ? ControlledEnemyTracker.LastRequestedSpawnRotation : (((Object)(object)enemyGameObject != (Object)null) ? enemyGameObject.transform.rotation : ((Component)enemyAI).transform.rotation));
			moddedEnemyAdapter.Bind(enemyAI, controller, enemyGameObject, spawnPosition, spawnRotation);
			return moddedEnemyAdapter;
		}
	}
	public class DontTouchMeAdapter : ModdedEnemyAdapter
	{
		private bool _sentInitialSpawnSync;

		private bool _wasAttacking;

		private int _currentDisguiseId = -1;

		private float _syncTimer;

		private Vector3 _lastSyncedPos;

		private float _lastSyncedYRot;

		public static object BuildAttributes()
		{
			return ControlCompanyBridge.CreateEnemyAttributes("Don't Touch Me", PluginConfig.DtmWalkSpeed.Value, PluginConfig.DtmRunSpeed.Value, -3f, 1.6f, playerControlsRotation: true, useLerpRotation: false);
		}

		public override void OnInitialized()
		{
			//IL_0020: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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_0046: Unknown result type (might be due to invalid IL or missing references)
			base.OnInitialized();
			if ((Object)(object)base.EnemyAI != (Object)null)
			{
				((Component)base.EnemyAI).transform.SetPositionAndRotation(base.SpawnPosition, base.SpawnRotation);
				_lastSyncedPos = base.SpawnPosition;
				Quaternion spawnRotation = base.SpawnRotation;
				_lastSyncedYRot = ((Quaternion)(ref spawnRotation)).eulerAngles.y;
				_currentDisguiseId = -1;
			}
		}

		public override bool CanMove()
		{
			if (!((Object)(object)base.EnemyAI == (Object)null))
			{
				return !DontTouchMeReflection.GetIsAttacking(base.EnemyAI);
			}
			return true;
		}

		public override void OnLateUpdate()
		{
			//IL_0056: 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_0068: 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_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			base.OnLateUpdate();
			if ((Object)(object)base.EnemyAI == (Object)null || base.EnemyAI.isEnemyDead)
			{
				return;
			}
			bool isAttacking = DontTouchMeReflection.GetIsAttacking(base.EnemyAI);
			if (!_sentInitialSpawnSync && ((NetworkBehaviour)base.EnemyAI).IsOwner)
			{
				_sentInitialSpawnSync = true;
				((Component)base.EnemyAI).transform.SetPositionAndRotation(base.SpawnPosition, base.SpawnRotation);
				Vector3 spawnPosition = base.SpawnPosition;
				Quaternion spawnRotation = base.SpawnRotation;
				SyncNow(spawnPosition, ((Quaternion)(ref spawnRotation)).eulerAngles.y, _currentDisguiseId);
			}
			if (base.IsAIControlled)
			{
				_wasAttacking = isAttacking;
				return;
			}
			if (_wasAttacking && !isAttacking && ((NetworkBehaviour)base.EnemyAI).IsOwner)
			{
				SyncNow(((Component)base.EnemyAI).transform.position, ((Component)base.EnemyAI).transform.eulerAngles.y, _currentDisguiseId);
			}
			_wasAttacking = isAttacking;
			if (isAttacking || !((NetworkBehaviour)base.EnemyAI).IsOwner)
			{
				return;
			}
			_syncTimer += Time.deltaTime;
			if (!(_syncTimer < PluginConfig.DtmSyncIntervalSeconds.Value))
			{
				_syncTimer = 0f;
				Vector3 position = ((Component)base.EnemyAI).transform.position;
				float y = ((Component)base.EnemyAI).transform.eulerAngles.y;
				Vector3 val = position - _lastSyncedPos;
				if (((Vector3)(ref val)).sqrMagnitude > 0.0064f || Mathf.Abs(Mathf.DeltaAngle(_lastSyncedYRot, y)) > 4f)
				{
					SyncNow(position, y, _currentDisguiseId);
				}
			}
		}

		private void SyncNow(Vector3 pos, float yRot, int disguiseId)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			_lastSyncedPos = pos;
			_lastSyncedYRot = yRot;
			DontTouchMeReflection.InvokeSpawnClientRpc(base.EnemyAI, pos, yRot, disguiseId);
		}

		public override void OnPrimaryDown()
		{
			if (!((Object)(object)base.EnemyAI == (Object)null) && !base.EnemyAI.isEnemyDead && !DontTouchMeReflection.GetIsAttacking(base.EnemyAI))
			{
				bool outside = !ControlCompanyBridge.IsGhostIndoors();
				DontTouchMeReflection.InvokeStartAttack(base.EnemyAI, outside);
			}
		}

		public override void OnSecondaryDown()
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)base.EnemyAI == (Object)null) && !base.EnemyAI.isEnemyDead && !DontTouchMeReflection.GetIsAttacking(base.EnemyAI))
			{
				int disguiseCount = DontTouchMeReflection.GetDisguiseCount(base.EnemyAI);
				if (disguiseCount <= 0)
				{
					_currentDisguiseId = -1;
				}
				else if (_currentDisguiseId < 0)
				{
					_currentDisguiseId = 0;
				}
				else if (_currentDisguiseId + 1 < disguiseCount)
				{
					_currentDisguiseId++;
				}
				else
				{
					_currentDisguiseId = -1;
				}
				SyncNow(((Component)base.EnemyAI).transform.position, ((Component)base.EnemyAI).transform.eulerAngles.y, _currentDisguiseId);
			}
		}

		public override string GetPrimarySkillName()
		{
			if (!((Object)(object)base.EnemyAI != (Object)null) || !DontTouchMeReflection.GetIsAttacking(base.EnemyAI))
			{
				return "Trigger Attack";
			}
			return "Attacking...";
		}

		public override string GetSecondarySkillName()
		{
			if (_currentDisguiseId >= 0)
			{
				return $"Disguise: Prop #{_currentDisguiseId + 1}";
			}
			return "Disguise: Red Button";
		}
	}
	internal static class DontTouchMeReflection
	{
		private static FieldInfo _isAttackingField;

		private static FieldInfo _disguiseField;

		private static FieldInfo _destroyAfterTouchField;

		private static MethodInfo _spawnClientRpc;

		private static MethodInfo _startAttack;

		public static Type DtmAIType { get; private set; }

		public static Type DtmPluginType { get; private set; }

		public static bool Initialize()
		{
			DtmAIType = AccessTools.TypeByName("DontTouchMe.DTMEntityAI");
			if (DtmAIType == null)
			{
				return false;
			}
			DtmPluginType = AccessTools.TypeByName("DontTouchMe.Plugin");
			_isAttackingField = AccessTools.Field(DtmAIType, "IsAttacking");
			_disguiseField = AccessTools.Field(DtmAIType, "Disguise");
			_destroyAfterTouchField = ((DtmPluginType != null) ? AccessTools.Field(DtmPluginType, "DestroyEntityAfterTouch") : null);
			_spawnClientRpc = AccessTools.Method(DtmAIType, "SpawnClientRpc", new Type[3]
			{
				typeof(Vector3),
				typeof(float),
				typeof(int)
			}, (Type[])null);
			_startAttack = AccessTools.Method(DtmAIType, "StartAttack", new Type[1] { typeof(bool) }, (Type[])null);
			return true;
		}

		public static bool GetIsAttacking(EnemyAI ai)
		{
			if (_isAttackingField != null)
			{
				return (bool)_isAttackingField.GetValue(ai);
			}
			return false;
		}

		public static int GetDisguiseCount(EnemyAI ai)
		{
			object? obj = _disguiseField?.GetValue(ai);
			GameObject val = (GameObject)((obj is GameObject) ? obj : null);
			if (!((Object)(object)val != (Object)null))
			{
				return 0;
			}
			return val.transform.childCount;
		}

		public static bool GetDestroyAfterTouch()
		{
			if (_destroyAfterTouchField != null)
			{
				return (bool)_destroyAfterTouchField.GetValue(null);
			}
			return false;
		}

		public static void SetDestroyAfterTouch(bool value)
		{
			_destroyAfterTouchField?.SetValue(null, value);
		}

		public static void InvokeSpawnClientRpc(EnemyAI ai, Vector3 pos, float yRot, int disguise)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			_spawnClientRpc?.Invoke(ai, new object[3] { pos, yRot, disguise });
		}

		public static void InvokeStartAttack(EnemyAI ai, bool outside)
		{
			_startAttack?.Invoke(ai, new object[1] { outside });
		}
	}
	public static class DontTouchMePatches
	{
		private struct UpdateRestoreState
		{
			public bool ModifiedDestroyFlag;

			public bool OriginalDestroyFlag;

			public bool ModifiedPlayerControlled;

			public PlayerControllerB LocalPlayer;

			public bool OriginalPlayerControlled;
		}

		public static bool Apply(Harmony harmony)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Expected O, but got Unknown
			//IL_00f4: Expected O, but got Unknown
			if (!DontTouchMeReflection.Initialize())
			{
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(DontTouchMeReflection.DtmAIType, "ResetInteraction", new Type[1] { typeof(bool) }, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(DontTouchMeReflection.DtmAIType, "OnTouched", new Type[1] { typeof(PlayerControllerB) }, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(DontTouchMeReflection.DtmAIType, "Update", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(DontTouchMePatches), "ResetInteractionPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(DontTouchMePatches), "OnTouchedPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo3 != null)
			{
				harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(DontTouchMePatches), "UpdatePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(DontTouchMePatches), "UpdateFinalizer", (Type[])null), (HarmonyMethod)null);
			}
			return true;
		}

		private static void ResetInteractionPrefix(EnemyAI __instance, ref bool changeLocation)
		{
			if (ControlledEnemyTracker.IsControlledOrSpawning(__instance))
			{
				changeLocation = false;
			}
		}

		private static bool OnTouchedPrefix(EnemyAI __instance, PlayerControllerB player)
		{
			if (!ControlledEnemyTracker.IsPlayerControlled(__instance))
			{
				return true;
			}
			PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
			if ((Object)(object)val != (Object)null && (Object)(object)player == (Object)(object)val)
			{
				return false;
			}
			return true;
		}

		private static void UpdatePrefix(EnemyAI __instance, ref UpdateRestoreState __state)
		{
			__state = default(UpdateRestoreState);
			if (ControlledEnemyTracker.IsPlayerControlled(__instance))
			{
				__state.OriginalDestroyFlag = DontTouchMeReflection.GetDestroyAfterTouch();
				if (__state.OriginalDestroyFlag)
				{
					DontTouchMeReflection.SetDestroyAfterTouch(value: false);
					__state.ModifiedDestroyFlag = true;
				}
				PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
				if ((Object)(object)val != (Object)null && val.isPlayerControlled)
				{
					__state.LocalPlayer = val;
					__state.OriginalPlayerControlled = val.isPlayerControlled;
					__state.ModifiedPlayerControlled = true;
					val.isPlayerControlled = false;
				}
			}
		}

		private static void UpdateFinalizer(UpdateRestoreState __state)
		{
			if (__state.ModifiedDestroyFlag)
			{
				DontTouchMeReflection.SetDestroyAfterTouch(__state.OriginalDestroyFlag);
			}
			if (__state.ModifiedPlayerControlled && (Object)(object)__state.LocalPlayer != (Object)null)
			{
				__state.LocalPlayer.isPlayerControlled = __state.OriginalPlayerControlled;
			}
		}
	}
	public class GenericModdedEnemyAdapter : ModdedEnemyAdapter
	{
		private float _syncTimer;

		private int _cycledState;

		public override void OnLateUpdate()
		{
			base.OnLateUpdate();
			if (!((Object)(object)base.EnemyAI == (Object)null) && !base.IsAIControlled && !base.EnemyAI.isEnemyDead)
			{
				EnemySyncHelper.FreezeAgent(base.Agent);
				EnemySyncHelper.TickHostSync(base.EnemyAI, ref _syncTimer);
			}
		}

		public override void OnEnableAI()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			base.OnEnableAI();
			if (!((Object)(object)base.EnemyAI == (Object)null))
			{
				float originalAgentSpeed = ControlCompanyBridge.GetOriginalAgentSpeed(base.EnemyAIController);
				float originalAgentAngularSpeed = ControlCompanyBridge.GetOriginalAgentAngularSpeed(base.EnemyAIController);
				EnemySyncHelper.RestoreAgent(base.Agent, ((Component)base.EnemyAI).transform.position, originalAgentSpeed, originalAgentAngularSpeed);
			}
		}

		public override void OnPrimaryDown()
		{
			if (!((Object)(object)base.EnemyAI == (Object)null))
			{
				int num = ((base.EnemyAI.enemyBehaviourStates != null && base.EnemyAI.enemyBehaviourStates.Length != 0) ? base.EnemyAI.enemyBehaviourStates.Length : 3);
				_cycledState = (_cycledState + 1) % num;
				base.EnemyAI.SwitchToBehaviourState(_cycledState);
			}
		}

		public override void OnSecondaryDown()
		{
			if (!((Object)(object)base.EnemyAI == (Object)null))
			{
				_cycledState = 1;
				base.EnemyAI.SwitchToBehaviourState(1);
			}
		}

		public override void OnSecondaryUp()
		{
			if (!((Object)(object)base.EnemyAI == (Object)null))
			{
				_cycledState = 0;
				base.EnemyAI.SwitchToBehaviourState(0);
			}
		}

		public override string GetPrimarySkillName()
		{
			return $"Cycle AI State ({_cycledState})";
		}

		public override string GetSecondarySkillName()
		{
			return "(HOLD) AI State 1";
		}
	}
	public class HerobrineAdapter : ModdedEnemyAdapter
	{
		private float _syncTimer;

		private bool _secondaryHeld;

		private float _secondaryHoldTime;

		private bool _breakerTriggeredThisHold;

		public static object BuildAttributes()
		{
			return ControlCompanyBridge.CreateEnemyAttributes("Herobrine", PluginConfig.HerobrineWalkSpeed.Value, PluginConfig.HerobrineRunSpeed.Value, -3.5f, 2.2f);
		}

		public override void OnInitialized()
		{
			base.OnInitialized();
			if (ControlledEnemyTracker.ConsumeStartedDuringSpawn(base.EnemyAI))
			{
				OnNativeStartCompleted();
			}
		}

		public void OnNativeStartCompleted()
		{
			//IL_001b: 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)
			if (!((Object)(object)base.EnemyAI == (Object)null))
			{
				((Component)base.EnemyAI).transform.SetPositionAndRotation(base.SpawnPosition, base.SpawnRotation);
				base.EnemyAI.ventAnimationFinished = true;
				HerobrineReflection.SetIsInitialized(base.EnemyAI, value: true);
				LookAtConstraint entityLookAt = HerobrineReflection.GetEntityLookAt(base.EnemyAI);
				if ((Object)(object)entityLookAt != (Object)null)
				{
					((Behaviour)entityLookAt).enabled = false;
				}
				if (!base.IsAIControlled)
				{
					EnemySyncHelper.FreezeAgent(base.Agent);
				}
				PlayerControllerB val = EnemySyncHelper.FindAnyLivingTargetPlayer();
				if ((Object)(object)val != (Object)null)
				{
					base.AllowOwnershipTransfer = false;
					HerobrineReflection.InvokeSyncNewTargetClientRpc(base.EnemyAI, (int)val.playerClientId, isReq: false);
				}
				HerobrineReflection.InvokeSetEnemyVisible(base.EnemyAI, visible: true);
				base.EnemyAI.SwitchToBehaviourState(2);
				EnemySyncHelper.ForceSyncTransform(base.EnemyAI);
			}
		}

		public override void OnLateUpdate()
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			base.OnLateUpdate();
			if ((Object)(object)base.EnemyAI == (Object)null || base.EnemyAI.isEnemyDead || base.IsAIControlled)
			{
				return;
			}
			EnemySyncHelper.FreezeAgent(base.Agent);
			HerobrineReflection.InvokeSetEnemyVisible(base.EnemyAI, visible: true);
			SkinnedMeshRenderer mainRenderer = HerobrineReflection.GetMainRenderer(base.EnemyAI);
			if ((Object)(object)mainRenderer != (Object)null)
			{
				((Renderer)mainRenderer).enabled = true;
			}
			LookAtConstraint entityLookAt = HerobrineReflection.GetEntityLookAt(base.EnemyAI);
			if ((Object)(object)entityLookAt != (Object)null && ((Behaviour)entityLookAt).enabled)
			{
				((Behaviour)entityLookAt).enabled = false;
			}
			if ((Object)(object)base.EnemyAI.creatureAnimator != (Object)null)
			{
				Vector3 controllerVelocity = ControlCompanyBridge.GetControllerVelocity(base.EnemyAIController);
				bool flag = ((Vector3)(ref controllerVelocity)).sqrMagnitude > 0.15f;
				base.EnemyAI.creatureAnimator.SetBool("Walk", flag);
			}
			EnemySyncHelper.TickHostSync(base.EnemyAI, ref _syncTimer);
			if (_secondaryHeld && !_breakerTriggeredThisHold)
			{
				_secondaryHoldTime += Time.deltaTime;
				if (_secondaryHoldTime >= 0.75f)
				{
					_breakerTriggeredThisHold = true;
					HerobrineReflection.InvokeFlipLightsBreakerClientRpc(base.EnemyAI);
				}
			}
		}

		public override void OnDisableAI()
		{
			base.OnDisableAI();
			if (!((Object)(object)base.EnemyAI == (Object)null))
			{
				LookAtConstraint entityLookAt = HerobrineReflection.GetEntityLookAt(base.EnemyAI);
				if ((Object)(object)entityLookAt != (Object)null)
				{
					((Behaviour)entityLookAt).enabled = false;
				}
				HerobrineReflection.InvokeSetEnemyVisible(base.EnemyAI, visible: true);
				base.EnemyAI.SwitchToBehaviourState(2);
			}
		}

		public override void OnEnableAI()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			base.OnEnableAI();
			if (!((Object)(object)base.EnemyAI == (Object)null))
			{
				LookAtConstraint entityLookAt = HerobrineReflection.GetEntityLookAt(base.EnemyAI);
				if ((Object)(object)entityLookAt != (Object)null)
				{
					((Behaviour)entityLookAt).enabled = true;
				}
				Vector4 agentSpeeds = HerobrineReflection.GetAgentSpeeds(base.EnemyAI);
				float speed = ((agentSpeeds.x > 0.1f) ? agentSpeeds.x : 5.3f);
				float originalAgentAngularSpeed = ControlCompanyBridge.GetOriginalAgentAngularSpeed(base.EnemyAIController);
				EnemySyncHelper.RestoreAgent(base.Agent, ((Component)base.EnemyAI).transform.position, speed, originalAgentAngularSpeed);
				base.AllowOwnershipTransfer = true;
				PlayerControllerB val = EnemySyncHelper.FindNearestLivingPlayer(((Component)base.EnemyAI).transform.position, 9999f) ?? EnemySyncHelper.FindAnyLivingTargetPlayer(preferNonHost: false);
				if ((Object)(object)val != (Object)null)
				{
					HerobrineReflection.InvokeSyncNewTargetClientRpc(base.EnemyAI, (int)val.playerClientId, isReq: false);
					base.EnemyAI.ChangeOwnershipOfEnemy(val.actualClientId);
				}
			}
		}

		public override void OnPrimaryDown()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: 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_0071: 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_0084: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)base.EnemyAI == (Object)null || base.EnemyAI.isEnemyDead)
			{
				return;
			}
			PlayerControllerB val = EnemySyncHelper.FindNearestLivingPlayer(((Component)base.EnemyAI).transform.position, 3.2f);
			if ((Object)(object)val != (Object)null)
			{
				Vector3 val2 = ((Component)val).transform.position - ((Component)base.EnemyAI).transform.position;
				Vector3 hitDirection = ((Vector3)(ref val2)).normalized * 20f;
				hitDirection.y = 12f;
				EnemySyncHelper.KillPlayerHostSafe(val, hitDirection);
				AudioClip[] hitAudioClips = HerobrineReflection.GetHitAudioClips(base.EnemyAI);
				if ((Object)(object)base.EnemyAI.creatureVoice != (Object)null && hitAudioClips != null && hitAudioClips.Length != 0)
				{
					base.EnemyAI.creatureVoice.PlayOneShot(hitAudioClips[Random.Range(0, hitAudioClips.Length)]);
				}
			}
			HerobrineReflection.InvokeMessWithLightsClientRpc(base.EnemyAI);
		}

		public override void OnSecondaryDown()
		{
			_secondaryHeld = true;
			_secondaryHoldTime = 0f;
			_breakerTriggeredThisHold = false;
		}

		public override void OnSecondaryUp()
		{
			if ((Object)(object)base.EnemyAI != (Object)null && _secondaryHeld && !_breakerTriggeredThisHold)
			{
				HerobrineReflection.InvokeMessWithLightsClientRpc(base.EnemyAI);
			}
			_secondaryHeld = false;
			_secondaryHoldTime = 0f;
			_breakerTriggeredThisHold = false;
		}

		public override string GetPrimarySkillName()
		{
			return "Strike / Kill Nearby";
		}

		public override string GetSecondarySkillName()
		{
			return "Tap: Flicker / Hold: Breaker";
		}
	}
	internal static class HerobrineReflection
	{
		private static FieldInfo _isInitializedField;

		private static FieldInfo _entityLookAtField;

		private static FieldInfo _mainRendererField;

		private static FieldInfo _hauntingPlayerField;

		private static FieldInfo _agentSpeedsField;

		private static FieldInfo _hitAudioClipsField;

		private static FieldInfo _targetYRotationField;

		private static MethodInfo _setEnemyVisible;

		private static MethodInfo _syncNewTargetClientRpc;

		private static MethodInfo _messWithLightsClientRpc;

		private static MethodInfo _flipLightsBreakerClientRpc;

		public static Type HerobrineAIType { get; private set; }

		public static bool Initialize()
		{
			HerobrineAIType = AccessTools.TypeByName("Kittenji.HerobrineMod.HerobrineAI");
			if (HerobrineAIType == null)
			{
				return false;
			}
			_isInitializedField = AccessTools.Field(HerobrineAIType, "IsInitialized");
			_entityLookAtField = AccessTools.Field(HerobrineAIType, "EntityLookAt");
			_mainRendererField = AccessTools.Field(HerobrineAIType, "MainRenderer");
			_hauntingPlayerField = AccessTools.Field(HerobrineAIType, "hauntingPlayer");
			_agentSpeedsField = AccessTools.Field(HerobrineAIType, "AgentSpeeds");
			_hitAudioClipsField = AccessTools.Field(HerobrineAIType, "HitAudioClips");
			_targetYRotationField = AccessTools.Field(typeof(EnemyAI), "targetYRotation");
			_setEnemyVisible = AccessTools.Method(HerobrineAIType, "SetEnemyVisible", new Type[1] { typeof(bool) }, (Type[])null);
			_syncNewTargetClientRpc = AccessTools.Method(HerobrineAIType, "SyncNewTargetClientRpc", new Type[2]
			{
				typeof(int),
				typeof(bool)
			}, (Type[])null);
			_messWithLightsClientRpc = AccessTools.Method(HerobrineAIType, "MessWithLightsClientRpc", (Type[])null, (Type[])null);
			_flipLightsBreakerClientRpc = AccessTools.Method(HerobrineAIType, "FlipLightsBreakerClientRpc", (Type[])null, (Type[])null);
			return true;
		}

		public static void SetIsInitialized(EnemyAI ai, bool value)
		{
			_isInitializedField?.SetValue(ai, value);
		}

		public static LookAtConstraint GetEntityLookAt(EnemyAI ai)
		{
			object? obj = _entityLookAtField?.GetValue(ai);
			return (LookAtConstraint)((obj is LookAtConstraint) ? obj : null);
		}

		public static SkinnedMeshRenderer GetMainRenderer(EnemyAI ai)
		{
			object? obj = _mainRendererField?.GetValue(ai);
			return (SkinnedMeshRenderer)((obj is SkinnedMeshRenderer) ? obj : null);
		}

		public static PlayerControllerB GetHauntingPlayer(EnemyAI ai)
		{
			object? obj = _hauntingPlayerField?.GetValue(ai);
			return (PlayerControllerB)((obj is PlayerControllerB) ? obj : null);
		}

		public static Vector4 GetAgentSpeeds(EnemyAI ai)
		{
			//IL_0032: 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)
			if (!(_agentSpeedsField != null))
			{
				return new Vector4(5.3f, 8f, 0f, 0f);
			}
			return (Vector4)_agentSpeedsField.GetValue(ai);
		}

		public static AudioClip[] GetHitAudioClips(EnemyAI ai)
		{
			return _hitAudioClipsField?.GetValue(ai) as AudioClip[];
		}

		public static float GetTargetYRotation(EnemyAI ai)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (!(_targetYRotationField != null))
			{
				return ((Component)ai).transform.eulerAngles.y;
			}
			return (float)_targetYRotationField.GetValue(ai);
		}

		public static void InvokeSetEnemyVisible(EnemyAI ai, bool visible)
		{
			_setEnemyVisible?.Invoke(ai, new object[1] { visible });
		}

		public static void InvokeSyncNewTargetClientRpc(EnemyAI ai, int id, bool isReq)
		{
			_syncNewTargetClientRpc?.Invoke(ai, new object[2] { id, isReq });
		}

		public static void InvokeMessWithLightsClientRpc(EnemyAI ai)
		{
			_messWithLightsClientRpc?.Invoke(ai, null);
		}

		public static void InvokeFlipLightsBreakerClientRpc(EnemyAI ai)
		{
			_flipLightsBreakerClientRpc?.Invoke(ai, null);
		}
	}
	public static class HerobrinePatches
	{
		public static bool Apply(Harmony harmony)
		{
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Expected O, but got Unknown
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Expected O, but got Unknown
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Expected O, but got Unknown
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Expected O, but got Unknown
			if (!HerobrineReflection.Initialize())
			{
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(HerobrineReflection.HerobrineAIType, "Start", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(HerobrineReflection.HerobrineAIType, "Update", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(HerobrineReflection.HerobrineAIType, "DoAIInterval", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(HerobrineReflection.HerobrineAIType, "OnCollideWithPlayer", new Type[1] { typeof(Collider) }, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(HerobrineReflection.HerobrineAIType, "SyncNewTargetClientRpc", new Type[2]
			{
				typeof(int),
				typeof(bool)
			}, (Type[])null);
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(HerobrinePatches), "StartPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(HerobrinePatches), "UpdatePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo3 != null)
			{
				harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(HerobrinePatches), "DoAIIntervalPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo4 != null)
			{
				harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeof(HerobrinePatches), "OnCollideWithPlayerPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo5 != null)
			{
				harmony.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, new HarmonyMethod(typeof(HerobrinePatches), "SyncNewTargetPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			return true;
		}

		private static void StartPostfix(EnemyAI __instance)
		{
			if (((NetworkBehaviour)__instance).IsServer)
			{
				if (ControlledEnemyTracker.TryGet(__instance, out var adapter) && adapter is HerobrineAdapter herobrineAdapter)
				{
					herobrineAdapter.OnNativeStartCompleted();
				}
				else if (ControlledEnemyTracker.IsSpawningFromControlCompany)
				{
					ControlledEnemyTracker.MarkStartedDuringSpawn(__instance);
				}
			}
		}

		private static void SyncNewTargetPostfix(EnemyAI __instance)
		{
			if (ControlledEnemyTracker.IsPlayerControlled(__instance))
			{
				LookAtConstraint entityLookAt = HerobrineReflection.GetEntityLookAt(__instance);
				if ((Object)(object)entityLookAt != (Object)null)
				{
					((Behaviour)entityLookAt).enabled = false;
				}
				HerobrineReflection.InvokeSetEnemyVisible(__instance, visible: true);
				SkinnedMeshRenderer mainRenderer = HerobrineReflection.GetMainRenderer(__instance);
				if ((Object)(object)mainRenderer != (Object)null)
				{
					((Renderer)mainRenderer).enabled = true;
				}
			}
		}

		private static bool UpdatePrefix(EnemyAI __instance)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: 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_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: 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)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			if (ControlledEnemyTracker.IsPlayerControlled(__instance))
			{
				return false;
			}
			if (!((NetworkBehaviour)__instance).IsHost && !((NetworkBehaviour)__instance).IsOwner && ((NetworkBehaviour)__instance).OwnerClientId == 0L && PluginConfig.HerobrineVisibleToAllClientsWithAddon.Value && __instance.currentBehaviourStateIndex == 2)
			{
				PlayerControllerB hauntingPlayer = HerobrineReflection.GetHauntingPlayer(__instance);
				PlayerControllerB[] array = StartOfRound.Instance?.allPlayerScripts;
				PlayerControllerB val = ((array != null && array.Length != 0) ? array[0] : null);
				if ((Object)(object)hauntingPlayer != (Object)null && (Object)(object)val != (Object)null && (Object)(object)hauntingPlayer != (Object)(object)val)
				{
					Vector3 position = ((Component)__instance).transform.position;
					Vector3 serverPosition = __instance.serverPosition;
					if (serverPosition != Vector3.zero)
					{
						((Component)__instance).transform.position = Vector3.Lerp(position, serverPosition, Time.deltaTime * 12f);
					}
					float targetYRotation = HerobrineReflection.GetTargetYRotation(__instance);
					Vector3 eulerAngles = ((Component)__instance).transform.eulerAngles;
					eulerAngles.y = Mathf.LerpAngle(eulerAngles.y, targetYRotation, Time.deltaTime * 12f);
					((Component)__instance).transform.eulerAngles = eulerAngles;
					LookAtConstraint entityLookAt = HerobrineReflection.GetEntityLookAt(__instance);
					if ((Object)(object)entityLookAt != (Object)null && ((Behaviour)entityLookAt).enabled)
					{
						((Behaviour)entityLookAt).enabled = false;
					}
					HerobrineReflection.InvokeSetEnemyVisible(__instance, visible: true);
					SkinnedMeshRenderer mainRenderer = HerobrineReflection.GetMainRenderer(__instance);
					if ((Object)(object)mainRenderer != (Object)null)
					{
						((Renderer)mainRenderer).enabled = true;
					}
					if ((Object)(object)__instance.creatureAnimator != (Object)null)
					{
						Vector3 val2 = serverPosition - position;
						float num = ((Vector3)(ref val2)).magnitude / Mathf.Max(Time.deltaTime, 0.001f);
						__instance.creatureAnimator.SetBool("Walk", num > 0.15f);
					}
					return false;
				}
			}
			return true;
		}

		private static bool DoAIIntervalPrefix(EnemyAI __instance)
		{
			return !ControlledEnemyTracker.IsPlayerControlled(__instance);
		}

		private static bool OnCollideWithPlayerPrefix(EnemyAI __instance)
		{
			return !ControlledEnemyTracker.IsPlayerControlled(__instance);
		}
	}
	public abstract class ModdedEnemyAdapter : MonoBehaviour
	{
		public EnemyAI EnemyAI { get; private set; }

		public GameObject EnemyGameObject { get; private set; }

		public object EnemyAIController { get; private set; }

		public NavMeshAgent Agent { get; private set; }

		public Vector3 SpawnPosition { get; private set; }

		public Quaternion SpawnRotation { get; private set; }

		public bool IsAIControlled { get; private set; }

		public bool AllowOwnershipTransfer { get; protected set; }

		public void Bind(EnemyAI enemyAI, object controller, GameObject enemyGameObject, Vector3 spawnPosition, Quaternion spawnRotation)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			EnemyAI = enemyAI;
			EnemyAIController = controller;
			EnemyGameObject = enemyGameObject;
			Agent = ControlCompanyBridge.GetEnemyAIAgent(controller) ?? (((Object)(object)enemyGameObject != (Object)null) ? enemyGameObject.GetComponentInChildren<NavMeshAgent>() : null);
			SpawnPosition = spawnPosition;
			SpawnRotation = spawnRotation;
			IsAIControlled = ControlCompanyBridge.IsAIControlled(controller);
			ControlledEnemyTracker.Register(enemyAI, this);
		}

		public virtual void OnInitialized()
		{
			IsAIControlled = ControlCompanyBridge.IsAIControlled(EnemyAIController);
			if ((Object)(object)EnemyAI != (Object)null)
			{
				EnemyAI.ventAnimationFinished = true;
			}
			if (!IsAIControlled)
			{
				EnemySyncHelper.FreezeAgent(Agent);
			}
		}

		public virtual void OnLateUpdate()
		{
			IsAIControlled = ControlCompanyBridge.IsAIControlled(EnemyAIController);
		}

		public virtual bool CanMove()
		{
			return true;
		}

		public virtual bool CanControlEnemy(bool baseResult)
		{
			return baseResult;
		}

		public virtual void OnEnableAI()
		{
			IsAIControlled = true;
		}

		public virtual void OnDisableAI()
		{
			IsAIControlled = false;
			AllowOwnershipTransfer = false;
			EnemySyncHelper.FreezeAgent(Agent);
		}

		public virtual void OnPrimaryDown()
		{
		}

		public virtual void OnPrimaryUp()
		{
		}

		public virtual void OnSecondaryDown()
		{
		}

		public virtual void OnSecondaryUp()
		{
		}

		public virtual string GetPrimarySkillName()
		{
			return string.Empty;
		}

		public virtual string GetSecondarySkillName()
		{
			return string.Empty;
		}

		public virtual void OnCleanUp()
		{
			ControlledEnemyTracker.Unregister(EnemyAI);
		}

		protected virtual void OnDestroy()
		{
			ControlledEnemyTracker.Unregister(EnemyAI);
		}
	}
	public class SlendermanAdapter : ModdedEnemyAdapter
	{
		private float _syncTimer;

		private readonly Dictionary<ulong, float> _killCooldownByClient = new Dictionary<ulong, float>();

		public bool IsInChaseMode { get; private set; }

		public bool IsInvisible { get; private set; }

		public static object BuildAttributes()
		{
			return ControlCompanyBridge.CreateEnemyAttributes("Faceless Stalker", PluginConfig.SlenderWalkSpeed.Value, PluginConfig.SlenderRunSpeed.Value, -4f, 2.8f);
		}

		public override void OnInitialized()
		{
			base.OnInitialized();
			if (ControlledEnemyTracker.ConsumeStartedDuringSpawn(base.EnemyAI))
			{
				OnNativeStartCompleted();
			}
		}

		public void OnNativeStartCompleted()
		{
			//IL_001b: 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)
			if (!((Object)(object)base.EnemyAI == (Object)null))
			{
				((Component)base.EnemyAI).transform.SetPositionAndRotation(base.SpawnPosition, base.SpawnRotation);
				base.EnemyAI.ventAnimationFinished = true;
				Coroutine disappearCoroutine = SlendermanReflection.GetDisappearCoroutine(base.EnemyAI);
				if (disappearCoroutine != null)
				{
					((MonoBehaviour)base.EnemyAI).StopCoroutine(disappearCoroutine);
					SlendermanReflection.SetDisappearCoroutine(base.EnemyAI, null);
				}
				if (!base.IsAIControlled)
				{
					EnemySyncHelper.FreezeAgent(base.Agent);
				}
				PlayerControllerB val = EnemySyncHelper.FindAnyLivingTargetPlayer();
				if ((Object)(object)val != (Object)null)
				{
					SlendermanReflection.InvokeHandleChangeHauntingPlayerClientRpc(base.EnemyAI, (int)val.playerClientId);
				}
				IsInvisible = false;
				IsInChaseMode = false;
				SlendermanReflection.InvokeEnableEnemyMeshEveryoneClientRpc(base.EnemyAI);
				SlendermanReflection.InvokeAnimStalkingBaseClientRpc(base.EnemyAI);
				EnemySyncHelper.ForceSyncTransform(base.EnemyAI);
			}
		}

		public override void OnLateUpdate()
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			base.OnLateUpdate();
			if ((Object)(object)base.EnemyAI == (Object)null || base.IsAIControlled || base.EnemyAI.isEnemyDead)
			{
				return;
			}
			EnemySyncHelper.FreezeAgent(base.Agent);
			EnemySyncHelper.TickHostSync(base.EnemyAI, ref _syncTimer);
			if (IsInChaseMode && !IsInvisible)
			{
				PlayerControllerB val = EnemySyncHelper.FindNearestLivingPlayer(((Component)base.EnemyAI).transform.position, 1.8f);
				if ((Object)(object)val != (Object)null)
				{
					TriggerKillOnPlayer(val);
				}
			}
		}

		public override void OnEnableAI()
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			base.OnEnableAI();
			if (!((Object)(object)base.EnemyAI == (Object)null))
			{
				PlayerControllerB val = SlendermanReflection.GetHauntingPlayer(base.EnemyAI) ?? EnemySyncHelper.FindAnyLivingTargetPlayer();
				if ((Object)(object)val != (Object)null)
				{
					SlendermanReflection.InvokeHandleChangeHauntingPlayerClientRpc(base.EnemyAI, (int)val.playerClientId);
				}
				float speed = (IsInChaseMode ? 13f : ControlCompanyBridge.GetOriginalAgentSpeed(base.EnemyAIController));
				float originalAgentAngularSpeed = ControlCompanyBridge.GetOriginalAgentAngularSpeed(base.EnemyAIController);
				EnemySyncHelper.RestoreAgent(base.Agent, ((Component)base.EnemyAI).transform.position, speed, originalAgentAngularSpeed);
			}
		}

		public override void OnDisableAI()
		{
			base.OnDisableAI();
			if (!((Object)(object)base.EnemyAI == (Object)null) && !IsInvisible)
			{
				SlendermanReflection.InvokeEnableEnemyMeshEveryoneClientRpc(base.EnemyAI);
			}
		}

		public override void OnPrimaryDown()
		{
			if ((Object)(object)base.EnemyAI == (Object)null || base.EnemyAI.isEnemyDead)
			{
				return;
			}
			IsInChaseMode = !IsInChaseMode;
			if (IsInChaseMode)
			{
				if (IsInvisible)
				{
					IsInvisible = false;
					SlendermanReflection.InvokeEnableEnemyMeshEveryoneClientRpc(base.EnemyAI);
				}
				SlendermanReflection.InvokeStartChaseAnimClientRpc(base.EnemyAI);
				SlendermanReflection.InvokePlaySfxClientRpc(base.EnemyAI, "approachingSFX", spatial: true);
				ControlCompanyBridge.SetWalkRunSpeed(base.EnemyAIController, PluginConfig.SlenderWalkSpeed.Value, 13f);
			}
			else
			{
				SlendermanReflection.InvokeStopChaseAnimClientRpc(base.EnemyAI);
				SlendermanReflection.InvokeAnimStalkingBaseClientRpc(base.EnemyAI);
				ControlCompanyBridge.SetWalkRunSpeed(base.EnemyAIController, PluginConfig.SlenderWalkSpeed.Value, PluginConfig.SlenderRunSpeed.Value);
			}
		}

		public override void OnSecondaryDown()
		{
			if ((Object)(object)base.EnemyAI == (Object)null || base.EnemyAI.isEnemyDead)
			{
				return;
			}
			IsInvisible = !IsInvisible;
			if (IsInvisible)
			{
				if (IsInChaseMode)
				{
					IsInChaseMode = false;
					SlendermanReflection.InvokeStopChaseAnimClientRpc(base.EnemyAI);
					ControlCompanyBridge.SetWalkRunSpeed(base.EnemyAIController, PluginConfig.SlenderWalkSpeed.Value, PluginConfig.SlenderRunSpeed.Value);
				}
				SlendermanReflection.InvokeDisableEnemyMeshClientRpc(base.EnemyAI);
			}
			else
			{
				SlendermanReflection.InvokeEnableEnemyMeshEveryoneClientRpc(base.EnemyAI);
				SlendermanReflection.InvokeAnimStalkingBaseClientRpc(base.EnemyAI);
				SlendermanReflection.InvokeMessWithLightsClientRpc(base.EnemyAI);
				SlendermanReflection.InvokePlaySfxClientRpc(base.EnemyAI, "approachingSFX", spatial: true);
			}
		}

		public void HandleCollision(Collider other)
		{
			if (!((Object)(object)base.EnemyAI == (Object)null) && !base.EnemyAI.isEnemyDead && !((Object)(object)other == (Object)null) && IsInChaseMode && !IsInvisible)
			{
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				TriggerKillOnPlayer(component);
			}
		}

		public void TriggerKillOnPlayer(PlayerControllerB player)
		{
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)player == (Object)null) && player.isPlayerControlled && !player.isPlayerDead)
			{
				PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
				if ((!((Object)(object)val != (Object)null) || !((Object)(object)player == (Object)(object)val)) && (!_killCooldownByClient.TryGetValue(player.playerClientId, out var value) || !(Time.time - value < 1.5f)))
				{
					_killCooldownByClient[player.playerClientId] = Time.time;
					SlendermanReflection.InvokeHandleChangeHauntingPlayerClientRpc(base.EnemyAI, (int)player.playerClientId);
					SlendermanReflection.InvokePlaySfxClientRpc(base.EnemyAI, "jumpscareSFX", spatial: false);
					SlendermanReflection.InvokeKillHauntedPlayerClientRpc(base.EnemyAI);
					EnemySyncHelper.KillPlayerHostSafe(player, Vector3.zero);
				}
			}
		}

		public override string GetPrimarySkillName()
		{
			if (!IsInChaseMode)
			{
				return "Chase Mode: OFF";
			}
			return "Chase Mode: ON (Touch Kills)";
		}

		public override string GetSecondarySkillName()
		{
			if (!IsInvisible)
			{
				return "Vanish (Invisible)";
			}
			return "Appear + Flicker Lights";
		}
	}
	internal static class SlendermanReflection
	{
		private static FieldInfo _hauntingPlayerField;

		private static FieldInfo _disappearCoroutineField;

		private static MethodInfo _handleChangeHauntingRpc;

		private static MethodInfo _enableMeshEveryoneRpc;

		private static MethodInfo _disableMeshRpc;

		private static MethodInfo _animStalkingBaseRpc;

		private static MethodInfo _startChaseAnimRpc;

		private static MethodInfo _stopChaseAnimRpc;

		private static MethodInfo _playSfxRpc;

		private static MethodInfo _messWithLightsRpc;

		private static MethodInfo _killHauntedRpc;

		public static Type SlenderAIType { get; private set; }

		public static bool Initialize()
		{
			SlenderAIType = AccessTools.TypeByName("SlendermanMod.SlendermanEnemyAI");
			if (SlenderAIType == null)
			{
				return false;
			}
			_hauntingPlayerField = AccessTools.Field(SlenderAIType, "hauntingPlayer");
			_disappearCoroutineField = AccessTools.Field(SlenderAIType, "disappearOnDelayCoroutine");
			_handleChangeHauntingRpc = AccessTools.Method(SlenderAIType, "HandleChangeHauntingPlayerClientRpc", new Type[1] { typeof(int) }, (Type[])null);
			_enableMeshEveryoneRpc = AccessTools.Method(SlenderAIType, "EnableEnemyMeshEveryoneClientRpc", (Type[])null, (Type[])null);
			_disableMeshRpc = AccessTools.Method(SlenderAIType, "DisableEnemyMeshClientRpc", (Type[])null, (Type[])null);
			_animStalkingBaseRpc = AccessTools.Method(SlenderAIType, "AnimStalkingBaseClientRpc", (Type[])null, (Type[])null);
			_startChaseAnimRpc = AccessTools.Method(SlenderAIType, "StartChaseAnimClientRpc", (Type[])null, (Type[])null);
			_stopChaseAnimRpc = AccessTools.Method(SlenderAIType, "StopChaseAnimClientRpc", (Type[])null, (Type[])null);
			_playSfxRpc = AccessTools.Method(SlenderAIType, "PlaySfxClientRpc", new Type[2]
			{
				typeof(string),
				typeof(bool)
			}, (Type[])null);
			_messWithLightsRpc = AccessTools.Method(SlenderAIType, "MessWithLightsClientRpc", (Type[])null, (Type[])null);
			_killHauntedRpc = AccessTools.Method(SlenderAIType, "KillHauntedPlayerClientRpc", (Type[])null, (Type[])null);
			return true;
		}

		public static PlayerControllerB GetHauntingPlayer(EnemyAI ai)
		{
			object? obj = _hauntingPlayerField?.GetValue(ai);
			return (PlayerControllerB)((obj is PlayerControllerB) ? obj : null);
		}

		public static Coroutine GetDisappearCoroutine(EnemyAI ai)
		{
			object? obj = _disappearCoroutineField?.GetValue(ai);
			return (Coroutine)((obj is Coroutine) ? obj : null);
		}

		public static void SetDisappearCoroutine(EnemyAI ai, Coroutine c)
		{
			_disappearCoroutineField?.SetValue(ai, c);
		}

		public static void InvokeHandleChangeHauntingPlayerClientRpc(EnemyAI ai, int id)
		{
			_handleChangeHauntingRpc?.Invoke(ai, new object[1] { id });
		}

		public static void InvokeEnableEnemyMeshEveryoneClientRpc(EnemyAI ai)
		{
			_enableMeshEveryoneRpc?.Invoke(ai, null);
		}

		public static void InvokeDisableEnemyMeshClientRpc(EnemyAI ai)
		{
			_disableMeshRpc?.Invoke(ai, null);
		}

		public static void InvokeAnimStalkingBaseClientRpc(EnemyAI ai)
		{
			_animStalkingBaseRpc?.Invoke(ai, null);
		}

		public static void InvokeStartChaseAnimClientRpc(EnemyAI ai)
		{
			_startChaseAnimRpc?.Invoke(ai, null);
		}

		public static void InvokeStopChaseAnimClientRpc(EnemyAI ai)
		{
			_stopChaseAnimRpc?.Invoke(ai, null);
		}

		public static void InvokePlaySfxClientRpc(EnemyAI ai, string clip, bool spatial)
		{
			_playSfxRpc?.Invoke(ai, new object[2] { clip, spatial });
		}

		public static void InvokeMessWithLightsClientRpc(EnemyAI ai)
		{
			_messWithLightsRpc?.Invoke(ai, null);
		}

		public static void InvokeKillHauntedPlayerClientRpc(EnemyAI ai)
		{
			_killHauntedRpc?.Invoke(ai, null);
		}
	}
	public static class SlendermanPatches
	{
		public static bool Apply(Harmony harmony)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Expected O, but got Unknown
			if (!SlendermanReflection.Initialize())
			{
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(SlendermanReflection.SlenderAIType, "Start", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(SlendermanReflection.SlenderAIType, "Update", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(SlendermanReflection.SlenderAIType, "DoAIInterval", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(SlendermanReflection.SlenderAIType, "OnCollideWithPlayer", new Type[1] { typeof(Collider) }, (Type[])null);
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(SlendermanPatches), "StartPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(SlendermanPatches), "UpdatePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo3 != null)
			{
				harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(SlendermanPatches), "DoAIIntervalPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo4 != null)
			{
				harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeof(SlendermanPatches), "OnCollideWithPlayerPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			return true;
		}

		private static void StartPostfix(EnemyAI __instance)
		{
			if (((NetworkBehaviour)__instance).IsServer)
			{
				if (ControlledEnemyTracker.TryGet(__instance, out var adapter) && adapter is SlendermanAdapter slendermanAdapter)
				{
					slendermanAdapter.OnNativeStartCompleted();
				}
				else if (ControlledEnemyTracker.IsSpawningFromControlCompany)
				{
					ControlledEnemyTracker.MarkStartedDuringSpawn(__instance);
				}
			}
		}

		private static bool UpdatePrefix(EnemyAI __instance)
		{
			return !ControlledEnemyTracker.IsPlayerControlled(__instance);
		}

		private static bool DoAIIntervalPrefix(EnemyAI __instance)
		{
			return !ControlledEnemyTracker.IsPlayerControlled(__instance);
		}

		private static bool OnCollideWithPlayerPrefix(EnemyAI __instance, Collider other)
		{
			if (!ControlledEnemyTracker.TryGet(__instance, out var adapter) || adapter.IsAIControlled)
			{
				return true;
			}
			if (adapter is SlendermanAdapter slendermanAdapter)
			{
				slendermanAdapter.HandleCollision(other);
				return false;
			}
			return true;
		}
	}
	public class SnailAdapter : ModdedEnemyAdapter
	{
		private float _syncTimer;

		private float _lastKillTime = -10f;

		private int _targetCycleIndex;

		private string _targetName = "Auto";

		public static object BuildAttributes()
		{
			return ControlCompanyBridge.CreateEnemyAttributes("Immortal Snail", PluginConfig.SnailWalkSpeed.Value, PluginConfig.SnailRunSpeed.Value, -2.8f, 1.4f);
		}

		public override void OnInitialized()
		{
			base.OnInitialized();
			if ((Object)(object)base.EnemyAI != (Object)null && (Object)(object)base.EnemyAI.targetPlayer != (Object)null)
			{
				_targetName = base.EnemyAI.targetPlayer.playerUsern