Decompiled source of americanompany v1.0.1

BepInEx/plugins/americanompany/AmmoTin.dll

Decompiled 2 years ago
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLib.Modules;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("LethalCompanyAmmoTin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LethalCompanyAmmoTin")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("85d63194-36a9-4b57-9db1-9b88fba8b04e")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace LethalCompanyAmmoTin;

[BepInPlugin("htd.lethalcompany.ammotin", "Ammo Tin", "1.0.0.0")]
public class ModAmmoTinMain : BaseUnityPlugin
{
	[HarmonyPatch(typeof(ShotgunItem), "ReloadedGun")]
	private static class ShotgunItemReloadedGunPatches
	{
		private static void Postfix(ShotgunItem __instance, ref bool __result)
		{
			if (__result)
			{
				return;
			}
			for (int i = 0; i < ((GrabbableObject)__instance).playerHeldBy.ItemSlots.Length; i++)
			{
				if ((Object)(object)((GrabbableObject)__instance).playerHeldBy.ItemSlots[i] != (Object)null && ((GrabbableObject)__instance).playerHeldBy.ItemSlots[i].itemProperties.itemName == "Ammo Tin" && ((GrabbableObject)__instance).playerHeldBy.ItemSlots[i].insertedBattery.charge >= shotgunDrainCost)
				{
					Battery insertedBattery = ((GrabbableObject)__instance).playerHeldBy.ItemSlots[i].insertedBattery;
					insertedBattery.charge -= shotgunDrainCost;
					__result = true;
					__instance.ammoSlotToUse = 100;
					break;
				}
			}
		}
	}

	[HarmonyPatch(typeof(PlayerControllerB), "DestroyItemInSlot")]
	private static class PlayerControllerBDestroyItemInSlotPatches
	{
		private static bool Prefix(PlayerControllerB __instance, ref int itemSlot)
		{
			if (itemSlot == 100)
			{
				if ((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null || (Object)(object)NetworkManager.Singleton == (Object)null || NetworkManager.Singleton.ShutdownInProgress)
				{
					return true;
				}
				return false;
			}
			return true;
		}
	}

	public const string Version = "1.0.0.0";

	public const string ModName = "Ammo Tin";

	public const string GUID = "htd.lethalcompany.ammotin";

	private Harmony _Harmony = new Harmony("htd.lethalcompany.ammotin");

	public static ManualLogSource Log;

	public static AssetBundle AmmoTinAssets;

	public static int maxShotgunReloads = 8;

	public static float shotgunDrainCost = 1f / (float)maxShotgunReloads;

	private void Awake()
	{
		string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
		AmmoTinAssets = AssetBundle.LoadFromFile(Path.Combine(directoryName, "ammotin"));
		if ((Object)(object)AmmoTinAssets == (Object)null)
		{
			Log.LogError((object)"Failed to load custom assets.");
			return;
		}
		Item val = AmmoTinAssets.LoadAsset<Item>("Assets/Prefab/AmmoTin.asset");
		Item val2 = AmmoTinAssets.LoadAsset<Item>("Assets/Prefab/AmmoTinScrap.asset");
		NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
		NetworkPrefabs.RegisterNetworkPrefab(val2.spawnPrefab);
		bool value = ((BaseUnityPlugin)this).Config.Bind<bool>("2-Scrap", "Allow Ammo Tin to be Scrap", false, "Setting this to true will add it to scrap lists for all moons.").Value;
		int value2 = ((BaseUnityPlugin)this).Config.Bind<int>("2-Scrap", "Ammo Tin Default Rarity", 5, "What Weighted Value does this have.").Value;
		int value3 = ((BaseUnityPlugin)this).Config.Bind<int>("2-Scrap", "Ammo Tin Min", 65, "Min Scrap value.").Value;
		int value4 = ((BaseUnityPlugin)this).Config.Bind<int>("2-Scrap", "Ammo Tin Max", 215, "Max Scrap value.").Value;
		int value5 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin Experimentation Rarity", -1, "What Weighted Value does this have for Moon Experimentation If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		int value6 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin Assurance Rarity", -1, "What Weighted Value does this have for Moon Assurance If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		int value7 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin Vow Rarity", -1, "What Weighted Value does this have for Moon Vow If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		int value8 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin Offense Rarity", -1, "What Weighted Value does this have for Moon Offense If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		int value9 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin March Rarity", -1, "What Weighted Value does this have for Moon March If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		int value10 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin Adamance Rarity", -1, "What Weighted Value does this have for Moon Adamance If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		int value11 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin Rend Rarity", -1, "What Weighted Value does this have for Moon Rend If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		int value12 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin Dine Rarity", -1, "What Weighted Value does this have for Moon Dine If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		int value13 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin Titan Rarity", -1, "What Weighted Value does this have for Moon Titan If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		int value14 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin Embrion Rarity", -1, "What Weighted Value does this have for Moon Embrion If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		int value15 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin Artifice Rarity", -1, "What Weighted Value does this have for Moon Artifice If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		int value16 = ((BaseUnityPlugin)this).Config.Bind<int>("3-Moon Rarity", "Ammo Tin Modded Moons Rarity", -1, "What Weighted Value does this have for Modded Moons If set to -1 defualt is used, if set to 0 it won't spawn here.").Value;
		if (value)
		{
			val2.minValue = value3;
			val2.maxValue = value4;
			if (value5 != 0)
			{
				Items.RegisterScrap(val2, (value5 < 0) ? value2 : value5, (LevelTypes)4);
			}
			if (value6 != 0)
			{
				Items.RegisterScrap(val2, (value6 < 0) ? value2 : value6, (LevelTypes)8);
			}
			if (value7 != 0)
			{
				Items.RegisterScrap(val2, (value7 < 0) ? value2 : value7, (LevelTypes)16);
			}
			if (value8 != 0)
			{
				Items.RegisterScrap(val2, (value8 < 0) ? value2 : value8, (LevelTypes)32);
			}
			if (value9 != 0)
			{
				Items.RegisterScrap(val2, (value9 < 0) ? value2 : value9, (LevelTypes)64);
			}
			if (value10 != 0)
			{
				Items.RegisterScrap(val2, (value10 < 0) ? value2 : value10, (LevelTypes)2048);
			}
			if (value11 != 0)
			{
				Items.RegisterScrap(val2, (value11 < 0) ? value2 : value11, (LevelTypes)128);
			}
			if (value12 != 0)
			{
				Items.RegisterScrap(val2, (value12 < 0) ? value2 : value12, (LevelTypes)256);
			}
			if (value13 != 0)
			{
				Items.RegisterScrap(val2, (value13 < 0) ? value2 : value13, (LevelTypes)512);
			}
			if (value14 != 0)
			{
				Items.RegisterScrap(val2, (value14 < 0) ? value2 : value14, (LevelTypes)8192);
			}
			if (value15 != 0)
			{
				Items.RegisterScrap(val2, (value15 < 0) ? value2 : value15, (LevelTypes)4096);
			}
			if (value16 != 0)
			{
				Items.RegisterScrap(val2, (value16 < 0) ? value2 : value16, (LevelTypes)1024);
			}
		}
		bool value17 = ((BaseUnityPlugin)this).Config.Bind<bool>("1-Shop", "Ammo Tin In Shop", true, "Is it possible to buy the Ammo Tin from the shop.").Value;
		int value18 = ((BaseUnityPlugin)this).Config.Bind<int>("1-Shop", "Ammo Tin Price", 600, "Price of the Ammo Tin in the shop.").Value;
		int num = value18;
		if (value17)
		{
			TerminalNode val3 = AmmoTinAssets.LoadAsset<TerminalNode>("Assets/Terminal/WI.asset");
			Items.RegisterShopItem(val, (TerminalNode)null, (TerminalNode)null, val3, num);
		}
		maxShotgunReloads = ((BaseUnityPlugin)this).Config.Bind<int>("0-Reloads", "Total Shotgun Reloads from Full Ammo Tin", 8, "If an Ammo Tin is full, this is the possible amount of reloads you can get.").Value;
		shotgunDrainCost = 1f / (float)maxShotgunReloads;
		_Harmony.PatchAll();
		((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
	}
}

BepInEx/plugins/americanompany/AmmoTinPVCom.dll

Decompiled 2 years ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using PiggyVarietyMod.Patches;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("LethalCompanyAmmoTinPiggyVarietyCompat")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LethalCompanyAmmoTinPiggyVarietyCompat")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("dfc547b3-8844-42f7-aeba-ed1788a8bbc7")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace LethalCompanyAmmoTinPiggyVarietyCompat;

[HarmonyPatch(typeof(M4Item))]
public class M4ItemPatches
{
	[HarmonyPatch("ReloadedGun")]
	[HarmonyPostfix]
	public static void Postfix(M4Item __instance, ref bool __result)
	{
		if (__result)
		{
			return;
		}
		for (int i = 0; i < ((GrabbableObject)__instance).playerHeldBy.ItemSlots.Length; i++)
		{
			if ((Object)(object)((GrabbableObject)__instance).playerHeldBy.ItemSlots[i] != (Object)null && ((GrabbableObject)__instance).playerHeldBy.ItemSlots[i].itemProperties.itemName == "Ammo Tin" && ((GrabbableObject)__instance).playerHeldBy.ItemSlots[i].insertedBattery.charge >= ModAmmoTinPVComMain.m4DrainCost)
			{
				Battery insertedBattery = ((GrabbableObject)__instance).playerHeldBy.ItemSlots[i].insertedBattery;
				insertedBattery.charge -= ModAmmoTinPVComMain.m4DrainCost;
				__result = true;
				__instance.ammoSlotToUse = 100;
				break;
			}
		}
	}
}
[BepInPlugin("htd.lethalcompany.ammotinPVCom", "Ammo Tin Piggys Variety Compatability", "1.0.1")]
public class ModAmmoTinPVComMain : BaseUnityPlugin
{
	public const string Version = "1.0.1";

	public const string ModName = "Ammo Tin Piggys Variety Compatability";

	public const string GUID = "htd.lethalcompany.ammotinPVCom";

	private Harmony _Harmony = new Harmony("htd.lethalcompany.ammotinPVCom");

	public static ManualLogSource Log;

	public static int maxM4Reloads = 2;

	public static float m4DrainCost = 1f / (float)maxM4Reloads;

	public static int maxRevolverReloads = 12;

	public static float revolverDrainCost = 1f / (float)maxRevolverReloads;

	private void Awake()
	{
		maxM4Reloads = ((BaseUnityPlugin)this).Config.Bind<int>("Reloads", "Total M4(Rifle) Reloads from Full Ammo Tin", 2, "If an Ammo Tin is full, this is the possible amount of reloads you can get.").Value;
		m4DrainCost = 1f / (float)maxM4Reloads;
		maxRevolverReloads = ((BaseUnityPlugin)this).Config.Bind<int>("Reloads", "Total Revolver Reloads from Full Ammo Tin", 12, "If an Ammo Tin is full, this is the possible amount of reloads you can get.").Value;
		revolverDrainCost = 1f / (float)maxRevolverReloads;
		_Harmony.PatchAll();
		((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
	}
}
[HarmonyPatch(typeof(RevolverItem))]
public class RevolverItemPatches
{
	[HarmonyPatch("ReloadedGun")]
	[HarmonyPostfix]
	public static void Postfix(RevolverItem __instance, ref bool __result)
	{
		if (__result)
		{
			return;
		}
		for (int i = 0; i < ((GrabbableObject)__instance).playerHeldBy.ItemSlots.Length; i++)
		{
			if ((Object)(object)((GrabbableObject)__instance).playerHeldBy.ItemSlots[i] != (Object)null && ((GrabbableObject)__instance).playerHeldBy.ItemSlots[i].itemProperties.itemName == "Ammo Tin" && ((GrabbableObject)__instance).playerHeldBy.ItemSlots[i].insertedBattery.charge >= ModAmmoTinPVComMain.revolverDrainCost)
			{
				Battery insertedBattery = ((GrabbableObject)__instance).playerHeldBy.ItemSlots[i].insertedBattery;
				insertedBattery.charge -= ModAmmoTinPVComMain.revolverDrainCost;
				__result = true;
				__instance.ammoSlotToUse = 100;
				break;
			}
		}
	}
}

BepInEx/plugins/americanompany/BagConfig.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BagConfig.Dependency;
using BagConfig.Patches;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using HarmonyLib.Public.Patching;
using LethalConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using LobbyCompatibility.Enums;
using LobbyCompatibility.Features;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.RuntimeDetour;
using MonoMod.Utils;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: AssemblyCompany("BagConfig")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.0.5")]
[assembly: AssemblyInformationalVersion("0.0.5-beta+e7d81f5a424d08fe51b7d90704f57c344c149b36")]
[assembly: AssemblyProduct("BagConfig")]
[assembly: AssemblyTitle("BagConfig - My Assembly Title")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.5.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BagConfig
{
	[BepInPlugin("mattymatty.BagConfig", "BagConfig", "0.0.5")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class BagConfig : BaseUnityPlugin
	{
		internal static readonly ISet<Hook> Hooks = new HashSet<Hook>();

		internal static readonly Harmony Harmony = new Harmony("mattymatty.BagConfig");

		public const string GUID = "mattymatty.BagConfig";

		public const string NAME = "BagConfig";

		public const string VERSION = "0.0.5";

		internal static ManualLogSource Log;

		public static BagConfig INSTANCE { get; private set; }

		private void Awake()
		{
			INSTANCE = this;
			Log = ((BaseUnityPlugin)this).Logger;
			try
			{
				if (LobbyCompatibilityChecker.Enabled)
				{
					LobbyCompatibilityChecker.Init();
				}
				Log.LogInfo((object)"Initializing Configs");
				PluginConfig.Init();
				Log.LogInfo((object)"Patching Methods");
				PatchLateJoin.Init();
				Harmony.PatchAll();
				BeltBagPatch.Patch();
				Log.LogInfo((object)"BagConfig v0.0.5 Loaded!");
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Exception while initializing: \n" + ex));
			}
		}
	}
	internal static class PluginConfig
	{
		public static class Misc
		{
			public static ConfigEntry<bool> Tooltip { get; internal set; }

			public static ConfigEntry<bool> DropAll { get; internal set; }

			public static ConfigEntry<bool> HideBag { get; internal set; }

			public static ConfigEntry<float> GrabRange { get; internal set; }
		}

		public static class Host
		{
			public static ConfigEntry<bool> Capacity { get; internal set; }

			public static ConfigEntry<bool> Category { get; internal set; }

			public static ConfigEntry<bool> Range { get; internal set; }
		}

		public static class Limits
		{
			public static StringDictionary ItemCategoryAssociations = new StringDictionary();

			public static readonly Dictionary<string, ICategoryConfig> CategoryConfigs = new Dictionary<string, ICategoryConfig>();

			public static ConfigEntry<int> Capacity { get; internal set; }

			public static ConfigEntry<string> ItemCategories { get; internal set; }
		}

		public interface ICategoryConfig
		{
			string CategoryName { get; }

			bool Allow { get; }

			int Limit { get; }
		}

		public class StaticCategoryConfig : ICategoryConfig
		{
			public string CategoryName { get; }

			public bool Allow { get; }

			public int Limit { get; }

			public StaticCategoryConfig(string categoryName, bool allow, int limit)
			{
				CategoryName = categoryName;
				Allow = allow;
				Limit = limit;
			}
		}

		public class BepInExCategoryConfig : ICategoryConfig
		{
			private readonly ConfigEntry<bool> _allowConfig;

			private readonly ConfigEntry<int> _limitConfig;

			public string CategoryName { get; }

			public bool Allow => _allowConfig.Value;

			public int Limit => _limitConfig.Value;

			public BepInExCategoryConfig(string categoryName, bool allow = false, int max = -1)
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Expected O, but got Unknown
				//IL_008e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0098: Expected O, but got Unknown
				CategoryName = categoryName;
				_allowConfig = ((BaseUnityPlugin)BagConfig.INSTANCE).Config.Bind<bool>("Limit." + CategoryName, "Allow", allow, new ConfigDescription("Allow grabbing this category!", (AcceptableValueBase)null, Array.Empty<object>()));
				_limitConfig = ((BaseUnityPlugin)BagConfig.INSTANCE).Config.Bind<int>("Limit." + CategoryName, "Max Amount", max, new ConfigDescription("How many items of this category can be stored at the same time?", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-1, Limits.Capacity?.Value ?? int.MaxValue), Array.Empty<object>()));
				if (LethalConfigProxy.Enabled)
				{
					LethalConfigProxy.AddConfig(_allowConfig);
					LethalConfigProxy.AddConfig(_limitConfig);
				}
			}
		}

		private const string ToolsCategory = "Tools";

		private const string DenyCategory = "Deny";

		private const string OneHandedCategory = "One Handed Scrap";

		private const string TwoHandedCategory = "Two Handed Scrap";

		internal static void Init()
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Expected O, but got Unknown
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			ConfigFile config = ((BaseUnityPlugin)BagConfig.INSTANCE).Config;
			Misc.Tooltip = config.Bind<bool>("Miscellaneous", "Tooltip", true, "Show a tooltip if the target item cannot be stored");
			Misc.DropAll = config.Bind<bool>("Miscellaneous", "Add Empty Bag Action", true, "Add action to Drop the entire bag inventory");
			Misc.HideBag = config.Bind<bool>("Miscellaneous", "Hide Bag When Pocketed", false, "Hide the bag when in pocket ( also disables opening it by looking down )");
			Misc.GrabRange = config.Bind<float>("Miscellaneous", "Grab Range", 4f, new ConfigDescription("Max range for grabbing items with the bag", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20f), Array.Empty<object>()));
			Host.Capacity = config.Bind<bool>("Host Settings", "Enforce Capacity", true, "Server-side check to limit the bag Capacity");
			Host.Category = config.Bind<bool>("Host Settings", "Enforce Restrictions", true, "Server-side check to limit the items allowed inside the Bag");
			Host.Range = config.Bind<bool>("Host Settings", "Enforce Range", true, "Server-side check to limit the grab range");
			Limits.Capacity = config.Bind<int>("Limits", "Capacity", 15, new ConfigDescription("How many items can the bag store", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, int.MaxValue), Array.Empty<object>()));
			Limits.ItemCategories = config.Bind<string>("Limits", "Item Categories", "Body: Deny", new ConfigDescription("Dictionary describing the association between a Item and a Category name", (AcceptableValueBase)null, Array.Empty<object>()));
			Limits.CategoryConfigs["Tools"] = new BepInExCategoryConfig("Tools", allow: true);
			Limits.CategoryConfigs["One Handed Scrap"] = new BepInExCategoryConfig("One Handed Scrap");
			Limits.CategoryConfigs["Two Handed Scrap"] = new BepInExCategoryConfig("Two Handed Scrap");
			Limits.CategoryConfigs["Deny"] = new StaticCategoryConfig("Deny", allow: false, 0);
			ProcessCategories(Limits.ItemCategories);
			Limits.ItemCategories.SettingChanged += delegate
			{
				ProcessCategories(Limits.ItemCategories);
			};
			if (LethalConfigProxy.Enabled)
			{
				LethalConfigProxy.AddConfig(Misc.Tooltip);
				LethalConfigProxy.AddConfig(Misc.DropAll, requiresRestart: true);
				LethalConfigProxy.AddConfig(Misc.HideBag);
				LethalConfigProxy.AddConfig(Misc.GrabRange);
				LethalConfigProxy.AddConfig(Limits.Capacity);
				LethalConfigProxy.AddConfig(Limits.ItemCategories);
				LethalConfigProxy.AddConfig(Host.Capacity);
				LethalConfigProxy.AddConfig(Host.Category);
				LethalConfigProxy.AddConfig(Host.Range);
			}
			CleanAndSave();
			static void ProcessCategories(ConfigEntry<string> entry)
			{
				Limits.ItemCategoryAssociations = ProcessDictionary(entry);
				foreach (string value3 in Limits.ItemCategoryAssociations.Values)
				{
					if (!Limits.CategoryConfigs.ContainsKey(value3))
					{
						Limits.CategoryConfigs[value3] = new BepInExCategoryConfig(value3, allow: true);
					}
				}
			}
			static StringDictionary ProcessDictionary(ConfigEntry<string> entry)
			{
				string value = entry.Value;
				StringDictionary stringDictionary = new StringDictionary();
				string[] array = value.Split(",");
				foreach (string text in array)
				{
					string text2 = text.Trim();
					string[] array2 = text2.Split(":");
					if (array2.Length != 2)
					{
						BagConfig.Log.LogError((object)("Item Association: malformed Entry! " + text2));
					}
					else
					{
						string text3 = array2[0].Trim();
						string value2 = array2[1].Trim();
						if (stringDictionary.ContainsKey(text3))
						{
							BagConfig.Log.LogWarning((object)("Item Association: " + text3 + " was already defined - overwriting!"));
						}
						stringDictionary[text3] = value2;
					}
				}
				return stringDictionary;
			}
		}

		internal static void CleanAndSave()
		{
			ConfigFile config = ((BaseUnityPlugin)BagConfig.INSTANCE).Config;
			PropertyInfo propertyInfo = AccessTools.Property(((object)config).GetType(), "OrphanedEntries");
			Dictionary<ConfigDefinition, string> dictionary = (Dictionary<ConfigDefinition, string>)propertyInfo.GetValue(config, null);
			dictionary.Clear();
			config.Save();
		}

		public static ICategoryConfig GetBagCategory(this GrabbableObject grabbable)
		{
			if (Limits.ItemCategoryAssociations.ContainsKey(grabbable.itemProperties.itemName))
			{
				return Limits.CategoryConfigs[Limits.ItemCategoryAssociations[grabbable.itemProperties.itemName]];
			}
			bool isScrap = grabbable.itemProperties.isScrap;
			bool twoHanded = grabbable.itemProperties.twoHanded;
			if (!isScrap)
			{
				return Limits.CategoryConfigs["Tools"];
			}
			if (!twoHanded)
			{
				return Limits.CategoryConfigs["One Handed Scrap"];
			}
			return Limits.CategoryConfigs["Two Handed Scrap"];
		}
	}
	public static class Utils
	{
		private static readonly MethodInfo BeginSendClientRpc = AccessTools.Method(typeof(NetworkBehaviour), "__beginSendClientRpc", (Type[])null, (Type[])null);

		private static readonly MethodInfo BeginSendServerRpc = AccessTools.Method(typeof(NetworkBehaviour), "__beginSendServerRpc", (Type[])null, (Type[])null);

		internal static bool TryGetRpcID(MethodInfo methodInfo, out uint rpcID)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			Collection<Instruction> instructions = PatchManager.GetMethodPatcher((MethodBase)methodInfo).CopyOriginal().Definition.Body.Instructions;
			rpcID = 0u;
			for (int i = 0; i < instructions.Count; i++)
			{
				if (instructions[i].OpCode == OpCodes.Ldc_I4 && instructions[i - 1].OpCode == OpCodes.Ldarg_0)
				{
					rpcID = (uint)(int)instructions[i].Operand;
				}
				if (!(instructions[i].OpCode != OpCodes.Call))
				{
					object operand = instructions[i].Operand;
					MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null);
					if (val != null && (Extensions.Is((MemberReference)(object)val, (MemberInfo)BeginSendClientRpc) || Extensions.Is((MemberReference)(object)val, (MemberInfo)BeginSendServerRpc)))
					{
						BagConfig.Log.LogDebug((object)$"Rpc Id found for {methodInfo.Name}: {rpcID}U");
						return true;
					}
				}
			}
			BagConfig.Log.LogFatal((object)("Cannot find Rpc ID for " + methodInfo.Name));
			return false;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "mattymatty.BagConfig";

		public const string PLUGIN_NAME = "BagConfig";

		public const string PLUGIN_VERSION = "0.0.5";
	}
}
namespace BagConfig.Patches
{
	[HarmonyPatch]
	internal static class BeltBagPatch
	{
		private class CategoryCount
		{
			public int Count;
		}

		private static readonly Action<GrabbableObject, bool> BaseInteractMethod;

		private static readonly ConditionalWeakTable<BeltBagItem, ConditionalWeakTable<PluginConfig.ICategoryConfig, CategoryCount>> CategoryMemory;

		internal static void Patch()
		{
			//IL_0037: 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)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(BeltBagItem), "ItemInteractLeftRight", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(BeltBagPatch), "OverrideGrab", (Type[])null, (Type[])null);
			BagConfig.Hooks.Add(new Hook((MethodBase)methodInfo, methodInfo2, new HookConfig
			{
				Priority = -999
			}));
		}

		static BeltBagPatch()
		{
			CategoryMemory = new ConditionalWeakTable<BeltBagItem, ConditionalWeakTable<PluginConfig.ICategoryConfig, CategoryCount>>();
			MethodInfo meth = AccessTools.Method(typeof(GrabbableObject), "ItemInteractLeftRight", (Type[])null, (Type[])null);
			DynamicMethod dynamicMethod = new DynamicMethod("Base.ItemInteractLeftRight", null, new Type[2]
			{
				typeof(GrabbableObject),
				typeof(bool)
			}, typeof(BeltBagItem));
			ILGenerator iLGenerator = dynamicMethod.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Call, meth);
			iLGenerator.Emit(OpCodes.Ret);
			BaseInteractMethod = (Action<GrabbableObject, bool>)dynamicMethod.CreateDelegate(typeof(Action<GrabbableObject, bool>));
		}

		private static IEnumerator EmptyBagCoroutine(BeltBagItem @this)
		{
			while (@this.objectsInBag.Count > 0)
			{
				@this.RemoveObjectFromBag(0);
				yield return (object)new WaitForEndOfFrame();
			}
		}

		private static void OverrideGrab(Action<BeltBagItem, bool> orig, BeltBagItem @this, bool right)
		{
			//IL_0090: 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)
			BaseInteractMethod((GrabbableObject)(object)@this, right);
			if (right)
			{
				if (PluginConfig.Misc.DropAll.Value)
				{
					((MonoBehaviour)@this).StartCoroutine(EmptyBagCoroutine(@this));
				}
			}
			else
			{
				if ((Object)(object)((GrabbableObject)@this).playerHeldBy == (Object)null || @this.tryingAddToBag)
				{
					return;
				}
				if (@this.objectsInBag.Count >= PluginConfig.Limits.Capacity.Value)
				{
					if (PluginConfig.Misc.Tooltip.Value)
					{
						HUDManager.Instance.DisplayTip("Belt bag Info", "This bag is Full!", false, false, "LC_Tip1");
					}
				}
				else
				{
					RaycastHit val = default(RaycastHit);
					if (!Physics.Raycast(((Component)((GrabbableObject)@this).playerHeldBy.gameplayCamera).transform.position, ((Component)((GrabbableObject)@this).playerHeldBy.gameplayCamera).transform.forward, ref val, PluginConfig.Misc.GrabRange.Value, GameNetworkManager.Instance.localPlayerController.interactableObjectsMask))
					{
						return;
					}
					ManualLogSource log = BagConfig.Log;
					Transform parent = ((Component)((RaycastHit)(ref val)).collider).transform.parent;
					log.LogDebug((object)("Grab Hit: " + ((parent != null) ? ((Object)parent).name : null) + "." + ((Object)((Component)((RaycastHit)(ref val)).collider).gameObject).name));
					if (((Component)((RaycastHit)(ref val)).collider).gameObject.layer == 8 || ((Component)((RaycastHit)(ref val)).collider).tag != "PhysicsProp")
					{
						return;
					}
					GrabbableObject component = ((Component)((RaycastHit)(ref val)).collider).gameObject.GetComponent<GrabbableObject>();
					if (!@this.CanBePutInBag(component))
					{
						return;
					}
					if (@this.CheckBagFilters(component, out var limited, out var disallowed))
					{
						@this.TryAddObjectToBag(component);
					}
					else if (PluginConfig.Misc.Tooltip.Value)
					{
						if (!disallowed && limited)
						{
							PluginConfig.ICategoryConfig bagCategory = component.GetBagCategory();
							HUDManager.Instance.DisplayTip("Belt bag Info", "Cannot store any more " + bagCategory.CategoryName + " inside of the bag!", false, false, "LC_Tip1");
						}
						else
						{
							HUDManager.Instance.DisplayTip("Belt bag Info", "Cannot store " + component.itemProperties.itemName + " inside of the bag!", false, false, "LC_Tip1");
						}
					}
				}
			}
		}

		private static bool CanBePutInBag(this BeltBagItem @this, GrabbableObject grabbable)
		{
			if (Object.op_Implicit((Object)(object)grabbable) && (Object)(object)grabbable != (Object)(object)@this && !grabbable.isHeld && !grabbable.isHeldByEnemy)
			{
				return grabbable.itemProperties.itemId != 123984;
			}
			return false;
		}

		private static bool CheckBagFilters(this BeltBagItem @this, GrabbableObject grabbable, out bool limited, out bool disallowed)
		{
			limited = false;
			PluginConfig.ICategoryConfig bagCategory = grabbable.GetBagCategory();
			disallowed = !bagCategory.Allow;
			int limit = bagCategory.Limit;
			if (limit < 0)
			{
				return !disallowed;
			}
			if (limit == 0)
			{
				limited = true;
				return false;
			}
			ConditionalWeakTable<PluginConfig.ICategoryConfig, CategoryCount> orCreateValue = CategoryMemory.GetOrCreateValue(@this);
			if (orCreateValue.TryGetValue(bagCategory, out var value) && value.Count >= limit)
			{
				limited = true;
				return false;
			}
			return !disallowed;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(StartOfRound), "Start")]
		private static void AddBagTooltip(StartOfRound __instance)
		{
			if (!PluginConfig.Misc.DropAll.Value)
			{
				return;
			}
			BeltBagItem val = default(BeltBagItem);
			foreach (Item items in __instance.allItemsList.itemsList)
			{
				if (Object.op_Implicit((Object)(object)items.spawnPrefab) && items.spawnPrefab.TryGetComponent<BeltBagItem>(ref val))
				{
					Array.Resize(ref items.toolTips, items.toolTips.Length + 1);
					items.toolTips[^1] = "Empty Bag: [E]";
					break;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BeltBagItem), "PutObjectInBagLocalClient")]
		private static void TriggerHeldActions(BeltBagItem __instance, GrabbableObject gObject)
		{
			LungProp val = (LungProp)(object)((gObject is LungProp) ? gObject : null);
			if (val != null)
			{
				if (val.isLungDocked)
				{
					val.isLungDocked = false;
					if (val.disconnectAnimation != null)
					{
						((MonoBehaviour)val).StopCoroutine(val.disconnectAnimation);
					}
					val.disconnectAnimation = ((MonoBehaviour)val).StartCoroutine(val.DisconnectFromMachinery());
				}
				if (val.isLungDockedInElevator)
				{
					val.isLungDockedInElevator = false;
					((Component)val).gameObject.GetComponent<AudioSource>().PlayOneShot(val.disconnectSFX);
				}
			}
			if (!((GrabbableObject)__instance).hasBeenHeld)
			{
				((GrabbableObject)__instance).hasBeenHeld = true;
				if (!((GrabbableObject)__instance).isInShipRoom && !StartOfRound.Instance.inShipPhase && StartOfRound.Instance.currentLevel.spawnEnemiesAndScrap)
				{
					RoundManager instance = RoundManager.Instance;
					instance.valueOfFoundScrapItems += ((GrabbableObject)__instance).scrapValue;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BeltBagItem), "PutObjectInBagLocalClient")]
		private static void TrackAdd(BeltBagItem __instance, GrabbableObject gObject)
		{
			PluginConfig.ICategoryConfig bagCategory = gObject.GetBagCategory();
			ConditionalWeakTable<PluginConfig.ICategoryConfig, CategoryCount> orCreateValue = CategoryMemory.GetOrCreateValue(__instance);
			orCreateValue.GetOrCreateValue(bagCategory).Count++;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BeltBagItem), "RemoveFromBagLocalClientNonElevatorParent")]
		[HarmonyPatch(typeof(BeltBagItem), "RemoveFromBagLocalClient")]
		private static void TrackRemove(BeltBagItem __instance, NetworkObjectReference objectRef)
		{
			ConditionalWeakTable<PluginConfig.ICategoryConfig, CategoryCount> orCreateValue = CategoryMemory.GetOrCreateValue(__instance);
			NetworkObject val = default(NetworkObject);
			GrabbableObject grabbable = default(GrabbableObject);
			if (((NetworkObjectReference)(ref objectRef)).TryGet(ref val, (NetworkManager)null) && ((Component)val).TryGetComponent<GrabbableObject>(ref grabbable))
			{
				PluginConfig.ICategoryConfig bagCategory = grabbable.GetBagCategory();
				orCreateValue.GetOrCreateValue(bagCategory).Count--;
			}
			if (__instance.objectsInBag.Count == 0)
			{
				orCreateValue.Clear();
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(BeltBagItem), "TryAddObjectToBagServerRpc")]
		private static bool EnforceLimits(BeltBagItem __instance, NetworkObjectReference netObjectRef, int playerWhoAdded)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening)
			{
				return true;
			}
			if ((int)((NetworkBehaviour)__instance).__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return true;
			}
			NetworkObject val = default(NetworkObject);
			if (!((NetworkObjectReference)(ref netObjectRef)).TryGet(ref val, (NetworkManager)null))
			{
				return true;
			}
			GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
			if (!__instance.CanBePutInBag(component))
			{
				__instance.CancelAddObjectToBagClientRpc(playerWhoAdded);
				return false;
			}
			if (PluginConfig.Host.Capacity.Value && __instance.objectsInBag.Count >= PluginConfig.Limits.Capacity.Value)
			{
				__instance.CancelAddObjectToBagClientRpc(playerWhoAdded);
				return false;
			}
			if (PluginConfig.Host.Category.Value && !__instance.CheckBagFilters(component, out var _, out var _))
			{
				__instance.CancelAddObjectToBagClientRpc(playerWhoAdded);
				return false;
			}
			if (PluginConfig.Host.Range.Value)
			{
				Vector3 position = ((Component)component).transform.position;
				PlayerControllerB playerHeldBy = ((GrabbableObject)__instance).playerHeldBy;
				if (Vector3.Distance(position, (playerHeldBy != null) ? ((Component)playerHeldBy.gameplayCamera).transform.position : Vector3.positiveInfinity) > PluginConfig.Misc.GrabRange.Value)
				{
					__instance.CancelAddObjectToBagClientRpc(playerWhoAdded);
					return false;
				}
			}
			return true;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BeltBagItem), "CancelAddObjectToBagClientRpc")]
		private static void OnServerRefusal(int playerWhoAdded)
		{
			if (!((Object)(object)StartOfRound.Instance.allPlayerScripts[playerWhoAdded] != (Object)(object)GameNetworkManager.Instance.localPlayerController))
			{
				HUDManager.Instance.DisplayTip("Belt bag Info", "Host refused your grab request!", true, false, "LC_Tip1");
			}
		}

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(BeltBagItem), "RemoveObjectFromBag")]
		private static IEnumerable<CodeInstruction> FixDrop(IEnumerable<CodeInstruction> instructions, ILGenerator ilGenerator)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Expected O, but got Unknown
			List<CodeInstruction> list = instructions.ToList();
			MethodInfo methodInfo = AccessTools.Method(typeof(GrabbableObject), "GetItemFloorPosition", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(BeltBagPatch), "FixVerticalOffset", (Type[])null, (Type[])null);
			CodeMatcher val = new CodeMatcher((IEnumerable<CodeInstruction>)list, ilGenerator);
			val.MatchForward(true, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)methodInfo, (string)null)
			});
			if (val.IsInvalid)
			{
				BagConfig.Log.LogError((object)"Patch RemoveObjectFromBag, Fail - 1 ");
				return list;
			}
			val.Advance(1);
			val.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Ldarg_0, (object)null)
			});
			val.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Ldarg_1, (object)null)
			});
			val.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Call, (object)methodInfo2)
			});
			return val.Instructions();
		}

		private static Vector3 FixVerticalOffset(Vector3 position, BeltBagItem beltBagItem, int index)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (beltBagItem.objectsInBag.Count <= index)
			{
				return position;
			}
			GrabbableObject val = beltBagItem.objectsInBag[index];
			if (!Object.op_Implicit((Object)(object)val))
			{
				return position;
			}
			position += Vector3.down * ((GrabbableObject)beltBagItem).itemProperties.verticalOffset;
			position += Vector3.up * val.itemProperties.verticalOffset;
			return position;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BeltBagItem), "PocketItem")]
		private static void HideWhenInPocket(BeltBagItem __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && PluginConfig.Misc.HideBag.Value)
			{
				((Component)__instance.useBagTrigger).GetComponent<Collider>().enabled = false;
				((GrabbableObject)__instance).EnableItemMeshes(false);
			}
		}
	}
	internal static class PatchLateJoin
	{
		private static uint _tryAddObjectToBagClientRpc;

		internal static void Init()
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(BeltBagItem), "TryAddObjectToBagClientRpc", (Type[])null, (Type[])null);
			if (!Utils.TryGetRpcID(methodInfo, out _tryAddObjectToBagClientRpc))
			{
				throw new MissingMemberException("BeltBagItem", "TryAddObjectToBagClientRpc");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "SyncAlreadyHeldObjectsClientRpc")]
		private static void SyncItemsInBags(StartOfRound __instance, NetworkObjectReference[] gObjects, int joiningClientId)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			//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_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening || (int)((NetworkBehaviour)__instance).__rpc_exec_stage == 2 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			NetworkObject val2 = default(NetworkObject);
			BeltBagItem val3 = default(BeltBagItem);
			for (int i = 0; i < gObjects.Length; i++)
			{
				NetworkObjectReference val = gObjects[i];
				if (!((NetworkObjectReference)(ref val)).TryGet(ref val2, (NetworkManager)null) || !((Component)val2).TryGetComponent<BeltBagItem>(ref val3))
				{
					continue;
				}
				foreach (GrabbableObject item in val3.objectsInBag)
				{
					NetworkObjectReference val4 = NetworkObjectReference.op_Implicit(((NetworkBehaviour)item).NetworkObject);
					ClientRpcParams val5 = default(ClientRpcParams);
					val5.Send = new ClientRpcSendParams
					{
						TargetClientIds = new <>z__ReadOnlyArray<ulong>(new ulong[1] { (ulong)joiningClientId })
					};
					ClientRpcParams val6 = val5;
					FastBufferWriter val7 = ((NetworkBehaviour)val3).__beginSendClientRpc(_tryAddObjectToBagClientRpc, val6, (RpcDelivery)0);
					((FastBufferWriter)(ref val7)).WriteValueSafe<NetworkObjectReference>(ref val4, default(ForNetworkSerializable));
					BytePacker.WriteValueBitPacked(val7, ((GrabbableObject)val3).playerHeldBy.actualClientId);
					((NetworkBehaviour)val3).__endSendClientRpc(ref val7, _tryAddObjectToBagClientRpc, val6, (RpcDelivery)0);
				}
			}
		}
	}
}
namespace BagConfig.Dependency
{
	public static class LethalConfigProxy
	{
		private static bool? _enabled;

		public static bool Enabled
		{
			get
			{
				bool valueOrDefault = _enabled.GetValueOrDefault();
				if (!_enabled.HasValue)
				{
					valueOrDefault = Chainloader.PluginInfos.ContainsKey("ainavt.lc.lethalconfig");
					_enabled = valueOrDefault;
				}
				return _enabled.Value;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void AddConfig(ConfigEntry<string> entry, bool requiresRestart = false)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			LethalConfigManager.AddConfigItem((BaseConfigItem)new TextInputFieldConfigItem(entry, new TextInputFieldOptions
			{
				RequiresRestart = requiresRestart
			}));
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void AddConfig(ConfigEntry<bool> entry, bool requiresRestart = false)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(entry, new BoolCheckBoxOptions
			{
				RequiresRestart = requiresRestart
			}));
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void AddConfig(ConfigEntry<float> entry, bool requiresRestart = false)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(entry, new FloatInputFieldOptions
			{
				RequiresRestart = requiresRestart
			}));
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void AddConfig(ConfigEntry<int> entry, bool requiresRestart = false)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			LethalConfigManager.AddConfigItem((BaseConfigItem)new IntInputFieldConfigItem(entry, new IntInputFieldOptions
			{
				RequiresRestart = requiresRestart
			}));
		}
	}
	public static class LobbyCompatibilityChecker
	{
		private static bool? _enabled;

		public static bool Enabled
		{
			get
			{
				bool valueOrDefault = _enabled.GetValueOrDefault();
				if (!_enabled.HasValue)
				{
					valueOrDefault = Chainloader.PluginInfos.ContainsKey("BMX.LobbyCompatibility");
					_enabled = valueOrDefault;
				}
				return _enabled.Value;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void Init()
		{
			PluginHelper.RegisterPlugin("mattymatty.BagConfig", Version.Parse("0.0.5"), (CompatibilityLevel)0, (VersionStrictness)2);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T>
{
	int ICollection.Count => _items.Length;

	bool ICollection.IsSynchronized => false;

	object ICollection.SyncRoot => this;

	object IList.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	bool IList.IsFixedSize => true;

	bool IList.IsReadOnly => true;

	int IReadOnlyCollection<T>.Count => _items.Length;

	T IReadOnlyList<T>.this[int index] => _items[index];

	int ICollection<T>.Count => _items.Length;

	bool ICollection<T>.IsReadOnly => true;

	T IList<T>.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	public <>z__ReadOnlyArray(T[] items)
	{
		_items = items;
	}

	IEnumerator IEnumerable.GetEnumerator()
	{
		return ((IEnumerable)_items).GetEnumerator();
	}

	void ICollection.CopyTo(Array array, int index)
	{
		((ICollection)_items).CopyTo(array, index);
	}

	int IList.Add(object value)
	{
		throw new NotSupportedException();
	}

	void IList.Clear()
	{
		throw new NotSupportedException();
	}

	bool IList.Contains(object value)
	{
		return ((IList)_items).Contains(value);
	}

	int IList.IndexOf(object value)
	{
		return ((IList)_items).IndexOf(value);
	}

	void IList.Insert(int index, object value)
	{
		throw new NotSupportedException();
	}

	void IList.Remove(object value)
	{
		throw new NotSupportedException();
	}

	void IList.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}

	IEnumerator<T> IEnumerable<T>.GetEnumerator()
	{
		return ((IEnumerable<T>)_items).GetEnumerator();
	}

	void ICollection<T>.Add(T item)
	{
		throw new NotSupportedException();
	}

	void ICollection<T>.Clear()
	{
		throw new NotSupportedException();
	}

	bool ICollection<T>.Contains(T item)
	{
		return ((ICollection<T>)_items).Contains(item);
	}

	void ICollection<T>.CopyTo(T[] array, int arrayIndex)
	{
		((ICollection<T>)_items).CopyTo(array, arrayIndex);
	}

	bool ICollection<T>.Remove(T item)
	{
		throw new NotSupportedException();
	}

	int IList<T>.IndexOf(T item)
	{
		return ((IList<T>)_items).IndexOf(item);
	}

	void IList<T>.Insert(int index, T item)
	{
		throw new NotSupportedException();
	}

	void IList<T>.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}
}

BepInEx/plugins/americanompany/BuyableShotgunPlus.dll

Decompiled 2 years ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BuyableShotgun.Config;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BuyableShotgunPlus
{
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "BuyableShotgunPlus";

		public const string PLUGIN_NAME = "BuyableShotgunPlus";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace BuyableShotgun
{
	[BepInPlugin("Entity378.BuyableShotgunPlus", "BuyableShotgunPlus", "1.2.1")]
	[BepInDependency("evaisa.lethallib", "0.14.2")]
	public class Plugin : BaseUnityPlugin
	{
		private const string GUID = "Entity378.BuyableShotgunPlus";

		private const string NAME = "BuyableShotgunPlus";

		private const string VERSION = "1.2.1";

		private Harmony harmony = new Harmony("Entity378.BuyableShotgunPlus");

		public static Item ShotgunItem;

		public static Item ShotgunShellItem;

		private void Awake()
		{
			BuyableShotgunConfigs.LoadConfig(((BaseUnityPlugin)this).Config);
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"BuyableShotgunPlus Log: Config loaded");
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "shotgun");
			AssetBundle val = AssetBundle.LoadFromFile(text);
			ShotgunItem = val.LoadAsset<Item>("Assets/LethalCompany/SHOTGUN/ShotgunItem.asset");
			ShotgunShellItem = val.LoadAsset<Item>("Assets/LethalCompany/SHOTGUN/ShotgunShellItem.asset");
			NetworkPrefabs.RegisterNetworkPrefab(ShotgunItem.spawnPrefab);
			Utilities.FixMixerGroups(ShotgunItem.spawnPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(ShotgunShellItem.spawnPrefab);
			Utilities.FixMixerGroups(ShotgunShellItem.spawnPrefab);
		}
	}
}
namespace BuyableShotgun.Patch
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class ShotgunPatcher
	{
		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		private static void PatchAwake(StartOfRound __instance)
		{
			if (BuyableShotgunConfigs.EnableBuyableShotgun)
			{
				Items.RegisterShopItem(Plugin.ShotgunItem, (TerminalNode)null, (TerminalNode)null, CreateInfoNode("Shotgun+", "Nutcracker's Shotgun. Can hold 2 shells. Recommended to keep safety on while not using or it might shoot randomly."), BuyableShotgunConfigs.ShotgunPrice);
			}
			if (BuyableShotgunConfigs.EnableBuyableShotgunShell)
			{
				Items.RegisterShopItem(Plugin.ShotgunShellItem, (TerminalNode)null, (TerminalNode)null, CreateInfoNode("ShotgunShell+", "Ammo for the Nutcracker's Shotgun."), BuyableShotgunConfigs.ShotgunShellPrice);
			}
		}

		private static TerminalNode CreateInfoNode(string name, string description)
		{
			TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
			val.clearPreviousText = true;
			((Object)val).name = name;
			val.displayText = description + "\n\n";
			return val;
		}
	}
}
namespace BuyableShotgun.Config
{
	internal class BuyableShotgunConfigs
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnRequestSync;

			public static HandleNamedMessageDelegate <1>__OnReceiveSync;
		}

		private const int byteDimInt = 4;

		private const int byteDimBool = 1;

		private const int byteDimConfig = 11;

		private static int ShotgunPriceLocal = 666;

		private static int ShotgunShellPriceLocal = 20;

		private static bool EnableBuyableShotgunLocal = true;

		private static bool EnableBuyableShotgunShellLocal = true;

		public static int ShotgunPrice = 666;

		public static int ShotgunShellPrice = 20;

		public static bool EnableBuyableShotgun = true;

		public static bool EnableBuyableShotgunShell = true;

		private static void SetValues(int PriceShotgun, int PriceShotgunShell, bool EnableShotgun, bool EnableShotgunShell)
		{
			ShotgunPrice = PriceShotgun;
			ShotgunShellPrice = PriceShotgunShell;
			EnableBuyableShotgun = EnableShotgun;
			EnableBuyableShotgunShell = EnableShotgunShell;
		}

		private static void SetToLocalValues()
		{
			SetValues(ShotgunPriceLocal, ShotgunShellPriceLocal, EnableBuyableShotgunLocal, EnableBuyableShotgunShellLocal);
		}

		public static void LoadConfig(ConfigFile config)
		{
			ShotgunPriceLocal = config.Bind<int>("General", "ShotgunPrice", 666, (ConfigDescription)null).Value;
			ShotgunShellPriceLocal = config.Bind<int>("General", "ShotgunShellPrice", 20, (ConfigDescription)null).Value;
			EnableBuyableShotgunLocal = config.Bind<bool>("General", "EnableBuyableShotgun", true, (ConfigDescription)null).Value;
			EnableBuyableShotgunShellLocal = config.Bind<bool>("General", "EnableBuyableShotgunShell", true, (ConfigDescription)null).Value;
			SetToLocalValues();
		}

		public static byte[] GetSettings()
		{
			byte[] array = new byte[11]
			{
				1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
				0
			};
			Array.Copy(BitConverter.GetBytes(ShotgunPriceLocal), 0, array, 1, 4);
			Array.Copy(BitConverter.GetBytes(ShotgunShellPriceLocal), 0, array, 5, 4);
			Array.Copy(BitConverter.GetBytes(EnableBuyableShotgunLocal), 0, array, 9, 1);
			Array.Copy(BitConverter.GetBytes(EnableBuyableShotgunShellLocal), 0, array, 10, 1);
			return array;
		}

		public static void SetSettings(byte[] data)
		{
			byte b = data[0];
			byte b2 = b;
			if (b2 == 1)
			{
				ShotgunPrice = BitConverter.ToInt32(data, 1);
				ShotgunShellPrice = BitConverter.ToInt32(data, 5);
				EnableBuyableShotgun = BitConverter.ToBoolean(data, 9);
				EnableBuyableShotgunShell = BitConverter.ToBoolean(data, 10);
				Debug.Log((object)"BuyableShotgunPlus Log: Host config set successfully");
				return;
			}
			throw new Exception("BuyableShotgunPlus Log: Invalid version byte");
		}

		private static bool IsHost()
		{
			return NetworkManager.Singleton.IsHost;
		}

		public static void OnRequestSync(ulong clientID, FastBufferReader reader)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			if (!IsHost())
			{
				return;
			}
			Debug.Log((object)("BuyableShotgunPlus Log: Sending config to client " + clientID));
			byte[] settings = GetSettings();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(settings.Length, (Allocator)2, settings.Length);
			try
			{
				((FastBufferWriter)(ref val)).WriteBytes(settings, -1, 0);
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("BuyableShotgun_OnReceiveConfigSync", clientID, val, (NetworkDelivery)2);
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("BuyableShotgunPlus Log: Failed to send config: " + ex));
			}
			finally
			{
				((FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnReceiveSync(ulong clientID, FastBufferReader reader)
		{
			Debug.Log((object)"BuyableShotgunPlus Log: Received config from host");
			byte[] settings = new byte[11];
			try
			{
				((FastBufferReader)(ref reader)).ReadBytes(ref settings, 11, 0);
				SetSettings(settings);
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("BuyableShotgunPlus Log: Failed to receive config: " + ex));
				SetToLocalValues();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		private static void ServerConnect()
		{
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			//IL_003b: 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: Expected O, but got Unknown
			if (IsHost())
			{
				Debug.Log((object)"BuyableShotgunPlus Log: Started hosting, using local settings");
				SetToLocalValues();
				CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
				object obj = <>O.<0>__OnRequestSync;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = OnRequestSync;
					<>O.<0>__OnRequestSync = val;
					obj = (object)val;
				}
				customMessagingManager.RegisterNamedMessageHandler("BuyableShotgun_OnRequestConfigSync", (HandleNamedMessageDelegate)obj);
				return;
			}
			Debug.Log((object)"BuyableShotgunPlus Log: Connected to server, requesting settings");
			CustomMessagingManager customMessagingManager2 = NetworkManager.Singleton.CustomMessagingManager;
			object obj2 = <>O.<1>__OnReceiveSync;
			if (obj2 == null)
			{
				HandleNamedMessageDelegate val2 = OnReceiveSync;
				<>O.<1>__OnReceiveSync = val2;
				obj2 = (object)val2;
			}
			customMessagingManager2.RegisterNamedMessageHandler("BuyableShotgun_OnReceiveConfigSync", (HandleNamedMessageDelegate)obj2);
			FastBufferWriter val3 = default(FastBufferWriter);
			((FastBufferWriter)(ref val3))..ctor(0, (Allocator)2, -1);
			NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("BuyableShotgun_OnRequestConfigSync", 0uL, val3, (NetworkDelivery)2);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		private static void ServerDisconnect()
		{
			Debug.Log((object)"BuyableShotgunPlus Log: Server disconnect");
			SetToLocalValues();
		}
	}
}

BepInEx/plugins/americanompany/com.ctnoriginals.crosshair.dll

Decompiled 2 years ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
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 CrossHair.Utilities;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[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("com.ctnoriginals.crosshair")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Adds a CrossHair to the center of your screen to indicate where you are aiming.")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1")]
[assembly: AssemblyProduct("CrossHair")]
[assembly: AssemblyTitle("com.ctnoriginals.crosshair")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CrossHair
{
	[BepInPlugin("com.ctnoriginals.crosshair", "CrossHair", "1.1.1")]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("com.ctnoriginals.crosshair");

		public static ConfigFile Config = new ConfigFile(Paths.ConfigPath + "\\com.ctnoriginals.crosshair.cfg", true);

		public static ConfigEntry<string> CrossHairText;

		public static ConfigEntry<float> CrossHairSize;

		public static ConfigEntry<bool> CrossHairShadow;

		public static ConfigEntry<string> CrossHairColor;

		public static ConfigEntry<int> CrossHairOpacity;

		public static ConfigEntry<bool> CrossHairFading;

		public static ManualLogSource CLog;

		public static bool DebugMode = false;

		private void Awake()
		{
			CLog = ((BaseUnityPlugin)this).Logger;
			CLog.LogInfo((object)("Plugin com.ctnoriginals.crosshair is loaded! Version: 1.1.1 (" + (DebugMode ? "Debug" : "Release") + ")"));
			ConfigFile();
			harmony.PatchAll();
		}

		private void ConfigFile()
		{
			CrossHairText = Config.Bind<string>("!General", "CrossHairText", "-  +  -", "Text to display as crosshair (use \\n for new line)");
			CrossHairSize = Config.Bind<float>("!General", "CrossHairSize", 50f, "Size of the crosshair");
			CrossHairShadow = Config.Bind<bool>("!General", "CrossHairShadow", true, "Whether to display a shadow behind the crosshair");
			CrossHairColor = Config.Bind<string>("Appearance", "CrossHairColor", "ffffff", "Color of the crosshair in hexadecimal (Do not include the #)");
			CrossHairOpacity = Config.Bind<int>("Appearance", "CrossHairOpacity", 80, "Opacity of the crosshair (0 to 100)%");
			CrossHairFading = Config.Bind<bool>("Appearance", "CrossHairFading", true, "Whether the crosshair should fade in and out in specific situations");
			CrossHair.Utilities.Console.LogMessage("CrossHairText: " + CrossHairText.Value);
			CrossHair.Utilities.Console.LogMessage($"CrossHairSize: {CrossHairSize.Value}");
			CrossHair.Utilities.Console.LogMessage($"CrossHairShadow: {CrossHairShadow.Value}");
			CrossHair.Utilities.Console.LogMessage("CrossHairColor: " + CrossHairColor.Value);
			CrossHair.Utilities.Console.LogMessage($"CrossHairOpacity: {CrossHairOpacity.Value}");
			CrossHair.Utilities.Console.LogMessage($"CrossHairFading: {CrossHairFading.Value}");
			Config.Save();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "com.ctnoriginals.crosshair";

		public const string PLUGIN_NAME = "CrossHair";

		public const string PLUGIN_VERSION = "1.1.1";
	}
}
namespace CrossHair.Utilities
{
	public static class Console
	{
		public static void Log(string message)
		{
			SendLog(message, "Log");
		}

		public static void LogInfo(string message)
		{
			SendLog(message, "LogInfo");
		}

		public static void LogError(string message)
		{
			SendLog(message, "LogError");
		}

		public static void LogWarning(string message)
		{
			SendLog(message, "LogWarning");
		}

		public static void LogDebug(string message)
		{
			SendLog(message, "LogDebug");
		}

		public static void LogFatal(string message)
		{
			SendLog(message, "LogFatal");
		}

		public static void LogMessage(string message)
		{
			SendLog(message, "LogMessage");
		}

		private static void SendLog(string message, string level = null)
		{
			if (!Plugin.DebugMode && (level == "LogDebug" || level == "LogInfo"))
			{
				return;
			}
			switch (level)
			{
			case "LogInfo":
				Plugin.CLog.LogInfo((object)message);
				return;
			case "LogError":
				Plugin.CLog.LogError((object)message);
				return;
			case "LogWarning":
				Plugin.CLog.LogWarning((object)message);
				return;
			case "LogDebug":
				Plugin.CLog.LogDebug((object)message);
				return;
			case "LogFatal":
				Plugin.CLog.LogFatal((object)message);
				return;
			case "LogMessage":
				Plugin.CLog.LogMessage((object)message);
				return;
			}
			if (level != "Log")
			{
				Debug.Log((object)("[" + level + "]: " + message));
			}
			else
			{
				Debug.Log((object)message);
			}
		}
	}
	public class PrivateFieldAccessor<InstanceType>
	{
		private FieldInfo _field;

		private object _instance;

		public PrivateFieldAccessor(object instance, string fieldname)
		{
			_field = typeof(InstanceType).GetField(fieldname, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			_instance = instance;
		}

		public T Get<T>()
		{
			return Utils.GetInstanceField<T>(_instance, _field.Name);
		}

		public void Set<T>(T value)
		{
			_field.SetValue(_instance, value);
		}
	}
	internal static class Utils
	{
		public static T GetInstanceField<T>(object instance, string fieldName)
		{
			BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
			return (T)instance.GetType().GetField(fieldName, bindingAttr).GetValue(instance);
		}
	}
}
namespace CrossHair.Patches
{
	[HarmonyPatch(typeof(HUDManager))]
	internal class HUDManagerPatch
	{
		public static Transform CrossHair;

		public static TextMeshProUGUI CrossHairTMP;

		public static float CrossHairAlpha = 200f;

		public static Transform CrossHairShadow;

		public static float CrossHairShadowAlpha = 100f;

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void Start(ref HUDManager __instance)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: 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_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			CrossHair = ((TMP_Text)Object.Instantiate<TextMeshProUGUI>(new GameObject().AddComponent<TextMeshProUGUI>())).transform;
			global::CrossHair.Utilities.Console.LogDebug(((Object)CrossHair).name ?? "");
			((Object)CrossHair).name = "CrossHair";
			Transform transform = ((Component)((Component)__instance.PTTIcon).transform.parent.parent.parent.Find("PlayerCursor").Find("Cursor")).transform;
			CrossHairTMP = ((Component)CrossHair).GetComponent<TextMeshProUGUI>();
			RectTransform rectTransform = ((TMP_Text)CrossHairTMP).rectTransform;
			((Transform)rectTransform).SetParent(transform, false);
			rectTransform.anchoredPosition = new Vector2(0f, 0f);
			((Transform)rectTransform).localPosition = new Vector3(0f, 0f, 0f);
			rectTransform.offsetMin = new Vector2(-500f, -500f);
			rectTransform.offsetMax = new Vector2(500f, 500f);
			string text = Plugin.CrossHairColor.Value;
			if (text.Length != 6)
			{
				text = HexFormatException("character amount: \"" + text + "\"");
			}
			int num = 16777215;
			try
			{
				num = int.Parse(text.Replace("#", ""), NumberStyles.HexNumber);
			}
			catch (FormatException)
			{
				num = int.Parse(HexFormatException("color: \"" + text + "\""), NumberStyles.HexNumber);
			}
			Color color = Color.FromArgb(num);
			CrossHairAlpha = (int)(byte)(Plugin.CrossHairOpacity.Value * 255 / 100);
			CrossHairShadowAlpha = (int)(byte)(CrossHairAlpha * 50f / 100f);
			((TMP_Text)CrossHairTMP).text = Plugin.CrossHairText.Value;
			((TMP_Text)CrossHairTMP).fontSize = Plugin.CrossHairSize.Value;
			((Graphic)CrossHairTMP).color = Color32.op_Implicit(new Color32(color.R, color.G, color.B, (byte)Mathf.RoundToInt(CrossHairAlpha)));
			global::CrossHair.Utilities.Console.LogDebug($"CrossHairColor: ({color.R}, {color.G}, {color.B}, {CrossHairAlpha})");
			((TMP_Text)CrossHairTMP).alignment = (TextAlignmentOptions)514;
			((TMP_Text)CrossHairTMP).font = ((TMP_Text)__instance.controlTipLines[0]).font;
			((Behaviour)CrossHairTMP).enabled = true;
			if (Plugin.CrossHairShadow.Value)
			{
				CrossHairShadow = Object.Instantiate<Transform>(CrossHair, transform);
				TextMeshProUGUI component = ((Component)CrossHairShadow).GetComponent<TextMeshProUGUI>();
				((Object)CrossHairShadow).name = "CrossHairShadow";
				((TMP_Text)component).fontSize = Plugin.CrossHairSize.Value;
				((Graphic)component).color = Color32.op_Implicit(new Color32((byte)0, (byte)0, (byte)0, (byte)CrossHairShadowAlpha));
				((Transform)((TMP_Text)component).rectTransform).localPosition = new Vector3(2f, -2f, 0f);
				((Transform)rectTransform).SetAsLastSibling();
			}
		}

		public static void SetCrossHairAlphaPercent(float target)
		{
			if (Object.op_Implicit((Object)(object)CrossHair))
			{
				((TMP_Text)((Component)CrossHair).GetComponent<TextMeshProUGUI>()).alpha = target * (CrossHairAlpha / 255f);
				if (Object.op_Implicit((Object)(object)CrossHairShadow))
				{
					((TMP_Text)((Component)CrossHairShadow).GetComponent<TextMeshProUGUI>()).alpha = target * (CrossHairShadowAlpha / 255f);
				}
			}
		}

		private static string HexFormatException(string message = "color")
		{
			global::CrossHair.Utilities.Console.LogMessage("Invalid hex " + message + ", using default color (ffffff)");
			Plugin.CrossHairColor.Value = "ffffff";
			Plugin.Config.Save();
			return "ffffff";
		}
	}
	public class TargetFieldHook
	{
		public string fieldName;

		public object targetValue;

		private float fadeValue;

		private float fadeOutDuration;

		private float fadeInDuration;

		public PrivateFieldAccessor<PlayerControllerB> field;

		private bool isFading;

		public float currentFade = 1f;

		private float fadeTimer;

		public TargetFieldHook(PlayerControllerB playerInstance, string fieldName, object targetValue, float fadeValue = 0.2f, float fadeOutDuration = 0.2f, float fadeInDuration = 0.5f)
		{
			this.fieldName = fieldName;
			this.targetValue = targetValue;
			this.fadeValue = fadeValue;
			this.fadeOutDuration = fadeOutDuration;
			this.fadeInDuration = fadeInDuration;
			field = new PrivateFieldAccessor<PlayerControllerB>(playerInstance, fieldName);
		}

		public bool GetState()
		{
			object obj = field.Get<object>();
			try
			{
				object obj2 = targetValue;
				InteractTrigger val = (InteractTrigger)((obj2 is InteractTrigger) ? obj2 : null);
				if (val == null)
				{
					if (!(obj2 is bool flag))
					{
						if (!(obj2 is float num))
						{
							if (!(obj2 is int num2))
							{
								if (obj2 is string text)
								{
									return (string)obj == text;
								}
								throw new TypeAccessException($"TargetFieldHook.GetState() - Unknown type: {targetValue.GetType()}");
							}
							return (int)obj == num2;
						}
						return (float)obj == num;
					}
					return (bool)obj == flag;
				}
				return obj != null == Object.op_Implicit((Object)(object)val);
			}
			catch (TypeAccessException ex)
			{
				CrossHair.Utilities.Console.LogError(ex.ToString());
			}
			CrossHair.Utilities.Console.LogDebug($"{fieldName} - Unknown type: {targetValue.GetType()}");
			return false;
		}

		public void Update()
		{
			if (isFading)
			{
				if (!GetState())
				{
					isFading = false;
					fadeTimer = currentFade;
				}
				else if (currentFade > fadeValue)
				{
					currentFade = Mathf.Lerp(1f, fadeValue, fadeTimer);
					fadeTimer += Time.deltaTime / fadeOutDuration;
				}
			}
			else if (GetState())
			{
				isFading = true;
				fadeTimer = 1f - currentFade;
			}
			else if (currentFade < 1f)
			{
				currentFade = Mathf.Lerp(fadeValue, 1f, fadeTimer);
				fadeTimer += Time.deltaTime / fadeInDuration;
			}
			currentFade = Mathf.Clamp(currentFade, 0f, 1f);
			fadeTimer = Mathf.Clamp(fadeTimer, 0f, 1f);
		}

		public void LogValues()
		{
			CrossHair.Utilities.Console.LogDebug($"{fieldName}\nValue: {field.Get<object>()} - Target: {targetValue}\nFade: {fadeValue} - Duration: {fadeOutDuration} - {fadeInDuration}");
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal static class PlayerControllerBPatch
	{
		private static List<TargetFieldHook> targetFields = new List<TargetFieldHook>();

		[HarmonyPatch("ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		private static void ConnectClientToPlayerObject(ref PlayerControllerB __instance)
		{
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if (!((Object)(object)__instance != (Object)(object)localPlayerController))
			{
				CrossHair.Utilities.Console.LogInfo("PlayerControllerB.ConnectClientToPlayerObject() called");
				if (Plugin.CrossHairFading.Value)
				{
					targetFields = new List<TargetFieldHook>
					{
						new TargetFieldHook(__instance, "isWalking", true, 0.5f, 1f, 0.25f),
						new TargetFieldHook(__instance, "isSprinting", true, 0.25f, 0.5f, 0.25f),
						new TargetFieldHook(__instance, "isJumping", true, 0.1f, 0.05f, 1f),
						new TargetFieldHook(__instance, "isFallingFromJump", true, 0.1f, 0.01f, 1f),
						new TargetFieldHook(__instance, "isFallingNoJump", true, 0.1f, 0.01f, 1f),
						new TargetFieldHook(__instance, "isCrouching", true, 0.5f, 0.5f, 1f),
						new TargetFieldHook(__instance, "isClimbingLadder", true, 0.01f, 0.25f, 2f),
						new TargetFieldHook(__instance, "twoHanded", true, 0.1f, 0.01f),
						new TargetFieldHook(__instance, "performingEmote", true, 0.05f, 0.2f, 2f),
						new TargetFieldHook(__instance, "isUnderwater", true, 0.025f, 0.1f, 1f),
						new TargetFieldHook(__instance, "inTerminalMenu", true, 0f, 0.2f, 1.5f),
						new TargetFieldHook(__instance, "isPlayerDead", true, 0.05f, 2.5f, 1f),
						new TargetFieldHook(__instance, "hasBegunSpectating", true, 0f, 5f, 50f),
						new TargetFieldHook(__instance, "isHoldingInteract", true, 0.1f, 0.5f)
					};
					CrossHair.Utilities.Console.LogDebug($"PlayerControllerB.targetFields.Count: {targetFields.Count}");
				}
			}
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void Update(ref PlayerControllerB __instance)
		{
			if ((Object)(object)__instance != (Object)(object)GameNetworkManager.Instance.localPlayerController)
			{
				return;
			}
			float num = 1f;
			foreach (TargetFieldHook targetField in targetFields)
			{
				targetField.Update();
				if (targetField.currentFade < num)
				{
					num = targetField.currentFade;
					_ = targetField.fieldName;
				}
			}
			if (Mathf.Abs(((TMP_Text)HUDManagerPatch.CrossHairTMP).alpha - num * (HUDManagerPatch.CrossHairAlpha / 255f)) > 0.0001f)
			{
				HUDManagerPatch.SetCrossHairAlphaPercent(num);
			}
		}
	}
}

BepInEx/plugins/americanompany/com.github.zehsteam.Hitmarker.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
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 GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;
using com.github.zehsteam.Hitmarker.MonoBehaviours;
using com.github.zehsteam.Hitmarker.Patches;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("com.github.zehsteam.Hitmarker")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Shows a hitmarker when you successfully hit an enemy. With additional features. (Client-side)")]
[assembly: AssemblyFileVersion("1.2.3.0")]
[assembly: AssemblyInformationalVersion("1.2.3+9f550c00a965039c6c13c3bda8cf3750925b11f7")]
[assembly: AssemblyProduct("Hitmarker")]
[assembly: AssemblyTitle("com.github.zehsteam.Hitmarker")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.3.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace com.github.zehsteam.Hitmarker
{
	internal class ConfigManager
	{
		public ConfigEntry<bool> ExtendedLogging { get; private set; }

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

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

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

		public ConfigEntry<float> MessageDuration { get; private set; }

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

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

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

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

		public ConfigManager()
		{
			BindConfigs();
			ClearUnusedEntries();
		}

		private void BindConfigs()
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			ConfigFile config = ((BaseUnityPlugin)Plugin.Instance).Config;
			ExtendedLogging = config.Bind<bool>("General Settings", "ExtendedLogging", false, "Enable extended logging.");
			ShowHitmarkerImage = config.Bind<bool>("Hitmarker Settings", "ShowHitmarkerImage", true, "Do you want to show the hitmarker image?");
			HitmarkerImageSize = config.Bind<int>("Hitmarker Settings", "HitmarkerImageSize", 40, new ConfigDescription("The size of the hitmarker image in pixels.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(10, 100), Array.Empty<object>()));
			PlayHitmarkerSound = config.Bind<bool>("Hitmarker Settings", "PlayHitmarkerSound", true, "Do you want to play the hitmarker sound?");
			MessageDuration = config.Bind<float>("Message Settings", "MessageDuration", 4f, "The message duration in seconds.");
			MessageFontSize = config.Bind<int>("Message Settings", "MessageFontSize", 35, new ConfigDescription("The message font size in pixels.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(10, 100), Array.Empty<object>()));
			ShowDamageMessage = config.Bind<bool>("Message Settings", "ShowDamageMessage", true, "Shows a message of how much damage you did to an enemy.");
			ShowKillMessage = config.Bind<bool>("Message Settings", "ShowKillMessage", true, "Shows a message when an enemy is killed.");
			OnlyShowLocalKillMessage = config.Bind<bool>("Message Settings", "OnlyShowLocalKillMessage", true, "Will only show your kill messages.");
		}

		private void ClearUnusedEntries()
		{
			ConfigFile config = ((BaseUnityPlugin)Plugin.Instance).Config;
			PropertyInfo property = ((object)config).GetType().GetProperty("OrphanedEntries", BindingFlags.Instance | BindingFlags.NonPublic);
			Dictionary<ConfigDefinition, string> dictionary = (Dictionary<ConfigDefinition, string>)property.GetValue(config, null);
			dictionary.Clear();
			config.Save();
		}
	}
	internal class Content
	{
		public static GameObject HitmarkerCanvasPrefab;

		public static void Load()
		{
			LoadAssetsFromAssetBundle();
		}

		private static void LoadAssetsFromAssetBundle()
		{
			try
			{
				string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)Plugin.Instance).Info.Location);
				string text = Path.Combine(directoryName, "hitmarker_assets");
				AssetBundle val = AssetBundle.LoadFromFile(text);
				HitmarkerCanvasPrefab = val.LoadAsset<GameObject>("HitmarkerCanvas");
				Plugin.logger.LogInfo((object)"Successfully loaded assets from AssetBundle!");
			}
			catch (Exception arg)
			{
				Plugin.logger.LogError((object)$"Error: failed to load assets from AssetBundle.\n\n{arg}");
			}
		}
	}
	[BepInPlugin("com.github.zehsteam.Hitmarker", "Hitmarker", "1.2.3")]
	internal class Plugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("com.github.zehsteam.Hitmarker");

		internal static Plugin Instance;

		internal static ManualLogSource logger;

		internal static ConfigManager ConfigManager;

		internal static bool IsHostOrServer => NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			logger = Logger.CreateLogSource("com.github.zehsteam.Hitmarker");
			logger.LogInfo((object)"Hitmarker has awoken!");
			harmony.PatchAll(typeof(HUDManagerPatch));
			harmony.PatchAll(typeof(EnemyAIPatch));
			ConfigManager = new ConfigManager();
			Content.Load();
		}

		public void CreateHitmarkerCanvas()
		{
			if (!((Object)(object)HitmarkerCanvasBehaviour.Instance != (Object)null))
			{
				Object.Instantiate<GameObject>(Content.HitmarkerCanvasPrefab);
				logger.LogInfo((object)"Instantiated Hitmarker canvas.");
			}
		}

		public void LogInfoExtended(object data)
		{
			if (ConfigManager.ExtendedLogging.Value)
			{
				logger.LogInfo(data);
			}
		}
	}
	internal class Utils
	{
		public static bool IsLocalPlayer(PlayerControllerB playerScript)
		{
			return (Object)(object)StartOfRound.Instance.localPlayerController == (Object)(object)playerScript;
		}

		public static PlayerControllerB GetPlayerScript(int playerWhoHit)
		{
			if (playerWhoHit < 0 || playerWhoHit > StartOfRound.Instance.allPlayerScripts.Length - 1)
			{
				return null;
			}
			return StartOfRound.Instance.allPlayerScripts[playerWhoHit];
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "com.github.zehsteam.Hitmarker";

		public const string PLUGIN_NAME = "Hitmarker";

		public const string PLUGIN_VERSION = "1.2.3";
	}
}
namespace com.github.zehsteam.Hitmarker.Patches
{
	[HarmonyPatch(typeof(EnemyAI))]
	internal class EnemyAIPatch
	{
		[HarmonyPatch("HitEnemyOnLocalClient")]
		[HarmonyPrefix]
		private static void HitEnemyOnLocalClientPatch(ref EnemyAI __instance, int force, PlayerControllerB playerWhoHit = null)
		{
			if (!((Object)(object)playerWhoHit == (Object)null) && Utils.IsLocalPlayer(playerWhoHit))
			{
				HitEnemy(__instance, force, playerWhoHit);
			}
		}

		[HarmonyPatch("HitEnemyServerRpc")]
		[HarmonyPrefix]
		private static void HitEnemyServerRpcPatch(ref EnemyAI __instance, int force, int playerWhoHit)
		{
			if (playerWhoHit != -1)
			{
				PlayerControllerB playerScript = Utils.GetPlayerScript(playerWhoHit);
				if (!Utils.IsLocalPlayer(playerScript))
				{
					HitEnemy(__instance, force, playerScript);
				}
			}
		}

		[HarmonyPatch("HitEnemyClientRpc")]
		[HarmonyPrefix]
		private static void HitEnemyClientRpcPatch(ref EnemyAI __instance, int force, int playerWhoHit)
		{
			if (playerWhoHit != -1 && !Plugin.IsHostOrServer)
			{
				PlayerControllerB playerScript = Utils.GetPlayerScript(playerWhoHit);
				if (!Utils.IsLocalPlayer(playerScript))
				{
					HitEnemy(__instance, force, playerScript);
				}
			}
		}

		private static void HitEnemy(EnemyAI enemyAI, int force, PlayerControllerB playerWhoHit)
		{
			if (enemyAI.enemyType.canDie && !enemyAI.isEnemyDead && enemyAI.enemyHP > 0)
			{
				bool flag = Utils.IsLocalPlayer(playerWhoHit);
				string enemyName = enemyAI.enemyType.enemyName;
				bool flag2 = enemyAI.enemyHP - force <= 0;
				if (flag)
				{
					HitmarkerCanvasBehaviour.Instance.ShowHitmarker(flag2);
					HitmarkerCanvasBehaviour.Instance.ShowDamageMessage(enemyName, force);
				}
				if (flag2)
				{
					HitmarkerCanvasBehaviour.Instance.ShowKillMessage(enemyName, flag, playerWhoHit.playerUsername);
				}
				LogInfoExtended("HitEnemy();", enemyAI, force, playerWhoHit);
			}
		}

		private static void LogInfoExtended(string functionName, EnemyAI enemyAI, int force, PlayerControllerB playerWhoHit)
		{
			NetworkObject component = ((Component)enemyAI).gameObject.GetComponent<NetworkObject>();
			string text = (Utils.IsLocalPlayer(playerWhoHit) ? " (LOCAL)" : "");
			string text2 = $"{functionName} NetworkObjectId: {component.NetworkObjectId}\n\n";
			text2 += $"Player \"{playerWhoHit.playerUsername}\"{text} hit \"{enemyAI.enemyType.enemyName}\" for {force} force.\n";
			text2 += $"isEnemyDead: {enemyAI.isEnemyDead}, enemyHP: {enemyAI.enemyHP}, (new enemyHP should be {enemyAI.enemyHP - force})\n";
			Plugin.Instance.LogInfoExtended("\n\n" + text2.Trim() + "\n");
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	internal class HUDManagerPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPatch()
		{
			Plugin.Instance.CreateHitmarkerCanvas();
		}
	}
}
namespace com.github.zehsteam.Hitmarker.MonoBehaviours
{
	public class HitmarkerCanvasBehaviour : MonoBehaviour
	{
		public static HitmarkerCanvasBehaviour Instance;

		public HitmarkerImageBehaviour HitmarkerImageBehaviour;

		public AudioClip HitSFX;

		public RectTransform MessageListTransform;

		public RectTransform MessageItemPrefab;

		private Queue<RectTransform> _messageItemPool = new Queue<RectTransform>();

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
		}

		private void Start()
		{
			InitializeMessageItemPool();
		}

		private void InitializeMessageItemPool()
		{
			_messageItemPool = new Queue<RectTransform>();
			for (int i = 0; i < 20; i++)
			{
				RectTransform val = Object.Instantiate<RectTransform>(MessageItemPrefab, (Transform)(object)MessageListTransform);
				((Component)val).gameObject.SetActive(false);
				_messageItemPool.Enqueue(val);
			}
		}

		public void ShowHitmarker(bool killed = false)
		{
			ShowHitmarkerImage(killed);
			PlayHitSFX();
		}

		private void ShowHitmarkerImage(bool killed = false)
		{
			if (Plugin.ConfigManager.ShowHitmarkerImage.Value)
			{
				HitmarkerImageBehaviour.ShowImage(killed);
			}
		}

		private void PlayHitSFX()
		{
			if (Plugin.ConfigManager.PlayHitmarkerSound.Value)
			{
				HUDManager.Instance.UIAudio.PlayOneShot(HitSFX);
			}
		}

		public void ShowDamageMessage(string enemyName, int damage = 1)
		{
			if (Plugin.ConfigManager.ShowDamageMessage.Value)
			{
				ShowMessage($"{enemyName} -{damage} HP");
			}
		}

		public void ShowKillMessage(string enemyName, bool fromLocalPlayer = true, string fromPlayerName = "")
		{
			//IL_0063: 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)
			if (Plugin.ConfigManager.ShowKillMessage.Value && (fromLocalPlayer || !Plugin.ConfigManager.OnlyShowLocalKillMessage.Value))
			{
				if (!fromLocalPlayer)
				{
					ShowMessage(fromPlayerName + " Killed " + enemyName, Color.red);
				}
				else
				{
					ShowMessage("Killed " + enemyName, Color.red);
				}
			}
		}

		private void ShowMessage(string text)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			ShowMessage(text, Color.white);
		}

		private void ShowMessage(string text, Color color)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			SpawnMessageItemFromPool(text, color);
		}

		private RectTransform SpawnMessageItemFromPool(string text, Color color)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			if (_messageItemPool == null || _messageItemPool.Count == 0)
			{
				Plugin.logger.LogError((object)"Error: Failed to spawn message item from pool. Message item pool is either null or empty.");
				return null;
			}
			RectTransform val = _messageItemPool.Dequeue();
			((Component)val).gameObject.SetActive(true);
			((Transform)val).SetAsLastSibling();
			MessageItemBehaviour messageItemBehaviour = default(MessageItemBehaviour);
			if (((Component)val).TryGetComponent<MessageItemBehaviour>(ref messageItemBehaviour))
			{
				messageItemBehaviour.SetText(text, color);
			}
			_messageItemPool.Enqueue(val);
			return val;
		}
	}
	public class HitmarkerImageBehaviour : MonoBehaviour
	{
		public Image Image;

		public Color32 DefaultColor;

		public Color32 KilledColor;

		private Coroutine _fadeOutCoroutine;

		private void Start()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			int value = Plugin.ConfigManager.HitmarkerImageSize.Value;
			((Graphic)Image).rectTransform.sizeDelta = new Vector2((float)value, (float)value);
			SetAlpha(0f);
		}

		public void ShowImage(bool killed = false)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			((Graphic)Image).color = Color32.op_Implicit(killed ? KilledColor : DefaultColor);
			if (_fadeOutCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(_fadeOutCoroutine);
			}
			_fadeOutCoroutine = ((MonoBehaviour)this).StartCoroutine(FadeOut(0.25f));
		}

		private IEnumerator FadeOut(float duration)
		{
			SetAlpha(255f);
			for (float timer = 0f; timer < duration; timer += Time.deltaTime)
			{
				float percent = 1f / duration * timer;
				float alpha = 255f + -255f * percent;
				SetAlpha(alpha);
				yield return null;
			}
			SetAlpha(0f);
		}

		private void SetAlpha(float a)
		{
			//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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			a = Mathf.Clamp(a, 0f, 255f);
			Color32 val = Color32.op_Implicit(((Graphic)Image).color);
			val.a = (byte)a;
			((Graphic)Image).color = Color32.op_Implicit(val);
		}
	}
	public class MessageItemBehaviour : MonoBehaviour
	{
		public TextMeshProUGUI TextUGUI;

		private Coroutine _animationCoroutine;

		private void Start()
		{
			((TMP_Text)TextUGUI).fontSize = Plugin.ConfigManager.MessageFontSize.Value;
		}

		private void OnEnable()
		{
			if (_animationCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(_animationCoroutine);
			}
			_animationCoroutine = ((MonoBehaviour)this).StartCoroutine(PlayAnimation());
		}

		private void OnDisable()
		{
			if (_animationCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(_animationCoroutine);
			}
		}

		private IEnumerator PlayAnimation()
		{
			yield return (object)new WaitForSeconds(Plugin.ConfigManager.MessageDuration.Value);
			float fadeOutDuration = 1f;
			SetAlpha(255f);
			for (float timer = 0f; timer < fadeOutDuration; timer += Time.deltaTime)
			{
				float percent = 1f / fadeOutDuration * timer;
				float alpha = 255f + -255f * percent;
				SetAlpha(alpha);
				yield return null;
			}
			SetAlpha(0f);
			yield return null;
			((Component)this).gameObject.SetActive(false);
		}

		public void SetText(string text)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			SetText(text, Color.white);
		}

		public void SetText(string text, Color color)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			((TMP_Text)TextUGUI).text = text;
			((Graphic)TextUGUI).color = color;
		}

		private void SetAlpha(float a)
		{
			//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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			a = Mathf.Clamp(a, 0f, 255f);
			Color32 val = Color32.op_Implicit(((Graphic)TextUGUI).color);
			val.a = (byte)a;
			((Graphic)TextUGUI).color = Color32.op_Implicit(val);
		}
	}
}

BepInEx/plugins/americanompany/com.github.zehsteam.ToilHead.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using com.github.zehsteam.ToilHead.Compatibility;
using com.github.zehsteam.ToilHead.MonoBehaviours;
using com.github.zehsteam.ToilHead.MonoBehaviours.TurretHeads;
using com.github.zehsteam.ToilHead.NetcodePatcher;
using com.github.zehsteam.ToilHead.Patches;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("com.github.zehsteam.ToilHead")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("CoilHeads, Manticoils, and other entities can sometimes spawn with a turret on their head. Highly Configurable.")]
[assembly: AssemblyFileVersion("1.7.2.0")]
[assembly: AssemblyInformationalVersion("1.7.2+13ae783a09c02f93fd4ce1f29c4c3515ccdfa834")]
[assembly: AssemblyProduct("ToilHead")]
[assembly: AssemblyTitle("com.github.zehsteam.ToilHead")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.7.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace com.github.zehsteam.ToilHead
{
	public class Api
	{
		public static Dictionary<EnemyAI, TurretHeadControllerBehaviour> EnemyTurretHeadControllerPairs => TurretHeadManager.EnemyTurretHeadControllerPairs;

		public static Dictionary<PlayerControllerB, TurretHeadControllerBehaviour> PlayerTurretHeadControllerPairs => TurretHeadManager.PlayerTurretHeadControllerPairs;

		public static Dictionary<PlayerControllerB, TurretHeadControllerBehaviour> DeadBodyTurretHeadControllerPairs => TurretHeadManager.DeadBodyTurretHeadControllerPairs;

		public static TurretHeadData ToilHeadData => TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: false);

		public static bool ForceToilHeadSpawns
		{
			get
			{
				return ToilHeadData.ForceSpawns;
			}
			set
			{
				ToilHeadData.ForceSpawns = value;
			}
		}

		public static int ForceToilHeadMaxSpawnCount
		{
			get
			{
				return ToilHeadData.ForceMaxSpawnCount;
			}
			set
			{
				ToilHeadData.ForceMaxSpawnCount = value;
			}
		}

		public static TurretHeadData MantiToilData => TurretHeadManager.GetEnemyTurretHeadData("Manticoil", isSlayer: false);

		public static bool ForceMantiToilSpawns
		{
			get
			{
				return MantiToilData.ForceSpawns;
			}
			set
			{
				MantiToilData.ForceSpawns = value;
			}
		}

		public static int ForceMantiToilMaxSpawnCount
		{
			get
			{
				return MantiToilData.ForceMaxSpawnCount;
			}
			set
			{
				MantiToilData.ForceMaxSpawnCount = value;
			}
		}

		public static TurretHeadData ToilSlayerData => TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: true);

		public static bool ForceToilSlayerSpawns
		{
			get
			{
				return ToilSlayerData.ForceSpawns;
			}
			set
			{
				ToilSlayerData.ForceSpawns = value;
			}
		}

		public static int ForceToilSlayerMaxSpawnCount
		{
			get
			{
				return ToilSlayerData.ForceMaxSpawnCount;
			}
			set
			{
				ToilSlayerData.ForceMaxSpawnCount = value;
			}
		}

		public static TurretHeadData MantiSlayerData => TurretHeadManager.GetEnemyTurretHeadData("Manticoil", isSlayer: true);

		public static bool ForceMantiSlayerSpawns
		{
			get
			{
				return MantiSlayerData.ForceSpawns;
			}
			set
			{
				MantiSlayerData.ForceSpawns = value;
			}
		}

		public static int ForceMantiSlayerMaxSpawnCount
		{
			get
			{
				return MantiSlayerData.ForceMaxSpawnCount;
			}
			set
			{
				MantiSlayerData.ForceMaxSpawnCount = value;
			}
		}

		public static TurretHeadData ToilPlayerData => TurretHeadManager.PlayerTurretHeadData;

		public static bool ForceToilPlayerSpawns
		{
			get
			{
				return ToilPlayerData.ForceSpawns;
			}
			set
			{
				ToilPlayerData.ForceSpawns = value;
			}
		}

		public static int ForceToilPlayerMaxSpawnCount
		{
			get
			{
				return ToilPlayerData.ForceMaxSpawnCount;
			}
			set
			{
				ToilPlayerData.ForceMaxSpawnCount = value;
			}
		}

		public static TurretHeadData ToilMaskedData => TurretHeadManager.GetEnemyTurretHeadData("Masked", isSlayer: false);

		public static bool ForceToilMaskedSpawns
		{
			get
			{
				return ToilMaskedData.ForceSpawns;
			}
			set
			{
				ToilMaskedData.ForceSpawns = value;
			}
		}

		public static int ForceToilMaskedMaxSpawnCount
		{
			get
			{
				return ToilMaskedData.ForceMaxSpawnCount;
			}
			set
			{
				ToilMaskedData.ForceMaxSpawnCount = value;
			}
		}

		public static TurretHeadData SlayerMaskedData => TurretHeadManager.GetEnemyTurretHeadData("Masked", isSlayer: true);

		public static bool ForceSlayerMaskedSpawns
		{
			get
			{
				return SlayerMaskedData.ForceSpawns;
			}
			set
			{
				SlayerMaskedData.ForceSpawns = value;
			}
		}

		public static int ForceSlayerMaskedMaxSpawnCount
		{
			get
			{
				return SlayerMaskedData.ForceMaxSpawnCount;
			}
			set
			{
				SlayerMaskedData.ForceMaxSpawnCount = value;
			}
		}

		[Obsolete("EnemyTurretPairs is deprecated, please use EnemyTurretHeadControllerPairs instead.", true)]
		public static Dictionary<EnemyAI, ToilHeadTurretBehaviour> EnemyTurretPairs => new Dictionary<EnemyAI, ToilHeadTurretBehaviour>();

		[Obsolete("PlayerTurretPairs is deprecated, please use PlayerTurretHeadControllerPairs instead.", true)]
		public static Dictionary<PlayerControllerB, ToilHeadTurretBehaviour> PlayerTurretPairs => new Dictionary<PlayerControllerB, ToilHeadTurretBehaviour>();

		[Obsolete("enemyTurretPairs is deprecated, please use EnemyTurretHeadControllerPairs instead.", true)]
		public static Dictionary<NetworkObject, NetworkObject> enemyTurretPairs => new Dictionary<NetworkObject, NetworkObject>();

		[Obsolete("MaxSpawnCount is deprecated, please use ToilHeadMaxSpawnCount instead.", true)]
		public static int MaxSpawnCount => TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: false).GetSpawnDataForCurrentMoon().MaxSpawnCount;

		[Obsolete("SpawnChance is deprecated, please use ToilHeadSpawnChance instead.", true)]
		public static float SpawnChance => TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: false).GetSpawnDataForCurrentMoon().SpawnChance;

		[Obsolete("spawnCount is deprecated, please use ToilHeadSpawnCount instead.", true)]
		public static int spawnCount => TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: false).SpawnCount;

		[Obsolete("forceSpawns is deprecated, please use ForceToilHeadSpawns instead.", true)]
		public static bool forceSpawns
		{
			get
			{
				return TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: false).ForceSpawns;
			}
			set
			{
				TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: false).ForceSpawns = value;
			}
		}

		[Obsolete("forceMaxSpawnCount is deprecated, please use ForceToilHeadMaxSpawnCount instead.", true)]
		public static int forceMaxSpawnCount
		{
			get
			{
				return TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: false).ForceMaxSpawnCount;
			}
			set
			{
				TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: false).ForceMaxSpawnCount = value;
			}
		}

		[Obsolete("mantiToilSpawnCount is deprecated, please use MantiToilSpawnCount instead.", true)]
		public static int mantiToilSpawnCount => TurretHeadManager.GetEnemyTurretHeadData("Manticoil", isSlayer: false).SpawnCount;

		[Obsolete("forceMantiToilSpawns is deprecated, please use ForceMantiToilSpawns instead.", true)]
		public static bool forceMantiToilSpawns
		{
			get
			{
				return TurretHeadManager.GetEnemyTurretHeadData("Manticoil", isSlayer: false).ForceSpawns;
			}
			set
			{
				TurretHeadManager.GetEnemyTurretHeadData("Manticoil", isSlayer: false).ForceSpawns = value;
			}
		}

		[Obsolete("forceMantiToilMaxSpawnCount is deprecated, please use ForceMantiToilMaxSpawnCount instead.", true)]
		public static int forceMantiToilMaxSpawnCount
		{
			get
			{
				return TurretHeadManager.GetEnemyTurretHeadData("Manticoil", isSlayer: false).ForceMaxSpawnCount;
			}
			set
			{
				TurretHeadManager.GetEnemyTurretHeadData("Manticoil", isSlayer: false).ForceMaxSpawnCount = value;
			}
		}

		[Obsolete("toilSlayerSpawnCount is deprecated, please use ToilSlayerSpawnCount instead.", true)]
		public static int toilSlayerSpawnCount => TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: true).SpawnCount;

		[Obsolete("forceToilSlayerSpawns is deprecated, please use ForceToilSlayerSpawns instead.", true)]
		public static bool forceToilSlayerSpawns
		{
			get
			{
				return TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: true).ForceSpawns;
			}
			set
			{
				TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: true).ForceSpawns = value;
			}
		}

		[Obsolete("forceToilSlayerMaxSpawnCount is deprecated, please use ForceToilSlayerMaxSpawnCount instead.", true)]
		public static int forceToilSlayerMaxSpawnCount
		{
			get
			{
				return TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: true).ForceMaxSpawnCount;
			}
			set
			{
				TurretHeadManager.GetEnemyTurretHeadData("Spring", isSlayer: true).ForceMaxSpawnCount = value;
			}
		}

		public static bool SetToilHeadOnServer(EnemyAI enemyScript)
		{
			return TurretHeadManager.SetEnemyTurretHeadOnServer(enemyScript, isSlayer: false);
		}

		public static bool SetMantiToilOnServer(EnemyAI enemyScript)
		{
			return TurretHeadManager.SetEnemyTurretHeadOnServer(enemyScript, isSlayer: false);
		}

		public static bool SetToilSlayerOnServer(EnemyAI enemyScript)
		{
			return TurretHeadManager.SetEnemyTurretHeadOnServer(enemyScript, isSlayer: true);
		}

		public static bool SetMantiSlayerOnServer(EnemyAI enemyScript)
		{
			return TurretHeadManager.SetEnemyTurretHeadOnServer(enemyScript, isSlayer: true);
		}

		public static bool SetToilPlayerOnServer(PlayerControllerB playerScript, bool isSlayer = false)
		{
			return TurretHeadManager.SetPlayerTurretHeadOnServer(playerScript, isSlayer);
		}

		public static bool SetToilMaskedOnServer(EnemyAI enemyScript)
		{
			return TurretHeadManager.SetEnemyTurretHeadOnServer(enemyScript, isSlayer: false);
		}

		public static bool SetSlayerMaskedOnServer(EnemyAI enemyScript)
		{
			return TurretHeadManager.SetEnemyTurretHeadOnServer(enemyScript, isSlayer: true);
		}
	}
	internal class Content
	{
		public static GameObject NetworkHandlerPrefab;

		public static GameObject TurretPropPrefab;

		public static GameObject MinigunPropPrefab;

		public static GameObject ToilPlayerControllerPrefab;

		public static GameObject SlayerPlayerControllerPrefab;

		public static GameObject ToiledDeadBodyControllerPrefab;

		public static GameObject SlayedDeadBodyControllerPrefab;

		public static GameObject ToilHeadControllerPrefab;

		public static GameObject ToilSlayerControllerPrefab;

		public static GameObject MantiToilControllerPrefab;

		public static GameObject MantiSlayerControllerPrefab;

		public static GameObject ToilMaskedControllerPrefab;

		public static GameObject SlayerMaskedControllerPrefab;

		public static Item ToilHeadPlush;

		public static Item ToilSlayerPlush;

		public static void Load()
		{
			LoadAssetsFromAssetBundle();
		}

		private static void LoadAssetsFromAssetBundle()
		{
			try
			{
				string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)Plugin.Instance).Info.Location);
				string text = Path.Combine(directoryName, "toilhead_assets");
				AssetBundle val = AssetBundle.LoadFromFile(text);
				NetworkHandlerPrefab = val.LoadAsset<GameObject>("NetworkHandler");
				NetworkHandlerPrefab.AddComponent<PluginNetworkBehaviour>();
				TurretPropPrefab = val.LoadAsset<GameObject>("TurretHeadTurretProp");
				MinigunPropPrefab = val.LoadAsset<GameObject>("MinigunTurretHeadTurretProp");
				ToilPlayerControllerPrefab = val.LoadAsset<GameObject>("ToilPlayerController");
				SlayerPlayerControllerPrefab = val.LoadAsset<GameObject>("SlayerPlayerController");
				ToiledDeadBodyControllerPrefab = val.LoadAsset<GameObject>("ToiledDeadBodyController");
				SlayedDeadBodyControllerPrefab = val.LoadAsset<GameObject>("SlayedDeadBodyController");
				ToilHeadControllerPrefab = val.LoadAsset<GameObject>("ToilHeadController");
				ToilSlayerControllerPrefab = val.LoadAsset<GameObject>("ToilSlayerController");
				MantiToilControllerPrefab = val.LoadAsset<GameObject>("MantiToilController");
				MantiSlayerControllerPrefab = val.LoadAsset<GameObject>("MantiSlayerController");
				ToilMaskedControllerPrefab = val.LoadAsset<GameObject>("ToilMaskedController");
				SlayerMaskedControllerPrefab = val.LoadAsset<GameObject>("SlayerMaskedController");
				ToilHeadPlush = val.LoadAsset<Item>("ToilHeadPlush");
				ToilSlayerPlush = val.LoadAsset<Item>("ToilSlayerPlush");
				Plugin.logger.LogInfo((object)"Successfully loaded assets from AssetBundle!");
			}
			catch (Exception arg)
			{
				Plugin.logger.LogError((object)$"Error: Failed to load assets from AssetBundle.\n\n{arg}");
			}
		}
	}
	public class ExtendedConfigEntry<T>
	{
		public ConfigEntry<T> ConfigEntry;

		public Func<T> GetValue;

		public Action<T> SetValue;

		public bool UseEnableConfiguration = true;

		public T DefaultValue => (T)((ConfigEntryBase)ConfigEntry).DefaultValue;

		public T Value
		{
			get
			{
				return GetValue();
			}
			set
			{
				SetValue(value);
			}
		}

		public ExtendedConfigEntry(string section, string key, T defaultValue, string description, bool useEnableConfiguration = true)
		{
			ConfigEntry = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<T>(section, key, defaultValue, description);
			UseEnableConfiguration = useEnableConfiguration;
			Initialize();
		}

		public ExtendedConfigEntry(string section, string key, T defaultValue, ConfigDescription configDescription = null, bool useEnableConfiguration = true)
		{
			ConfigEntry = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<T>(section, key, defaultValue, configDescription);
			UseEnableConfiguration = useEnableConfiguration;
			Initialize();
		}

		private void Initialize()
		{
			if (GetValue == null)
			{
				GetValue = () => (UseEnableConfiguration && !Plugin.ConfigManager.EnableConfiguration.Value) ? DefaultValue : ConfigEntry.Value;
			}
			if (SetValue == null)
			{
				SetValue = delegate(T value)
				{
					ConfigEntry.Value = value;
				};
			}
		}

		public void ResetToDefault()
		{
			ConfigEntry.Value = (T)((ConfigEntryBase)ConfigEntry).DefaultValue;
		}
	}
	internal class PlayerUtils
	{
		public static bool IsLocalPlayer(PlayerControllerB playerScript)
		{
			return (Object)(object)playerScript == (Object)(object)GetLocalPlayerScript();
		}

		public static int GetPlayerId(PlayerControllerB playerScript)
		{
			return (int)playerScript.playerClientId;
		}

		public static int GetLocalPlayerId()
		{
			return (int)GetLocalPlayerScript().playerClientId;
		}

		public static PlayerControllerB GetPlayerScript(int playerId)
		{
			try
			{
				return StartOfRound.Instance.allPlayerScripts[playerId];
			}
			catch
			{
				return null;
			}
		}

		public static PlayerControllerB GetLocalPlayerScript()
		{
			return GameNetworkManager.Instance.localPlayerController;
		}
	}
	[BepInPlugin("com.github.zehsteam.ToilHead", "ToilHead", "1.7.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class Plugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("com.github.zehsteam.ToilHead");

		internal static Plugin Instance;

		internal static ManualLogSource logger;

		internal static SyncedConfigManager ConfigManager;

		public static bool IsHostOrServer => NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			logger = Logger.CreateLogSource("com.github.zehsteam.ToilHead");
			logger.LogInfo((object)"ToilHead has awoken!");
			harmony.PatchAll(typeof(GameNetworkManagerPatch));
			harmony.PatchAll(typeof(StartOfRoundPatch));
			harmony.PatchAll(typeof(RoundManagerPatch));
			harmony.PatchAll(typeof(TerminalPatch));
			harmony.PatchAll(typeof(PlayerControllerBPatch));
			harmony.PatchAll(typeof(RagdollGrabbableObjectPatch));
			harmony.PatchAll(typeof(EnemyAIPatch));
			harmony.PatchAll(typeof(SpringManAIPatch));
			harmony.PatchAll(typeof(MaskedPlayerEnemyPatch));
			harmony.PatchAll(typeof(TurretPatch));
			ConfigManager = new SyncedConfigManager();
			Content.Load();
			TurretHeadManager.Initialize();
			RegisterScrapItems();
			NetcodePatcherAwake();
		}

		private void NetcodePatcherAwake()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}

		public void OnLocalDisconnect()
		{
			logger.LogInfo((object)"Local player disconnected. Removing hostConfigData.");
			ConfigManager.SetHostConfigData(null);
			TurretHeadManager.Reset();
		}

		public void OnNewLevelLoaded()
		{
			Secret.SpawnSecrets();
		}

		public void OnNewLevelFinishedLoading()
		{
			TurretHeadManager.TrySetPlayerTurretHeadsOnServer();
		}

		public void OnShipHasLeft()
		{
			TurretHeadManager.Reset();
		}

		private void RegisterScrapItems()
		{
			if (!LethalLibCompat.HasMod || !MonsterPlushiesCompat.HasMod)
			{
				return;
			}
			try
			{
				ScrapHelper.RegisterScrap(Content.ToilHeadPlush, ConfigManager.ToilHeadPlushieSpawnWeight.Value, ConfigManager.ToilHeadPlushieSpawnAllMoons.Value, ConfigManager.ToilHeadPlushieMoonSpawnList.Value, twoHanded: false, ConfigManager.ToilHeadPlushieCarryWeight.Value, ConfigManager.ToilHeadPlushieMinValue.Value, ConfigManager.ToilHeadPlushieMaxValue.Value);
				ScrapHelper.RegisterScrap(Content.ToilSlayerPlush, ConfigManager.ToilSlayerPlushieSpawnWeight.Value, ConfigManager.ToilSlayerPlushieSpawnAllMoons.Value, ConfigManager.ToilSlayerPlushieMoonSpawnList.Value, twoHanded: false, ConfigManager.ToilSlayerPlushieCarryWeight.Value, ConfigManager.ToilSlayerPlushieMinValue.Value, ConfigManager.ToilSlayerPlushieMaxValue.Value);
			}
			catch (Exception arg)
			{
				logger.LogWarning((object)$"Warning: Failed to register scrap items.\n\n{arg}");
			}
		}

		public void LogInfoExtended(object data)
		{
			if (ConfigManager.ExtendedLogging.Value)
			{
				logger.LogInfo(data);
			}
		}

		public void LogWarningExtended(object data)
		{
			if (ConfigManager.ExtendedLogging.Value)
			{
				logger.LogWarning(data);
			}
		}

		public void LogErrorExtended(object data)
		{
			if (ConfigManager.ExtendedLogging.Value)
			{
				logger.LogError(data);
			}
		}
	}
	internal class ScrapHelper
	{
		public static void RegisterScrap(Item item, int iRarity, bool spawnAllMoons, string moonSpawnList, bool twoHanded, int carryWeight, int minValue, int maxValue)
		{
			if (!LethalLibCompat.HasMod)
			{
				return;
			}
			try
			{
				item.twoHanded = twoHanded;
				item.weight = (float)carryWeight / 105f + 1f;
				item.minValue = minValue;
				item.maxValue = maxValue;
				Utilities.FixMixerGroups(item.spawnPrefab);
				NetworkPrefabs.RegisterNetworkPrefab(item.spawnPrefab);
				if (spawnAllMoons)
				{
					Items.RegisterScrap(item, iRarity, (LevelTypes)(-1));
					Plugin.logger.LogInfo((object)$"Registered \"{item.itemName}\" scrap item with {iRarity} rarity.");
				}
				else
				{
					RegisterScrapForMoons(item, iRarity, moonSpawnList);
				}
			}
			catch (Exception arg)
			{
				Plugin.logger.LogError((object)$"Error: Failed to register \"{item.itemName}\" scrap item.\n\n{arg}");
			}
		}

		private static void RegisterScrapForMoons(Item item, int iRarity, string moonSpawnList)
		{
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, LevelTypes> dictionary = new Dictionary<string, LevelTypes>();
			dictionary.Add("Experimentation", (LevelTypes)4);
			dictionary.Add("Assurance", (LevelTypes)8);
			dictionary.Add("Vow", (LevelTypes)16);
			dictionary.Add("Offense", (LevelTypes)32);
			dictionary.Add("March", (LevelTypes)64);
			dictionary.Add("Adamance", (LevelTypes)2048);
			dictionary.Add("Rend", (LevelTypes)128);
			dictionary.Add("Dine", (LevelTypes)256);
			dictionary.Add("Titan", (LevelTypes)512);
			dictionary.Add("Artifice", (LevelTypes)4096);
			dictionary.Add("Embrion", (LevelTypes)8192);
			foreach (string item2 in from _ in moonSpawnList.Split(',')
				select GetFormattedSting(_.Trim()))
			{
				if (dictionary.TryGetValue(item2, out var value))
				{
					Items.RegisterScrap(item, iRarity, value);
					Plugin.logger.LogInfo((object)$"Registered \"{item.itemName}\" scrap item on moon \"{item2}\" with {iRarity} rarity.");
				}
			}
		}

		private static string GetFormattedSting(string value)
		{
			if (value.Length <= 1)
			{
				return value.ToUpper();
			}
			return value.Substring(0, 1).ToUpper() + value.Substring(1, value.Length - 1).ToLower();
		}
	}
	internal class Secret
	{
		public static void SpawnSecrets()
		{
			string planetName = StartOfRound.Instance.currentLevel.PlanetName;
			if (planetName == "57 Asteroid-13")
			{
				SpawnAsteroid13Secrets();
			}
		}

		public static void SpawnAsteroid13Secrets()
		{
			//IL_0032: 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_0041: 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)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: 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_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: 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_00e3: 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_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: 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_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: 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_0154: 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_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Content.TurretPropPrefab == (Object)null)
			{
				Plugin.Instance.LogWarningExtended("Warning: Failed to spawn Asteroid13 secrets. turretPropPrefab is null.");
				return;
			}
			Vector3 val = Content.TurretPropPrefab.transform.localScale * 1.3f;
			Vector3 positionOffset = default(Vector3);
			((Vector3)(ref positionOffset))..ctor(0f, 3.031f, -0.464f);
			Vector3 rotationOffset = default(Vector3);
			((Vector3)(ref rotationOffset))..ctor(-27.2f, 0f, 0f);
			Vector3 positionOffset2 = default(Vector3);
			((Vector3)(ref positionOffset2))..ctor(0f, 3.105f, -0.11f);
			Vector3 zero = Vector3.zero;
			Vector3 positionOffset3 = default(Vector3);
			((Vector3)(ref positionOffset3))..ctor(0f, 6.217f, -0.225f);
			Vector3 zero2 = Vector3.zero;
			SpawnTurretProp("coilheadstuck_model", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadrigged", positionOffset3, zero2, val * 2f);
			SpawnTurretProp("coilheadstuck_model (5)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadstuck_model (7)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadstuck_model (8)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadstuck_model (9)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadstuck_model (10)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadstuck_model (6)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (29)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (24)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (25)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (26)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (27)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (28)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadstuck_model (23)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadstuck_model (18)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadstuck_model (19)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadstuck_model (20)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadstuck_model (21)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadstuck_model (22)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (17)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (12)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (13)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (14)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (15)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_model (16)", positionOffset, rotationOffset, val);
			SpawnTurretProp("asteroid(Clone)/coilheadstuck_2_model (7)", positionOffset2, zero, val);
			SpawnTurretProp("coilheadstuck_2_model (1)", positionOffset2, zero, val);
			SpawnTurretProp("coilheadstuck_model (11)", positionOffset, rotationOffset, val);
			SpawnTurretProp("coilheadrigged (1)", positionOffset3, zero2, val * 2f);
			Plugin.Instance.LogInfoExtended("Spawned Asteroid13 secrets.");
		}

		private static void SpawnTurretProp(string parentName, Vector3 positionOffset, Vector3 rotationOffset)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			SpawnTurretProp(parentName, positionOffset, rotationOffset, Content.TurretPropPrefab.transform.localScale);
		}

		private static void SpawnTurretProp(string parentName, Vector3 positionOffset, Vector3 rotationOffset, Vector3 scale)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Content.TurretPropPrefab == (Object)null)
			{
				Plugin.Instance.LogWarningExtended("Warning: Failed to Instantiate turretPropPrefab. turretPropPrefab is null.");
				return;
			}
			GameObject val = GameObject.Find(parentName);
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Instance.LogWarningExtended("Warning: Failed to Instantiate turretPropPrefab. Parent GameObject is null.");
				return;
			}
			Transform transform = Object.Instantiate<GameObject>(Content.TurretPropPrefab, Vector3.zero, Quaternion.identity, val.transform).transform;
			transform.localScale = scale;
			transform.localRotation = Quaternion.identity;
			transform.Rotate(rotationOffset, (Space)1);
			transform.localPosition = positionOffset;
			Utils.DisableColliders(((Component)transform).gameObject);
		}
	}
	public class SpawnData
	{
		public int MaxSpawnCount;

		public float SpawnChance;

		public SpawnData(string value)
		{
			ParseValue(value);
		}

		protected virtual void ParseValue(string value)
		{
			string[] array = (from _ in value.Split(':')
				select _.Trim()).ToArray();
			int num = 2;
			if (array.Length != num)
			{
				Plugin.logger.LogError((object)$"ParseValue Error: Invalid item length for string \"{value}\". Length is {array.Length} but should have been {num}.");
				return;
			}
			TryParseInt(array[0], out MaxSpawnCount);
			TryParseFloat(array[1], out SpawnChance);
			Plugin.Instance.LogInfoExtended($"Parsed SpawnData value string. MaxSpawnCount: {MaxSpawnCount}, SpawnChance: {SpawnChance}");
		}

		protected bool TryParseInt(string value, out int parsedInt)
		{
			if (int.TryParse(value, out parsedInt))
			{
				return true;
			}
			Plugin.logger.LogError((object)("TryParseItem Error: Failed to parse int from string \"" + value + "\"."));
			return false;
		}

		protected bool TryParseFloat(string value, out float parsedFloat)
		{
			if (float.TryParse(value, out parsedFloat))
			{
				return true;
			}
			Plugin.logger.LogError((object)("TryParseItem Error: Failed to parse float from string \"" + value + "\"."));
			return false;
		}
	}
	public class MoonSpawnData : SpawnData
	{
		public string PlanetName;

		public MoonSpawnData(string value)
			: base(value)
		{
		}

		protected override void ParseValue(string value)
		{
			string[] array = (from _ in value.Split(':')
				select _.Trim()).ToArray();
			int num = 3;
			if (array.Length != num)
			{
				Plugin.logger.LogError((object)$"ParseValue Error: Invalid item length for string \"{value}\". Length is {array.Length} but should have been {num}.");
				return;
			}
			PlanetName = array[0];
			TryParseInt(array[1], out MaxSpawnCount);
			TryParseFloat(array[2], out SpawnChance);
			Plugin.Instance.LogInfoExtended($"Parsed MoonSpawnData value string. PlanetName: \"{PlanetName}\", MaxSpawnCount: {MaxSpawnCount}, SpawnChance: {SpawnChance}");
		}
	}
	public class MoonSpawnDataList
	{
		public List<MoonSpawnData> List = new List<MoonSpawnData>();

		public SpawnData DefaultSpawnData;

		public MoonSpawnDataList(string value)
		{
			ParseValue(value);
		}

		public MoonSpawnDataList(string value, SpawnData defaultSpawnData)
		{
			ParseValue(value);
			DefaultSpawnData = defaultSpawnData;
		}

		private void ParseValue(string value)
		{
			if (value == string.Empty)
			{
				return;
			}
			if (string.IsNullOrWhiteSpace(value))
			{
				Plugin.logger.LogError((object)"ParseValue Error: MoonSpawnDataList value is null or whitespace.");
				return;
			}
			string[] array = (from _ in value.Split(',')
				select _.Trim()).ToArray();
			List = new List<MoonSpawnData>();
			string[] array2 = array;
			foreach (string value2 in array2)
			{
				List.Add(new MoonSpawnData(value2));
			}
		}

		public SpawnData GetSpawnDataForCurrentMoon()
		{
			if ((Object)(object)StartOfRound.Instance == (Object)null)
			{
				return DefaultSpawnData;
			}
			return GetSpawnDataForMoon(StartOfRound.Instance.currentLevel.PlanetName);
		}

		public SpawnData GetSpawnDataForMoon(string planetName)
		{
			foreach (MoonSpawnData item in List)
			{
				if (item.PlanetName == planetName)
				{
					return item;
				}
			}
			return DefaultSpawnData;
		}
	}
	[Serializable]
	public class SyncedConfigData : INetworkSerializable
	{
		public float TurretLostLOSDuration;

		public float TurretRotationRange;

		public float TurretCodeAccessCooldownDuration;

		public bool TurretDetectionRotation;

		public float TurretDetectionRotationSpeed;

		public float TurretChargingDuration;

		public float TurretChargingRotationSpeed;

		public float TurretFiringRotationSpeed;

		public float TurretBerserkDuration;

		public float TurretBerserkRotationSpeed;

		public SyncedConfigData()
		{
		}

		public SyncedConfigData(SyncedConfigManager configManager)
		{
			TurretLostLOSDuration = configManager.TurretLostLOSDuration.Value;
			TurretRotationRange = configManager.TurretRotationRange.Value;
			TurretCodeAccessCooldownDuration = configManager.TurretCodeAccessCooldownDuration.Value;
			TurretDetectionRotation = configManager.TurretDetectionRotation.Value;
			TurretDetectionRotationSpeed = configManager.TurretDetectionRotationSpeed.Value;
			TurretChargingDuration = configManager.TurretChargingDuration.Value;
			TurretChargingRotationSpeed = configManager.TurretChargingRotationSpeed.Value;
			TurretFiringRotationSpeed = configManager.TurretFiringRotationSpeed.Value;
			TurretBerserkDuration = configManager.TurretBerserkDuration.Value;
			TurretBerserkRotationSpeed = configManager.TurretBerserkRotationSpeed.Value;
		}

		public unsafe void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref TurretLostLOSDuration, default(ForPrimitives));
			((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref TurretRotationRange, default(ForPrimitives));
			((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref TurretCodeAccessCooldownDuration, default(ForPrimitives));
			((BufferSerializer<bool>*)(&serializer))->SerializeValue<bool>(ref TurretDetectionRotation, default(ForPrimitives));
			((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref TurretDetectionRotationSpeed, default(ForPrimitives));
			((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref TurretChargingDuration, default(ForPrimitives));
			((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref TurretChargingRotationSpeed, default(ForPrimitives));
			((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref TurretFiringRotationSpeed, default(ForPrimitives));
			((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref TurretBerserkDuration, default(ForPrimitives));
			((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref TurretBerserkRotationSpeed, default(ForPrimitives));
		}
	}
	public class SyncedConfigManager
	{
		public SyncedConfigData HostConfigData { get; private set; }

		public ExtendedConfigEntry<bool> EnableConfiguration { get; private set; }

		public ExtendedConfigEntry<bool> ExtendedLogging { get; private set; }

		public ExtendedConfigEntry<string> ToilationToilPlayerSpawnSettings { get; private set; }

		public ExtendedConfigEntry<float> ToilationToilPlayerSlayerChance { get; private set; }

		public ExtendedConfigEntry<string> ToilationToilHeadSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> ToilationToilSlayerSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> ToilationMantiToilSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> ToilationMantiSlayerSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> ToilationToilMaskedSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> ToilationSlayerMaskedSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> ToilPlayerDefaultSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> ToilPlayerSpawnSettingsMoonList { get; private set; }

		public ExtendedConfigEntry<float> ToilPlayerSlayerChance { get; private set; }

		public ExtendedConfigEntry<bool> SpawnToiledPlayerRagdolls { get; private set; }

		public ExtendedConfigEntry<bool> SpawnRealToiledPlayerRagdolls { get; private set; }

		public ExtendedConfigEntry<string> ToilHeadDefaultSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> ToilHeadSpawnSettingsMoonList { get; private set; }

		public ExtendedConfigEntry<string> MantiToilDefaultSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> MantiToilSpawnSettingsMoonList { get; private set; }

		public ExtendedConfigEntry<string> ToilSlayerDefaultSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> ToilSlayerSpawnSettingsMoonList { get; private set; }

		public ExtendedConfigEntry<string> MantiSlayerDefaultSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> MantiSlayerSpawnSettingsMoonList { get; private set; }

		public ExtendedConfigEntry<string> ToilMaskedDefaultSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> ToilMaskedSpawnSettingsMoonList { get; private set; }

		public ExtendedConfigEntry<string> SlayerMaskedDefaultSpawnSettings { get; private set; }

		public ExtendedConfigEntry<string> SlayerMaskedSpawnSettingsMoonList { get; private set; }

		public ExtendedConfigEntry<int> ToilHeadPlushieSpawnWeight { get; private set; }

		public ExtendedConfigEntry<bool> ToilHeadPlushieSpawnAllMoons { get; private set; }

		public ExtendedConfigEntry<string> ToilHeadPlushieMoonSpawnList { get; private set; }

		public ExtendedConfigEntry<int> ToilHeadPlushieCarryWeight { get; private set; }

		public ExtendedConfigEntry<int> ToilHeadPlushieMinValue { get; private set; }

		public ExtendedConfigEntry<int> ToilHeadPlushieMaxValue { get; private set; }

		public ExtendedConfigEntry<int> ToilSlayerPlushieSpawnWeight { get; private set; }

		public ExtendedConfigEntry<bool> ToilSlayerPlushieSpawnAllMoons { get; private set; }

		public ExtendedConfigEntry<string> ToilSlayerPlushieMoonSpawnList { get; private set; }

		public ExtendedConfigEntry<int> ToilSlayerPlushieCarryWeight { get; private set; }

		public ExtendedConfigEntry<int> ToilSlayerPlushieMinValue { get; private set; }

		public ExtendedConfigEntry<int> ToilSlayerPlushieMaxValue { get; private set; }

		public ExtendedConfigEntry<float> TurretLostLOSDuration { get; private set; }

		public ExtendedConfigEntry<float> TurretRotationRange { get; private set; }

		public ExtendedConfigEntry<float> TurretCodeAccessCooldownDuration { get; private set; }

		public ExtendedConfigEntry<bool> TurretDetectionRotation { get; private set; }

		public ExtendedConfigEntry<float> TurretDetectionRotationSpeed { get; private set; }

		public ExtendedConfigEntry<float> TurretChargingDuration { get; private set; }

		public ExtendedConfigEntry<float> TurretChargingRotationSpeed { get; private set; }

		public ExtendedConfigEntry<float> TurretFiringRotationSpeed { get; private set; }

		public ExtendedConfigEntry<float> TurretBerserkDuration { get; private set; }

		public ExtendedConfigEntry<float> TurretBerserkRotationSpeed { get; private set; }

		public SyncedConfigManager()
		{
			BindConfigs();
			ClearUnusedEntries();
		}

		private void BindConfigs()
		{
			EnableConfiguration = new ExtendedConfigEntry<bool>("General Settings", "EnableConfiguration", defaultValue: false, "Enable if you want to use custom set config setting values. If disabled, the default config setting values will be used.", useEnableConfiguration: false);
			ExtendedLogging = new ExtendedConfigEntry<bool>("General Settings", "ExtendedLogging", defaultValue: false, "Enable extended logging.", useEnableConfiguration: false);
			ToilationToilPlayerSpawnSettings = new ExtendedConfigEntry<string>("Toilation Settings", "ToilPlayerSpawnSettings", "1:7", GetDescriptionForMoonSpawnSettings("Toil-Player", "69-Toilation"));
			ToilationToilPlayerSlayerChance = new ExtendedConfigEntry<float>("Toilation Settings", "ToilPlayerSlayerChance", 20f, "The percent chance a Toil-Player will become a Slayer-Player for 69-Toilation.");
			ToilationToilHeadSpawnSettings = new ExtendedConfigEntry<string>("Toilation Settings", "ToilHeadSpawnSettings", "6:75", GetDescriptionForMoonSpawnSettings("Toil-Head", "69-Toilation"));
			ToilationMantiToilSpawnSettings = new ExtendedConfigEntry<string>("Toilation Settings", "MantiToilSpawnSettings", "50:90", GetDescriptionForMoonSpawnSettings("Manti-Toil", "69-Toilation"));
			ToilationToilSlayerSpawnSettings = new ExtendedConfigEntry<string>("Toilation Settings", "ToilSlayerSpawnSettings", "2:10", GetDescriptionForMoonSpawnSettings("Toil-Slayer", "69-Toilation"));
			ToilationMantiSlayerSpawnSettings = new ExtendedConfigEntry<string>("Toilation Settings", "MantiSlayerSpawnSettings", "2:20", GetDescriptionForMoonSpawnSettings("Manti-Slayer", "69-Toilation"));
			ToilationToilMaskedSpawnSettings = new ExtendedConfigEntry<string>("Toilation Settings", "ToilMaskedSpawnSettings", "2:15", GetDescriptionForMoonSpawnSettings("Toil-Masked", "69-Toilation"));
			ToilationSlayerMaskedSpawnSettings = new ExtendedConfigEntry<string>("Toilation Settings", "SlayerMaskedSpawnSettings", "1:5", GetDescriptionForMoonSpawnSettings("Slayer-Masked", "69-Toilation"));
			ToilPlayerDefaultSpawnSettings = new ExtendedConfigEntry<string>("Toil-Player Settings", "ToilPlayerDefaultSpawnSettings", "1:3", GetDescriptionForDefaultSpawnSettings("Toil-Player"));
			string defaultValue = "85 Rend:1:4, 7 Dine:1:4, 8 Titan:1:5, 68 Artifice:1:5, 57 Asteroid-13:1:5, 523 Ooblterra:1:6";
			ToilPlayerSpawnSettingsMoonList = new ExtendedConfigEntry<string>("Toil-Player Settings", "ToilPlayerSpawnSettingsMoonList", defaultValue, GetDescriptionForMoonSpawnSettingsList("Toil-Player"));
			ToilPlayerSlayerChance = new ExtendedConfigEntry<float>("Toil-Player Settings", "ToilPlayerSlayerChance", 10f, "The percent chance a Toil-Player will become a Slayer-Player.");
			SpawnToiledPlayerRagdolls = new ExtendedConfigEntry<bool>("Player Ragdoll Settings", "SpawnToiledPlayerRagdolls", defaultValue: true, "If enabled, will spawn a Toiled player ragdoll when a player dies to a Turret-Head in any way.");
			SpawnRealToiledPlayerRagdolls = new ExtendedConfigEntry<bool>("Player Ragdoll Settings", "SpawnRealToiledPlayerRagdolls", defaultValue: true, "If enabled, will spawn a real turret on the Toiled player ragdoll.");
			ToilHeadDefaultSpawnSettings = new ExtendedConfigEntry<string>("Toil-Head Settings", "ToilHeadDefaultSpawnSettings", "1:30", GetDescriptionForDefaultSpawnSettings("Toil-Head"));
			string defaultValue2 = "41 Experimentation:1:10, 220 Assurance:1:20, 56 Vow:1:20, 21 Offense:1:20, 61 March:1:20, 20 Adamance:1:30, 85 Rend:1:40, 7 Dine:1:45, 8 Titan:1:50, 68 Artifice:2:70, 5 Embrion:1:30, 57 Asteroid-13:2:30, 523 Ooblterra:2:70";
			ToilHeadSpawnSettingsMoonList = new ExtendedConfigEntry<string>("Toil-Head Settings", "ToilHeadSpawnSettingsMoonList", defaultValue2, GetDescriptionForMoonSpawnSettingsList("Toil-Head"));
			MantiToilDefaultSpawnSettings = new ExtendedConfigEntry<string>("Manti-Toil Settings", "MantiToilDefaultSpawnSettings", "5:50", GetDescriptionForDefaultSpawnSettings("Manti-Toil"));
			string defaultValue3 = "20 Adamance:5:60, 85 Rend:5:60, 7 Dine:5:65, 8 Titan:5:70, 68 Artifice:8:75";
			MantiToilSpawnSettingsMoonList = new ExtendedConfigEntry<string>("Manti-Toil Settings", "MantiToilSpawnSettingsMoonList", defaultValue3, GetDescriptionForMoonSpawnSettingsList("Manti-Toil"));
			ToilSlayerDefaultSpawnSettings = new ExtendedConfigEntry<string>("Toil-Slayer Settings", "ToilSlayerDefaultSpawnSettings", "1:10", GetDescriptionForDefaultSpawnSettings("Toil-Slayer"));
			string defaultValue4 = "20 Adamance:1:15, 85 Rend:1:15, 7 Dine:1:15, 8 Titan:1:20, 68 Artifice:1:20, 57 Asteroid-13:1:15, 523 Ooblterra:1:25";
			ToilSlayerSpawnSettingsMoonList = new ExtendedConfigEntry<string>("Toil-Slayer Settings", "ToilSlayerSpawnSettingsMoonList", defaultValue4, GetDescriptionForMoonSpawnSettingsList("Toil-Slayer"));
			MantiSlayerDefaultSpawnSettings = new ExtendedConfigEntry<string>("Manti-Slayer Settings", "MantiSlayerDefaultSpawnSettings", "1:10", GetDescriptionForDefaultSpawnSettings("Manti-Slayer"));
			string defaultValue5 = "20 Adamance:1:15, 85 Rend:1:15, 7 Dine:1:15, 8 Titan:1:20, 68 Artifice:1:20, 57 Asteroid-13:1:15, 523 Ooblterra:1:25";
			MantiSlayerSpawnSettingsMoonList = new ExtendedConfigEntry<string>("Manti-Slayer Settings", "MantiSlayerSpawnSettingsMoonList", defaultValue5, GetDescriptionForMoonSpawnSettingsList("Manti-Slayer"));
			ToilMaskedDefaultSpawnSettings = new ExtendedConfigEntry<string>("Toil-Masked Settings", "ToilMaskedDefaultSpawnSettings", "1:10", GetDescriptionForDefaultSpawnSettings("Toil-Masked"));
			string defaultValue6 = "";
			ToilMaskedSpawnSettingsMoonList = new ExtendedConfigEntry<string>("Toil-Masked Settings", "ToilMaskedSpawnSettingsMoonList", defaultValue6, GetDescriptionForMoonSpawnSettingsList("Toil-Masked"));
			SlayerMaskedDefaultSpawnSettings = new ExtendedConfigEntry<string>("Slayer-Masked Settings", "SlayerMaskedDefaultSpawnSettings", "1:5", GetDescriptionForDefaultSpawnSettings("Slayer-Masked"));
			string defaultValue7 = "";
			SlayerMaskedSpawnSettingsMoonList = new ExtendedConfigEntry<string>("Slayer-Masked Settings", "SlayerMaskedSpawnSettingsMoonList", defaultValue7, GetDescriptionForMoonSpawnSettingsList("Slayer-Masked"));
			ToilHeadPlushieSpawnWeight = new ExtendedConfigEntry<int>("Toil-Head Plushie Settings", "SpawnWeight", 10, "Toil-Head plushie spawn chance weight.");
			ToilHeadPlushieSpawnAllMoons = new ExtendedConfigEntry<bool>("Toil-Head Plushie Settings", "SpawnAllMoons", defaultValue: true, "If true, the Toil-Head plushie will spawn on all moons. If false, the Toil-Head plushie will only spawn on moons set in the moons list.");
			ToilHeadPlushieMoonSpawnList = new ExtendedConfigEntry<string>("Toil-Head Plushie Settings", "MoonSpawnList", "Experimentation, Assurance, Vow, Offense, March, Adamance, Rend, Dine, Titan, Artifice, Embrion", "The list of moons the Toil-Head plushie will spawn on.\nCurrently only works for vanilla moons.\nOnly works if PlushieSpawnAllMoons is false.");
			ToilHeadPlushieCarryWeight = new ExtendedConfigEntry<int>("Toil-Head Plushie Settings", "CarryWeight", 6, "Toil-Head plushie carry weight in pounds.");
			ToilHeadPlushieMinValue = new ExtendedConfigEntry<int>("Toil-Head Plushie Settings", "MinValue", 80, "Toil-Head plushie min scrap value.");
			ToilHeadPlushieMaxValue = new ExtendedConfigEntry<int>("Toil-Head Plushie Settings", "MaxValue", 250, "Toil-Head plushie max scrap value.");
			ToilSlayerPlushieSpawnWeight = new ExtendedConfigEntry<int>("Toil-Slayer Plushie Settings", "SpawnWeight", 5, "Toil-Slayer plushie spawn chance weight.");
			ToilSlayerPlushieSpawnAllMoons = new ExtendedConfigEntry<bool>("Toil-Slayer Plushie Settings", "SpawnAllMoons", defaultValue: true, "If true, the Toil-Slayer plushie will spawn on all moons. If false, the Toil-Slayer plushie will only spawn on moons set in the moons list.");
			ToilSlayerPlushieMoonSpawnList = new ExtendedConfigEntry<string>("Toil-Slayer Plushie Settings", "MoonSpawnList", "Experimentation, Assurance, Vow, Offense, March, Adamance, Rend, Dine, Titan, Artifice, Embrion", "The list of moons the Toil-Slayer plushie will spawn on.\nCurrently only works for vanilla moons.\nOnly works if PlushieSpawnAllMoons is false.");
			ToilSlayerPlushieCarryWeight = new ExtendedConfigEntry<int>("Toil-Slayer Plushie Settings", "CarryWeight", 12, "Toil-Slayer plushie carry weight in pounds.");
			ToilSlayerPlushieMinValue = new ExtendedConfigEntry<int>("Toil-Slayer Plushie Settings", "MinValue", 150, "Toil-Slayer plushie min scrap value.");
			ToilSlayerPlushieMaxValue = new ExtendedConfigEntry<int>("Toil-Slayer Plushie Settings", "MaxValue", 380, "Toil-Slayer plushie max scrap value.");
			TurretLostLOSDuration = new ExtendedConfigEntry<float>("Turret Settings", "LostLOSDuration", 0.75f, "The duration until the turret loses the target player when not in line of sight.\nVanilla Turret Default value: 2");
			TurretLostLOSDuration.GetValue = () => (HostConfigData == null) ? TurretLostLOSDuration.ConfigEntry.Value : HostConfigData.TurretLostLOSDuration;
			TurretRotationRange = new ExtendedConfigEntry<float>("Turret Settings", "RotationRange", 75f, "The rotation range of the turret in degrees.\nVanilla Turret Default value: 75");
			TurretRotationRange.GetValue = () => (HostConfigData == null) ? TurretRotationRange.ConfigEntry.Value : HostConfigData.TurretRotationRange;
			TurretCodeAccessCooldownDuration = new ExtendedConfigEntry<float>("Turret Settings", "CodeAccessCooldownDuration", 7f, "The duration of the turret being disabled from the terminal in seconds.\nVanilla Turret Default value: 7");
			TurretCodeAccessCooldownDuration.GetValue = () => (HostConfigData == null) ? TurretCodeAccessCooldownDuration.ConfigEntry.Value : HostConfigData.TurretCodeAccessCooldownDuration;
			TurretDetectionRotation = new ExtendedConfigEntry<bool>("Turret Detection Settings", "Rotation", defaultValue: false, "If enabled, the turret will rotate when searching for players.\nVanilla Turret Default value: true");
			TurretDetectionRotation.GetValue = () => (HostConfigData == null) ? TurretDetectionRotation.ConfigEntry.Value : HostConfigData.TurretDetectionRotation;
			TurretDetectionRotationSpeed = new ExtendedConfigEntry<float>("Turret Detection Settings", "RotationSpeed", 28f, "The rotation speed of the turret when in detection state.\nVanilla Turret Default value: 28");
			TurretDetectionRotationSpeed.GetValue = () => (HostConfigData == null) ? TurretDetectionRotationSpeed.ConfigEntry.Value : HostConfigData.TurretDetectionRotationSpeed;
			TurretChargingDuration = new ExtendedConfigEntry<float>("Turret Charging Settings", "ChargingDuration", 2f, "The duration of the turret charging state.\nVanilla Turret Default value: 1.5");
			TurretChargingDuration.GetValue = () => (HostConfigData == null) ? TurretChargingDuration.ConfigEntry.Value : HostConfigData.TurretChargingDuration;
			TurretChargingRotationSpeed = new ExtendedConfigEntry<float>("Turret Charging Settings", "RotationSpeed", 95f, "The rotation speed of the turret when in charging state.\nVanilla Turret Default value: 95");
			TurretChargingRotationSpeed.GetValue = () => (HostConfigData == null) ? TurretChargingRotationSpeed.ConfigEntry.Value : HostConfigData.TurretChargingRotationSpeed;
			TurretFiringRotationSpeed = new ExtendedConfigEntry<float>("Turret Firing Settings", "RotationSpeed", 95f, "The rotation speed of the turret when in firing state.\nVanilla Turret Default value: 95");
			TurretFiringRotationSpeed.GetValue = () => (HostConfigData == null) ? TurretFiringRotationSpeed.ConfigEntry.Value : HostConfigData.TurretFiringRotationSpeed;
			TurretBerserkDuration = new ExtendedConfigEntry<float>("Turret Berserk Settings", "BerserkDuration", 9f, "The duration of the turret berserk state.\nVanilla Turret Default value: 9");
			TurretBerserkDuration.GetValue = () => (HostConfigData == null) ? TurretBerserkDuration.ConfigEntry.Value : HostConfigData.TurretBerserkDuration;
			TurretBerserkRotationSpeed = new ExtendedConfigEntry<float>("Turret Berserk Settings", "RotationSpeed", 77f, "The rotation speed of the turret when in berserk state.\nVanilla Turret Default value: 77");
			TurretBerserkRotationSpeed.GetValue = () => (HostConfigData == null) ? TurretBerserkRotationSpeed.ConfigEntry.Value : HostConfigData.TurretBerserkRotationSpeed;
		}

		private string GetDescriptionForSpawnSettings(string enemyName)
		{
			string text = enemyName + " spawn settings.\n";
			text += "MaxSpawnCount,SpawnChance\n";
			return text + "<int>,<float>";
		}

		private string GetDescriptionForMoonSpawnSettings(string enemyName, string planetName)
		{
			string text = enemyName + " spawn settings for " + planetName + ".\n";
			text += "MaxSpawnCount,SpawnChance\n";
			return text + "<int>,<float>";
		}

		private string GetDescriptionForMoonSpawnSettingsList(string enemyName)
		{
			string text = enemyName + " spawn settings list for moons.\n";
			text += "Separate each entry with a comma.\n";
			text += "PlanetName:MaxSpawnCount:SpawnChance\n";
			return text + "<string>:<int>:<float>";
		}

		private string GetDescriptionForDefaultSpawnSettings(string enemyName)
		{
			string text = enemyName + " default spawn settings for all moons.\n";
			text += "MaxSpawnCount:SpawnChance\n";
			return text + "<int>:<float>";
		}

		private void ClearUnusedEntries()
		{
			ConfigFile config = ((BaseUnityPlugin)Plugin.Instance).Config;
			PropertyInfo property = ((object)config).GetType().GetProperty("OrphanedEntries", BindingFlags.Instance | BindingFlags.NonPublic);
			Dictionary<ConfigDefinition, string> dictionary = (Dictionary<ConfigDefinition, string>)property.GetValue(config, null);
			dictionary.Clear();
			config.Save();
		}

		internal void SetHostConfigData(SyncedConfigData syncedConfigData)
		{
			HostConfigData = syncedConfigData;
		}

		private void SyncedConfigsChanged()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.IsHostOrServer)
			{
				PluginNetworkBehaviour.Instance.SendConfigToPlayerClientRpc(new SyncedConfigData(this));
			}
		}
	}
	public class TurretHeadData
	{
		public bool ForceSpawns = false;

		public int ForceMaxSpawnCount = -1;

		public string EnemyName { get; private set; }

		public bool IsSlayer { get; private set; }

		public GameObject ControllerPrefab { get; private set; }

		public MoonSpawnDataList MoonSpawnDataList { get; private set; }

		public SpawnData ToilationSpawnData { get; private set; }

		public int SpawnCount { get; private set; }

		public TurretHeadData(string enemyName, bool isSlayer, GameObject controllerPrefab, MoonSpawnDataList moonSpawnDataList, SpawnData toilationSpawnData)
		{
			EnemyName = enemyName;
			IsSlayer = isSlayer;
			ControllerPrefab = controllerPrefab;
			MoonSpawnDataList = moonSpawnDataList;
			ToilationSpawnData = toilationSpawnData;
		}

		public void Reset()
		{
			SpawnCount = 0;
			ForceSpawns = false;
			ForceMaxSpawnCount = -1;
		}

		public void AddToSpawnCount()
		{
			SpawnCount++;
		}

		public SpawnData GetSpawnDataForCurrentMoon()
		{
			if (Utils.IsCurrentMoonToilation())
			{
				return ToilationSpawnData;
			}
			return MoonSpawnDataList.GetSpawnDataForCurrentMoon();
		}
	}
	public class TurretHeadManager
	{
		private static Coroutine _setDeadBodyTurretHeadOnServerCoroutine;

		public static List<TurretHeadData> TurretHeadDataList { get; private set; } = new List<TurretHeadData>();


		public static TurretHeadData PlayerTurretHeadData { get; private set; }

		public static Dictionary<EnemyAI, TurretHeadControllerBehaviour> EnemyTurretHeadControllerPairs { get; private set; } = new Dictionary<EnemyAI, TurretHeadControllerBehaviour>();


		public static Dictionary<PlayerControllerB, TurretHeadControllerBehaviour> PlayerTurretHeadControllerPairs { get; private set; } = new Dictionary<PlayerControllerB, TurretHeadControllerBehaviour>();


		public static Dictionary<PlayerControllerB, TurretHeadControllerBehaviour> DeadBodyTurretHeadControllerPairs { get; private set; } = new Dictionary<PlayerControllerB, TurretHeadControllerBehaviour>();


		internal static void Initialize()
		{
			TurretHeadDataList = new List<TurretHeadData>(6)
			{
				new TurretHeadData("Spring", isSlayer: false, Content.ToilHeadControllerPrefab, new MoonSpawnDataList(Plugin.ConfigManager.ToilHeadSpawnSettingsMoonList.Value, new SpawnData(Plugin.ConfigManager.ToilHeadDefaultSpawnSettings.Value)), new SpawnData(Plugin.ConfigManager.ToilationToilHeadSpawnSettings.Value)),
				new TurretHeadData("Spring", isSlayer: true, Content.ToilSlayerControllerPrefab, new MoonSpawnDataList(Plugin.ConfigManager.ToilSlayerSpawnSettingsMoonList.Value, new SpawnData(Plugin.ConfigManager.ToilSlayerDefaultSpawnSettings.Value)), new SpawnData(Plugin.ConfigManager.ToilationToilSlayerSpawnSettings.Value)),
				new TurretHeadData("Manticoil", isSlayer: false, Content.MantiToilControllerPrefab, new MoonSpawnDataList(Plugin.ConfigManager.MantiToilSpawnSettingsMoonList.Value, new SpawnData(Plugin.ConfigManager.MantiToilDefaultSpawnSettings.Value)), new SpawnData(Plugin.ConfigManager.ToilationMantiToilSpawnSettings.Value)),
				new TurretHeadData("Manticoil", isSlayer: true, Content.MantiSlayerControllerPrefab, new MoonSpawnDataList(Plugin.ConfigManager.MantiSlayerSpawnSettingsMoonList.Value, new SpawnData(Plugin.ConfigManager.MantiSlayerDefaultSpawnSettings.Value)), new SpawnData(Plugin.ConfigManager.ToilationMantiSlayerSpawnSettings.Value)),
				new TurretHeadData("Masked", isSlayer: false, Content.ToilMaskedControllerPrefab, new MoonSpawnDataList(Plugin.ConfigManager.ToilMaskedSpawnSettingsMoonList.Value, new SpawnData(Plugin.ConfigManager.ToilMaskedDefaultSpawnSettings.Value)), new SpawnData(Plugin.ConfigManager.ToilationToilMaskedSpawnSettings.Value)),
				new TurretHeadData("Masked", isSlayer: true, Content.SlayerMaskedControllerPrefab, new MoonSpawnDataList(Plugin.ConfigManager.SlayerMaskedSpawnSettingsMoonList.Value, new SpawnData(Plugin.ConfigManager.SlayerMaskedDefaultSpawnSettings.Value)), new SpawnData(Plugin.ConfigManager.ToilationSlayerMaskedSpawnSettings.Value))
			};
			PlayerTurretHeadData = new TurretHeadData(string.Empty, isSlayer: false, null, new MoonSpawnDataList(Plugin.ConfigManager.ToilPlayerSpawnSettingsMoonList.Value, new SpawnData(Plugin.ConfigManager.ToilPlayerDefaultSpawnSettings.Value)), new SpawnData(Plugin.ConfigManager.ToilationToilPlayerSpawnSettings.Value));
			EnemyTurretHeadControllerPairs = new Dictionary<EnemyAI, TurretHeadControllerBehaviour>();
			PlayerTurretHeadControllerPairs = new Dictionary<PlayerControllerB, TurretHeadControllerBehaviour>();
			DeadBodyTurretHeadControllerPairs = new Dictionary<PlayerControllerB, TurretHeadControllerBehaviour>();
			_setDeadBodyTurretHeadOnServerCoroutine = null;
		}

		internal static void Reset()
		{
			TurretHeadDataList.ForEach(delegate(TurretHeadData _)
			{
				_.Reset();
			});
			PlayerTurretHeadData.Reset();
			EnemyTurretHeadControllerPairs.Clear();
			PlayerTurretHeadControllerPairs.Clear();
			DeadBodyTurretHeadControllerPairs.Clear();
			_setDeadBodyTurretHeadOnServerCoroutine = null;
			DespawnAllControllersOnServer();
		}

		internal static bool TrySetEnemyTurretHeadOnServer(EnemyAI enemyScript, bool isSlayer)
		{
			if (!Plugin.IsHostOrServer)
			{
				return false;
			}
			string enemyName = enemyScript.enemyType.enemyName;
			TurretHeadData enemyTurretHeadData = GetEnemyTurretHeadData(enemyName, isSlayer);
			if (enemyTurretHeadData == null)
			{
				Plugin.logger.LogError((object)("Error: Failed to try set \"" + enemyName + "\" Turret-Head on server. TurretHeadData is null."));
				return false;
			}
			SpawnData spawnDataForCurrentMoon = enemyTurretHeadData.GetSpawnDataForCurrentMoon();
			int num = spawnDataForCurrentMoon.MaxSpawnCount;
			if (enemyTurretHeadData.ForceMaxSpawnCount > -1)
			{
				num = enemyTurretHeadData.ForceMaxSpawnCount;
			}
			if (!enemyTurretHeadData.ForceSpawns)
			{
				if (enemyTurretHeadData.SpawnCount >= num)
				{
					return false;
				}
				if (!Utils.RandomPercent(spawnDataForCurrentMoon.SpawnChance))
				{
					return false;
				}
			}
			return SetEnemyTurretHeadOnServer(enemyScript, isSlayer);
		}

		internal static void TrySetPlayerTurretHeadsOnServer()
		{
			if (!Plugin.IsHostOrServer || !StartOfRound.Instance.currentLevel.spawnEnemiesAndScrap || GameNetworkManager.Instance.connectedPlayers == 1)
			{
				return;
			}
			List<PlayerControllerB> list = StartOfRound.Instance.allPlayerScripts.ToList();
			for (int num = list.Count - 1; num >= 0; num--)
			{
				int index = Random.Range(0, num);
				bool isSlayer = Utils.RandomPercent(Plugin.ConfigManager.ToilPlayerSlayerChance.Value);
				PlayerControllerB val = list[index];
				if (((Component)val).gameObject.activeSelf && val.isPlayerControlled)
				{
					TrySetPlayerTurretHeadOnServer(val, isSlayer);
					list.RemoveAt(index);
				}
			}
		}

		internal static bool TrySetPlayerTurretHeadOnServer(PlayerControllerB playerScript, bool isSlayer)
		{
			if (!Plugin.IsHostOrServer)
			{
				return false;
			}
			TurretHeadData playerTurretHeadData = PlayerTurretHeadData;
			SpawnData spawnDataForCurrentMoon = playerTurretHeadData.GetSpawnDataForCurrentMoon();
			int num = spawnDataForCurrentMoon.MaxSpawnCount;
			if (playerTurretHeadData.ForceMaxSpawnCount > -1)
			{
				num = playerTurretHeadData.ForceMaxSpawnCount;
			}
			if (!playerTurretHeadData.ForceSpawns)
			{
				if (playerTurretHeadData.SpawnCount >= num)
				{
					return false;
				}
				if (!Utils.RandomPercent(spawnDataForCurrentMoon.SpawnChance))
				{
					return false;
				}
			}
			return SetPlayerTurretHeadOnServer(playerScript, isSlayer);
		}

		public static bool SetEnemyTurretHeadOnServer(EnemyAI enemyScript, bool isSlayer)
		{
			if (!Plugin.IsHostOrServer)
			{
				return false;
			}
			if ((Object)(object)enemyScript == (Object)null)
			{
				Plugin.logger.LogError((object)$"Error: Failed to set enemy Turret-Head (isSlayer? {isSlayer}) on server. EnemyAI is null.");
				return false;
			}
			string enemyName = enemyScript.enemyType.enemyName;
			if (enemyScript.isEnemyDead)
			{
				Plugin.logger.LogError((object)$"Error: Failed to set enemy \"{enemyName}\" Turret-Head (isSlayer? {isSlayer}) on server. Enemy is already dead.");
				return false;
			}
			if (Utils.IsTurretHead(enemyScript))
			{
				Plugin.logger.LogError((object)$"Error: Failed to set enemy \"{enemyName}\" Turret-Head (isSlayer? {isSlayer}) on server. Enemy is already a Turret-Head.");
				return false;
			}
			TurretHeadData enemyTurretHeadData = GetEnemyTurretHeadData(enemyName, isSlayer);
			if (enemyTurretHeadData == null)
			{
				Plugin.logger.LogError((object)$"Error: Failed to set enemy \"{enemyName}\" Turret-Head (isSlayer? {isSlayer}) on server. TurretHeadData is null.");
				return false;
			}
			SpawnTurretHeadControllerOnServer(enemyTurretHeadData.ControllerPrefab, ((Component)enemyScript).transform);
			Plugin.Instance.LogInfoExtended($"Set enemy \"{enemyName}\" Turret-Head (isSlayer? {isSlayer}) on server.");
			return true;
		}

		public static bool SetPlayerTurretHeadOnServer(PlayerControllerB playerScript, bool isSlayer)
		{
			if (!Plugin.IsHostOrServer)
			{
				return false;
			}
			string playerUsername = playerScript.playerUsername;
			if ((Object)(object)playerScript == (Object)null)
			{
				Plugin.logger.LogError((object)$"Error: Failed to set player \"{playerUsername}\" Turret-Head (isSlayer? {isSlayer}) on server. PlayerControllerB is null.");
				return false;
			}
			if (playerScript.isPlayerDead)
			{
				Plugin.logger.LogError((object)$"Error: Failed to set player \"{playerUsername}\" Turret-Head (isSlayer? {isSlayer}) on server. Player is already dead.");
				return false;
			}
			if (Utils.IsTurretHead(playerScript))
			{
				Plugin.logger.LogError((object)$"Error: Failed to set player \"{playerUsername}\" Turret-Head (isSlayer? {isSlayer}) on server. Player is already a Turret-Head.");
				return false;
			}
			GameObject controllerPrefab = (isSlayer ? Content.SlayerPlayerControllerPrefab : Content.ToilPlayerControllerPrefab);
			SpawnTurretHeadControllerOnServer(controllerPrefab, ((Component)playerScript).transform);
			Plugin.Instance.LogInfoExtended($"Set player \"{playerUsername}\" Turret-Head (isSlayer? {isSlayer}) on server.");
			return true;
		}

		public static void SetDeadBodyTurretHead(PlayerControllerB playerScript, bool isSlayer)
		{
			if (Plugin.IsHostOrServer)
			{
				SetDeadBodyTurretHeadOnServer(playerScript, isSlayer);
			}
			else
			{
				PluginNetworkBehaviour.Instance.SetToilHeadPlayerRagdollServerRpc(PlayerUtils.GetPlayerId(playerScript), isSlayer);
			}
		}

		public static void SetDeadBodyTurretHeadOnServer(PlayerControllerB playerScript, bool isSlayer)
		{
			if (!Plugin.IsHostOrServer)
			{
				return;
			}
			bool value = Plugin.ConfigManager.SpawnRealToiledPlayerRagdolls.Value;
			if (!Plugin.ConfigManager.SpawnToiledPlayerRagdolls.Value)
			{
				Plugin.Instance.LogErrorExtended($"Error: Failed to set player ragdoll Turret-Head (isSlayer? {isSlayer}, isReal? {value}) on server. Spawning player ragdoll Turret-Heads is disabled in the config settings.");
				return;
			}
			if ((Object)(object)playerScript == (Object)null)
			{
				Plugin.logger.LogError((object)$"Error: Failed to set player ragdoll Turret-Head (isSlayer? {isSlayer}, isReal? {value}) on server. PlayerControllerB is null.");
				return;
			}
			if (_setDeadBodyTurretHeadOnServerCoroutine != null)
			{
				((MonoBehaviour)StartOfRound.Instance).StopCoroutine(_setDeadBodyTurretHeadOnServerCoroutine);
			}
			_setDeadBodyTurretHeadOnServerCoroutine = ((MonoBehaviour)StartOfRound.Instance).StartCoroutine(SetDeadBodyTurretHeadOnServerCO(playerScript, isSlayer, value));
		}

		private static IEnumerator SetDeadBodyTurretHeadOnServerCO(PlayerControllerB playerScript, bool isSlayer, bool isReal)
		{
			if (!Plugin.IsHostOrServer)
			{
				yield break;
			}
			string playerUsername = playerScript.playerUsername;
			yield return Utils.WaitUntil(() => (Object)(object)playerScript.deadBody != (Object)null);
			DeadBodyInfo deadBodyScript = playerScript.deadBody;
			if ((Object)(object)deadBodyScript == (Object)null)
			{
				Plugin.logger.LogError((object)$"Error: Failed to set player \"{playerUsername}\" ragdoll Turret-Head (isSlayer? {isSlayer}, isReal? {isReal}) on server. DeadBodyInfo is null.");
				yield break;
			}
			GameObject ragdollObject = ((Component)deadBodyScript).gameObject;
			if (((Object)ragdollObject).name != "PlayerRagdollSpring Variant(Clone)")
			{
				Plugin.logger.LogError((object)$"Error: Failed to set player \"{playerUsername}\" ragdoll Turret-Head (isSlayer? {isSlayer}, isReal? {isReal}) on server. Player ragdoll is not of type \"PlayerRagdollSpring Variant\".");
				yield break;
			}
			yield return Utils.WaitUntil(() => (Object)(object)ragdollObject.GetComponentInChildren<NetworkObject>() != (Object)null);
			NetworkObject ragdollNetworkObject = ragdollObject.GetComponentInChildren<NetworkObject>();
			if ((Object)(object)ragdollNetworkObject == (Object)null)
			{
				Plugin.logger.LogError((object)$"Error: Failed to set player \"{playerUsername}\" ragdoll Turret-Head (isSlayer? {isSlayer}, isReal? {isReal}) on server. NetworkObject is null.");
				yield break;
			}
			if (Utils.IsTurretHead(deadBodyScript))
			{
				Plugin.logger.LogError((object)$"Error: Failed to set player \"{playerUsername}\" ragdoll Turret-Head (isSlayer? {isSlayer}, isReal? {isReal}) on server. Player is already a player ragdoll Turret-Head.");
				yield break;
			}
			GameObject controllerPrefab = (isSlayer ? Content.SlayedDeadBodyControllerPrefab : Content.ToiledDeadBodyControllerPrefab);
			SpawnTurretHeadControllerOnServer(controllerPrefab, ((Component)ragdollNetworkObject).transform);
			Plugin.Instance.LogInfoExtended($"Set player \"{playerUsername}\" ragdoll Turret-Head (isSlayer? {isSlayer}, isReal? {isReal}) on server.");
		}

		private static void SpawnTurretHeadControllerOnServer(GameObject controllerPrefab, Transform parentTransform)
		{
			if (Plugin.IsHostOrServer)
			{
				GameObject val = Object.Instantiate<GameObject>(controllerPrefab, parentTransform);
				val.GetComponent<NetworkObject>().Spawn(false);
				val.transform.SetParent(parentTransform);
				val.GetComponent<TurretHeadControllerBehaviour>().SetupTurret();
			}
		}

		public static void AddEnemyTurretHeadControllerPair(EnemyAI enemyScript, TurretHeadControllerBehaviour behaviour)
		{
			EnemyTurretHeadControllerPairs.Add(enemyScript, behaviour);
		}

		public static void AddPlayerTurretHeadControllerPair(PlayerControllerB playerScript, TurretHeadControllerBehaviour behaviour)
		{
			PlayerTurretHeadControllerPairs.Add(playerScript, behaviour);
		}

		public static void AddDeadBodyTurretHeadControllerPair(PlayerControllerB playerScript, TurretHeadControllerBehaviour behaviour)
		{
			DeadBodyTurretHeadControllerPairs.Add(playerScript, behaviour);
		}

		internal static void AddToEnemySpawnCount(EnemyAI enemyScript, bool isSlayer)
		{
			string enemyName = enemyScript.enemyType.enemyName;
			TurretHeadData enemyTurretHeadData = GetEnemyTurretHeadData(enemyName, isSlayer);
			if (enemyTurretHeadData == null)
			{
				Plugin.logger.LogError((object)("Error: Failed to add to spawn count for enemy \"" + enemyName + "\". TurretHeadData is null."));
				return;
			}
			enemyTurretHeadData.AddToSpawnCount();
			Plugin.Instance.LogInfoExtended($"AddToEnemySpawnCount(); Enemy \"{enemyName}\" SpawnCount: {enemyTurretHeadData.SpawnCount}, MaxSpawnCount: {enemyTurretHeadData.GetSpawnDataForCurrentMoon().MaxSpawnCount}, SpawnChance: {enemyTurretHeadData.GetSpawnDataForCurrentMoon().SpawnChance}");
		}

		internal static void AddToPlayerSpawnCount()
		{
			TurretHeadData playerTurretHeadData = PlayerTurretHeadData;
			playerTurretHeadData.AddToSpawnCount();
		}

		public static TurretHeadData GetEnemyTurretHeadData(string enemyName, bool isSlayer)
		{
			foreach (TurretHeadData turretHeadData in TurretHeadDataList)
			{
				if (!turretHeadData.EnemyName.Equals(enemyName, StringComparison.OrdinalIgnoreCase) || turretHeadData.IsSlayer != isSlayer)
				{
					continue;
				}
				return turretHeadData;
			}
			return null;
		}

		public static void DespawnEnemyControllerOnServer(EnemyAI enemyScript)
		{
			if (!Plugin.IsHostOrServer)
			{
				return;
			}
			string enemyName = enemyScript.enemyType.enemyName;
			if (EnemyTurretHeadControllerPairs.TryGetValue(enemyScript, out var value))
			{
				NetworkObject val = default(NetworkObject);
				if (((Component)value).TryGetComponent<NetworkObject>(ref val))
				{
					val.Despawn(true);
					Plugin.Instance.LogInfoExtended("Despawned enemy \"" + enemyName + "\" Turret-Head controller.");
				}
				else
				{
					Plugin.logger.LogError((object)("Error: Failed to despawn enemy \"" + enemyName + "\" Turret-Head controller. NetworkObject is null."));
				}
				EnemyTurretHeadControllerPairs.Remove(enemyScript);
			}
			else
			{
				Plugin.logger.LogError((object)("Error: Failed to despawn enemy \"" + enemyName + "\" Turret-Head controller. Could not find value from key."));
			}
		}

		public static void DespawnPlayerControllerOnServer(PlayerControllerB playerScript)
		{
			if (!Plugin.IsHostOrServer)
			{
				return;
			}
			string playerUsername = playerScript.playerUsername;
			if (PlayerTurretHeadControllerPairs.TryGetValue(playerScript, out var value))
			{
				NetworkObject val = default(NetworkObject);
				if (((Component)value).TryGetComponent<NetworkObject>(ref val))
				{
					val.Despawn(true);
					Plugin.Instance.LogInfoExtended("Despawned player \"" + playerUsername + "\" Turret-Head controller.");
				}
				else
				{
					Plugin.logger.LogError((object)("Error: Failed to despawn player \"" + playerUsername + "\" Turret-Head controller. NetworkObject is null."));
				}
				PlayerTurretHeadControllerPairs.Remove(playerScript);
			}
			else
			{
				Plugin.logger.LogError((object)("Error: Failed to despawn player \"" + playerUsername + "\" Turret-Head controller. Could not find value from key."));
			}
		}

		public static void DespawnDeadBodyControllerOnServer(PlayerControllerB playerScript)
		{
			if (!Plugin.IsHostOrServer)
			{
				return;
			}
			string playerUsername = playerScript.playerUsername;
			if (DeadBodyTurretHeadControllerPairs.TryGetValue(playerScript, out var value))
			{
				NetworkObject val = default(NetworkObject);
				if (((Component)value).TryGetComponent<NetworkObject>(ref val))
				{
					val.Despawn(true);
					Plugin.Instance.LogInfoExtended("Despawned player \"" + playerUsername + "\" ragdoll Turret-Head controller.");
				}
				else
				{
					Plugin.logger.LogError((object)("Error: Failed to despawn player \"" + playerUsername + "\" ragdoll Turret-Head controller. NetworkObject is null."));
				}
				DeadBodyTurretHeadControllerPairs.Remove(playerScript);
			}
			else
			{
				Plugin.logger.LogError((object)("Error: Failed to despawn player \"" + playerUsername + "\" ragdoll Turret-Head controller. Could not find value from key."));
			}
		}

		private static void DespawnAllControllersOnServer()
		{
			if (!Plugin.IsHostOrServer)
			{
				return;
			}
			try
			{
				TurretHeadControllerBehaviour[] array = Object.FindObjectsByType<TurretHeadControllerBehaviour>((FindObjectsSortMode)0);
				NetworkObject val = default(NetworkObject);
				foreach (TurretHeadControllerBehaviour turretHeadControllerBehaviour in array)
				{
					if (!((Component)turretHeadControllerBehaviour).TryGetComponent<NetworkObject>(ref val))
					{
						Plugin.logger.LogError((object)"Error: Failed to despawn TurretHeadBehaviour. NetworkObject is null.");
					}
					else
					{
						val.Despawn(true);
					}
				}
				Plugin.Instance.LogInfoExtended("Finished despawning all TurretHeadBehaviour(s).");
			}
			catch (Exception arg)
			{
				Plugin.logger.LogError((object)$"Error: Failed to despawn all TurretHeadBehaviour(s).\n\n{arg}");
			}
		}

		public static bool IsEnemyTurretHead(EnemyAI enemyScript)
		{
			return EnemyTurretHeadControllerPairs.ContainsKey(enemyScript);
		}

		public static bool IsPlayerTurretHead(PlayerControllerB playerScript)
		{
			return PlayerTurretHeadControllerPairs.ContainsKey(playerScript);
		}

		public static bool IsDeadBodyTurretHead(PlayerControllerB playerScript)
		{
			return DeadBodyTurretHeadControllerPairs.ContainsKey(playerScript);
		}
	}
	public class Utils
	{
		public static bool RandomPercent(float percent)
		{
			if (percent <= 0f)
			{
				return false;
			}
			if (percent >= 100f)
			{
				return true;
			}
			return Random.value <= percent * 0.01f;
		}

		public static void DisableColliders(GameObject gameObject, bool keepScanNodeEnabled = false)
		{
			Collider[] componentsInChildren = gameObject.GetComponentsInChildren<Collider>();
			Collider[] array = componentsInChildren;
			foreach (Collider val in array)
			{
				if (!keepScanNodeEnabled || !(((Object)((Component)val).gameObject).name == "ScanNode"))
				{
					val.enabled = false;
				}
			}
		}

		public static void DisableRenderers(GameObject gameObject)
		{
			MeshRenderer[] componentsInChildren = gameObject.GetComponentsInChildren<MeshRenderer>();
			foreach (MeshRenderer val in componentsInChildren)
			{
				((Renderer)val).enabled = false;
			}
			SkinnedMeshRenderer[] componentsInChildren2 = gameObject.GetComponentsInChildren<SkinnedMeshRenderer>();
			foreach (SkinnedMeshRenderer val2 in componentsInChildren2)
			{
				((Renderer)val2).enabled = false;
			}
		}

		public static IEnumerator WaitUntil(Func<bool> predicate, float maxDuration = 5f, int iterationsPerSecond = 10)
		{
			float timer = 0f;
			float timePerIteration = 1f / (float)iterationsPerSecond;
			for (; timer < maxDuration; timer += Time.deltaTime)
			{
				if (predicate())
				{
					break;
				}
				yield return (object)new WaitForSeconds(timePerIteration);
			}
		}

		public static bool IsValidEnemy(EnemyAI enemyScript)
		{
			if (IsSpring(enemyScript))
			{
				return true;
			}
			if (IsManticoil(enemyScript))
			{
				return true;
			}
			if (IsMasked(enemyScript))
			{
				return true;
			}
			return false;
		}

		public static bool IsSpring(EnemyAI enemyScript)
		{
			return enemyScript.enemyType.enemyName == "Spring";
		}

		public static bool IsManticoil(EnemyAI enemyScript)
		{
			return enemyScript.enemyType.enemyName == "Manticoil";
		}

		public static bool IsMasked(EnemyAI enemyScript)
		{
			return enemyScript.enemyType.enemyName == "Masked";
		}

		public static bool IsTurretHead(EnemyAI enemyScript)
		{
			return (Object)(object)((Component)enemyScript).GetComponentInChildren<TurretHeadControllerBehaviour>() != (Object)null;
		}

		public static bool IsTurretHead(PlayerControllerB playerScript)
		{
			return (Object)(object)((Component)playerScript).GetComponentInChildren<TurretHeadControllerBehaviour>() != (Object)null;
		}

		public static bool IsTurretHead(DeadBodyInfo deadBodyScript)
		{
			return (Object)(object)((Component)deadBodyScript).GetComponentInChildren<TurretHeadControllerBehaviour>() != (Object)null;
		}

		public static bool IsCurrentMoonToilation()
		{
			if ((Object)(object)StartOfRound.Instance == (Object)null)
			{
				return false;
			}
			string planetName = StartOfRound.Instance.currentLevel.PlanetName;
			if (planetName.Equals("69 Toilation", StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
			if (planetName.Contains("Toilation", StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
			return false;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "com.github.zehsteam.ToilHead";

		public const string PLUGIN_NAME = "ToilHead";

		public const string PLUGIN_VERSION = "1.7.2";
	}
}
namespace com.github.zehsteam.ToilHead.Patches
{
	[HarmonyPatch(typeof(EnemyAI))]
	internal class EnemyAIPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPatch(ref EnemyAI __instance)
		{
			if (Utils.IsValidEnemy(__instance) && !TurretHeadManager.TrySetEnemyTurretHeadOnServer(__instance, isSlayer: true))
			{
				TurretHeadManager.TrySetEnemyTurretHeadOnServer(__instance, isSlayer: false);
			}
		}

		[HarmonyPatch("HitEnemyServerRpc")]
		[HarmonyPostfix]
		private static void HitEnemyServerRpcPatch(ref EnemyAI __instance, int playerWhoHit)
		{
			if (!__instance.isEnemyDead && TurretHeadManager.EnemyTurretHeadControllerPairs.TryGetValue(__instance, out var value) && value.TurretBehaviour.turretActive)
			{
				value.TurretBehaviour.EnterBerserkModeClientRpc();
			}
		}

		[HarmonyPatch("KillEnemy")]
		[HarmonyPrefix]
		private static void KillEnemyPatch(ref EnemyAI __instance, bool destroy)
		{
			if (Plugin.IsHostOrServer && destroy && TurretHeadManager.IsEnemyTurretHead(__instance))
			{
				TurretHeadManager.DespawnEnemyControllerOnServer(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPatch()
		{
			AddNetworkPrefabs();
		}

		private static void AddNetworkPrefabs()
		{
			AddNetworkPrefab(Content.NetworkHandlerPrefab);
			AddNetworkPrefab(Content.ToilHeadControllerPrefab);
			AddNetworkPrefab(Content.ToilSlayerControllerPrefab);
			AddNetworkPrefab(Content.MantiToilControllerPrefab);
			AddNetworkPrefab(Content.MantiSlayerControllerPrefab);
			AddNetworkPrefab(Content.ToilPlayerControllerPrefab);
			AddNetworkPrefab(Content.SlayerPlayerControllerPrefab);
			AddNetworkPrefab(Content.ToiledDeadBodyControllerPrefab);
			AddNetworkPrefab(Content.SlayedDeadBodyControllerPrefab);
			AddNetworkPrefab(Content.ToilMaskedControllerPrefab);
			AddNetworkPrefab(Content.SlayerMaskedControllerPrefab);
		}

		private static void AddNetworkPrefab(GameObject prefab)
		{
			if ((Object)(object)prefab == (Object)null)
			{
				Plugin.logger.LogError((object)"Error: Failed to register network prefab. Prefab is null.");
				return;
			}
			NetworkManager.Singleton.AddNetworkPrefab(prefab);
			Plugin.logger.LogInfo((object)("Registered \"" + ((Object)prefab).name + "\" network prefab."));
		}
	}
	[HarmonyPatch(typeof(MaskedPlayerEnemy))]
	internal class MaskedPlayerEnemyPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPatch(ref EnemyAI __instance)
		{
			if (!TurretHeadManager.TrySetEnemyTurretHeadOnServer(__instance, isSlayer: true))
			{
				TurretHeadManager.TrySetEnemyTurretHeadOnServer(__instance, isSlayer: false);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		[HarmonyPatch("KillPlayerServerRpc")]
		[HarmonyPrefix]
		private static void KillPlayerServerRpcPatch(ref PlayerControllerB __instance)
		{
			if (TurretHeadManager.IsPlayerTurretHead(__instance))
			{
				TurretHeadManager.DespawnPlayerControllerOnServer(__instance);
			}
		}

		[HarmonyPatch("OnDestroy")]
		[HarmonyPrefix]
		private static void OnDestroyPatch(ref PlayerControllerB __instance)
		{
			if (Plugin.IsHostOrServer && TurretHeadManager.IsPlayerTurretHead(__instance))
			{
				TurretHeadManager.DespawnPlayerControllerOnServer(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(RagdollGrabbableObject))]
	internal class RagdollGrabbableObjectPatch
	{
		[HarmonyPatch("OnDestroy")]
		[HarmonyPrefix]
		private static void OnDestroyPatch(ref RagdollGrabbableObject __instance)
		{
			if (Plugin.IsHostOrServer)
			{
				PlayerControllerB playerScript = __instance.ragdoll.playerScript;
				if (TurretHeadManager.IsDeadBodyTurretHead(playerScript))
				{
					TurretHeadManager.DespawnDeadBodyControllerOnServer(playerScript);
				}
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	internal class RoundManagerPatch
	{
		[HarmonyPatch("LoadNewLevel")]
		[HarmonyPostfix]
		private static void LoadNewLevelPatch()
		{
			Plugin.Instance.OnNewLevelLoaded();
		}

		[HarmonyPatch("GenerateNewLevelClientRpc")]
		[HarmonyPrefix]
		private static void GenerateNewLevelClientRpcPatch()
		{
			if (!Plugin.IsHostOrServer)
			{
				Plugin.Instance.OnNewLevelLoaded();
			}
		}

		[HarmonyPatch("FinishGeneratingNewLevelClientRpc")]
		[HarmonyPostfix]
		private static void FinishGeneratingNewLevelClientRpcPatch()
		{
			Plugin.Instance.OnNewLevelFinishedLoading();
		}
	}
	[HarmonyPatch(typeof(SpringManAI))]
	internal class SpringManAIPatch
	{
		[HarmonyPatch("OnCollideWithPlayer")]
		[HarmonyPostfix]
		private static void OnCollideWithPlayerPatch(ref SpringManAI __instance, ref Collider other)
		{
			TurretHeadControllerBehaviour componentInChildren = ((Component)__instance).GetComponentInChildren<TurretHeadControllerBehaviour>();
			if (!((Object)(object)componentInChildren == (Object)null))
			{
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if (!((Object)(object)component == (Object)null) && PlayerUtils.IsLocalPlayer(component) && component.AllowPlayerDeath())
				{
					bool isMinigun = componentInChildren.TurretBehaviour.IsMinigun;
					Plugin.Instance.LogInfoExtended($"SpringManAI OnCollideWithPlayer \"{component.playerUsername}\" isSlayer? {isMinigun}");
					TurretHeadManager.SetDeadBodyTurretHead(component, isMinigun);
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void AwakePatch()
		{
			SpawnNetworkHandler();
		}

		private static void SpawnNetworkHandler()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.IsHostOrServer)
			{
				GameObject val = Object.Instantiate<GameObject>(Content.NetworkHandlerPrefab, Vector3.zero, Quaternion.identity);
				val.GetComponent<NetworkObject>().Spawn(false);
			}
		}

		[HarmonyPatch("OnClientConnect")]
		[HarmonyPrefix]
		private static void OnClientConnectPatch(ref ulong clientId)
		{
			SendConfigToNewConnectedPlayer(clientId);
		}

		private static void SendConfigToNewConnectedPlayer(ulong clientId)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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_0038: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.IsHostOrServer)
			{
				ClientRpcParams val = default(ClientRpcParams);
				val.Send = new ClientRpcSendParams
				{
					TargetClientIds = new <>z__ReadOnlyArray<ulong>(new ulong[1] { clientId })
				};
				ClientRpcParams clientRpcParams = val;
				Plugin.logger.LogInfo((object)$"Sending config to client: {clientId}");
				PluginNetworkBehaviour.Instance.SendConfigToPlayerClientRpc(new SyncedConfigData(Plugin.ConfigManager), clientRpcParams);
			}
		}

		[HarmonyPatch("ShipHasLeft")]
		[HarmonyPostfix]
		private static void ShipHasLeftPatch()
		{
			Plugin.Instance.OnShipHasLeft();
		}

		[HarmonyPatch("OnLocalDisconnect")]
		[HarmonyPrefix]
		private static void OnLocalDisconnectPatch()
		{
			Plugin.Instance.OnLocalDisconnect();
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	internal class TerminalPatch
	{
		[HarmonyPatch("CallFunctionInAccessibleTerminalObject")]
		[HarmonyPostfix]
		private static void CallFunctionInAccessibleTerminalObjectPatch(string word, ref bool ___broadcastedCodeThisFrame)
		{
			FollowTerminalAccessibleObjectBehaviour[] array = Object.FindObjectsByType<FollowTerminalAccessibleObjectBehaviour>((FindObjectsSortMode)0);
			FollowTerminalAccessibleObjectBehaviour[] array2 = array;
			foreach (FollowTerminalAccessibleObjectBehaviour followTerminalAccessibleObjectBehaviour in array2)
			{
				if (!(followTerminalAccessibleObjectBehaviour.objectCode != word))
				{
					Plugin.Instance.LogInfoExtended("Found accessible terminal object with corresponding string, calling function.");
					___broadcastedCodeThisFrame = true;
					followTerminalAccessibleObjectBehaviour.CallFunctionFromTerminal();
				}
			}
		}
	}
	[HarmonyPatch(typeof(Turret))]
	internal class TurretPatch
	{
		[HarmonyPatch("CheckForPlayersInLineOfSight")]
		[HarmonyPostfix]
		private static void CheckForPlayersInLineOfSightPatch(ref PlayerControllerB __result)
		{
			if ((Object)(object)__result != (Object)null && TurretHeadManager.IsPlayerTurretHead(__result))
			{
				__result = null;
			}
		}
	}
}
namespace com.github.zehsteam.ToilHead.MonoBehaviours
{
	public class FollowTerminalAccessibleObjectBehaviour : NetworkBehaviour
	{
		[HideInInspector]
		public string objectCode;

		[HideInInspector]
		public float codeAccessCooldownTimer = 7f;

		public InteractEvent terminalCodeEvent;

		public InteractEvent terminalCodeCooldownEvent;

		[Space(3f)]
		[HideInInspector]
		public MeshRenderer[] codeMaterials;

		[HideInInspector]
		public int rows;

		[HideInInspector]
		public int columns;

		private bool initializedValues;

		private TextMeshProUGUI mapRadarText;

		private Image mapRadarBox;

		[HideInInspector]
		public bool inCooldown { get; private set; }

		[HideInInspector]
		public float currentCooldownTimer { get; private set; }

		[HideInInspector]
		public RectTransform mapRadarRectTransform { get; private set; }

		private void Start()
		{
			InitializeValues();
			codeAccessCooldownTimer = Plugin.ConfigManager.TurretCodeAccessCooldownDuration.Value;
		}

		public void InitializeValues()
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: 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_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			if (!initializedValues)
			{
				initializedValues = true;
				GameObject val = Object.Instantiate<GameObject>(StartOfRound.Instance.objectCodePrefab, StartOfRound.Instance.mapScreen.mapCameraStationaryUI, false);
				mapRadarRectTransform = val.GetComponent<RectTransform>();
				((Transform)mapRadarRectTransform).position = ((Component)this).transform.position + Vector3.up * 4.35f;
				RectTransform obj = mapRadarRectTransform;
				((Transform)obj).position = ((Transform)obj).position + (((Transform)mapRadarRectTransform).up * 1.2f - ((Transform)mapRadarRectTransform).right * 1.2f);
				mapRadarText = val.GetComponentInChildren<TextMeshProUGUI>();
				((TMP_Text)mapRadarText).text = objectCode;
				mapRadarBox = val.GetComponentInChildren<Image>();
			}
		}

		private void Update()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)mapRadarRectTransform == (Object)null))
			{
				((Transform)mapRadarRectTransform).position = ((Component)this).transform.position + Vector3.up * 4.35f;
				RectTransform obj = mapRadarRectTransform;
				((Transform)obj).position = ((Transform)obj).position + (((Transform)mapRadarRectTransform).up * 1.2f - ((Transform)mapRadarRectTransform).right * 1.2f);
			}
		}

		public void CallFunctionFromTerminal()
		{
			if (!inCooldown)
			{
				((UnityEvent<PlayerControllerB>)(object)terminalCodeEvent).Invoke(GameNetworkManager.Instance.localPlayerController);
				if (codeAccessCooldownTimer > 0f)
				{
					currentCooldownTimer = codeAccessCooldownTimer;
					((MonoBehaviour)this).StartCoroutine(countCodeAccessCooldown());
				}
				Plugin.Instance.LogInfoExtended("calling terminal function for code : " + objectCode + "; object name: " + ((Object)((Component)this).gameObject).name);
			}
		}

		public void TerminalCodeCooldownReached()
		{
			((UnityEvent<PlayerControllerB>)(object)terminalCodeCooldownEvent).Invoke((PlayerControllerB)null);
			Plugin.Instance.LogInfoExtended("cooldown reached for object with code : " + objectCode + "; object name: " + ((Object)((Component)this).gameObject).name);
		}

		private IEnumerator countCodeAccessCooldown()
		{
			inCooldown = true;
			if (!initializedValues)
			{
				InitializeValues();
			}
			Image cooldownBar = mapRadarBox;
			Image[] componentsInChildren = ((Component)mapRadarText).gameObject.GetComponentsInChildren<Image>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if ((int)componentsInChildren[i].type == 3)
				{
					cooldownBar = componentsInChildren[i];
				}
			}
			((Behaviour)cooldownBar).enabled = true;
			((Graphic)mapRadarText).color = Color.red;
			((Graphic)mapRadarBox).color = Color.red;
			while (currentCooldownTimer > 0f)
			{
				yield return null;
				currentCooldownTimer -= Time.deltaTime;
				cooldownBar.fillAmount = currentCooldownTimer / codeAccessCooldownTimer;
			}
			TerminalCodeCooldownReached();
			((Graphic)mapRadarText).color = Color.green;
			((Graphic)mapRadarBox).color = Color.green;
			currentCooldownTimer = 1.5f;
			int frameNum = 0;
			while (currentCooldownTimer > 0f)
			{
				yield return null;
				currentCooldownTimer -= Time.deltaTime;
				cooldownBar.fillAmount = Mathf.Abs(currentCooldownTimer / 1.5f - 1f);
				frameNum++;
				if (frameNum % 7 == 0)
				{
					((Behaviour)mapRadarText).enabled = !((Behaviour)mapRadarText).enabled;
				}
			}
			((Behaviour)mapRadarText).enabled = true;
			((Behaviour)cooldownBar).enabled = false;
			inCooldown = false;
		}

		public voi

BepInEx/plugins/americanompany/CountryRoadCreature.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BigEyes.Utils;
using CountryRoadCreature.Scripts;
using GameNetcodeStuff;
using LethalConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BigEyes.Utils
{
	public class RegisterUtil
	{
		public static void RegisterEnemyWithConfig(string configMoonRarity, EnemyType enemy, TerminalNode terminalNode, TerminalKeyword terminalKeyword, float powerLevel, int spawnCount)
		{
			enemy.MaxCount = spawnCount;
			enemy.PowerLevel = powerLevel;
			var (dictionary, dictionary2) = ConfigParsing(configMoonRarity);
			Enemies.RegisterEnemy(enemy, dictionary, dictionary2, terminalNode, terminalKeyword);
		}

		public static void RegisterScrapWithConfig(string configMoonRarity, Item scrap)
		{
			var (dictionary, dictionary2) = ConfigParsing(configMoonRarity);
			Items.RegisterScrap(scrap, dictionary, dictionary2);
		}

		public static void RegisterShopItemWithConfig(bool enabledScrap, Item item, TerminalNode terminalNode, int itemCost, string configMoonRarity)
		{
			Items.RegisterShopItem(item, (TerminalNode)null, (TerminalNode)null, terminalNode, itemCost);
			if (enabledScrap)
			{
				RegisterScrapWithConfig(configMoonRarity, item);
			}
		}

		public static (Dictionary<LevelTypes, int> spawnRateByLevelType, Dictionary<string, int> spawnRateByCustomLevelType) ConfigParsing(string configMoonRarity)
		{
			//IL_0099: 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)
			Dictionary<LevelTypes, int> dictionary = new Dictionary<LevelTypes, int>();
			Dictionary<string, int> dictionary2 = new Dictionary<string, int>();
			foreach (string item in from s in configMoonRarity.Split(',')
				select s.Trim())
			{
				string[] array = item.Split(':');
				if (array.Length != 2)
				{
					continue;
				}
				string text = array[0];
				if (!int.TryParse(array[1], out var result))
				{
					continue;
				}
				if (Enum.TryParse<LevelTypes>(text, ignoreCase: true, out LevelTypes result2))
				{
					dictionary[result2] = result;
					continue;
				}
				string value = text + "Level";
				if (Enum.TryParse<LevelTypes>(value, ignoreCase: true, out result2))
				{
					dictionary[result2] = result;
				}
				else
				{
					dictionary2[text] = result;
				}
			}
			return (dictionary, dictionary2);
		}
	}
}
namespace CountryRoadCreature
{
	[BepInPlugin("wexop.country_road_creature", "CountryRoadCreature", "1.0.7")]
	[BepInDependency("evaisa.lethallib", "0.15.1")]
	public class CountryRoadCreaturePlugin : BaseUnityPlugin
	{
		private const string GUID = "wexop.country_road_creature";

		private const string NAME = "CountryRoadCreature";

		private const string VERSION = "1.0.7";

		public Dictionary<int, LightInformation> lightsInUse = new Dictionary<int, LightInformation>();

		public static CountryRoadCreaturePlugin instance;

		public ConfigEntry<string> spawnMoonRarity;

		public ConfigEntry<string> headScrapMoonRarity;

		public ConfigEntry<string> handScrapMoonRarity;

		public ConfigEntry<int> maxCountryRoadCreatureSpawnNb;

		public ConfigEntry<float> countryRoadBaseSpeed;

		public ConfigEntry<float> countryRoadMaxSpeedMutliplier;

		public ConfigEntry<int> scrapHitPlayerChance;

		private void Awake()
		{
			instance = this;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"CountryRoadCreature starting....");
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "countryroadcreature");
			AssetBundle bundle = AssetBundle.LoadFromFile(text);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"CountryRoadCreature bundle found !");
			LoadConfigs();
			RegisterMonster(bundle);
			RegisterScrap(bundle);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"CountryRoadCreature is ready!");
		}

		private void LoadConfigs()
		{
			spawnMoonRarity = ((BaseUnityPlugin)this).Config.Bind<string>("General", "SpawnRarity", "Modded:40,ExperimentationLevel:20,AssuranceLevel:20,VowLevel:20,OffenseLevel:25,MarchLevel:25,RendLevel:30,DineLevel:30,TitanLevel:50,Adamance:50,Embrion:50,Artifice:55", "Chance for Country road creature to spawn for any moon, example => assurance:100,offense:50 . You need to restart the game.");
			CreateStringConfig(spawnMoonRarity, requireRestart: true);
			maxCountryRoadCreatureSpawnNb = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MaxSpawnNumber", 1, "Max country road creatures spawn number. You need to restart the game.");
			CreateIntConfig(maxCountryRoadCreatureSpawnNb);
			handScrapMoonRarity = ((BaseUnityPlugin)this).Config.Bind<string>("General", "HandScrapSpawnRarity", "Modded:30,ExperimentationLevel:20,AssuranceLevel:20,VowLevel:25,OffenseLevel:25,MarchLevel:30,RendLevel:35,DineLevel:35,TitanLevel:35,Adamance:35,Embrion:35,Artifice:40", "Chance for creature hand scrap to spawn for any moon, example => assurance:100,offense:50 . You need to restart the game.");
			CreateStringConfig(handScrapMoonRarity, requireRestart: true);
			headScrapMoonRarity = ((BaseUnityPlugin)this).Config.Bind<string>("General", "HeadScrapSpawnRarity", "Modded:10,ExperimentationLevel:5,AssuranceLevel:5,VowLevel:10,OffenseLevel:10,MarchLevel:10,RendLevel:13,DineLevel:13,TitanLevel:15,Adamance:15,Embrion:20,Artifice:22", "Chance for creature head scrap to spawn for any moon, example => assurance:100,offense:50 . You need to restart the game.");
			CreateStringConfig(headScrapMoonRarity, requireRestart: true);
			scrapHitPlayerChance = ((BaseUnityPlugin)this).Config.Bind<int>("General", "HeadScrapHitPlayerChance", 10, "Chance for creature head scrap item to hit player after lights animation. You don't need to restart the game.");
			CreateIntConfig(scrapHitPlayerChance);
			countryRoadBaseSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("MonsterBehavior", "CountryRoadBaseSpeed", 3.33f, "Country road Creature base speed. You don't need to restart the game.");
			CreateFloatConfig(countryRoadBaseSpeed);
			countryRoadMaxSpeedMutliplier = ((BaseUnityPlugin)this).Config.Bind<float>("MonsterBehavior", "CountryRoadMaxSpeedMultiplier", 2.4f, "Country road Creature max speed multiplier, based on his angry gauge. You don't need to restart the game.");
			CreateFloatConfig(countryRoadMaxSpeedMutliplier, 1f, 50f);
		}

		private void RegisterMonster(AssetBundle bundle)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			EnemyType val = bundle.LoadAsset<EnemyType>("Assets/LethalCompany/Mods/CountryRoadCreature/CountryRoadCreature.asset");
			val.MaxCount = maxCountryRoadCreatureSpawnNb.Value;
			((BaseUnityPlugin)this).Logger.LogInfo((object)(((Object)val).name + " FOUND"));
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"{val.enemyPrefab} prefab");
			NetworkPrefabs.RegisterNetworkPrefab(val.enemyPrefab);
			Utilities.FixMixerGroups(val.enemyPrefab);
			TerminalNode val2 = new TerminalNode();
			val2.creatureName = "CountryRoadCreature";
			val2.displayText = "Run.";
			TerminalKeyword val3 = new TerminalKeyword();
			val3.word = "CountryRoadCreature";
			RegisterUtil.RegisterEnemyWithConfig(spawnMoonRarity.Value, val, val2, val3, val.PowerLevel, val.MaxCount);
		}

		private void RegisterScrap(AssetBundle bundle)
		{
			Item val = bundle.LoadAsset<Item>("Assets/LethalCompany/Mods/CountryRoadCreature/CountryRoadCreatureScrap.asset");
			((BaseUnityPlugin)this).Logger.LogInfo((object)(((Object)val).name + " FOUND"));
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"{val.spawnPrefab} prefab");
			NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
			Utilities.FixMixerGroups(val.spawnPrefab);
			RegisterUtil.RegisterScrapWithConfig(headScrapMoonRarity.Value, val);
			Item val2 = bundle.LoadAsset<Item>("Assets/LethalCompany/Mods/CountryRoadCreature/CountryRoadCreatureHandScrap.asset");
			((BaseUnityPlugin)this).Logger.LogInfo((object)(((Object)val2).name + " FOUND"));
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"{val2.spawnPrefab} prefab");
			NetworkPrefabs.RegisterNetworkPrefab(val2.spawnPrefab);
			Utilities.FixMixerGroups(val2.spawnPrefab);
			RegisterUtil.RegisterScrapWithConfig(handScrapMoonRarity.Value, val2);
		}

		private void CreateFloatConfig(ConfigEntry<float> configEntry, float min = 0f, float max = 100f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			FloatSliderOptions val = new FloatSliderOptions();
			((BaseRangeOptions<float>)val).Min = min;
			((BaseRangeOptions<float>)val).Max = max;
			((BaseOptions)val).RequiresRestart = false;
			FloatSliderConfigItem val2 = new FloatSliderConfigItem(configEntry, val);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val2);
		}

		private void CreateIntConfig(ConfigEntry<int> configEntry, int min = 0, int max = 100)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			IntSliderOptions val = new IntSliderOptions();
			((BaseRangeOptions<int>)val).Min = min;
			((BaseRangeOptions<int>)val).Max = max;
			((BaseOptions)val).RequiresRestart = false;
			IntSliderConfigItem val2 = new IntSliderConfigItem(configEntry, val);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val2);
		}

		private void CreateStringConfig(ConfigEntry<string> configEntry, bool requireRestart = false)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			TextInputFieldConfigItem val = new TextInputFieldConfigItem(configEntry, new TextInputFieldOptions
			{
				RequiresRestart = requireRestart
			});
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "CountryRoadCreature";

		public const string PLUGIN_NAME = "CountryRoadCreature";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace CountryRoadCreature.Scripts
{
	public class CountryRoadCreatureEnemyAI : EnemyAI
	{
		public AudioClip seePlayerSound;

		public List<AudioClip> walkSounds;

		public AudioClip screamSound;

		public AudioClip runSound;

		public AudioSource walkSource;

		public GameObject creatureObject;

		public Transform grabPosition;

		private static readonly int walk = Animator.StringToHash("walk");

		private static readonly int grab = Animator.StringToHash("grab");

		private static readonly int walkSpeed = Animator.StringToHash("walkSpeed");

		private static readonly int stun = Animator.StringToHash("stun");

		public float aiInterval;

		public int lastBehaviorState;

		private float lookAtPlayerTimer;

		private float monsterRunTimer;

		private float walkSoundTimer;

		private float animationParanoidTimer;

		private float animationGrabTimer;

		private float lostPlayerTimer;

		private float stunedTimer;

		private bool isLookingAtPlayer = false;

		private bool isRunningToPlayer = false;

		private bool isWalking = false;

		private bool isStuned = false;

		private float monsterAngryValue = 0f;

		private float monsterSpeedMultiplier = 1f;

		private float monsterLookPlayerTime = 2.5f;

		private float monsterRunToPlayerTime = 5f;

		private float monsterGrabTime = 3f;

		private float lostPlayerTime = 2f;

		private float stunTime = 1.25f;

		private float speed = 3.33f;

		private float normalAcceleration = 255f;

		private float angularSpeed = 900f;

		private float visionWidth = 60f;

		private float maxSpeed = 2f;

		private float timeBetweenWalkSound = 0.75f;

		private PlayerControllerB playerToKIll = null;

		private List<LightInformation> lights = new List<LightInformation>();

		private bool playerToKillIsLocal;

		private void AddAngryValue(float value)
		{
			monsterAngryValue = Mathf.Clamp(monsterAngryValue += value, 0f, 100f);
			monsterSpeedMultiplier = 1f + maxSpeed * (monsterAngryValue / 100f);
		}

		private void WalkingSound()
		{
			if (walkSoundTimer <= 0f)
			{
				walkSource.clip = walkSounds[Random.Range(0, walkSounds.Count)];
				walkSource.Play();
				walkSoundTimer = timeBetweenWalkSound / Mathf.Clamp(monsterSpeedMultiplier, 1f, 1.3f);
			}
		}

		private void ActiveLightList(bool active)
		{
			//IL_0045: 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)
			foreach (LightInformation light in lights)
			{
				float num = Random.Range(0.1f, 0.5f);
				light.Light.color = (Color)(active ? light.color : new Color(num, 0f, 0f));
			}
		}

		private IEnumerator ParanoidAnimation()
		{
			lights.Clear();
			List<Light> closeLights = Object.FindObjectsByType<Light>((FindObjectsSortMode)0).ToList().FindAll((Light light) => Vector3.Distance(((Component)light).transform.position, ((Component)this).transform.position) < 20f && Object.op_Implicit((Object)(object)light));
			foreach (Light closeObject in closeLights)
			{
				LightInformation lightInformation = new LightInformation
				{
					Light = closeObject,
					color = closeObject.color
				};
				lights.Add(lightInformation);
			}
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 1f));
			creatureObject.SetActive(false);
			ActiveLightList(active: true);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 1.2f));
			creatureObject.SetActive(true);
			ActiveLightList(active: false);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 1.5f));
			creatureObject.SetActive(false);
			ActiveLightList(active: true);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2f));
			creatureObject.SetActive(true);
			ActiveLightList(active: false);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2.1f));
			creatureObject.SetActive(false);
			ActiveLightList(active: true);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2.2f));
			creatureObject.SetActive(true);
			ActiveLightList(active: false);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2.3f));
			creatureObject.SetActive(false);
			ActiveLightList(active: true);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2.4f));
			creatureObject.SetActive(true);
			ActiveLightList(active: false);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2.5f));
			creatureObject.SetActive(false);
			ActiveLightList(active: false);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > monsterLookPlayerTime));
			creatureObject.SetActive(true);
			yield return (object)new WaitForSeconds(1f);
			ActiveLightList(active: true);
		}

		public override void Start()
		{
			speed = CountryRoadCreaturePlugin.instance.countryRoadBaseSpeed.Value;
			maxSpeed = CountryRoadCreaturePlugin.instance.countryRoadMaxSpeedMutliplier.Value - 1f;
			((EnemyAI)this).Start();
			AllClientOnSwitchBehaviorState();
			base.agent.angularSpeed = angularSpeed;
		}

		public override void Update()
		{
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			((EnemyAI)this).Update();
			aiInterval -= Time.deltaTime;
			walkSoundTimer -= Time.deltaTime;
			animationGrabTimer -= Time.deltaTime;
			if (isStuned)
			{
				stunedTimer -= Time.deltaTime;
			}
			if (isLookingAtPlayer)
			{
				lookAtPlayerTimer -= Time.deltaTime;
				animationParanoidTimer += Time.deltaTime;
			}
			if (isRunningToPlayer)
			{
				monsterRunTimer -= Time.deltaTime;
			}
			if (isWalking)
			{
				lostPlayerTimer -= Time.deltaTime;
				WalkingSound();
			}
			if (isStuned)
			{
				isStuned = stunedTimer > 0f;
			}
			if (lastBehaviorState != base.currentBehaviourStateIndex)
			{
				lastBehaviorState = base.currentBehaviourStateIndex;
				AllClientOnSwitchBehaviorState();
			}
			if (isRunningToPlayer && GameNetworkManager.Instance.localPlayerController.HasLineOfSightToPosition(((Component)this).transform.position + Vector3.up * 0.25f, 100f, 60, -1f))
			{
				GameNetworkManager.Instance.localPlayerController.JumpToFearLevel(0.8f, true);
			}
			if (base.currentBehaviourStateIndex == 3)
			{
				GrabAnimation();
			}
			if (aiInterval <= 0f && ((NetworkBehaviour)this).IsOwner)
			{
				aiInterval = base.AIIntervalTime;
				((EnemyAI)this).DoAIInterval();
			}
		}

		public override void DoAIInterval()
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			//IL_00a8: 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)
			((EnemyAI)this).DoAIInterval();
			switch (base.currentBehaviourStateIndex)
			{
			case 0:
				if (lostPlayerTimer <= 0f)
				{
					((EnemyAI)this).TargetClosestPlayer(1.5f, true, visionWidth);
				}
				if ((Object)(object)base.targetPlayer == (Object)null)
				{
					if (!base.currentSearch.inProgress)
					{
						AISearchRoutine val = new AISearchRoutine();
						val.searchWidth = 200f;
						val.searchPrecision = 8f;
						((EnemyAI)this).StartSearch(((EnemyAI)this).ChooseFarthestNodeFromPosition(((Component)this).transform.position, true, 0, false, 50, false).position, val);
					}
				}
				else if (((EnemyAI)this).PlayerIsTargetable(base.targetPlayer, false, false))
				{
					lookAtPlayerTimer = monsterLookPlayerTime;
					((EnemyAI)this).SwitchToBehaviourState(1);
				}
				break;
			case 1:
				base.currentSearch.inProgress = false;
				if (lookAtPlayerTimer > 0f)
				{
					((Component)this).transform.LookAt(((Component)base.targetPlayer).transform);
				}
				else if (((EnemyAI)this).PlayerIsTargetable(base.targetPlayer, false, false))
				{
					monsterRunTimer = monsterRunToPlayerTime;
					((EnemyAI)this).SwitchToBehaviourState(2);
				}
				else
				{
					((EnemyAI)this).SwitchToBehaviourState(0);
				}
				break;
			case 2:
				if (monsterRunTimer <= 0f)
				{
					((EnemyAI)this).TargetClosestPlayer(1.5f, true, visionWidth);
					if ((Object)(object)base.targetPlayer != (Object)null)
					{
						monsterRunTimer += 1f;
						break;
					}
					lostPlayerTimer = lostPlayerTime;
					((EnemyAI)this).SwitchToBehaviourState(0);
				}
				else if ((Object)(object)base.targetPlayer != (Object)null && ((EnemyAI)this).PlayerIsTargetable(base.targetPlayer, false, false))
				{
					((EnemyAI)this).SetMovingTowardsTargetPlayer(base.targetPlayer);
				}
				break;
			case 3:
				if (!(animationGrabTimer <= 0f))
				{
					base.targetPlayer = null;
				}
				break;
			case 4:
				Debug.Log((object)$"IS STUNED {isStuned}");
				if (!isStuned)
				{
					monsterRunTimer = monsterRunToPlayerTime;
					((EnemyAI)this).SwitchToBehaviourState(2);
				}
				break;
			}
		}

		private void LateUpdate()
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)playerToKIll != (Object)null && animationGrabTimer > 0f && (Object)(object)base.inSpecialAnimationWithPlayer != (Object)null && !isStuned)
			{
				((Component)base.inSpecialAnimationWithPlayer.gameplayCamera).transform.rotation = grabPosition.rotation;
				base.inSpecialAnimationWithPlayer.cameraContainerTransform.rotation = grabPosition.rotation;
			}
		}

		private void CancelPlayerEffects()
		{
			if ((Object)(object)playerToKIll != (Object)null)
			{
				playerToKIll.disableMoveInput = false;
				playerToKIll.disableLookInput = false;
				playerToKIll.inAnimationWithEnemy = null;
				playerToKIll.isInElevator = false;
				playerToKIll.disableInteract = false;
				playerToKIll.isInHangarShipRoom = false;
			}
			if (playerToKillIsLocal)
			{
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				localPlayerController.disableMoveInput = false;
				localPlayerController.disableLookInput = false;
				localPlayerController.inAnimationWithEnemy = null;
				localPlayerController.isInElevator = false;
				localPlayerController.disableInteract = false;
				localPlayerController.isInHangarShipRoom = false;
			}
			base.inSpecialAnimationWithPlayer = null;
			base.inSpecialAnimation = false;
		}

		private void GrabAnimation()
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			base.targetPlayer = null;
			if ((Object)(object)playerToKIll == (Object)null || !playerToKillIsLocal)
			{
				return;
			}
			if (animationGrabTimer > 0f)
			{
				base.inSpecialAnimation = true;
				playerToKIll.disableMoveInput = true;
				playerToKIll.disableLookInput = true;
				playerToKIll.disableInteract = true;
				base.inSpecialAnimationWithPlayer = playerToKIll;
				playerToKIll.inAnimationWithEnemy = (EnemyAI)(object)this;
				((Component)playerToKIll).transform.position = grabPosition.position;
				((Component)playerToKIll).transform.rotation = grabPosition.rotation;
			}
			else
			{
				((EnemyAI)this).SwitchToBehaviourServerRpc(0);
				CancelPlayerEffects();
				if (playerToKillIsLocal)
				{
					GameNetworkManager.Instance.localPlayerController.KillPlayer(Vector3.zero, false, (CauseOfDeath)8, 0, default(Vector3));
					playerToKillIsLocal = false;
				}
				playerToKIll = null;
			}
		}

		public void AllClientOnSwitchBehaviorState()
		{
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			base.agent.speed = speed * monsterSpeedMultiplier;
			base.agent.acceleration = normalAcceleration;
			switch (base.currentBehaviourStateIndex)
			{
			case 0:
				lostPlayerTimer = lostPlayerTime;
				isLookingAtPlayer = false;
				isRunningToPlayer = false;
				isWalking = true;
				base.creatureAnimator.SetBool(walk, true);
				base.creatureAnimator.SetBool(grab, false);
				base.creatureAnimator.SetBool(stun, false);
				base.creatureAnimator.SetFloat(walkSpeed, 1f);
				break;
			case 1:
				monsterRunTimer = monsterRunToPlayerTime;
				base.agent.speed = 0f;
				base.creatureVoice.clip = seePlayerSound;
				base.creatureVoice.Play();
				lookAtPlayerTimer = monsterLookPlayerTime;
				isLookingAtPlayer = true;
				isWalking = false;
				animationParanoidTimer = 0f;
				base.agent.velocity = Vector3.zero;
				AddAngryValue(15f);
				base.creatureAnimator.SetBool(walk, false);
				base.creatureAnimator.SetBool(grab, false);
				base.creatureAnimator.SetBool(stun, false);
				((MonoBehaviour)this).StartCoroutine(ParanoidAnimation());
				break;
			case 2:
				base.creatureVoice.clip = runSound;
				base.creatureVoice.Play();
				monsterRunTimer = monsterRunToPlayerTime;
				isRunningToPlayer = true;
				base.creatureAnimator.SetBool(walk, true);
				base.creatureAnimator.SetBool(grab, false);
				base.creatureAnimator.SetBool(stun, false);
				base.creatureAnimator.SetFloat(walkSpeed, Mathf.Clamp(monsterSpeedMultiplier, 1f, 1.5f));
				isWalking = true;
				break;
			case 3:
				AddAngryValue(100f);
				base.agent.speed = 0f;
				base.agent.velocity = Vector3.zero;
				animationGrabTimer = monsterGrabTime;
				base.creatureVoice.clip = screamSound;
				base.creatureVoice.Play();
				base.creatureAnimator.SetBool(grab, true);
				base.creatureAnimator.SetBool(stun, false);
				break;
			case 4:
				AddAngryValue(100f);
				base.agent.speed = 0f;
				base.agent.velocity = Vector3.zero;
				base.creatureVoice.clip = screamSound;
				base.creatureVoice.Play();
				base.creatureAnimator.SetBool(stun, true);
				isRunningToPlayer = false;
				monsterRunTimer = monsterRunToPlayerTime;
				break;
			}
		}

		public override void OnCollideWithPlayer(Collider other)
		{
			if (!((Object)(object)playerToKIll != (Object)null) && !isStuned && !(animationGrabTimer > 0f))
			{
				animationGrabTimer = monsterGrabTime;
				PlayerControllerB val = ((EnemyAI)this).MeetsStandardPlayerCollisionConditions(other, false, true);
				if ((Object)(object)val != (Object)null)
				{
					((EnemyAI)this).SwitchToBehaviourServerRpc(3);
					playerToKillIsLocal = true;
					playerToKIll = val;
					playerToKIll.DropAllHeldItems(true, false);
				}
				((EnemyAI)this).PlayAnimationOfCurrentState();
			}
		}

		public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false, int hitID = -1)
		{
			if (!isStuned)
			{
				animationGrabTimer = 0.75f;
				CancelPlayerEffects();
				playerToKIll = null;
				playerToKillIsLocal = false;
				stunedTimer = stunTime;
				isStuned = true;
				base.targetPlayer = playerWhoHit;
				((EnemyAI)this).SwitchToBehaviourServerRpc(4);
			}
		}
	}
	public class CountryRoadCreatureHeadItem : NoisemakerProp
	{
		public AudioSource hitPlayerAudioSource;

		public AudioSource laughtAudioSource;

		private List<LightInformation> lights = new List<LightInformation>();

		private float animationParanoidTimer;

		private bool animationPlaying;

		private int hitPlayerChance = 10;

		public bool canHitPlayer;

		public override void Start()
		{
			((NoisemakerProp)this).Start();
			hitPlayerChance = CountryRoadCreaturePlugin.instance.scrapHitPlayerChance.Value;
		}

		private void ActiveLightList(bool active)
		{
			//IL_0045: 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)
			foreach (LightInformation light in lights)
			{
				float num = Random.Range(0.1f, 0.5f);
				light.Light.color = (Color)(active ? light.color : new Color(num, 0f, 0f));
			}
		}

		public override void Update()
		{
			((GrabbableObject)this).Update();
			if (animationPlaying)
			{
				animationParanoidTimer += Time.deltaTime;
			}
		}

		private IEnumerator ParanoidAnimation()
		{
			lights.Clear();
			List<Light> closeLights = Object.FindObjectsByType<Light>((FindObjectsSortMode)0).ToList().FindAll((Light light) => Vector3.Distance(((Component)light).transform.position, ((Component)this).transform.position) < 15f && Object.op_Implicit((Object)(object)light));
			foreach (Light closeObject in closeLights)
			{
				LightInformation lightInformation = new LightInformation
				{
					Light = closeObject,
					color = closeObject.color
				};
				int instanceId = ((Object)closeObject).GetInstanceID();
				if (CountryRoadCreaturePlugin.instance.lightsInUse.ContainsKey(instanceId))
				{
					lights.Add(CountryRoadCreaturePlugin.instance.lightsInUse[instanceId]);
					continue;
				}
				CountryRoadCreaturePlugin.instance.lightsInUse.Add(instanceId, lightInformation);
				lights.Add(lightInformation);
			}
			ActiveLightList(active: true);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 1f));
			ActiveLightList(active: true);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 1.2f));
			ActiveLightList(active: false);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 1.5f));
			ActiveLightList(active: true);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2f));
			ActiveLightList(active: false);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2.1f));
			ActiveLightList(active: true);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2.2f));
			ActiveLightList(active: false);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2.3f));
			ActiveLightList(active: true);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2.4f));
			ActiveLightList(active: false);
			yield return (object)new WaitUntil((Func<bool>)(() => animationParanoidTimer > 2.5f));
			ActiveLightList(active: false);
			yield return (object)new WaitForSeconds(2f);
			bool canHitPlayerValue = (Object)(object)((GrabbableObject)this).playerHeldBy != (Object)null && canHitPlayer;
			if (!(Random.Range(0, 100) < hitPlayerChance && canHitPlayerValue))
			{
				ActiveLightList(active: true);
				animationPlaying = false;
			}
			else
			{
				GameNetworkManager.Instance.localPlayerController.DamagePlayer(15, true, true, (CauseOfDeath)0, 0, false, default(Vector3));
				laughtAudioSource.Play();
				yield return (object)new WaitForSeconds(1f);
				animationPlaying = false;
				ActiveLightList(active: true);
			}
			lights.ForEach(delegate(LightInformation l)
			{
				CountryRoadCreaturePlugin.instance.lightsInUse.Remove(((Object)l.Light).GetInstanceID());
			});
		}

		public override void ItemActivate(bool used, bool buttonDown = true)
		{
			canHitPlayer = (Object)(object)((GrabbableObject)this).playerHeldBy == (Object)(object)GameNetworkManager.Instance.localPlayerController;
			if (!animationPlaying)
			{
				animationPlaying = true;
				animationParanoidTimer = 0f;
				((MonoBehaviour)this).StartCoroutine(ParanoidAnimation());
			}
			((NoisemakerProp)this).ItemActivate(used, buttonDown);
		}
	}
	public class LightInformation
	{
		public Light Light;

		public Color color;
	}
}

BepInEx/plugins/americanompany/DiversityLib.dll

Decompiled 2 years ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("DiversityLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DiversityLib")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("f3aa347e-bdfa-4c6a-b93f-1429e4f206c4")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace DiversityLib
{
	public static class DiversityLib
	{
		public static Texture2D RenderToTexture2D(this RenderTexture rTex)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(((Texture)rTex).width, ((Texture)rTex).height, (TextureFormat)4, false);
			RenderTexture.active = rTex;
			val.ReadPixels(new Rect(0f, 0f, (float)((Texture)rTex).width, (float)((Texture)rTex).height), 0, 0);
			val.Apply();
			return val;
		}

		public static Color[] GetPixels(this RenderTexture texture)
		{
			Texture2D val = texture.RenderToTexture2D();
			return val.GetPixels();
		}

		public static float CalculateAverageLuminance(this RenderTexture texture, bool useAlpha = false)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = texture.RenderToTexture2D();
			float num = ((Texture)val).width * ((Texture)val).height;
			float num2 = 0f;
			Color[] pixels = val.GetPixels();
			foreach (Color color in pixels)
			{
				num2 += color.CalculateLuminance(useAlpha);
			}
			return num2 / num;
		}

		public static float CalculateAverageLuminance(this Texture2D texture, bool useAlpha = false)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			float num = ((Texture)texture).width * ((Texture)texture).height;
			float num2 = 0f;
			Color[] pixels = texture.GetPixels();
			foreach (Color color in pixels)
			{
				num2 += color.CalculateLuminance(useAlpha);
			}
			return num2 / num;
		}

		public static float CalculateAverageLuminance(this Color[] colorArray, bool useAlpha = false)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			float num = colorArray.Length;
			float num2 = 0f;
			foreach (Color color in colorArray)
			{
				num2 += color.CalculateLuminance(useAlpha);
			}
			return num2 / num;
		}

		public static Color AverageDifference(this Texture2D texture, Texture2D secondTexture)
		{
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: 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_0042: 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)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: 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)
			float num = ((Texture)texture).width * ((Texture)texture).height;
			float num2 = 0f;
			float num3 = 0f;
			float num4 = 0f;
			float num5 = 0f;
			for (int i = 0; i < ((Texture)texture).width; i++)
			{
				for (int j = 0; j < ((Texture)texture).height; j++)
				{
					Color pixel = texture.GetPixel(i, j);
					Color pixel2 = secondTexture.GetPixel(i, j);
					num2 += Mathf.Abs(pixel.r - pixel2.r);
					num3 += Mathf.Abs(pixel.g - pixel2.g);
					num4 += Mathf.Abs(pixel.b - pixel2.b);
					num5 += Mathf.Abs(pixel.a - pixel2.a);
				}
			}
			num2 /= num;
			num3 /= num;
			num4 /= num;
			num5 /= num;
			return new Color(num2, num3, num4, num5);
		}

		public static float BW(this Color col)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			return col.r + col.g + col.b;
		}

		public static float CalculateLuminance(this Color color, bool useAlpha = false)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			return 0.299f * color.r * (useAlpha ? color.a : 1f) + 0.587f * color.g * (useAlpha ? color.a : 1f) + 0.114f * color.b * (useAlpha ? color.a : 1f);
		}

		public static Color GetAverageRGBA(this RenderTexture texture)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			Texture2D texture2 = texture.RenderToTexture2D();
			return texture2.GetAverageRGBA();
		}

		public static Color GetAverageRGBA(this Texture2D texture)
		{
			//IL_003b: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: 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)
			float num = ((Texture)texture).width * ((Texture)texture).height;
			float num2 = 0f;
			float num3 = 0f;
			float num4 = 0f;
			float num5 = 0f;
			Color[] pixels = texture.GetPixels();
			foreach (Color val in pixels)
			{
				num2 += val.r;
				num3 += val.g;
				num4 += val.b;
				num5 += val.a;
			}
			return new Color(num2 / num, num3 / num, num4 / num, num5 / num);
		}

		public static Color GetAverageRGBA(this Color[] colorArray)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			float num = colorArray.Length;
			float num2 = 0f;
			float num3 = 0f;
			float num4 = 0f;
			float num5 = 0f;
			foreach (Color val in colorArray)
			{
				num2 += val.r;
				num3 += val.g;
				num4 += val.b;
				num5 += val.a;
			}
			return new Color(num2 / num, num3 / num, num4 / num, num5 / num);
		}

		public static float Remap(this float value, float from1, float to1, float from2, float to2)
		{
			return (value - from1) / (to1 - from1) * (to2 - from2) + from2;
		}

		public static float OneMinus(this float f)
		{
			return 1f - f;
		}

		public static float Negate(this float f)
		{
			return 0f - f;
		}

		public static uint Random(this uint u)
		{
			Random random = new Random();
			uint num = (uint)random.Next(1073741824);
			uint num2 = (uint)random.Next(4);
			return (num << 2) | num2;
		}

		public static float Volume(this Vector3 v3)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			return v3.x * v3.y * v3.z;
		}
	}
}

BepInEx/plugins/americanompany/EverythingCanDie.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace EverythingCanDie
{
	public class Patches
	{
		public static List<string> UnkillableEnemies = new List<string>();

		public static List<string> BonkableEnemies = new List<string>();

		public static List<string> NotBonkableEnemies = new List<string>();

		public static List<string> InvalidEnemies = new List<string>();

		private static readonly int Damage = Animator.StringToHash("damage");

		private static bool CheckingIfBonkable = false;

		public static void StartOfRoundPatch()
		{
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Expected O, but got Unknown
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Expected O, but got Unknown
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Expected O, but got Unknown
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Expected O, but got Unknown
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02df: Expected O, but got Unknown
			//IL_032d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0337: Expected O, but got Unknown
			Plugin.enemies = (from EnemyType e in Resources.FindObjectsOfTypeAll(typeof(EnemyType))
				where (Object)(object)e != (Object)null
				select e).ToList();
			Plugin.items = (from Item i in Resources.FindObjectsOfTypeAll(typeof(Item))
				where (Object)(object)i != (Object)null
				select i).ToList();
			Plugin.ENEMY_MASK = 524288;
			Plugin.PLAYER_HIT_MASK = StartOfRound.Instance.collidersRoomMaskDefaultAndPlayers | (Plugin.ENEMY_MASK & 0x280008);
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "UnimmortalAllMobs")))
			{
				ConfigEntry<bool> val = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "UnimmortalAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Return To Normal(Make Immortal mobs immortal again).");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "ExplosionEffectAllMobs")))
			{
				ConfigEntry<bool> val2 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "ExplosionEffectAllMobs", true, "If this is set to true then explosion effect stays and removes the body otherwise when false all explosions on death will not appear and the body will appear.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "HealthAllMobs")))
			{
				ConfigEntry<bool> val3 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "HealthAllMobs", true, "If this is set to false the enemies health will remain the same otherwise have fun configging.");
			}
			foreach (EnemyType enemy in Plugin.enemies)
			{
				string text = Plugin.RemoveInvalidCharacters(enemy.enemyName).ToUpper();
				try
				{
					if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Unimmortal")))
					{
						ConfigEntry<bool> val4 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Unimmortal", true, "If true this mob will explode and if immortal it will also be killable.");
					}
					if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Explodeable")))
					{
						ConfigEntry<bool> val5 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Explodeable", true, "The value of whether to spawn an explosion effect(Default on)");
					}
					if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Hittable")))
					{
						ConfigEntry<bool> val6 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Hittable", true, "The value of whether this mob is hittable with things like shovels.(WARNING: If it is a modded item that happens to shoot then this might effect those items too)");
					}
					if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Shootable")))
					{
						ConfigEntry<bool> val7 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Shootable", true, "The value of whether this mob is shootable with things like shotguns.(WARNING: Only works for items that use the ShotgunItem as its parent)");
					}
					if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Health")))
					{
						EnemyAI component = enemy.enemyPrefab.GetComponent<EnemyAI>();
						ConfigEntry<int> val8 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<int>("Mobs", text + ".Health", component.enemyHP, "The value of the mobs health.(Default Vanilla is 3 for most unkillable mobs)");
						if (Plugin.CanMob("HealthAllMobs", ".Unimmortal", text))
						{
							component.enemyHP = val8.Value;
							Plugin.Log.LogInfo((object)$"Set {((Object)enemy).name} HP to {component.enemyHP}");
						}
					}
				}
				catch (Exception)
				{
					Plugin.Log.LogInfo((object)("It was not possible to generate the configs for the enemy: " + enemy.enemyName));
					InvalidEnemies.Add(enemy.enemyName);
				}
				try
				{
					if (Plugin.CanMob("UnimmortalAllMobs", ".Unimmortal", text))
					{
						UnkillableEnemies.Add(enemy.enemyName);
						enemy.canDie = true;
					}
					Plugin.Log.LogInfo((object)$"Vanilla canDie variable for {enemy.enemyName} = {enemy.canDie}");
				}
				catch (Exception)
				{
					Plugin.Log.LogError((object)("It was not possible to determine whether the enemy " + enemy.enemyName + " was killable or not"));
				}
			}
			if ((Object)(object)Plugin.explosionPrefab == (Object)null && (Object)(object)StartOfRound.Instance.explosionPrefab != (Object)null)
			{
				Plugin.explosionPrefab = Object.Instantiate<GameObject>(StartOfRound.Instance.explosionPrefab);
				if ((Object)(object)Plugin.explosionPrefab.GetComponent<AudioSource>() != (Object)null)
				{
					Plugin.explosionPrefab.GetComponent<AudioSource>().volume = 0.35f;
				}
				Plugin.explosionPrefab.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)Plugin.explosionPrefab);
			}
		}

		public static void HitEnemyPatch(ref EnemyAI __instance, int force = 1, PlayerControllerB playerWhoHit = null)
		{
			if (!((Object)(object)__instance != (Object)null) || CheckingIfBonkable || (InvalidEnemies.Contains(__instance.enemyType.enemyName) && __instance.isEnemyDead))
			{
				return;
			}
			EnemyType enemyType = __instance.enemyType;
			string text = Plugin.RemoveInvalidCharacters(enemyType.enemyName).ToUpper();
			bool flag = true;
			if (!Plugin.CanMob("UnimmortalAllMobs", ".Unimmortal", text) || ((Object)(object)playerWhoHit == (Object)null && __instance.enemyType.enemyName == "RadMech"))
			{
				return;
			}
			if ((Object)(object)playerWhoHit != (Object)null && (Object)(object)playerWhoHit.ItemSlots[playerWhoHit.currentItemSlot] != (Object)null)
			{
				GrabbableObject val = playerWhoHit.ItemSlots[playerWhoHit.currentItemSlot];
				if (val.itemProperties.isDefensiveWeapon && !Plugin.Can(text + ".Hittable"))
				{
					flag = false;
					Plugin.Log.LogInfo((object)("Hit Disabled for " + __instance.enemyType.enemyName + "!"));
				}
				else if (val is ShotgunItem && !Plugin.Can(text + ".Shootable"))
				{
					flag = false;
					Plugin.Log.LogInfo((object)("Shoot Disabled for " + __instance.enemyType.enemyName + "!"));
				}
			}
			if (!flag)
			{
				return;
			}
			if (!BonkableEnemies.Contains(__instance.enemyType.enemyName) && !NotBonkableEnemies.Contains(__instance.enemyType.enemyName))
			{
				Plugin.Log.LogInfo((object)(__instance.enemyType.enemyName + " is not in the Bonkable or in the NotBonkable list"));
				CanEnemyGetBonked(__instance);
			}
			if (BonkableEnemies.Contains(__instance.enemyType.enemyName))
			{
				Plugin.Log.LogInfo((object)(__instance.enemyType.enemyName + " is in the Bonkable list"));
			}
			else if (NotBonkableEnemies.Contains(__instance.enemyType.enemyName))
			{
				Plugin.Log.LogInfo((object)(__instance.enemyType.enemyName + " is in the NotBonkable list"));
				if ((Object)(object)__instance.creatureAnimator != (Object)null)
				{
					__instance.creatureAnimator.SetTrigger(Damage);
				}
				if (__instance.enemyHP - force > 0)
				{
					EnemyAI obj = __instance;
					obj.enemyHP -= force;
				}
				else
				{
					__instance.enemyHP = 0;
				}
				if (__instance.enemyHP <= 0)
				{
					__instance.KillEnemyOnOwnerClient(false);
				}
			}
		}

		public static void CanEnemyGetBonked(EnemyAI __instance)
		{
			CheckingIfBonkable = true;
			int enemyHP = __instance.enemyHP;
			Plugin.Log.LogInfo((object)$"Enemy HP before bonk test: {enemyHP}");
			__instance.HitEnemy(1, (PlayerControllerB)null, false, -3);
			int enemyHP2 = __instance.enemyHP;
			Plugin.Log.LogInfo((object)$"Enemy HP after bonk test: {enemyHP2}");
			if (enemyHP != enemyHP2)
			{
				BonkableEnemies.Add(__instance.enemyType.enemyName);
				__instance.enemyHP = enemyHP;
				Plugin.Log.LogInfo((object)$"{__instance.enemyType.enemyName} is been added to the Bonkable list, HP = {__instance.enemyHP}");
			}
			else
			{
				NotBonkableEnemies.Add(__instance.enemyType.enemyName);
				Plugin.Log.LogInfo((object)$"{__instance.enemyType.enemyName} is been added to the NotBonkable list, HP = {__instance.enemyHP}");
			}
			CheckingIfBonkable = false;
		}

		public static void KillEnemyPatch(ref EnemyAI __instance)
		{
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: 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_016e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)__instance != (Object)null) || InvalidEnemies.Contains(__instance.enemyType.enemyName))
			{
				return;
			}
			EnemyType enemyType = __instance.enemyType;
			string mobName = Plugin.RemoveInvalidCharacters(enemyType.enemyName).ToUpper();
			Plugin.Log.LogInfo((object)$"{((Object)__instance).name} HP is {__instance.enemyHP}, killing");
			if (!Plugin.CanMob("ExplosionEffectAllMobs", ".Explodeable", mobName))
			{
				return;
			}
			if (__instance.enemyType.enemyName == "Nutcracker" || __instance.enemyType.enemyName == "Butler")
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)0);
				if (((NetworkBehaviour)__instance).IsServer)
				{
					Object.Instantiate<GameObject>(Plugin.explosionPrefab, ((Component)__instance).transform.position, Quaternion.Euler(-90f, 0f, 0f), RoundManager.Instance.mapPropsContainer.transform).SetActive(true);
				}
				return;
			}
			if (Object.op_Implicit((Object)(object)((Component)__instance).GetComponentInChildren<PlayerControllerB>()))
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)0);
				if (((NetworkBehaviour)__instance).IsServer)
				{
					Object.Instantiate<GameObject>(Plugin.explosionPrefab, ((Component)__instance).transform.position, Quaternion.Euler(-90f, 0f, 0f), RoundManager.Instance.mapPropsContainer.transform).SetActive(true);
				}
				return;
			}
			HUDManager.Instance.ShakeCamera((ScreenShakeType)0);
			if (((NetworkBehaviour)__instance).IsServer)
			{
				Object.Instantiate<GameObject>(Plugin.explosionPrefab, ((Component)__instance).transform.position, Quaternion.Euler(-90f, 0f, 0f), RoundManager.Instance.mapPropsContainer.transform).SetActive(true);
			}
			((MonoBehaviour)__instance).StartCoroutine(MoveBody(__instance, 0.1f));
		}

		private static IEnumerator MoveBody(EnemyAI __instance, float time)
		{
			yield return (object)new WaitForSeconds(time);
			Vector3 OriginalBodyPos = new Vector3(-10000f, -10000f, -10000f);
			((Component)__instance).transform.position = OriginalBodyPos;
			__instance.SyncPositionToClients();
			if (__instance.enemyType.enemyName == "Blob" && ((NetworkBehaviour)__instance).IsServer)
			{
				((Component)__instance).GetComponent<NetworkObject>().Despawn(true);
			}
		}

		public static bool ReplaceShotgunCode(ref ShotgunItem __instance, Vector3 shotgunPosition, Vector3 shotgunForward)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			ShootGun(__instance, shotgunPosition, shotgunForward);
			return false;
		}

		public static void ShootGun(ShotgunItem gun, Vector3 shotgunPosition, Vector3 shotgunForward)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_032e: Unknown result type (might be due to invalid IL or missing references)
			//IL_032f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_0726: Unknown result type (might be due to invalid IL or missing references)
			//IL_0728: Unknown result type (might be due to invalid IL or missing references)
			//IL_0732: Unknown result type (might be due to invalid IL or missing references)
			//IL_0371: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_0379: Unknown result type (might be due to invalid IL or missing references)
			//IL_037e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0383: Unknown result type (might be due to invalid IL or missing references)
			//IL_0771: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0632: Unknown result type (might be due to invalid IL or missing references)
			//IL_0637: Unknown result type (might be due to invalid IL or missing references)
			//IL_067a: Unknown result type (might be due to invalid IL or missing references)
			//IL_067b: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0529: Unknown result type (might be due to invalid IL or missing references)
			//IL_052a: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB playerHeldBy = ((GrabbableObject)gun).playerHeldBy;
			bool flag = ((GrabbableObject)gun).isHeld && (Object)(object)((GrabbableObject)gun).playerHeldBy != (Object)null;
			if (flag)
			{
				shotgunPosition += ((Component)GameNetworkManager.Instance.localPlayerController.gameplayCamera).transform.up * 0.25f;
			}
			bool flag2 = flag && (Object)(object)((GrabbableObject)gun).playerHeldBy == (Object)(object)GameNetworkManager.Instance.localPlayerController;
			if (flag2)
			{
				((GrabbableObject)gun).playerHeldBy.playerBodyAnimator.SetTrigger("ShootShotgun");
			}
			RoundManager.PlayRandomClip(((Component)gun).GetComponent<ShotgunItem>().gunShootAudio, ((Component)gun).GetComponent<ShotgunItem>().gunShootSFX, true, 1f, 1840, 1000);
			WalkieTalkie.TransmitOneShotAudio(((Component)gun).GetComponent<ShotgunItem>().gunShootAudio, ((Component)gun).GetComponent<ShotgunItem>().gunShootSFX[0], 1f);
			gun.gunShootParticle.Play(true);
			gun.isReloading = false;
			gun.shellsLoaded = Mathf.Clamp(gun.shellsLoaded - 1, 0, 2);
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if ((Object)(object)localPlayerController == (Object)null)
			{
				return;
			}
			Vector3[] array = (Vector3[])(object)new Vector3[Plugin.numTightPellets + Plugin.numLoosePellets];
			State state = Random.state;
			for (int i = 0; i < Plugin.numTightPellets + Plugin.numLoosePellets; i++)
			{
				float num = ((i < Plugin.numTightPellets) ? Plugin.tightPelletAngle : Plugin.loosePelletAngle);
				Vector3 val = Random.onUnitSphere;
				float num2 = num * Mathf.Sqrt(Random.value);
				if (Vector3.Angle(shotgunForward, val) < num2)
				{
					val *= -1f;
				}
				Vector3 val2 = Vector3.RotateTowards(shotgunForward, val, num2 * MathF.PI / 180f, 0f);
				array[i] = val2;
			}
			Random.state = state;
			float num3 = Vector3.Distance(((Component)localPlayerController).transform.position, ((Component)gun.shotgunRayPoint).transform.position);
			float num4 = 0f;
			if (num3 < 5f)
			{
				num4 = 0.8f;
				HUDManager.Instance.ShakeCamera((ScreenShakeType)1);
			}
			else if (num3 < 15f)
			{
				num4 = 0.5f;
				HUDManager.Instance.ShakeCamera((ScreenShakeType)1);
			}
			else if (num3 < 23f)
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)0);
			}
			if (num4 > 0f && SoundManager.Instance.timeSinceEarsStartedRinging > 16f && !flag)
			{
				((MonoBehaviour)gun).StartCoroutine(DelayedEarsRinging(num4));
			}
			Plugin.CountHandler countHandler = new Plugin.CountHandler();
			Ray val4 = default(Ray);
			IHittable val6 = default(IHittable);
			EnemyAI val9 = default(EnemyAI);
			foreach (Vector3 val3 in array)
			{
				((Ray)(ref val4))..ctor(shotgunPosition, val3);
				RaycastHit[] array2 = Physics.RaycastAll(val4, 30f, Plugin.PLAYER_HIT_MASK, (QueryTriggerInteraction)2);
				Array.Sort(array2, (RaycastHit x, RaycastHit y) => ((RaycastHit)(ref x)).distance.CompareTo(((RaycastHit)(ref y)).distance));
				Vector3 val5 = shotgunPosition + val3 * 30f;
				Debug.Log((object)("SHOTGUN: RaycastAll hit " + array2.Length + " things (" + flag + "," + flag2 + ")"));
				for (int k = 0; k < array2.Length; k++)
				{
					GameObject gameObject = ((Component)((RaycastHit)(ref array2[k])).transform).gameObject;
					if (gameObject.TryGetComponent<IHittable>(ref val6))
					{
						if (val6 == ((GrabbableObject)gun).playerHeldBy)
						{
							continue;
						}
						EnemyAI val7 = null;
						EnemyAICollisionDetect val8 = (EnemyAICollisionDetect)(object)((val6 is EnemyAICollisionDetect) ? val6 : null);
						if (val8 != null)
						{
							val7 = val8.mainScript;
						}
						if ((Object)(object)val7 != (Object)null && (val7.isEnemyDead || val7.enemyHP <= 0 || !val7.enemyType.canDie))
						{
							continue;
						}
						if (val6 is PlayerControllerB)
						{
							countHandler.AddPlayerToCount((PlayerControllerB)(object)((val6 is PlayerControllerB) ? val6 : null));
						}
						else if ((Object)(object)val7 != (Object)null)
						{
							countHandler.AddEnemyToCount(val7);
						}
						else
						{
							if (!flag)
							{
								continue;
							}
							countHandler.AddOtherToCount(val6);
						}
						val5 = ((RaycastHit)(ref array2[k])).point;
						Debug.Log((object)("SHOTGUN: Hit [" + ((object)val6)?.ToString() + "] (" + (k + 1) + "@" + Vector3.Distance(shotgunPosition, val5) + ")"));
						break;
					}
					if (((Component)((RaycastHit)(ref array2[k])).collider).TryGetComponent<EnemyAI>(ref val9))
					{
						if (!flag || val9.isEnemyDead || val9.enemyHP <= 0 || !val9.enemyType.canDie)
						{
							continue;
						}
						countHandler.AddEnemyToCount(val9);
						val5 = ((RaycastHit)(ref array2[k])).point;
						Debug.Log((object)("SHOTGUN: Backup hit [" + ((object)val9)?.ToString() + "] (" + (k + 1) + "@" + Vector3.Distance(shotgunPosition, val5) + ")"));
						break;
					}
					val5 = ((RaycastHit)(ref array2[k])).point;
					Debug.Log((object)("SHOTGUN: Wall [" + ((object)gameObject)?.ToString() + "] (" + (k + 1) + "@" + Vector3.Distance(shotgunPosition, val5) + ")"));
					break;
				}
				Plugin.VisualiseShot(shotgunPosition, val5);
			}
			countHandler.player.ForEach(delegate(Plugin.Counter<PlayerControllerB> p)
			{
				//IL_0076: Unknown result type (might be due to invalid IL or missing references)
				int num7 = p.count * 20;
				Debug.Log((object)("SHOTGUN: Hit " + ((object)p.item)?.ToString() + " with " + p.count + " pellets for " + num7 + " damage"));
				p.item.DamagePlayer(num7, true, true, (CauseOfDeath)7, 0, false, shotgunForward);
			});
			countHandler.enemy.ForEach(delegate(Plugin.Counter<EnemyAI> e)
			{
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				int num6 = e.count / 2 + 1;
				Debug.Log((object)("SHOTGUN: Hit " + ((object)e.item)?.ToString() + " with " + e.count + " pellets for " + num6 + " damage"));
				e.item.HitEnemyOnLocalClient(num6, shotgunForward, ((GrabbableObject)gun).playerHeldBy, true, -1);
			});
			countHandler.other.ForEach(delegate(Plugin.Counter<IHittable> o)
			{
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				int num5 = o.count / 2 + 1;
				Debug.Log((object)("SHOTGUN: Hit " + ((object)o.item)?.ToString() + " with " + o.count + " pellets for " + num5 + " damage"));
				o.item.Hit(num5, shotgunForward, ((GrabbableObject)gun).playerHeldBy, true, -1);
			});
			((Ray)(ref val4))..ctor(shotgunPosition, shotgunForward);
			RaycastHit val10 = default(RaycastHit);
			if (Physics.Raycast(val4, ref val10, 30f, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))
			{
				((Component)gun.gunBulletsRicochetAudio).transform.position = ((Ray)(ref val4)).GetPoint(((RaycastHit)(ref val10)).distance - 0.5f);
				gun.gunBulletsRicochetAudio.Play();
			}
		}

		public static IEnumerator DelayedEarsRinging(float effectSeverity)
		{
			yield return (object)new WaitForSeconds(0.6f);
			SoundManager.Instance.earsRingingTimer = effectSeverity;
		}
	}
	[BepInPlugin("nwnt.EverythingCanDie", "EverythingCanDie", "1.2.22")]
	public class Plugin : BaseUnityPlugin
	{
		public class CountHandler
		{
			public List<Counter<PlayerControllerB>> player = new List<Counter<PlayerControllerB>>();

			public List<Counter<EnemyAI>> enemy = new List<Counter<EnemyAI>>();

			public List<Counter<IHittable>> other = new List<Counter<IHittable>>();

			public void AddPlayerToCount(PlayerControllerB p)
			{
				if (player.Any((Counter<PlayerControllerB> i) => (Object)(object)i.item == (Object)(object)p))
				{
					player.First((Counter<PlayerControllerB> i) => (Object)(object)i.item == (Object)(object)p).count++;
				}
				else
				{
					player.Add(new Counter<PlayerControllerB>
					{
						item = p,
						count = 1
					});
				}
			}

			public void AddEnemyToCount(EnemyAI ai)
			{
				if (enemy.Any((Counter<EnemyAI> i) => (Object)(object)i.item == (Object)(object)ai))
				{
					enemy.First((Counter<EnemyAI> i) => (Object)(object)i.item == (Object)(object)ai).count++;
				}
				else
				{
					enemy.Add(new Counter<EnemyAI>
					{
						item = ai,
						count = 1
					});
				}
			}

			public void AddOtherToCount(IHittable hit)
			{
				if (other.Any((Counter<IHittable> i) => i.item == hit))
				{
					other.First((Counter<IHittable> i) => i.item == hit).count++;
				}
				else
				{
					other.Add(new Counter<IHittable>
					{
						item = hit,
						count = 1
					});
				}
			}
		}

		public class Counter<T>
		{
			public T item;

			public int count;
		}

		public class FadeOutLine : MonoBehaviour
		{
			private const float lifetime = 0.4f;

			private const float width = 0.02f;

			private static readonly Color col = new Color(1f, 0f, 0f);

			private float alive = 0f;

			private LineRenderer line;

			public Vector3 start;

			public Vector3 end;

			private static readonly Material mat = new Material(Shader.Find("Legacy Shaders/Particles/Alpha Blended Premultiply"));

			public void Prep()
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: 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)
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0054: Unknown result type (might be due to invalid IL or missing references)
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
				float num = Vector3.Distance(start, end);
				float num2 = (30f - num) / 30f;
				line = ((Component)this).gameObject.AddComponent<LineRenderer>();
				line.startColor = col;
				line.endColor = col * num2 + Color.black * (1f - num2);
				line.startWidth = 0.02f;
				line.endWidth = num2 * 0.02f;
				line.SetPositions((Vector3[])(object)new Vector3[2] { start, end });
				((Renderer)line).material = mat;
			}

			private void Update()
			{
				//IL_006f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0086: Unknown result type (might be due to invalid IL or missing references)
				//IL_0096: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
				alive += Time.deltaTime;
				if (alive >= 0.4f)
				{
					Object.Destroy((Object)(object)((Component)this).gameObject);
					return;
				}
				line.startColor = new Color(col.r, col.g, col.b, (0.4f - alive) / 0.4f);
				line.endColor = new Color(line.endColor.r, line.endColor.g, line.endColor.b, (0.4f - alive) / 0.4f);
			}
		}

		public const string Guid = "nwnt.EverythingCanDie";

		public const string Name = "EverythingCanDie";

		public const string Version = "1.2.22";

		public static Plugin Instance;

		public static Harmony Harmony;

		public static ManualLogSource Log;

		public static GameObject explosionPrefab;

		public static List<EnemyType> enemies;

		public static List<Item> items;

		public const float range = 30f;

		public static int ENEMY_MASK = 524288;

		public static int PLAYER_HIT_MASK;

		public static int numTightPellets = 2;

		public static float tightPelletAngle = 2.5f;

		public static int numLoosePellets = 3;

		public static float loosePelletAngle = 10f;

		private void Awake()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			Harmony = new Harmony("nwnt.EverythingCanDie");
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			Harmony.PatchAll(typeof(Plugin));
			Log = ((BaseUnityPlugin)this).Logger;
			CreateHarmonyPatch(Harmony, typeof(StartOfRound), "Start", null, typeof(Patches), "StartOfRoundPatch", isPrefix: false);
			CreateHarmonyPatch(Harmony, typeof(EnemyAI), "HitEnemy", new Type[4]
			{
				typeof(int),
				typeof(PlayerControllerB),
				typeof(bool),
				typeof(int)
			}, typeof(Patches), "HitEnemyPatch", isPrefix: false);
			CreateHarmonyPatch(Harmony, typeof(EnemyAI), "KillEnemy", new Type[1] { typeof(bool) }, typeof(Patches), "KillEnemyPatch", isPrefix: false);
			CreateHarmonyPatch(Harmony, typeof(ShotgunItem), "ShootGun", new Type[2]
			{
				typeof(Vector3),
				typeof(Vector3)
			}, typeof(Patches), "ReplaceShotgunCode", isPrefix: true);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Patching should be complete now :]");
		}

		public static Type FindType(string fullName)
		{
			try
			{
				if ((from a in AppDomain.CurrentDomain.GetAssemblies()
					where !a.IsDynamic
					select a).SelectMany((Assembly a) => a.GetTypes()).FirstOrDefault((Type t) => t.FullName.Equals(fullName)) != null)
				{
					return (from a in AppDomain.CurrentDomain.GetAssemblies()
						where !a.IsDynamic
						select a).SelectMany((Assembly a) => a.GetTypes()).FirstOrDefault((Type t) => t.FullName.Equals(fullName));
				}
			}
			catch
			{
				return null;
			}
			return null;
		}

		public static void CreateHarmonyPatch(Harmony harmony, Type typeToPatch, string methodToPatch, Type[] parameters, Type patchType, string patchMethod, bool isPrefix)
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			if (typeToPatch == null || patchType == null)
			{
				Log.LogInfo((object)"Type is either incorrect or does not exist!");
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(typeToPatch, methodToPatch, parameters, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(patchType, patchMethod, (Type[])null, (Type[])null);
			if (isPrefix)
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)("Prefix " + methodInfo.Name + " Patched!"));
			}
			else
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)("Postfix " + methodInfo.Name + " Patched!"));
			}
		}

		public static string RemoveInvalidCharacters(string source)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (char c in source)
			{
				if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
				{
					stringBuilder.Append(c);
				}
			}
			return string.Join("", stringBuilder.ToString().Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries));
		}

		public static bool Can(string identifier)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			if (((BaseUnityPlugin)Instance).Config[new ConfigDefinition("Mobs", identifier)].BoxedValue.ToString().ToUpper().Equals("TRUE"))
			{
				return true;
			}
			return false;
		}

		public static bool CanMob(string parentIdentifier, string identifier, string mobName)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			string text = RemoveInvalidCharacters(mobName).ToUpper();
			if (((BaseUnityPlugin)Instance).Config[new ConfigDefinition("Mobs", parentIdentifier)].BoxedValue.ToString().ToUpper().Equals("TRUE"))
			{
				foreach (ConfigDefinition key in ((BaseUnityPlugin)Instance).Config.Keys)
				{
					if (RemoveInvalidCharacters(key.Key.ToUpper()).Equals(RemoveInvalidCharacters(text + identifier.ToUpper())))
					{
						return ((BaseUnityPlugin)Instance).Config[key].BoxedValue.ToString().ToUpper().Equals("TRUE");
					}
				}
				Log.LogInfo((object)(identifier + ": No mob found!"));
				return false;
			}
			Log.LogInfo((object)(parentIdentifier + ": All mobs disabled!"));
			return false;
		}

		public static void VisualiseShot(Vector3 start, Vector3 end)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Trail Visual");
			FadeOutLine fadeOutLine = val.AddComponent<FadeOutLine>();
			fadeOutLine.start = start;
			fadeOutLine.end = end;
			fadeOutLine.Prep();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "EverythingCanDie";

		public const string PLUGIN_NAME = "EverythingCanDie";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

BepInEx/plugins/americanompany/FairAI.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using FairAI.Component;
using FairAI.Patches;
using GameNetcodeStuff;
using HarmonyLib;
using LethalThings;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FairAI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FairAI")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("42deea12-f73e-4d63-81e9-5359e98c8d53")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace FairAI
{
	internal class FAIR_AI : NetworkBehaviour
	{
		public EnemyAI targetWithRotation;

		private void Awake()
		{
			targetWithRotation = null;
		}

		[ClientRpc]
		public void SwitchedTargetedEnemyClientRpc(Turret turret, EnemyAI enemy, bool setModeToCharging = false)
		{
			targetWithRotation = enemy;
			if (setModeToCharging)
			{
				Type typeFromHandle = typeof(Turret);
				MethodInfo method = typeFromHandle.GetMethod("SwitchTurretMode", BindingFlags.Instance | BindingFlags.NonPublic);
				method.Invoke(turret, new object[1] { 1 });
			}
		}

		[ClientRpc]
		public void RemoveTargetedEnemyClientRpc()
		{
			targetWithRotation = null;
		}
	}
	[BepInPlugin("GoldenKitten.FairAI", "Fair AI", "1.3.8")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "GoldenKitten.FairAI";

		private const string modName = "Fair AI";

		private const string modVersion = "1.3.8";

		private Harmony harmony = new Harmony("GoldenKitten.FairAI");

		public static Plugin Instance;

		public static ManualLogSource logger;

		public static List<EnemyType> enemies;

		public static List<Item> items;

		public static Assembly surfacedAssembly;

		public const string ltModID = "evaisa.lethalthings";

		public const string surfacedModID = "Surfaced";

		public static bool playersEnteredInside = false;

		public static bool surfacedEnabled = false;

		public static bool lethalThingsEnabled = false;

		public static int wallsAndEnemyLayerMask = 524288;

		public static int enemyMask = 524288;

		public static int allHittablesMask;

		private static float onMeshThreshold = 3f;

		private async void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			surfacedAssembly = null;
			harmony = new Harmony("GoldenKitten.FairAI");
			logger = Logger.CreateLogSource("GoldenKitten.FairAI");
			harmony.PatchAll(typeof(Plugin));
			CreateHarmonyPatch(harmony, typeof(RoundManager), "Start", null, typeof(RoundManagerPatch), "PatchStart", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(StartOfRound), "Start", null, typeof(StartOfRoundPatch), "PatchStart", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(StartOfRound), "Update", null, typeof(StartOfRoundPatch), "PatchUpdate", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Turret), "Update", null, typeof(TurretAIPatch), "PatchUpdate", isPrefix: true);
			CreateHarmonyPatch(harmony, typeof(Turret), "SetTargetToPlayerBody", null, typeof(TurretAIPatch), "PatchSetTargetToPlayerBody", isPrefix: true);
			CreateHarmonyPatch(harmony, typeof(Turret), "TurnTowardsTargetIfHasLOS", null, typeof(TurretAIPatch), "PatchTurnTowardsTargetIfHasLOS", isPrefix: true);
			CreateHarmonyPatch(harmony, typeof(Landmine), "SpawnExplosion", new Type[8]
			{
				typeof(Vector3),
				typeof(bool),
				typeof(float),
				typeof(float),
				typeof(int),
				typeof(float),
				typeof(GameObject),
				typeof(bool)
			}, typeof(MineAIPatch), "PatchSpawnExplosion", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Landmine), "OnTriggerEnter", null, typeof(MineAIPatch), "PatchOnTriggerEnter", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Landmine), "OnTriggerExit", null, typeof(MineAIPatch), "PatchOnTriggerExit", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Landmine), "Detonate", null, typeof(MineAIPatch), "DetonatePatch", isPrefix: false);
			await WaitForProcess(1);
			logger.LogInfo((object)"Fair AI initiated!");
		}

		public static async Task<IEnumerable<int>> WaitForProcess(int waitTime)
		{
			await Task.Delay(waitTime);
			bool done = false;
			while (!done)
			{
				await Instance.DelayedInitialization();
				done = true;
			}
			return new List<int>();
		}

		private async Task DelayedInitialization()
		{
			await Task.Run(delegate
			{
				TryLoadLethalThings();
				TryLoadSurfaced();
				logger.LogInfo((object)"Optional Components initiated!");
			});
		}

		private void TryLoadLethalThings()
		{
			try
			{
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				Assembly assembly = null;
				Assembly[] array = assemblies;
				foreach (Assembly assembly2 in array)
				{
					if (assembly2.GetName().Name == "LethalThings")
					{
						assembly = assembly2;
						break;
					}
				}
				if (assembly != null)
				{
					Type type = assembly.GetType("LethalThings.RoombaAI");
					if (type != null && BoombaPatch.enabled)
					{
						CreateHarmonyPatch(harmony, type, "Start", null, typeof(BoombaPatch), "PatchStart", isPrefix: false);
						CreateHarmonyPatch(harmony, type, "DoAIInterval", null, typeof(BoombaPatch), "PatchDoAIInterval", isPrefix: false);
						lethalThingsEnabled = true;
						logger.LogInfo((object)"LethalThings Component Initiated!");
					}
				}
				else
				{
					logger.LogWarning((object)"LethalThings assembly not found. Skipping optional patch.");
				}
			}
			catch (Exception ex)
			{
				logger.LogError((object)("An error occurred while trying to apply patches for LethalThings: " + ex.Message));
			}
		}

		private void TryLoadSurfaced()
		{
			try
			{
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				Assembly[] array = assemblies;
				foreach (Assembly assembly in array)
				{
					if (assembly.GetName().Name == "Surfaced")
					{
						surfacedAssembly = assembly;
						break;
					}
				}
				if (surfacedAssembly != null)
				{
					Type type = surfacedAssembly.GetType("Seamine");
					if (type != null)
					{
						if (SurfacedMinePatch.enabled)
						{
							CreateHarmonyPatch(harmony, type, "OnTriggerEnter", new Type[1] { typeof(Collider) }, typeof(SurfacedMinePatch), "PatchOnTriggerEnter", isPrefix: false);
							surfacedEnabled = true;
							logger.LogInfo((object)"Surfaced Component Initiated!");
						}
					}
					else
					{
						logger.LogInfo((object)"Surfaced Component Not Found!");
					}
				}
				else
				{
					logger.LogWarning((object)"Surfaced assembly not found. Skipping optional patch.");
				}
			}
			catch (Exception ex)
			{
				logger.LogError((object)("An error occurred while trying to apply patches for Surfaced: " + ex.Message));
			}
		}

		public static List<PlayerControllerB> GetActivePlayers()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			List<PlayerControllerB> list = new List<PlayerControllerB>();
			PlayerControllerB[] array = allPlayerScripts;
			foreach (PlayerControllerB val in array)
			{
				if ((Object)val != (Object)null && !val.isPlayerDead && ((Behaviour)val).isActiveAndEnabled && val.isPlayerControlled)
				{
					list.Add(val);
				}
			}
			return list;
		}

		public static bool AllowFairness(Vector3 position)
		{
			//IL_0027: 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)
			if ((Object)(object)StartOfRound.Instance != (Object)null && Can("CheckForPlayersInside"))
			{
				if (IsAPlayersOutside())
				{
					if (!(position.y > -80f))
					{
						Bounds bounds = StartOfRound.Instance.shipInnerRoomBounds.bounds;
						if (!((Bounds)(ref bounds)).Contains(position))
						{
							goto IL_005c;
						}
					}
					return true;
				}
				goto IL_005c;
			}
			return true;
			IL_005c:
			return playersEnteredInside;
		}

		public static bool IsAPlayersOutside()
		{
			List<PlayerControllerB> activePlayers = GetActivePlayers();
			for (int i = 0; i < activePlayers.Count; i++)
			{
				PlayerControllerB val = activePlayers[i];
				if (!val.isInsideFactory)
				{
					return true;
				}
			}
			return false;
		}

		public static bool IsAPlayerInsideShip()
		{
			List<PlayerControllerB> activePlayers = GetActivePlayers();
			for (int i = 0; i < activePlayers.Count; i++)
			{
				PlayerControllerB val = activePlayers[i];
				if (val.isInHangarShipRoom)
				{
					return true;
				}
			}
			return false;
		}

		public static bool IsAPlayerInsideDungeon()
		{
			List<PlayerControllerB> activePlayers = GetActivePlayers();
			for (int i = 0; i < activePlayers.Count; i++)
			{
				PlayerControllerB val = activePlayers[i];
				if (val.isInsideFactory)
				{
					return true;
				}
			}
			return false;
		}

		public static bool CanMob(string parentIdentifier, string identifier, string mobName)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			string text = RemoveInvalidCharacters(mobName).ToUpper();
			if (((BaseUnityPlugin)Instance).Config[new ConfigDefinition("Mobs", parentIdentifier)].BoxedValue.ToString().ToUpper().Equals("TRUE"))
			{
				foreach (ConfigDefinition key in ((BaseUnityPlugin)Instance).Config.Keys)
				{
					if (RemoveInvalidCharacters(key.Key.ToUpper()).Equals(RemoveInvalidCharacters(text + identifier.ToUpper())))
					{
						return ((BaseUnityPlugin)Instance).Config[key].BoxedValue.ToString().ToUpper().Equals("TRUE");
					}
				}
				return false;
			}
			return false;
		}

		public static bool Can(string identifier)
		{
			foreach (ConfigDefinition key in ((BaseUnityPlugin)Instance).Config.Keys)
			{
				if (RemoveInvalidCharacters(key.Key.ToUpper()).Equals(RemoveInvalidCharacters(identifier.ToUpper())))
				{
					return ((BaseUnityPlugin)Instance).Config[key].BoxedValue.ToString().ToUpper().Equals("TRUE");
				}
			}
			return false;
		}

		public static string RemoveWhitespaces(string source)
		{
			return string.Join("", source.Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries));
		}

		public static string RemoveSpecialCharacters(string source)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (char c in source)
			{
				if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString();
		}

		public static string RemoveInvalidCharacters(string source)
		{
			return RemoveWhitespaces(RemoveSpecialCharacters(source));
		}

		public static Type FindType(string fullName)
		{
			try
			{
				if ((from a in AppDomain.CurrentDomain.GetAssemblies()
					where !a.IsDynamic
					select a).SelectMany((Assembly a) => a.GetTypes()).FirstOrDefault((Type t) => t.FullName.Equals(fullName)) != null)
				{
					return (from a in AppDomain.CurrentDomain.GetAssemblies()
						where !a.IsDynamic
						select a).SelectMany((Assembly a) => a.GetTypes()).FirstOrDefault((Type t) => t.FullName.Equals(fullName));
				}
			}
			catch
			{
				return null;
			}
			return null;
		}

		public static void CreateHarmonyPatch(Harmony harmony, Type typeToPatch, string methodToPatch, Type[] parameters, Type patchType, string patchMethod, bool isPrefix, bool isTranspiler = false)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			if (typeToPatch == null || patchType == null)
			{
				logger.LogInfo((object)"Type is either incorrect or does not exist!");
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(typeToPatch, methodToPatch, parameters, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(patchType, patchMethod, (Type[])null, (Type[])null);
			if (isTranspiler)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null);
			}
			else if (isPrefix)
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			else
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		public static bool IsAgentOnNavMesh(GameObject agentObject)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = agentObject.transform.position;
			NavMeshHit val = default(NavMeshHit);
			if (NavMesh.SamplePosition(position, ref val, onMeshThreshold, -1) && Mathf.Approximately(position.x, ((NavMeshHit)(ref val)).position.x) && Mathf.Approximately(position.z, ((NavMeshHit)(ref val)).position.z))
			{
				return position.y >= ((NavMeshHit)(ref val)).position.y;
			}
			return false;
		}

		public static bool AttackTargets(Vector3 aimPoint, Vector3 forward, float range)
		{
			//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_0009: Unknown result type (might be due to invalid IL or missing references)
			return HitTargets(GetTargets(aimPoint, forward, range), forward);
		}

		public static List<GameObject> GetTargets(Vector3 aimPoint, Vector3 forward, float range)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: 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)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: 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_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			List<GameObject> list = new List<GameObject>();
			Ray val = default(Ray);
			((Ray)(ref val))..ctor(aimPoint, forward);
			RaycastHit[] array = Physics.RaycastAll(val, range, -5, (QueryTriggerInteraction)2);
			Array.Sort(array, (RaycastHit x, RaycastHit y) => ((RaycastHit)(ref x)).distance.CompareTo(((RaycastHit)(ref y)).distance));
			Vector3 val2 = aimPoint + forward * range;
			IHittable val3 = default(IHittable);
			EnemyAI val6 = default(EnemyAI);
			for (int i = 0; i < array.Length; i++)
			{
				GameObject gameObject = ((Component)((RaycastHit)(ref array[i])).transform).gameObject;
				Transform transform = ((RaycastHit)(ref array[i])).transform;
				if (((Component)transform).TryGetComponent<IHittable>(ref val3))
				{
					EnemyAI val4 = null;
					EnemyAICollisionDetect val5 = (EnemyAICollisionDetect)(object)((val3 is EnemyAICollisionDetect) ? val3 : null);
					if (val5 != null)
					{
						val4 = val5.mainScript;
					}
					if ((Object)(object)val4 != (Object)null && !val4.isEnemyDead && val4.enemyHP > 0)
					{
						list.Add(((Component)transform).gameObject);
					}
					val2 = ((RaycastHit)(ref array[i])).point;
				}
				else
				{
					if (((Component)transform).TryGetComponent<EnemyAI>(ref val6) && !val6.isEnemyDead && val6.enemyHP > 0)
					{
						list.Add(((Component)val6).gameObject);
						val2 = ((RaycastHit)(ref array[i])).point;
					}
					val2 = ((RaycastHit)(ref array[i])).point;
				}
			}
			return list;
		}

		public static bool HitTargets(List<GameObject> targets, Vector3 forward)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			bool hits = false;
			if (!targets.Any())
			{
				return hits;
			}
			targets.ForEach(delegate(GameObject t)
			{
				//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f0: Expected O, but got Unknown
				//IL_0098: 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_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_0077: Unknown result type (might be due to invalid IL or missing references)
				//IL_007d: Unknown result type (might be due to invalid IL or missing references)
				//IL_017e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0184: 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_0156: Unknown result type (might be due to invalid IL or missing references)
				//IL_015c: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)t != (Object)null)
				{
					if ((Object)(object)t.GetComponent<EnemyAI>() != (Object)null)
					{
						EnemyAI component = t.GetComponent<EnemyAI>();
						int num = 1;
						if (CanMob("TurretDamageAllMobs", ".Turret Damage", component.enemyType.enemyName))
						{
							if (component is NutcrackerEnemyAI)
							{
								if (((EnemyAI)(NutcrackerEnemyAI)component).currentBehaviourStateIndex > 0)
								{
									component.HitEnemyOnLocalClient(num, default(Vector3), (PlayerControllerB)null, false, -1);
									hits = true;
								}
							}
							else
							{
								component.HitEnemyOnLocalClient(num, default(Vector3), (PlayerControllerB)null, false, -1);
								hits = true;
							}
						}
					}
					else if (t.GetComponent<IHittable>() != null)
					{
						IHittable component2 = t.GetComponent<IHittable>();
						if (component2 is EnemyAICollisionDetect)
						{
							EnemyAICollisionDetect val = (EnemyAICollisionDetect)component2;
							int num2 = 1;
							if (CanMob("TurretDamageAllMobs", ".Turret Damage", val.mainScript.enemyType.enemyName))
							{
								if (val.mainScript is NutcrackerEnemyAI)
								{
									if (((EnemyAI)(NutcrackerEnemyAI)val.mainScript).currentBehaviourStateIndex > 0)
									{
										val.mainScript.HitEnemyOnLocalClient(num2, default(Vector3), (PlayerControllerB)null, false, -1);
										hits = true;
									}
								}
								else
								{
									val.mainScript.HitEnemyOnLocalClient(num2, default(Vector3), (PlayerControllerB)null, false, -1);
									hits = true;
								}
							}
						}
						else if (!(component2 is PlayerControllerB))
						{
							component2.Hit(1, forward, (PlayerControllerB)null, true, -1);
							hits = true;
						}
					}
				}
			});
			return hits;
		}
	}
}
namespace FairAI.Patches
{
	public static class BoombaPatch
	{
		private static bool? _enabled;

		public static bool enabled
		{
			get
			{
				if (!_enabled.HasValue)
				{
					_enabled = Chainloader.PluginInfos.ContainsKey("evaisa.lethalthings");
				}
				return _enabled.Value;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void PatchStart(ref RoombaAI __instance)
		{
			((Component)__instance).gameObject.AddComponent<BoombaTimer>();
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void PatchDoAIInterval(ref RoombaAI __instance)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.AllowFairness(((Component)__instance).transform.position) || !Plugin.IsAgentOnNavMesh(((Component)__instance).gameObject) || (((EnemyAI)__instance).currentSearch == null && !((EnemyAI)__instance).movingTowardsTargetPlayer) || (!__instance.mineAudio.isPlaying && !__instance.mineFarAudio.isPlaying) || !((Component)__instance).GetComponent<BoombaTimer>().IsActiveBomb())
			{
				return;
			}
			Vector3 val = ((Component)__instance).transform.position + Vector3.up;
			Collider[] array = Physics.OverlapSphere(val, 6f, 2621448, (QueryTriggerInteraction)2);
			for (int i = 0; i < array.Length; i++)
			{
				float num = Vector3.Distance(val, ((Component)array[i]).transform.position);
				if ((num > 4f && Physics.Linecast(val, ((Component)array[i]).transform.position + Vector3.up * 0.3f, 256, (QueryTriggerInteraction)1)) || !((Object)(object)((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>() != (Object)null))
				{
					continue;
				}
				EnemyAICollisionDetect component = ((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>();
				if (!((Object)(object)((Component)component.mainScript).gameObject != (Object)(object)((Component)__instance).gameObject) || !Plugin.CanMob("BoombaAllMobs", ".Boomba", component.mainScript.enemyType.enemyName))
				{
					continue;
				}
				if ((Object)(object)component != (Object)null && ((NetworkBehaviour)component.mainScript).IsOwner && !component.mainScript.isEnemyDead)
				{
					Object.Instantiate<GameObject>(StartOfRound.Instance.explosionPrefab, val, Quaternion.Euler(-90f, 0f, 0f), RoundManager.Instance.mapPropsContainer.transform).SetActive(true);
					if (num < 3f)
					{
						component.mainScript.KillEnemyOnOwnerClient(true);
					}
					else if (num < 6f)
					{
						component.mainScript.HitEnemyOnLocalClient(2, default(Vector3), (PlayerControllerB)null, false, -1);
					}
				}
				if (((NetworkBehaviour)__instance).IsServer)
				{
					((EnemyAI)__instance).KillEnemy(true);
				}
				else
				{
					((EnemyAI)__instance).KillEnemyServerRpc(true);
				}
			}
		}
	}
	internal class EnemyAIPatch
	{
	}
	internal class MineAIPatch
	{
		public static void PatchOnTriggerEnter(ref Landmine __instance, Collider other, ref float ___pressMineDebounceTimer)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.AllowFairness(((Component)__instance).transform.position))
			{
				EnemyAICollisionDetect component = ((Component)other).gameObject.GetComponent<EnemyAICollisionDetect>();
				if ((Object)(object)component != (Object)null && !component.mainScript.isEnemyDead && Plugin.CanMob("ExplodeAllMobs", ".Mine", component.mainScript.enemyType.enemyName.ToUpper()))
				{
					___pressMineDebounceTimer = 0.5f;
					__instance.PressMineServerRpc();
				}
			}
		}

		public static void PatchOnTriggerExit(ref Landmine __instance, Collider other, ref bool ___sendingExplosionRPC)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.AllowFairness(((Component)__instance).transform.position))
			{
				EnemyAICollisionDetect component = ((Component)other).gameObject.GetComponent<EnemyAICollisionDetect>();
				if ((Object)(object)component != (Object)null && !component.mainScript.isEnemyDead && Plugin.CanMob("ExplodeAllMobs", ".Mine", component.mainScript.enemyType.enemyName.ToUpper()) && !__instance.hasExploded)
				{
					__instance.SetOffMineAnimation();
					___sendingExplosionRPC = true;
					__instance.ExplodeMineServerRpc();
				}
			}
		}

		public static void DetonatePatch(ref Landmine __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				((MonoBehaviour)__instance).StartCoroutine(WaitForUpdate(1.5f, __instance));
			}
		}

		public static IEnumerator WaitForUpdate(float waitTime, Landmine mine)
		{
			yield return (object)new WaitForSeconds(waitTime);
			if (!((Object)(object)mine == (Object)null))
			{
				if ((Object)(object)((Component)mine).GetComponent<NetworkObject>() != (Object)null)
				{
					((Component)mine).GetComponent<NetworkObject>().Despawn(true);
				}
				else
				{
					Object.Destroy((Object)(object)((Component)mine).gameObject);
				}
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void PatchSpawnExplosion(Vector3 explosionPosition, bool spawnExplosionEffect = false, float killRange = 1f, float damageRange = 1f, int nonLethalDamage = 50, float physicsForce = 0f, GameObject overridePrefab = null, bool goThroughCar = false)
		{
			//IL_0004: 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_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			bool flag = true;
			Collider[] array = Physics.OverlapSphere(explosionPosition, 6f, 2621448, (QueryTriggerInteraction)2);
			for (int i = 0; i < array.Length; i++)
			{
				float num = Vector3.Distance(explosionPosition, ((Component)array[i]).transform.position);
				if (num > 4f && Physics.Linecast(explosionPosition, ((Component)array[i]).transform.position + Vector3.up * 0.3f, 256, (QueryTriggerInteraction)1))
				{
					continue;
				}
				if (Plugin.surfacedEnabled && Plugin.surfacedAssembly != null)
				{
					Type type = Plugin.surfacedAssembly.GetType("Seamine");
					if (type != null && (Object)(object)((Component)array[i]).gameObject.GetComponent(type) != (Object)null)
					{
						Component component = ((Component)array[i]).gameObject.GetComponent(type);
						FieldInfo field = type.GetField("mineActivated", BindingFlags.Instance | BindingFlags.NonPublic);
						FieldInfo field2 = type.GetField("hasExploded", BindingFlags.Instance | BindingFlags.Public);
						if (!(bool)field2.GetValue(component) || !(bool)field.GetValue(component))
						{
							break;
						}
						if (Plugin.AllowFairness(component.transform.position))
						{
							MethodInfo method = type.GetMethod("TriggerMineOnLocalClientByExiting", BindingFlags.Instance | BindingFlags.NonPublic);
							method.Invoke(component, new object[0]);
						}
					}
				}
				if (!((Object)(object)((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>() != (Object)null))
				{
					continue;
				}
				EnemyAICollisionDetect component2 = ((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>();
				if ((Object)(object)component2 != (Object)null && ((NetworkBehaviour)component2.mainScript).IsOwner && !component2.mainScript.isEnemyDead)
				{
					if (num < killRange)
					{
						component2.mainScript.HitEnemyOnLocalClient(component2.mainScript.enemyHP, default(Vector3), (PlayerControllerB)null, false, -1);
					}
					else if (num < damageRange)
					{
						component2.mainScript.HitEnemyOnLocalClient(Mathf.RoundToInt((float)(component2.mainScript.enemyHP / 2)), default(Vector3), (PlayerControllerB)null, false, -1);
					}
				}
			}
		}
	}
	internal class RoundManagerPatch
	{
		public static void PatchStart(ref RoundManager __instance)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Expected O, but got Unknown
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Expected O, but got Unknown
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Expected O, but got Unknown
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Expected O, but got Unknown
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Expected O, but got Unknown
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_0363: Expected O, but got Unknown
			Plugin.enemies = (from EnemyType e in Resources.FindObjectsOfTypeAll(typeof(EnemyType))
				where (Object)(object)e != (Object)null
				select e).ToList();
			Plugin.items = (from Item i in Resources.FindObjectsOfTypeAll(typeof(Item))
				where (Object)(object)i != (Object)null
				select i).ToList();
			Plugin.allHittablesMask = StartOfRound.Instance.collidersRoomMaskDefaultAndPlayers | 0x280008 | Plugin.enemyMask;
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "ExplodeAllMobs")))
			{
				ConfigEntry<bool> val = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "ExplodeAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Mines.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "BoombaAllMobs")))
			{
				ConfigEntry<bool> val2 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "BoombaAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Boombas.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretTargetAllMobs")))
			{
				ConfigEntry<bool> val3 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretTargetAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Targeted By Turrets.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretDamageAllMobs")))
			{
				ConfigEntry<bool> val4 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretDamageAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Killed By Turrets.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "CheckForPlayersInside")))
			{
				ConfigEntry<bool> val5 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "CheckForPlayersInside", false, "Whether to check for players inside the dungeon before anything else occurs.");
			}
			foreach (EnemyType enemy in Plugin.enemies)
			{
				string text = Plugin.RemoveInvalidCharacters(enemy.enemyName);
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Mine")))
				{
					ConfigEntry<bool> val6 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Mine", true, "Does it set off the landmine or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Boomba")))
				{
					ConfigEntry<bool> val7 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Boomba", true, "Does it set off the boomba or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Target")))
				{
					ConfigEntry<bool> val8 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Target", true, "Is it targetable by turrets?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Damage")))
				{
					ConfigEntry<bool> val9 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Damage", true, "Is it damageable by turrets?");
				}
			}
		}
	}
	internal class StartOfRoundPatch
	{
		public static void PatchStart(ref StartOfRound __instance)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Expected O, but got Unknown
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Expected O, but got Unknown
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Expected O, but got Unknown
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Expected O, but got Unknown
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Expected O, but got Unknown
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_0363: Expected O, but got Unknown
			Plugin.enemies = (from EnemyType e in Resources.FindObjectsOfTypeAll(typeof(EnemyType))
				where (Object)(object)e != (Object)null
				select e).ToList();
			Plugin.items = (from Item i in Resources.FindObjectsOfTypeAll(typeof(Item))
				where (Object)(object)i != (Object)null
				select i).ToList();
			Plugin.allHittablesMask = StartOfRound.Instance.collidersRoomMaskDefaultAndPlayers | 0x280008 | Plugin.enemyMask;
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "ExplodeAllMobs")))
			{
				ConfigEntry<bool> val = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "ExplodeAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Mines.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "BoombaAllMobs")))
			{
				ConfigEntry<bool> val2 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "BoombaAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Boombas.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretTargetAllMobs")))
			{
				ConfigEntry<bool> val3 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretTargetAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Targeted By Turrets.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretDamageAllMobs")))
			{
				ConfigEntry<bool> val4 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretDamageAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Killed By Turrets.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "CheckForPlayersInside")))
			{
				ConfigEntry<bool> val5 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "CheckForPlayersInside", false, "Whether to check for players inside the dungeon before anything else occurs.");
			}
			foreach (EnemyType enemy in Plugin.enemies)
			{
				string text = Plugin.RemoveInvalidCharacters(enemy.enemyName);
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Mine")))
				{
					ConfigEntry<bool> val6 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Mine", true, "Does it set off the landmine or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Boomba")))
				{
					ConfigEntry<bool> val7 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Boomba", true, "Does it set off the boomba or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Target")))
				{
					ConfigEntry<bool> val8 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Target", true, "Is it targetable by turrets?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Damage")))
				{
					ConfigEntry<bool> val9 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Damage", true, "Is it damageable by turrets?");
				}
			}
		}

		public static void PatchUpdate(ref StartOfRound __instance)
		{
			if (Plugin.Can("CheckForPlayersInside"))
			{
				if (__instance.shipIsLeaving)
				{
					Plugin.playersEnteredInside = false;
				}
				else
				{
					Plugin.playersEnteredInside = Plugin.IsAPlayerInsideDungeon();
				}
			}
		}
	}
	public static class SurfacedMinePatch
	{
		private static bool? _enabled;

		public static bool enabled
		{
			get
			{
				if (!_enabled.HasValue)
				{
					_enabled = Chainloader.PluginInfos.ContainsKey("Surfaced");
				}
				return _enabled.Value;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void PatchOnTriggerEnter(ref Seamine __instance, Collider other)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			Type typeFromHandle = typeof(Seamine);
			FieldInfo field = typeFromHandle.GetField("mineActivated", BindingFlags.Instance | BindingFlags.NonPublic);
			if (!__instance.hasExploded && (bool)field.GetValue(__instance) && Plugin.AllowFairness(((Component)__instance).transform.position))
			{
				EnemyAICollisionDetect component = ((Component)other).gameObject.GetComponent<EnemyAICollisionDetect>();
				if ((Object)(object)component != (Object)null && !component.mainScript.isEnemyDead && Plugin.CanMob("ExplodeAllMobs", ".Mine", component.mainScript.enemyType.enemyName.ToUpper()))
				{
					MethodInfo method = typeFromHandle.GetMethod("TriggerMineOnLocalClientByExiting", BindingFlags.Instance | BindingFlags.NonPublic);
					method.Invoke(__instance, new object[0]);
				}
			}
		}
	}
	internal class TurretAIPatch
	{
		public static float viewRadius = 16f;

		public static float viewAngle = 90f;

		public static void PatchUpdate(ref Turret __instance)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected I4, but got Unknown
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || !Plugin.AllowFairness(((Component)__instance).transform.position))
			{
				return;
			}
			FAIR_AI fAIR_AI = ((Component)__instance).gameObject.GetComponent<FAIR_AI>();
			if ((Object)(object)fAIR_AI == (Object)null)
			{
				fAIR_AI = ((Component)__instance).gameObject.AddComponent<FAIR_AI>();
			}
			Type typeFromHandle = typeof(Turret);
			FieldInfo field = typeFromHandle.GetField("wasTargetingPlayerLastFrame", BindingFlags.Instance | BindingFlags.NonPublic);
			FieldInfo field2 = typeFromHandle.GetField("hasLineOfSight", BindingFlags.Instance | BindingFlags.NonPublic);
			if ((Object)(object)fAIR_AI == (Object)null)
			{
				return;
			}
			FieldInfo field3 = typeFromHandle.GetField("turretInterval", BindingFlags.Instance | BindingFlags.NonPublic);
			TurretMode turretMode = __instance.turretMode;
			TurretMode val = turretMode;
			switch (val - 1)
			{
			case 0:
				if ((float)field3.GetValue(__instance) >= 1.5f)
				{
					Debug.Log((object)"Charging timer is up, setting to firing mode");
					if (!(bool)field2.GetValue(__instance))
					{
						Debug.Log((object)"hasLineOfSight is false");
						fAIR_AI.targetWithRotation = null;
						fAIR_AI.RemoveTargetedEnemyClientRpc();
					}
					else
					{
						__instance.turretMode = (TurretMode)2;
						__instance.SetToModeClientRpc(2);
					}
				}
				break;
			case 1:
				if ((float)field3.GetValue(__instance) >= 0.21f)
				{
					Vector3 forward2 = __instance.aimPoint.forward;
					forward2 = Quaternion.Euler(0f, (float)(int)(0f - __instance.rotationRange) / 3f, 0f) * forward2;
					Plugin.AttackTargets(__instance.centerPoint.position, forward2, 30f);
				}
				break;
			case 2:
				if ((float)field3.GetValue(__instance) >= 0.21f)
				{
					Vector3 forward = __instance.aimPoint.forward;
					forward = Quaternion.Euler(0f, (float)(int)(0f - __instance.rotationRange) / 3f, 0f) * forward;
					Plugin.AttackTargets(__instance.centerPoint.position, forward, 30f);
				}
				break;
			}
		}

		public static void PatchSetTargetToPlayerBody(ref Turret __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			Type typeFromHandle = typeof(Turret);
			FieldInfo field = typeFromHandle.GetField("targetingDeadPlayer", BindingFlags.Instance | BindingFlags.NonPublic);
			FAIR_AI component = ((Component)__instance).gameObject.GetComponent<FAIR_AI>();
			if ((Object)(object)component.targetWithRotation != (Object)null)
			{
				if (!(bool)field.GetValue(__instance))
				{
					field.SetValue(__instance, true);
				}
				if (!((Component)component.targetWithRotation).GetComponent<EnemyAI>().isEnemyDead)
				{
					field.SetValue(__instance, false);
					__instance.targetTransform = ((Component)component.targetWithRotation).transform;
				}
			}
		}

		public static void PatchTurnTowardsTargetIfHasLOS(ref Turret __instance)
		{
			TurnTowardsTargetEnemyIfHasLOS(__instance);
		}

		public static bool TurnTowardsTargetEnemyIfHasLOS(Turret turret)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			bool flag = true;
			Type typeFromHandle = typeof(Turret);
			FieldInfo field = typeFromHandle.GetField("targetingDeadPlayer", BindingFlags.Instance | BindingFlags.NonPublic);
			object value = field.GetValue(turret);
			FieldInfo field2 = typeFromHandle.GetField("hasLineOfSight", BindingFlags.Instance | BindingFlags.NonPublic);
			FieldInfo field3 = typeFromHandle.GetField("lostLOSTimer", BindingFlags.Instance | BindingFlags.NonPublic);
			if ((bool)value || Vector3.Angle(turret.targetTransform.position - turret.centerPoint.position, turret.forwardFacingPos.forward) > turret.rotationRange)
			{
				flag = false;
			}
			if (Physics.Linecast(turret.aimPoint.position, turret.targetTransform.position, StartOfRound.Instance.collidersAndRoomMask, (QueryTriggerInteraction)1))
			{
				flag = false;
			}
			List<EnemyAICollisionDetect> actualTargets = GetActualTargets(turret);
			if (flag && actualTargets != null && actualTargets.Any())
			{
				field2.SetValue(turret, true);
				field3.SetValue(turret, 0f);
				if ((Object)(object)((Component)turret).GetComponent<FAIR_AI>() != (Object)null)
				{
					FAIR_AI component = ((Component)turret).GetComponent<FAIR_AI>();
					if ((Object)(object)component.targetWithRotation == (Object)null)
					{
						component.targetWithRotation = actualTargets[0].mainScript;
					}
					turret.tempTransform.position = ((Component)component.targetWithRotation).transform.position;
					Transform tempTransform = turret.tempTransform;
					tempTransform.position -= Vector3.up * 0.15f;
					turret.turnTowardsObjectCompass.LookAt(turret.tempTransform);
				}
			}
			if (!flag)
			{
				object value2 = field2.GetValue(turret);
				if ((bool)value2)
				{
					field2.SetValue(turret, false);
					field3.SetValue(turret, 0f);
				}
				if (!((NetworkBehaviour)turret).IsServer)
				{
					field3.SetValue(turret, (float)field3.GetValue(turret) + Time.deltaTime);
					FAIR_AI component2 = ((Component)turret).gameObject.GetComponent<FAIR_AI>();
					List<EnemyAICollisionDetect> actualTargets2 = GetActualTargets(turret);
					if (actualTargets2.Any())
					{
						component2.targetWithRotation = actualTargets2[0].mainScript;
						component2.SwitchedTargetedEnemyClientRpc(turret, actualTargets2[0].mainScript);
					}
					else
					{
						component2.targetWithRotation = null;
						component2.RemoveTargetedEnemyClientRpc();
					}
				}
			}
			return flag;
		}

		public static List<EnemyAICollisionDetect> GetActualTargets(Turret turret)
		{
			List<EnemyAICollisionDetect> list = new List<EnemyAICollisionDetect>();
			List<EnemyAICollisionDetect> targets = GetTargets(turret);
			if (targets != null)
			{
				targets.RemoveAll((EnemyAICollisionDetect t) => (Object)(object)t == (Object)null);
				if (targets.Any())
				{
					foreach (EnemyAICollisionDetect item in targets)
					{
						if ((Object)(object)item != (Object)null)
						{
							list.Add(item);
						}
					}
				}
			}
			return list;
		}

		private static List<EnemyAICollisionDetect> GetTargets(Turret turret, float radius = 2f, bool angleRangeCheck = false)
		{
			List<Transform> list = FindVisibleTargets(turret);
			List<EnemyAICollisionDetect> en = new List<EnemyAICollisionDetect>();
			if (list.Any())
			{
				list.ForEach(delegate(Transform e)
				{
					EnemyAICollisionDetect component = ((Component)e).GetComponent<EnemyAICollisionDetect>();
					if ((Object)(object)component != (Object)null)
					{
						en.Add(component);
					}
				});
			}
			return en;
		}

		public static Vector3 DirectionFromAngle(Turret turret, float angleInDegrees, bool angleIsGlobal)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (!angleIsGlobal)
			{
				angleInDegrees += ((Component)turret).transform.eulerAngles.y;
			}
			return new Vector3(Mathf.Sin(angleInDegrees * ((float)Math.PI / 180f)), 0f, Mathf.Cos(angleInDegrees * ((float)Math.PI / 180f)));
		}

		public static List<Transform> FindVisibleTargets(Turret turret)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(turret.aimPoint.position, viewRadius, 0x280008 | Plugin.enemyMask | StartOfRound.Instance.playersMask);
			List<Transform> list = new List<Transform>();
			for (int i = 0; i < array.Length; i++)
			{
				Transform transform = ((Component)array[i]).transform;
				Vector3 val = transform.position - turret.aimPoint.position;
				Vector3 normalized = ((Vector3)(ref val)).normalized;
				if (!(Vector3.Angle(turret.aimPoint.forward, normalized) < viewAngle / 2f))
				{
					continue;
				}
				float num = Vector3.Distance(turret.aimPoint.position, transform.position);
				if (!Physics.Raycast(turret.aimPoint.position, normalized, num, ~(0x280008 | Plugin.enemyMask | StartOfRound.Instance.playersMask)))
				{
					if ((Object)(object)((Component)transform).GetComponent<EnemyAICollisionDetect>() != (Object)null)
					{
						list.Add(transform);
					}
					else if ((Object)(object)((Component)transform).GetComponent<EnemyAI>() != (Object)null)
					{
						list.Add(transform);
					}
				}
			}
			return list;
		}
	}
}
namespace FairAI.Component
{
	internal class BoombaTimer : MonoBehaviour
	{
		private bool isActiveBomb = false;

		private void Start()
		{
			((MonoBehaviour)this).StartCoroutine(StartBombTimer());
			Plugin.logger.LogInfo((object)"Boomba has been set active.");
		}

		public IEnumerator StartBombTimer()
		{
			SetActiveBomb(isActive: false);
			yield return (object)new WaitForSeconds(3f);
			SetActiveBomb(isActive: true);
		}

		public void SetActiveBomb(bool isActive)
		{
			isActiveBomb = isActive;
		}

		public bool IsActiveBomb()
		{
			return isActiveBomb;
		}
	}
}

BepInEx/plugins/americanompany/Full Darkness.dll

Decompiled 2 years ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DiversityLib;
using Full Darkness.NetcodePatcher;
using Full_Darkness.Manager;
using Full_Darkness.Patches;
using GameNetcodeStuff;
using HarmonyLib;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Full Darkness")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Full Darkness")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("1327764d-af71-48a4-ba41-6cbf7eed6d59")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Full_Darkness
{
	public class Configuration
	{
		public static ConfigEntry<float> fullDarknessIntensity;

		public static void Load()
		{
			fullDarknessIntensity = Plugin.config.Bind<float>("Full Darkness", "Full Darkness Intensity", 1f, "How intense should full darkness be?");
		}
	}
	[BepInPlugin("Chaos.FullDarkness", "Full Darkness", "1.0.1")]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "Chaos.FullDarkness";

		private const string modName = "Full Darkness";

		private const string modVersion = "1.0.1";

		private readonly Harmony harmony = new Harmony("Chaos.FullDarkness");

		public static Plugin Instance;

		public static ManualLogSource mls;

		public static ConfigFile config;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = ((BaseUnityPlugin)this).Logger;
			config = ((BaseUnityPlugin)this).Config;
			Configuration.Load();
			mls.LogDebug((object)"Patching full darkness...");
			harmony.PatchAll(typeof(FullDarknessPatch));
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			mls.LogInfo((object)"Full Darkness loaded.");
		}
	}
}
namespace Full_Darkness.Patches
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class FullDarknessPatch
	{
		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		private static void Awake(StartOfRound __instance)
		{
			if (!Object.op_Implicit((Object)(object)((Component)__instance).gameObject.GetComponent<FullDarknessManager>()))
			{
				((Component)__instance).gameObject.AddComponent<FullDarknessManager>();
			}
		}
	}
}
namespace Full_Darkness.Manager
{
	public class FullDarknessManager : NetworkBehaviour
	{
		public float intensityValue = 0f;

		public float nightVisionValue = 0f;

		public bool setup = false;

		public static FullDarknessManager Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
		}

		private void Start()
		{
			//IL_0044: 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)
			if (((NetworkBehaviour)this).IsOwner)
			{
				Plugin.mls.LogDebug((object)"I am the Host! Setting up full darkness locally...");
				SetupFullDarkness(Configuration.fullDarknessIntensity.Value);
			}
			else
			{
				Plugin.mls.LogDebug((object)"I am not the Host! Requesting host's config...");
				RequestDataServerRpc();
			}
		}

		private void Update()
		{
			if (!setup)
			{
				return;
			}
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if (nightVisionValue * DiversityLib.OneMinus(intensityValue) != val.nightVision.intensity)
				{
					val.nightVision.intensity = nightVisionValue * DiversityLib.OneMinus(intensityValue);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void RequestDataServerRpc(ServerRpcParams serverRpcParams = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1194691710u, serverRpcParams, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val, 1194691710u, serverRpcParams, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					ulong senderClientId = serverRpcParams.Receive.SenderClientId;
					ClientRpcParams val2 = default(ClientRpcParams);
					val2.Send = new ClientRpcSendParams
					{
						TargetClientIds = new ulong[1] { senderClientId }
					};
					ClientRpcParams clientRpcParams = val2;
					Plugin.mls.LogDebug((object)("Client: " + senderClientId + " is requesting config data..."));
					RequestDataClientRpc(Configuration.fullDarknessIntensity.Value, clientRpcParams);
				}
			}
		}

		[ClientRpc]
		public void RequestDataClientRpc(float _intensityValue, ClientRpcParams clientRpcParams = default(ClientRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(2393552199u, clientRpcParams, (RpcDelivery)0);
					((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref _intensityValue, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val, 2393552199u, clientRpcParams, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((NetworkBehaviour)this).IsOwner && !setup)
				{
					SetupFullDarkness(_intensityValue);
				}
			}
		}

		public void SetupFullDarkness(float _intensityValue)
		{
			Plugin.mls.LogDebug((object)"Setting up full darkness...");
			intensityValue = _intensityValue;
			PlayerControllerB[] array = Object.FindObjectsOfType<PlayerControllerB>();
			Plugin.mls.LogDebug((object)("Setting full darkness for the local player to " + intensityValue * 100f + "%."));
			PlayerControllerB[] array2 = array;
			foreach (PlayerControllerB val in array2)
			{
				nightVisionValue = val.nightVision.intensity;
				Light nightVision = val.nightVision;
				nightVision.intensity *= DiversityLib.OneMinus(intensityValue);
			}
			setup = true;
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_FullDarknessManager()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(1194691710u, new RpcReceiveHandler(__rpc_handler_1194691710));
			NetworkManager.__rpc_func_table.Add(2393552199u, new RpcReceiveHandler(__rpc_handler_2393552199));
		}

		private static void __rpc_handler_1194691710(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: 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_004d: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ServerRpcParams server = rpcParams.Server;
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((FullDarknessManager)(object)target).RequestDataServerRpc(server);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2393552199(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				float num = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num, default(ForPrimitives));
				ClientRpcParams client = rpcParams.Client;
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((FullDarknessManager)(object)target).RequestDataClientRpc(num, client);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "FullDarknessManager";
		}
	}
}
namespace Full Darkness.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}

BepInEx/plugins/americanompany/KillThemAll.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using KillThemAll.Extras;
using KillThemAll.Hooks;
using KillThemAll.Managers;
using KillThemAll.Models;
using KillThemAll.Network;
using LethalBestiary.Modules;
using LethalLib.Modules;
using Newtonsoft.Json;
using RuntimeNetcodeRPCValidator;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;
using UnityEngine.VFX;
using UnityEngine.VFX.Utility;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("KillThemAll")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("KillThemAll")]
[assembly: AssemblyTitle("KillThemAll")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace KillThemAll
{
	[BepInPlugin("KillThemAll.Main", "KillThemAll", "0.1.4")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class KillThemAll : BaseUnityPlugin
	{
		private const string modGUID = "KillThemAll.Main";

		private const string modName = "KillThemAll";

		private const string modVersion = "0.1.4";

		public static KillThemAll instance;

		public static AssetBundle hitMarkAsset;

		public static AssetBundle hitMarkSfxAsset;

		public static AssetBundle vfxBundle;

		public static AssetBundle playerReactionsSfxAsset;

		public static AssetBundle notificationAsset;

		public static AssetBundle tombstoneAsset;

		public static AssetBundle colliderTest;

		private readonly Harmony harmony = new Harmony("KillThemAll.Main");

		private NetcodeValidator netcodeValidator;

		private Dictionary<string, ConfigEntry<int>> enemyConfigEntries = new Dictionary<string, ConfigEntry<int>>();

		public ConfigEntry<string> TombSaveEntry;

		private void Awake()
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			if ((Object)(object)instance == (Object)null)
			{
				instance = this;
			}
			Utils.SetupLog();
			Utils.DebugLog("Awaking");
			LoadAssetBundles();
			harmony.PatchAll(typeof(VanillaHook));
			netcodeValidator = new NetcodeValidator("KillThemAll.Main");
			netcodeValidator.PatchAll();
			netcodeValidator.BindToPreExistingObjectByBehaviour<KillableEnemyEmitter, PlayerControllerB>();
			netcodeValidator.BindToPreExistingObjectByBehaviour<UIEmitter, PlayerControllerB>();
			netcodeValidator.BindToPreExistingObjectByBehaviour<TombScrapEmitter, PlayerControllerB>();
			netcodeValidator.BindToPreExistingObjectByBehaviour<OnSpawnEnemiesEmitter, PlayerControllerB>();
			Utils.DebugLog("Awaken");
		}

		public static List<Type> FindAllDerivedTypes<T>()
		{
			return FindAllDerivedTypes<T>(Assembly.GetAssembly(typeof(T)));
		}

		public static List<Type> FindAllDerivedTypes<T>(Assembly assembly)
		{
			Type baseType = typeof(T);
			return (from t in assembly.GetTypes()
				where t != baseType && baseType.IsAssignableFrom(t)
				select t).ToList();
		}

		public void Initialise()
		{
			AddKillThemAllBaseConfigs();
			AddBountyConfigs();
			Utils.DebugLog("Finding all base enemies...");
			List<string> list = new List<string>();
			List<Type> list2 = FindAllDerivedTypes<EnemyAI>();
			foreach (Type item in list2)
			{
				if (!(item.Name == "TestEnemy") && !(item.Name == "LassoMan"))
				{
					string name = item.Name;
					name = name.Replace("Enemy", "");
					name = name.Replace("(Clone)", "");
					name = name.Replace(".prefab", "");
					name = name.Replace("AI", "");
					Utils.DebugLog("Found enemy: " + name);
					list.Add(name);
				}
			}
			Utils.DebugLog("Finding all LethalLib enemies...");
			foreach (SpawnableEnemy spawnableEnemy in Enemies.spawnableEnemies)
			{
				string enemyName = spawnableEnemy.enemy.enemyName;
				enemyName = enemyName.Replace("Enemy", "");
				enemyName = enemyName.Replace("(Clone)", "");
				enemyName = enemyName.Replace(".prefab", "");
				enemyName = enemyName.Replace("AI", "");
				Utils.DebugLog("Found enemy from LethalLib: " + enemyName);
				list.Add(enemyName);
			}
			string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			directoryName.Replace("OLO-KillThemAll", "");
			directoryName += "TheWeavers-LethalBestiary/LethalBestiary/LethalBestiary.dll";
			Utils.DebugLog("Finding all LethalBestiary enemies...");
			foreach (SpawnableEnemy spawnableEnemy2 in Enemies.spawnableEnemies)
			{
				string enemyName2 = spawnableEnemy2.enemy.enemyName;
				enemyName2 = enemyName2.Replace("Enemy", "");
				enemyName2 = enemyName2.Replace("(Clone)", "");
				enemyName2 = enemyName2.Replace(".prefab", "");
				enemyName2 = enemyName2.Replace("AI", "");
				Utils.DebugLog("Found enemy from LethalBestiary: " + enemyName2);
				list.Add(enemyName2);
			}
			Utils.DebugLog("Creating config entries based on enemies found...");
			foreach (string item2 in list)
			{
				string text = "Enemy Health";
				string text2 = item2 + " Health";
				int num = 3;
				ConfigEntry<int> val = ((BaseUnityPlugin)this).Config.Bind<int>(text, text2, num, "Health points for " + item2 + "s");
				enemyConfigEntries.Add(item2, val);
				KillableEnemyManager.Instance.enemyHealthDictionary.Add(item2, val.Value);
				Utils.DebugLog("Config entry created for: " + item2);
			}
			foreach (KeyValuePair<string, ConfigEntry<int>> entry in enemyConfigEntries)
			{
				entry.Value.SettingChanged += delegate(object sender, EventArgs value)
				{
					if (sender is ConfigEntry<int> val2)
					{
						KillableEnemyManager.Instance.SetEnemyHealth(entry.Key, val2.Value);
						Utils.DebugLog("Saved health value for: " + entry.Key + " to: " + val2.Value);
					}
					else
					{
						Utils.DebugLog("ERROR: Tried to save config entry but entry = NULL");
					}
				};
			}
			Utils.DebugLog("Finished creating config entries based on enemies found!");
			TombSaveEntry = ((BaseUnityPlugin)this).Config.Bind<string>("!IGNORE THIS!", "Tomb Saving", "", "DO NOT DELETE");
		}

		public void AddKillThemAllBaseConfigs()
		{
			ConfigEntry<bool> debugLogEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("KillThemAll", "Debug Log", true, " if checked, log from this mod is output in the console");
			ConfigEntry<bool> showHitmarkVfxEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("KillThemAll", "Hit Marker", true, "If enabled, show hitmarker effect when damaging an enemy");
			ConfigEntry<bool> playHitmarkSfxEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("KillThemAll", "Hit Marker Sound Effect", true, "If enabled, play hitmarker sound effect when damaging an enemy");
			ConfigEntry<bool> playerReactionAKSfxEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("KillThemAll", "Player Reaction", true, "If enabled, play random sound effect when you or others kill an enemy (Its random if it plays or not)");
			ConfigEntry<bool> showEnemyDeathEffectEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("KillThemAll", "Enemy Death Effect", true, "If enabled, play enemy death effect");
			KillableEnemyManager.Instance.debugLog = debugLogEntry.Value;
			KillableEnemyManager.Instance.showHitmarkVfx = showHitmarkVfxEntry.Value;
			KillableEnemyManager.Instance.playHitmarkSfx = playHitmarkSfxEntry.Value;
			KillableEnemyManager.Instance.playerReactionAKSfx = playerReactionAKSfxEntry.Value;
			KillableEnemyManager.Instance.showEnemyDeathEffect = showEnemyDeathEffectEntry.Value;
			debugLogEntry.SettingChanged += delegate
			{
				KillableEnemyManager.Instance.debugLog = debugLogEntry.Value;
			};
			showHitmarkVfxEntry.SettingChanged += delegate
			{
				KillableEnemyManager.Instance.showHitmarkVfx = showHitmarkVfxEntry.Value;
			};
			playHitmarkSfxEntry.SettingChanged += delegate
			{
				KillableEnemyManager.Instance.playHitmarkSfx = playHitmarkSfxEntry.Value;
			};
			playerReactionAKSfxEntry.SettingChanged += delegate
			{
				KillableEnemyManager.Instance.playerReactionAKSfx = playerReactionAKSfxEntry.Value;
			};
			showEnemyDeathEffectEntry.SettingChanged += delegate
			{
				KillableEnemyManager.Instance.showEnemyDeathEffect = showEnemyDeathEffectEntry.Value;
			};
		}

		public void AddBountyConfigs()
		{
			ConfigEntry<int> chanceToSpawnPerRoundEntry = ((BaseUnityPlugin)this).Config.Bind<int>("Bounty Settings", "Rarity per round", 75, " Chance to spawn a bounty that round, the number is used like a percentage, the higher it is the higher the chances!");
			ConfigEntry<int> chanceToSpawnPerHourEntry = ((BaseUnityPlugin)this).Config.Bind<int>("Bounty Settings", "Rarity per hour", 50, " Chances to spawn a bounty every hour if one has not spawned yet, , the number is used like a percentage, the higher it is the higher the chances!");
			ConfigEntry<int> timeBetweenRetryingBountiesEntry = ((BaseUnityPlugin)this).Config.Bind<int>("Bounty Settings", "Retry per failed bounty", 2, " How many hours should it wait before retrying to spawn a bounty that failed the rarity check, In-game hours.");
			ConfigEntry<int> timeBetweenSuccesfulBountiesEntry = ((BaseUnityPlugin)this).Config.Bind<int>("Bounty Settings", "Time between next bounty", 4, " How many hours should it wait before spawning another bounty if possible, In-game hours.");
			ConfigEntry<int> bountiesPerRoundEntry = ((BaseUnityPlugin)this).Config.Bind<int>("Bounty Settings", "Bounties per round", 2, " How many bounties can spawn per round if they pass the rarity checks");
			ConfigEntry<int> spawnAfterHourEntry = ((BaseUnityPlugin)this).Config.Bind<int>("Bounty Settings", "Spawn after specific hour", 11, " Start spawning bounties after a specific hour, 0 = it will try and spawn from that start of the round, this uses a 24 hour clock.");
			ConfigEntry<int> rewardMultiplierEntry = ((BaseUnityPlugin)this).Config.Bind<int>("Bounty Settings", "Reward Multiplier", 4, " This value determines the end reward value for a bounty kill, (Enemy Health * Base Reward) * Reward Multiplier = Credit Reward");
			ConfigEntry<int> baseKillRewardMultiplierEntry = ((BaseUnityPlugin)this).Config.Bind<int>("KillThemAll", "Base Reward Multiplier", 4, " This value determines the end reward value for a kill, Enemy Health * Base Reward Multiplier = Credit Reward");
			BountyManager.Instance.chanceToSpawnPerRound = chanceToSpawnPerRoundEntry.Value;
			BountyManager.Instance.chanceToSpawnPerHour = chanceToSpawnPerHourEntry.Value;
			BountyManager.Instance.timeBetweenRetryingBounties = timeBetweenRetryingBountiesEntry.Value;
			BountyManager.Instance.timeBetweenSuccesfulBounties = timeBetweenSuccesfulBountiesEntry.Value;
			BountyManager.Instance.bountiesPerRound = bountiesPerRoundEntry.Value;
			BountyManager.Instance.spawnAfterHour = spawnAfterHourEntry.Value;
			BountyManager.Instance.rewardMultiplier = rewardMultiplierEntry.Value;
			KillableEnemyManager.Instance.baseKillRewardMultiplier = baseKillRewardMultiplierEntry.Value;
			chanceToSpawnPerRoundEntry.SettingChanged += delegate
			{
				BountyManager.Instance.chanceToSpawnPerRound = chanceToSpawnPerRoundEntry.Value;
				Utils.DebugLog("BM: chanceToSpawnPerRound to: " + chanceToSpawnPerRoundEntry.Value);
			};
			chanceToSpawnPerHourEntry.SettingChanged += delegate
			{
				BountyManager.Instance.chanceToSpawnPerHour = chanceToSpawnPerHourEntry.Value;
				Utils.DebugLog("BM: chanceToSpawnPerHourEntry to: " + chanceToSpawnPerHourEntry.Value);
			};
			timeBetweenRetryingBountiesEntry.SettingChanged += delegate
			{
				BountyManager.Instance.timeBetweenRetryingBounties = timeBetweenRetryingBountiesEntry.Value;
				Utils.DebugLog("BM: timeBetweenRetryingBountiesEntry to: " + timeBetweenRetryingBountiesEntry.Value);
			};
			timeBetweenSuccesfulBountiesEntry.SettingChanged += delegate
			{
				BountyManager.Instance.timeBetweenSuccesfulBounties = timeBetweenSuccesfulBountiesEntry.Value;
				Utils.DebugLog("BM: timeBetweenSuccesfulBountiesEntry to: " + timeBetweenSuccesfulBountiesEntry.Value);
			};
			bountiesPerRoundEntry.SettingChanged += delegate
			{
				BountyManager.Instance.bountiesPerRound = bountiesPerRoundEntry.Value;
				Utils.DebugLog("BM: bountiesPerRoundEntry to: " + bountiesPerRoundEntry.Value);
			};
			spawnAfterHourEntry.SettingChanged += delegate
			{
				BountyManager.Instance.spawnAfterHour = spawnAfterHourEntry.Value;
				Utils.DebugLog("BM: spawnAfterHourEntry to: " + spawnAfterHourEntry.Value);
			};
			rewardMultiplierEntry.SettingChanged += delegate
			{
				BountyManager.Instance.rewardMultiplier = rewardMultiplierEntry.Value;
				Utils.DebugLog("BM: rewardMultiplierEntry to: " + rewardMultiplierEntry.Value);
			};
			baseKillRewardMultiplierEntry.SettingChanged += delegate
			{
				KillableEnemyManager.Instance.baseKillRewardMultiplier = baseKillRewardMultiplierEntry.Value;
			};
		}

		private void LoadAssetBundles()
		{
			string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			hitMarkAsset = AssetBundle.LoadFromFile(Path.Combine(directoryName, "hitmarkassetbundle"));
			if ((Object)(object)hitMarkAsset == (Object)null)
			{
				Utils.DebugLog("ERROR: Failed to load hitMarkAsset asset bundles");
				return;
			}
			KillableEnemyManager.Instance.hitmarkHUD = hitMarkAsset.LoadAsset<GameObject>("HitmarkImg");
			if (Object.op_Implicit((Object)(object)KillableEnemyManager.Instance.hitmarkHUD))
			{
				Utils.DebugLog("Successfully found object in assetbundle ( hitmark HUD obj) " + ((Object)KillableEnemyManager.Instance.hitmarkHUD).name);
			}
			else
			{
				Utils.DebugLog("ERROR: Not found object in assetbundle ( hitmark HUD obj)");
			}
			hitMarkSfxAsset = AssetBundle.LoadFromFile(Path.Combine(directoryName, "hitmarksfxassetbundle"));
			if ((Object)(object)hitMarkSfxAsset == (Object)null)
			{
				Utils.DebugLog("ERROR: Failed to load hit mark sfx asset bundles");
				return;
			}
			KillableEnemyManager.Instance.hitmarkSfx = new List<AudioClip>();
			KillableEnemyManager.Instance.hitmarkSfx = hitMarkSfxAsset.LoadAllAssets<AudioClip>().ToList();
			if (Object.op_Implicit((Object)(object)KillableEnemyManager.Instance.hitmarkSfx[0]))
			{
				Utils.DebugLog("Successfully found object in assetbundle ( sfx hitmark )");
			}
			else
			{
				Utils.DebugLog("ERROR: Not found object in assetbundle ( sfx hitmark )");
			}
			vfxBundle = AssetBundle.LoadFromFile(Path.Combine(directoryName, "vfxbundle.assets"));
			if ((Object)(object)vfxBundle == (Object)null)
			{
				Utils.DebugLog("ERROR: Failed to load enemyExplosionEffect asset bundles");
				return;
			}
			KillableEnemyManager.Instance.enemyDeathEffect = vfxBundle.LoadAsset<GameObject>("Assets/LethalCompany/Mods/VFX/Blood.prefab");
			KillableEnemyManager.Instance.tombDropEffect = vfxBundle.LoadAsset<GameObject>("Assets/LethalCompany/Mods/VFX/Smoke.prefab");
			KillableEnemyManager.Instance.enemyBountyEffect = vfxBundle.LoadAsset<GameObject>("Assets/LethalCompany/Mods/VFX/BountyAura.prefab");
			if (Object.op_Implicit((Object)(object)KillableEnemyManager.Instance.enemyDeathEffect) && Object.op_Implicit((Object)(object)KillableEnemyManager.Instance.tombDropEffect) && Object.op_Implicit((Object)(object)KillableEnemyManager.Instance.enemyBountyEffect))
			{
				Utils.DebugLog("Successfully found objects in vfx bundle");
			}
			else
			{
				Utils.DebugLog("ERROR: Not found object in vfx bundle");
			}
			playerReactionsSfxAsset = AssetBundle.LoadFromFile(Path.Combine(directoryName, "reactionsfxassetbundle"));
			if ((Object)(object)playerReactionsSfxAsset == (Object)null)
			{
				Utils.DebugLog("ERROR: Failed to load hit mark sfx asset bundles");
				return;
			}
			KillableEnemyManager.Instance.playerReactionSfx = new List<AudioClip>();
			KillableEnemyManager.Instance.playerReactionSfx = playerReactionsSfxAsset.LoadAllAssets<AudioClip>().ToList();
			if (Object.op_Implicit((Object)(object)KillableEnemyManager.Instance.playerReactionSfx[0]))
			{
				Utils.DebugLog("Successfully found object in assetbundle ( playerReactionsSfxAsset )");
			}
			else
			{
				Utils.DebugLog("ERROR: Not found object in assetbundle ( playerReactionsSfxAsset )");
			}
			notificationAsset = AssetBundle.LoadFromFile(Path.Combine(directoryName, "notificationassetbundle"));
			if ((Object)(object)notificationAsset == (Object)null)
			{
				Utils.DebugLog("ERROR: Failed to load notificationAsset bundles");
				return;
			}
			UIManager.Instance.notificationElementObj = notificationAsset.LoadAllAssets<GameObject>().ToList();
			if (Object.op_Implicit((Object)(object)UIManager.Instance.notificationElementObj[0]))
			{
				Utils.DebugLog("Successfully found object in assetbundle ( notification element obj) " + ((Object)UIManager.Instance.notificationElementObj[0]).name);
			}
			else
			{
				Utils.DebugLog("ERROR: Not found object in assetbundle ( notification element obj)");
			}
			if (Object.op_Implicit((Object)(object)UIManager.Instance.notificationElementObj[1]))
			{
				Utils.DebugLog("Successfully found object in assetbundle ( notification top element obj) " + ((Object)UIManager.Instance.notificationElementObj[1]).name);
			}
			else
			{
				Utils.DebugLog("ERROR: Not found object in assetbundle ( notification top element obj)");
			}
			tombstoneAsset = AssetBundle.LoadFromFile(Path.Combine(directoryName, "tombstoneassetbundle.assets"));
			if ((Object)(object)tombstoneAsset == (Object)null)
			{
				Utils.DebugLog("ERROR: Failed to load tombstoneAsset bundles");
				return;
			}
			Item val = tombstoneAsset.LoadAsset<Item>("Assets/LethalCompany/Mods/Scraps/Tombstones/Tombstones.asset");
			if (Object.op_Implicit((Object)(object)val))
			{
				Utils.DebugLog("Successfully found object in assetbundle ( tombScrapAsset ) ");
				if (!Object.op_Implicit((Object)(object)val.spawnPrefab.GetComponent<TombScrap>()))
				{
					((Behaviour)val.spawnPrefab.AddComponent<TombScrap>()).enabled = false;
					((GrabbableObject)val.spawnPrefab.GetComponent<TombScrap>()).itemProperties = val;
					((GrabbableObject)val.spawnPrefab.GetComponent<TombScrap>()).itemProperties.saveItemVariable = true;
					Utils.DebugLog(" TombScrap added to prefab ");
				}
				else
				{
					Utils.DebugLog(" TombScrap already on prefab ");
					Utils.DebugLog("TombScrap is enabled: " + ((Behaviour)val.spawnPrefab.GetComponent<TombScrap>()).enabled);
				}
			}
			else
			{
				Utils.DebugLog("ERROR: Not found object in assetbundle ( tombScrapAsset )");
			}
			NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
			Items.RegisterScrap(val, 0, (LevelTypes)(-1));
			Utilities.FixMixerGroups(val.spawnPrefab);
			KillableEnemyManager.Instance.enemyTomb = val;
			colliderTest = AssetBundle.LoadFromFile(Path.Combine(directoryName, "colidertest"));
			if ((Object)(object)colliderTest == (Object)null)
			{
				Utils.DebugLog("ERROR: Failed to load colidertest asset bundles");
				return;
			}
			KillableEnemyManager.Instance.colliderTest = colliderTest.LoadAsset<GameObject>("Cube");
			if (Object.op_Implicit((Object)(object)KillableEnemyManager.Instance.colliderTest))
			{
				Utils.DebugLog("Successfully found object in assetbundle( colliderTest cube )" + (object)KillableEnemyManager.Instance.colliderTest);
			}
			else
			{
				Utils.DebugLog("ERROR: Not found object in assetbundle ( colliderTest cube )");
			}
		}

		public void SaveTombScrapOnShip(string fileSave, int id, int meshIndex, int matIndex, string enemyName, string playerThatKilled)
		{
			if (isIdInJason(id))
			{
				Utils.DebugLog("Tomb with id: " + id + " already exists, skipping save!");
				return;
			}
			Tomb tomb = new Tomb(fileSave, id, meshIndex, matIndex, enemyName, playerThatKilled);
			string text = JsonConvert.SerializeObject((object)tomb, (Formatting)0);
			string value = TombSaveEntry.Value + ((TombSaveEntry.Value == "") ? text : ("|" + text));
			Utils.DebugLog("Saving tomb: " + id + ", json: " + text);
			TombSaveEntry.Value = value;
		}

		public Tomb GetTombById(int id, string fileSave)
		{
			if (TombSaveEntry.Value.StartsWith('|'))
			{
				TombSaveEntry.Value = TombSaveEntry.Value.Substring(1);
			}
			string[] array = TombSaveEntry.Value.Split('|');
			List<Tomb> list = new List<Tomb>();
			if (array.Length == 0)
			{
				return null;
			}
			string[] array2 = array;
			foreach (string text in array2)
			{
				if (text == "")
				{
					continue;
				}
				Tomb tomb = JsonConvert.DeserializeObject<Tomb>(text);
				if (text.Length != 0)
				{
					if (tomb == null)
					{
						return null;
					}
					list.Add(tomb);
				}
			}
			if (list.Count > 0)
			{
				list.RemoveAll((Tomb t) => t.fileSave != fileSave);
				Tomb tomb2 = list.FirstOrDefault((Tomb t) => t.id == id);
				if (tomb2 != null)
				{
					string oldValue = JsonConvert.SerializeObject((object)tomb2);
					TombSaveEntry.Value = TombSaveEntry.Value.Replace(oldValue, "");
					TombSaveEntry.Value = TombSaveEntry.Value.Replace("||", "|");
				}
				return tomb2;
			}
			Utils.DebugLog("Zero saved tombs found, returning null!");
			return null;
		}

		public void OnDeleteGameSave(string fileSave)
		{
			if (TombSaveEntry.Value.StartsWith('|'))
			{
				TombSaveEntry.Value = TombSaveEntry.Value.Substring(1);
			}
			string[] array = TombSaveEntry.Value.Split('|');
			if (array.Length == 0)
			{
				return;
			}
			List<Tomb> list = new List<Tomb>();
			string[] array2 = array;
			foreach (string text in array2)
			{
				if (text.Length != 0)
				{
					Tomb tomb = JsonConvert.DeserializeObject<Tomb>(text);
					if (tomb == null)
					{
						Utils.DebugLog("Can not deserialize object to save tomb object!");
						return;
					}
					list.Add(tomb);
				}
			}
			if (list.Count > 0)
			{
				list.RemoveAll((Tomb t) => t.fileSave != fileSave);
				{
					foreach (Tomb item in list)
					{
						string oldValue = JsonConvert.SerializeObject((object)item);
						TombSaveEntry.Value = TombSaveEntry.Value.Replace(oldValue, "");
						TombSaveEntry.Value = TombSaveEntry.Value.Replace("||", "|");
						Utils.DebugLog("Removed Tomb from: " + fileSave + ", Tomb id: " + item.id);
					}
					return;
				}
			}
			Utils.DebugLog("No tombs saved to delete on: " + fileSave);
		}

		public void RemoveSavedTombThatDontExist(string fileSave)
		{
			if (TombSaveEntry.Value.StartsWith('|'))
			{
				TombSaveEntry.Value = TombSaveEntry.Value.Substring(1);
			}
			string[] array = TombSaveEntry.Value.Split('|');
			if (array.Length == 0)
			{
				return;
			}
			List<TombScrap> list = Object.FindObjectsByType<TombScrap>((FindObjectsInactive)0, (FindObjectsSortMode)0).ToList();
			List<Tomb> list2 = new List<Tomb>();
			string[] array2 = array;
			foreach (string text in array2)
			{
				if (text == "")
				{
					continue;
				}
				bool flag = false;
				Tomb tomb = JsonConvert.DeserializeObject<Tomb>(text);
				if (tomb == null)
				{
					return;
				}
				foreach (TombScrap item in list)
				{
					if (tomb.id == item.id)
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					list2.Add(tomb);
				}
			}
			if (list2.Count <= 0)
			{
				return;
			}
			list2.RemoveAll((Tomb t) => t.fileSave != fileSave);
			foreach (Tomb item2 in list2)
			{
				string oldValue = JsonConvert.SerializeObject((object)item2);
				TombSaveEntry.Value = TombSaveEntry.Value.Replace(oldValue, "");
				TombSaveEntry.Value = TombSaveEntry.Value.Replace("||", "|");
				Utils.DebugLog("Removed (NULL)Tomb from: " + fileSave + ", Tomb id: " + item2.id);
			}
		}

		public bool isIdInJason(int id)
		{
			return TombSaveEntry.Value.Contains(id.ToString());
		}
	}
	public class Tomb
	{
		public string fileSave;

		public int id;

		public int meshIndex;

		public int matIndex;

		public string enemyName;

		public string playerThatKilled;

		public Tomb(string fileSave, int id, int meshIndex, int matIndex, string enemyName, string playerThatKilled)
		{
			this.fileSave = fileSave;
			this.id = id;
			this.meshIndex = meshIndex;
			this.matIndex = matIndex;
			this.enemyName = enemyName;
			this.playerThatKilled = playerThatKilled;
		}
	}
}
namespace KillThemAll.Network
{
	public class KillableEnemyEmitter : NetworkBehaviour
	{
		[ServerRpc(RequireOwnership = false)]
		public void DoDamageServerRpc(ulong enemyObjectId, ulong playerObjectId, int damage)
		{
			DoDamageClientRpc(enemyObjectId, playerObjectId, damage);
		}

		[ServerRpc(RequireOwnership = false)]
		public void DoKillServerRpc(ulong objectId, ulong playerObjectId)
		{
			DoKillClientRpc(objectId, playerObjectId);
		}

		[ClientRpc]
		public void DoDamageClientRpc(ulong objectId, ulong playerObjectId, int damage)
		{
			KillableEnemyManager.Instance.OnEnemyHit(objectId, playerObjectId, damage);
		}

		[ClientRpc]
		public void DoKillClientRpc(ulong objectId, ulong playerObjectId)
		{
			KillableEnemyManager.Instance.OnEnemyDeath(objectId, playerObjectId);
		}
	}
	public class OnSpawnEnemiesEmitter : NetworkBehaviour
	{
		[ServerRpc(RequireOwnership = false)]
		public void AddObjectServerRpc(ulong enemyObjectId)
		{
			AddObjectClientRpc(enemyObjectId);
		}

		[ClientRpc]
		public void AddObjectClientRpc(ulong objectId)
		{
			SpawnEnemyManager.Instance.AddAuraToBounty(objectId);
		}
	}
	internal class TombScrapEmitter : NetworkBehaviour
	{
		[ServerRpc(RequireOwnership = false)]
		public void SpawnTombServerRpc(ulong enemyKilled_Id, ulong playerThatKilled_Id, ulong tombScrap_Id, int scrapValue, int mesh, int mat)
		{
			SpawnTombClientRpc(enemyKilled_Id, playerThatKilled_Id, tombScrap_Id, scrapValue, mesh, mat);
		}

		[ClientRpc]
		public void SpawnTombClientRpc(ulong enemyKilled_Id, ulong playerThatKilled_Id, ulong tombScrap_Id, int scrapValue, int mesh, int mat)
		{
			KillableEnemyManager.Instance.OnTombScrapSpawn(enemyKilled_Id, playerThatKilled_Id, tombScrap_Id, scrapValue, mesh, mat);
		}

		[ServerRpc]
		public void SendTombDataSaveServerRpc(ulong tombScrap_Id, string enemyKilled_Id, string playerKilled, int mesh, int mat)
		{
			SendTombDataSaveClientRpc(tombScrap_Id, enemyKilled_Id, playerKilled, mesh, mat);
		}

		[ClientRpc]
		public void SendTombDataSaveClientRpc(ulong tombScrap_Id, string enemyKilled_Id, string playerKilled, int mesh, int mat)
		{
			Utils.GetScrapObject(tombScrap_Id).GetComponent<TombScrap>().LoadItemSaveDataOnJoin(enemyKilled_Id, playerKilled, mesh, mat);
		}
	}
	internal class UIEmitter : NetworkBehaviour
	{
		[ServerRpc(RequireOwnership = false)]
		public void DoNotificationOnKillServerRpc(string enemyName, string playerThatKilledName, int rewardForKill, bool isBounty, int secondsOnScreen)
		{
			DoNotificationOnKillClientRpc(enemyName, playerThatKilledName, rewardForKill, isBounty, secondsOnScreen);
		}

		[ServerRpc(RequireOwnership = false)]
		public void DoNotificationOnBountyServerRpc(string enemyName, int rewardForKill, int secondsOnScreen)
		{
			DoNotificationOnBountyClientRpc(enemyName, rewardForKill, secondsOnScreen);
		}

		[ClientRpc]
		public void DoNotificationOnKillClientRpc(string enemyName, string playerThatKilledName, int rewardForKill, bool isBounty, int secondsOnScreen)
		{
			UIManager.Instance.ShowEnemyKilledNotfication(enemyName, playerThatKilledName, rewardForKill, isBounty, secondsOnScreen);
		}

		[ClientRpc]
		public void DoNotificationOnBountyClientRpc(string enemyName, int rewardForKill, int secondsOnScreen)
		{
			UIManager.Instance.ShowEnemyBountyNotfication(enemyName, rewardForKill, secondsOnScreen);
		}
	}
}
namespace KillThemAll.Models
{
	public class KillableEnemy : MonoBehaviour
	{
		private int startingHealth = 0;

		private int currentHealth = 0;

		private int reward = 0;

		private bool bounty = false;

		private ulong networkObjectId;

		private EnemyAI enemyAI;

		private GameObject collisionAIObject;

		public EnemyAI EnemyAI
		{
			get
			{
				return enemyAI;
			}
			set
			{
				enemyAI = value;
			}
		}

		public GameObject CollisionAIObject
		{
			get
			{
				return collisionAIObject;
			}
			set
			{
				collisionAIObject = value;
			}
		}

		public ulong NetworkObjectId
		{
			get
			{
				return networkObjectId;
			}
			set
			{
				networkObjectId = value;
			}
		}

		public int CurrentHealth
		{
			get
			{
				return currentHealth;
			}
			set
			{
				currentHealth = value;
			}
		}

		public int StartingHealth
		{
			get
			{
				return startingHealth;
			}
			set
			{
				startingHealth = value;
			}
		}

		public int Reward
		{
			get
			{
				return reward;
			}
			set
			{
				reward = value;
			}
		}

		public bool isBounty
		{
			get
			{
				return bounty;
			}
			set
			{
				bounty = value;
			}
		}

		public void DoDamage(int amount, ulong playerThatKilled_Id)
		{
			if (currentHealth != 0)
			{
				currentHealth -= amount;
				if (currentHealth < 0)
				{
					currentHealth = 0;
				}
				if (currentHealth == 0 && (((NetworkBehaviour)enemyAI).IsHost || ((NetworkBehaviour)enemyAI).IsServer))
				{
					((Behaviour)((Component)enemyAI).gameObject.GetComponentInChildren<EnemyAICollisionDetect>()).enabled = false;
					Utils.DebugLog("KillableEnemy: DoDamage() Enemy died sending ServerRPC");
					KillableEnemyManager.Instance.OnEnemyDeathPrepareServerRPC(((NetworkBehaviour)enemyAI).NetworkObjectId, playerThatKilled_Id);
				}
				else if (((NetworkBehaviour)enemyAI).IsHost || ((NetworkBehaviour)enemyAI).IsServer)
				{
					Utils.DebugLog("KillableEnemy: DoDamage() Enemy took damge sending ServerRPC");
					((Component)StartOfRound.Instance.allPlayerScripts[0]).gameObject.GetComponent<KillableEnemyEmitter>().DoDamageServerRpc(((NetworkBehaviour)enemyAI).NetworkObjectId, playerThatKilled_Id, amount);
				}
			}
		}

		public void DespawnEnemy()
		{
			((MonoBehaviour)this).StartCoroutine(DespawnEnemyOvertime());
		}

		public IEnumerator DespawnEnemyOvertime()
		{
			yield return (object)new WaitForSeconds(0.4f);
			if (Object.op_Implicit((Object)(object)((NetworkBehaviour)enemyAI).NetworkObject))
			{
				Utils.DebugLog("Despawning network object: " + ((Object)this).name);
				((NetworkBehaviour)enemyAI).NetworkObject.Despawn(true);
			}
		}
	}
	public enum EnemyType
	{
		default_
	}
}
namespace KillThemAll.Managers
{
	internal class BountyManager
	{
		public struct EnemyKilled
		{
			public string name;

			public string killerName;

			public bool wasBounty;

			public int reward;
		}

		private const string modGUID = "KillThemAll.BManager";

		private static BountyManager _instance;

		public Terminal __terminal;

		public bool isRoundActive = false;

		public int chanceToSpawnPerRound = 100;

		public int chanceToSpawnPerHour = 100;

		public int timeBetweenRetryingBounties = 1;

		public int timeBetweenSuccesfulBounties = 3;

		public int bountiesPerRound = 1;

		public int spawnAfterHour = 12;

		public int rewardMultiplier = 16;

		public bool isHost = false;

		private int bountiesSpawnedThisRound = 0;

		private int retryAtThisHour = 0;

		private bool shouldSpawnThisRound = false;

		private bool checkedIfItShouldSpawn = false;

		public List<EnemyKilled> enemyKilledList = new List<EnemyKilled>();

		private bool once = false;

		public static BountyManager Instance => _instance ?? (_instance = new BountyManager());

		static BountyManager()
		{
		}

		public void ServerUpdateOnRoundStart()
		{
			if (!checkedIfItShouldSpawn)
			{
				if (CheckIfBountyShouldSpawnThisRound())
				{
					Utils.DebugLog("Bounty will spawn this round!");
				}
				else
				{
					Utils.DebugLog("Bounty will not spawn this round!");
				}
				checkedIfItShouldSpawn = true;
			}
			if (!shouldSpawnThisRound || retryAtThisHour >= 24 || bountiesPerRound == 0 || bountiesSpawnedThisRound >= bountiesPerRound || Utils.GetTimeOfRound() < spawnAfterHour)
			{
				return;
			}
			if (Utils.GetTimeOfRound() >= retryAtThisHour)
			{
				Utils.DebugLog("Its time to try again and its: " + Utils.GetTimeOfRound());
				once = false;
				int num = Random.Range(0, 100);
				Utils.DebugLog("Chance = " + num + ", need below" + chanceToSpawnPerHour);
				if (num > chanceToSpawnPerHour)
				{
					retryAtThisHour = Utils.GetTimeOfRound() + timeBetweenRetryingBounties;
					Utils.DebugLog("Didnt pass rarity check retrying bounty at: " + retryAtThisHour);
				}
				else if (bountiesSpawnedThisRound < bountiesPerRound)
				{
					bountiesSpawnedThisRound++;
					retryAtThisHour = Utils.GetTimeOfRound() + timeBetweenSuccesfulBounties;
					Utils.DebugLog("Bounty spawned | count: " + bountiesSpawnedThisRound);
					Utils.DebugLog("Next spawn try at: " + retryAtThisHour);
					OnSpawnBounty();
				}
			}
			else if (!once)
			{
				Utils.DebugLog("Need to wait till " + retryAtThisHour + ", and its: " + Utils.GetTimeOfRound());
				once = true;
			}
		}

		public void ServerUpdateOnRoundEnd()
		{
			once = false;
			checkedIfItShouldSpawn = false;
			shouldSpawnThisRound = false;
			bountiesSpawnedThisRound = 0;
			retryAtThisHour = 0;
			enemyKilledList.Clear();
			Utils.DebugLog("ServerUpdateOnRoundEnd: resetting values");
		}

		public bool CheckIfBountyShouldSpawnThisRound()
		{
			int num = Random.Range(0, 100);
			return shouldSpawnThisRound = num <= chanceToSpawnPerRound;
		}

		public void OnSpawnBounty()
		{
			int reward = 0;
			string enemyName = SpawnEnemyManager.Instance.SpawnRandomEnemy(out reward);
			UIManager.Instance.PrepareOnBountyServerRPC_Notification(enemyName, reward);
		}

		public void SaveKilledEnemy(string name, string player, bool wasBounty, int reward)
		{
			EnemyKilled item = default(EnemyKilled);
			item.name = name;
			item.killerName = player;
			item.wasBounty = wasBounty;
			item.reward = reward;
			Utils.DebugLog("Added killed enemy: " + item.name + " that died by: " + item.killerName + " for " + item.reward + (item.wasBounty ? " and was a bounty" : " and was not a bounty"));
			enemyKilledList.Add(item);
		}

		private void GiveCreditsToCrew(int reward)
		{
			if (!Object.op_Implicit((Object)(object)__terminal))
			{
				Utils.DebugLog("ERROR: Reference to terminal is null! Cant give credits");
				return;
			}
			Terminal _terminal = __terminal;
			_terminal.groupCredits += reward;
			__terminal.SyncGroupCreditsServerRpc(__terminal.groupCredits, __terminal.numberOfItemsInDropship);
		}
	}
	internal class KillableEnemyManager
	{
		private const string modGUID = "KillThemAll.KEManager";

		private static KillableEnemyManager _instance;

		public Dictionary<string, int> enemyHealthDictionary = new Dictionary<string, int>();

		public PlayerControllerB localPlayer;

		public bool debugLog = true;

		public bool showHitmarkVfx = true;

		public bool playHitmarkSfx = true;

		public bool showEnemyDeathEffect = true;

		public bool playerReactionAKSfx = true;

		public int baseKillRewardMultiplier = 10;

		public Animator playerHitmarkAnimator;

		private AudioSource playerAudioSource;

		public GameObject hitmarkHUD;

		public List<AudioClip> hitmarkSfx;

		public GameObject enemyDeathEffect;

		public GameObject tombDropEffect;

		public GameObject enemyBountyEffect;

		public List<AudioClip> playerReactionSfx;

		public Item enemyTomb;

		public GameObject colliderTest;

		private GameObject hitMarkerHud;

		public static KillableEnemyManager Instance => _instance ?? (_instance = new KillableEnemyManager());

		public Dictionary<ulong, EnemyAI> NetworkObjectIDToEnemyAI { get; } = new Dictionary<ulong, EnemyAI>();


		public Dictionary<EnemyAI, ulong> EnemyAIToNetworkObjectID { get; } = new Dictionary<EnemyAI, ulong>();


		static KillableEnemyManager()
		{
		}

		public void SetEnemyHealth(string enemyName, int newHealth)
		{
			if (enemyHealthDictionary.ContainsKey(enemyName))
			{
				enemyHealthDictionary[enemyName] = newHealth;
			}
		}

		public void SetupHitmarkerHUD(PlayerControllerB __instance)
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)__instance) || Object.op_Implicit((Object)(object)hitMarkerHud))
			{
				return;
			}
			localPlayer = __instance;
			Transform transform = GameObject.Find("Systems/UI/Canvas/PlayerCursor/Cursor").transform;
			if (!Object.op_Implicit((Object)(object)transform))
			{
				Utils.DebugLog("ERROR: SetupHitmarkerHUD() => parentCanvas = NULL");
				return;
			}
			hitMarkerHud = Object.Instantiate<GameObject>(hitmarkHUD, transform.parent, false);
			if (!Object.op_Implicit((Object)(object)hitMarkerHud))
			{
				Utils.DebugLog("ERROR: SetupHitmarkerHUD() => hitMarkerHudObject = NULL");
				return;
			}
			hitMarkerHud.SetActive(true);
			hitMarkerHud.transform.localScale = new Vector3(1f, 1f, 1f);
			playerHitmarkAnimator = hitMarkerHud.GetComponent<Animator>();
			if (!Object.op_Implicit((Object)(object)playerHitmarkAnimator))
			{
				Utils.DebugLog("ERROR: SetupHitmarkerHUD() => playerHitmarkAnimator = NULL");
				return;
			}
			playerHitmarkAnimator.speed = 1.9f;
			Utils.DebugLog("HUD Instantiated for local player: " + localPlayer.playerUsername);
		}

		public KillableEnemy AssignKillableClassToEnemy(EnemyAI __instance)
		{
			if (Object.op_Implicit((Object)(object)((Component)__instance).gameObject.GetComponent<KillableEnemy>()))
			{
				return ((Component)__instance).gameObject.GetComponent<KillableEnemy>();
			}
			int num = 10000;
			string name = ((Object)__instance).name;
			name = name.Replace("Enemy", "");
			name = name.Replace("(Clone)", "");
			name = name.Replace(".prefab", "");
			double num2 = 0.0;
			string text = "null";
			if (enemyHealthDictionary.Count == 0)
			{
				Utils.DebugLog("enemyHealthDictionary is empty");
			}
			foreach (KeyValuePair<string, int> item in enemyHealthDictionary)
			{
				double num3 = Utils.SimilarityRatio(name, item.Key);
				if (num3 > num2)
				{
					num2 = num3;
					if (item.Value > 0)
					{
						num = item.Value;
					}
					text = item.Key;
					Utils.DebugLog("Comparing name: " + name + ", against: " + item.Key + " | Similarity = " + num3);
				}
			}
			if (text == "null")
			{
				Utils.DebugLog("Not found similar name for: " + name + "!!!");
				return null;
			}
			KillableEnemy killableEnemy = InitializeKillableData(__instance);
			killableEnemy.StartingHealth = num;
			killableEnemy.CurrentHealth = num;
			killableEnemy.Reward = num * baseKillRewardMultiplier;
			killableEnemy.EnemyAI = __instance;
			killableEnemy.NetworkObjectId = ((NetworkBehaviour)__instance).NetworkObjectId;
			killableEnemy.CollisionAIObject = ((Component)((Component)((Component)__instance).gameObject.transform.root).GetComponentInChildren<EnemyAICollisionDetect>()).gameObject;
			bool flag = false;
			MeshRenderer val = null;
			bool flag2 = false;
			Utils.DebugLog("Registering enemy: " + ((Object)((Component)__instance).gameObject).name + ", new HP: " + num);
			return killableEnemy;
		}

		private KillableEnemy InitializeKillableData(EnemyAI enemyAI)
		{
			EnemyAIToNetworkObjectID[enemyAI] = ((NetworkBehaviour)enemyAI).NetworkObjectId;
			NetworkObjectIDToEnemyAI[((NetworkBehaviour)enemyAI).NetworkObjectId] = enemyAI;
			return ((Component)enemyAI).gameObject.AddComponent<KillableEnemy>();
		}

		public void OnEnemyDeathPrepareServerRPC(ulong enemyHit_Id, ulong playerThatKilled_Id)
		{
			EnemyAI enemyAIClassFromNetID = Utils.GetEnemyAIClassFromNetID(enemyHit_Id);
			KillableEnemy component = ((Component)enemyAIClassFromNetID).GetComponent<KillableEnemy>();
			OnServerEnemyDropItem(enemyAIClassFromNetID);
			BountyManager.Instance.SaveKilledEnemy(Utils.GetEnemyName(enemyAIClassFromNetID), Utils.GetPlayerClassFromNetID(playerThatKilled_Id).playerUsername, component.isBounty, component.Reward);
			UIManager.Instance.PrepareOnKillServerRPC_Notification(((NetworkBehaviour)enemyAIClassFromNetID).NetworkObjectId, playerThatKilled_Id);
			((Component)StartOfRound.Instance.allPlayerScripts[0]).gameObject.GetComponent<KillableEnemyEmitter>().DoKillServerRpc(((NetworkBehaviour)enemyAIClassFromNetID).NetworkObjectId, playerThatKilled_Id);
		}

		private void OnServerEnemyDropItem(EnemyAI enemyAI)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: 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_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: 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)
			Vector3 val = ((Component)enemyAI).transform.position + new Vector3(0.2f, 5f, 0.2f);
			if (Object.op_Implicit((Object)(object)((Component)enemyAI).gameObject.GetComponent<NutcrackerEnemyAI>()))
			{
				Object.Instantiate<GameObject>(((Component)enemyAI).gameObject.GetComponent<NutcrackerEnemyAI>().gunPrefab, val, Quaternion.identity, RoundManager.Instance.spawnedScrapContainer).GetComponent<NetworkObject>().Spawn(false);
				val.x += 0.5f;
				val.z += 0.2f;
				Object.Instantiate<GameObject>(((Component)enemyAI).gameObject.GetComponent<NutcrackerEnemyAI>().shotgunShellPrefab, val, Quaternion.identity, RoundManager.Instance.spawnedScrapContainer).GetComponent<NetworkObject>().Spawn(false);
				val.z += 0.2f;
				Object.Instantiate<GameObject>(((Component)enemyAI).gameObject.GetComponent<NutcrackerEnemyAI>().shotgunShellPrefab, val, Quaternion.identity, RoundManager.Instance.spawnedScrapContainer).GetComponent<NetworkObject>().Spawn(false);
				Utils.DebugLog("Nutcracker Died: Spawned Shotgun and Ammo!");
			}
			if (Object.op_Implicit((Object)(object)((Component)enemyAI).gameObject.GetComponent<ButlerEnemyAI>()))
			{
				val.x += 0.5f;
				val.z += 0.5f;
				Object.Instantiate<GameObject>(((Component)enemyAI).gameObject.GetComponent<ButlerEnemyAI>().knifePrefab, val, Quaternion.identity, RoundManager.Instance.spawnedScrapContainer).GetComponent<NetworkObject>().Spawn(false);
				Utils.DebugLog("Butler Died: Spawned Knife!");
			}
		}

		public void OnEnemyHitPrepareServerRPC(ulong enemyHit_Id, ulong playerThatHit_Id, int damageHit)
		{
			EnemyAI enemyAIClassFromNetID = Utils.GetEnemyAIClassFromNetID(enemyHit_Id);
			if (Object.op_Implicit((Object)(object)enemyAIClassFromNetID))
			{
				KillableEnemy component = ((Component)enemyAIClassFromNetID).gameObject.GetComponent<KillableEnemy>();
				if ((Object)(object)component != (Object)null)
				{
					((Component)enemyAIClassFromNetID).gameObject.GetComponent<KillableEnemy>().DoDamage(damageHit, playerThatHit_Id);
				}
			}
		}

		public void OnEnemyHit(ulong enemyHit_Id, ulong playerThatHit_Id, int damageHit)
		{
			EnemyAI enemyAIClassFromNetID = Utils.GetEnemyAIClassFromNetID(enemyHit_Id);
			PlayerControllerB playerClassFromNetID = Utils.GetPlayerClassFromNetID(playerThatHit_Id);
			if (!Object.op_Implicit((Object)(object)enemyAIClassFromNetID))
			{
				Utils.DebugLog("ERROR: OnEnemyHit() => enemyAI = NULL");
				return;
			}
			if (!Object.op_Implicit((Object)(object)playerClassFromNetID))
			{
				Utils.DebugLog("ERROR: OnEnemyHit() => playerThatHit = NULL");
				return;
			}
			Utils.DebugLog("OnEnemyHit: " + ((Object)enemyAIClassFromNetID).name + " hit for " + damageHit + " damage! by: " + playerClassFromNetID.playerUsername);
		}

		public void OnEnemyDeath(ulong enemyKilled_Id, ulong playerThatKilled_Id)
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			EnemyAI enemyAIClassFromNetID = Utils.GetEnemyAIClassFromNetID(enemyKilled_Id);
			PlayerControllerB playerClassFromNetID = Utils.GetPlayerClassFromNetID(playerThatKilled_Id);
			if (!Object.op_Implicit((Object)(object)enemyAIClassFromNetID))
			{
				Utils.DebugLog("ERROR: OnEnemyDeath() => enemyAI = NULL");
				return;
			}
			if (!Object.op_Implicit((Object)(object)playerClassFromNetID))
			{
				Utils.DebugLog("ERROR: OnEnemyDeath() => playerThatKilled = NULL");
				return;
			}
			enemyAIClassFromNetID.KillEnemy(false);
			if (Object.op_Implicit((Object)(object)enemyAIClassFromNetID.creatureSFX))
			{
				enemyAIClassFromNetID.creatureSFX.Stop();
			}
			if (Object.op_Implicit((Object)(object)enemyAIClassFromNetID.creatureVoice))
			{
				enemyAIClassFromNetID.creatureVoice.Stop();
			}
			if (showEnemyDeathEffect)
			{
				Vector3 val = default(Vector3);
				((Vector3)(ref val))..ctor(((Component)enemyAIClassFromNetID).transform.position.x, ((Component)enemyAIClassFromNetID).transform.position.y + 2f, ((Component)enemyAIClassFromNetID).transform.position.z);
				GameObject val2 = Object.Instantiate<GameObject>(enemyDeathEffect, val, enemyDeathEffect.transform.rotation);
				val2.transform.localScale = val2.transform.localScale * 0.75f;
				val2.AddComponent<VfxDespawn>();
			}
			Utils.DebugLog("OnEnemyDeath: " + ((Object)enemyAIClassFromNetID).name + " Killed by " + playerClassFromNetID.playerUsername);
			PlayReactionAfterKillLocal(playerClassFromNetID);
			if (Utils.isHost)
			{
				KillableEnemy component = ((Component)enemyAIClassFromNetID).GetComponent<KillableEnemy>();
				Vector3 pos = default(Vector3);
				((Vector3)(ref pos))..ctor(((Component)enemyAIClassFromNetID).transform.position.x, ((Component)enemyAIClassFromNetID).transform.position.y + 2f, ((Component)enemyAIClassFromNetID).transform.position.z);
				Vector3 val3 = ((Component)playerClassFromNetID).transform.position - ((Component)enemyAIClassFromNetID).transform.position;
				val3.y = 0f;
				Quaternion rot = Quaternion.LookRotation(val3);
				ServerPrepareTombScrapSpawn(enemyKilled_Id, playerThatKilled_Id, component.Reward, pos, rot);
				component.DespawnEnemy();
			}
			((Component)enemyAIClassFromNetID).transform.position = new Vector3(((Component)enemyAIClassFromNetID).transform.position.x, -10000f, ((Component)enemyAIClassFromNetID).transform.position.z);
			Utils.DebugLog("Moved enemy more than 6feet under");
		}

		public void ServerPrepareTombScrapSpawn(ulong enemyKilled_Id, ulong playerThatKilled_Id, int scrapValue, Vector3 pos, Quaternion rot)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			Utilities.FixMixerGroups(enemyTomb.spawnPrefab);
			GameObject val = Object.Instantiate<GameObject>(enemyTomb.spawnPrefab, pos, rot);
			int mesh = Random.Range(0, 3);
			int mat = Random.Range(0, 3);
			val.GetComponent<NetworkObject>().Spawn(false);
			Utils.DebugLog("KEM: ServerPrepareTombScrapSpawn() Sending Server RPC");
			((Component)StartOfRound.Instance.allPlayerScripts[0]).gameObject.GetComponent<TombScrapEmitter>().SpawnTombServerRpc(enemyKilled_Id, playerThatKilled_Id, val.GetComponent<NetworkObject>().NetworkObjectId, scrapValue, mesh, mat);
		}

		public void OnTombScrapSpawn(ulong enemyKilled_Id, ulong playerThatKilled_Id, ulong tombScrap_Id, int scrapValue, int mesh, int mat)
		{
			PlayerControllerB playerClassFromNetID = Utils.GetPlayerClassFromNetID(playerThatKilled_Id);
			GameObject scrapObject = Utils.GetScrapObject(tombScrap_Id);
			if (!Object.op_Implicit((Object)(object)scrapObject))
			{
				Utils.DebugLog("tombObj not found in spawned objects list");
			}
			if (!Object.op_Implicit((Object)(object)scrapObject.GetComponent<TombScrap>()))
			{
				Utils.DebugLog("TombScrap not found on: " + ((Object)scrapObject).name);
			}
			else
			{
				TombScrap component = scrapObject.GetComponent<TombScrap>();
				component.scrapVal = scrapValue;
				component.enemyName = Utils.GetEnemyName(enemyKilled_Id);
				component.playerName = playerClassFromNetID.playerUsername;
				component.meshIndex = mesh;
				component.matIndex = mat;
				component.OnSpawnInit();
			}
			Utils.DebugLog("Tombstone Spawned! Killer: " + playerClassFromNetID.playerUsername + ", Enemy: " + Utils.GetEnemyName(enemyKilled_Id));
		}

		public void PlayHitmarkerLocal(PlayerControllerB playerController)
		{
			if (playHitmarkSfx)
			{
				if (!Object.op_Implicit((Object)(object)hitmarkSfx[0]))
				{
					Utils.DebugLog("ERROR: PlayHitmarkerLocal() => hitmarkSfx[0] = NULL");
					return;
				}
				if (!Object.op_Implicit((Object)(object)playerAudioSource))
				{
					if (!Object.op_Implicit((Object)(object)playerController.movementAudio))
					{
						Utils.DebugLog("ERROR: PlayHitmarkerLocal() => playerController.movementAudio = NULL");
						return;
					}
					playerAudioSource = playerController.movementAudio;
				}
				playerAudioSource.PlayOneShot(hitmarkSfx[0], 3f);
				Utils.DebugLog("Play Hitmark sound effect on local client");
			}
			if (showHitmarkVfx)
			{
				if (!Object.op_Implicit((Object)(object)playerHitmarkAnimator))
				{
					Utils.DebugLog("ERROR: PlayHitmarkerLocal() => playerHitmarkAnimator = NULL");
					return;
				}
				playerHitmarkAnimator.Play("HitmarkAnim", 0, 0f);
				Utils.DebugLog("Play Hitmark effect on local client");
			}
		}

		public void PlayReactionAfterKillLocal(PlayerControllerB playerController)
		{
			if (playerReactionAKSfx)
			{
				if (!Object.op_Implicit((Object)(object)playerController))
				{
					Utils.DebugLog("ERROR: PlayReactionAfterKillLocal() => playerController = NULL");
					return;
				}
				if (!Object.op_Implicit((Object)(object)playerReactionSfx[0]))
				{
					Utils.DebugLog("ERROR: PlayReactionAfterKillLocal() => playerReactionSfx[0] = NULL");
					return;
				}
				if (!Object.op_Implicit((Object)(object)playerController.movementAudio))
				{
					Utils.DebugLog("ERROR: PlayReactionAfterKillLocal() => playerController.movementAudio = NULL");
					return;
				}
				playerController.movementAudio.PlayOneShot(playerReactionSfx[0], 1f);
				Utils.DebugLog("Playing reaction for killing an enemy: " + playerController.playerUsername);
			}
		}
	}
	internal class SpawnEnemyManager
	{
		public struct Enemy
		{
			public string name;

			public GameObject prefab;

			public bool isOutside;
		}

		private const string modGUID = "KillThemAll.SManager";

		private static SpawnEnemyManager _instance;

		public static List<Enemy> listOfSpawnableEnemies;

		public static SpawnEnemyManager Instance => _instance ?? (_instance = new SpawnEnemyManager());

		static SpawnEnemyManager()
		{
			listOfSpawnableEnemies = new List<Enemy>();
		}

		public string SpawnRandomEnemy(out int reward)
		{
			Enemy enemy = listOfSpawnableEnemies[Random.Range(0, listOfSpawnableEnemies.Count)];
			reward = SpawnEnemy(enemy);
			return enemy.name;
		}

		private int SpawnEnemy(Enemy enemy)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			Vector3 zero = Vector3.zero;
			zero = ((!enemy.isOutside) ? RoundManager.Instance.allEnemyVents[Random.Range(0, RoundManager.Instance.allEnemyVents.Length)].floorNode.position : RoundManager.Instance.outsideAINodes[Random.Range(0, RoundManager.Instance.outsideAINodes.Length)].transform.position);
			if (!Object.op_Implicit((Object)(object)enemy.prefab))
			{
				Utils.DebugLog("enemy.prefab null");
			}
			GameObject val = Object.Instantiate<GameObject>(enemy.prefab, zero, Quaternion.identity);
			NetworkObject componentInChildren = val.GetComponentInChildren<NetworkObject>();
			componentInChildren.Spawn(true);
			if (!Object.op_Implicit((Object)(object)val.GetComponent<KillableEnemy>()))
			{
				if (Object.op_Implicit((Object)(object)val.GetComponent<EnemyAI>()))
				{
					Utils.DebugLog("ERROR: Cant find EnemyAI Class on " + ((Object)val).name);
				}
				EnemyAI component = val.GetComponent<EnemyAI>();
				if (!Object.op_Implicit((Object)(object)component))
				{
					Utils.DebugLog("ERROR: Cant find EnemyAI Class on " + ((Object)val).name);
					return 0;
				}
				KillableEnemy killableEnemy = KillableEnemyManager.Instance.AssignKillableClassToEnemy(component);
				killableEnemy.isBounty = true;
				killableEnemy.Reward = killableEnemy.StartingHealth * KillableEnemyManager.Instance.baseKillRewardMultiplier * BountyManager.Instance.rewardMultiplier;
				Utils.DebugLog("(had to attach KE class) spawned bounty: " + ((Object)val).name + ", reward: " + killableEnemy.Reward);
				((Component)StartOfRound.Instance.allPlayerScripts[0]).gameObject.GetComponent<OnSpawnEnemiesEmitter>().AddObjectServerRpc(componentInChildren.NetworkObjectId);
				return killableEnemy.Reward;
			}
			KillableEnemy component2 = val.GetComponent<KillableEnemy>();
			component2.isBounty = true;
			component2.Reward = component2.StartingHealth * KillableEnemyManager.Instance.baseKillRewardMultiplier * BountyManager.Instance.rewardMultiplier;
			Utils.DebugLog("(class already attached) spawned bounty: " + ((Object)val).name + ", reward: " + component2.Reward);
			((Component)StartOfRound.Instance.allPlayerScripts[0]).gameObject.GetComponent<OnSpawnEnemiesEmitter>().AddObjectServerRpc(componentInChildren.NetworkObjectId);
			return component2.Reward;
		}

		public void AddAuraToBounty(ulong enemy_Id)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			EnemyAI enemyAIClassFromNetID = Utils.GetEnemyAIClassFromNetID(enemy_Id);
			if (Object.op_Implicit((Object)(object)enemyAIClassFromNetID))
			{
				GameObject val = Object.Instantiate<GameObject>(KillableEnemyManager.Instance.enemyBountyEffect, Vector3.zero, Quaternion.identity);
				val.transform.SetParent(((Component)enemyAIClassFromNetID).transform, false);
				val.transform.localRotation = Quaternion.identity;
				val.transform.localPosition = Vector3.zero;
			}
			else
			{
				Utils.DebugLog("Could not find bounty enemy class to spawn aura!");
			}
		}
	}
	internal class UIManager
	{
		private const string modGUID = "KillThemAll.UIManager";

		private static UIManager _instance;

		public List<GameObject> notificationElementObj;

		private Transform topNotificationParent;

		private Transform sideNotificationParent;

		public static UIManager Instance => _instance ?? (_instance = new UIManager());

		static UIManager()
		{
		}

		public void PrepareOnKillServerRPC_Notification(ulong objectKilled_Id, ulong playerThatKilled_Id)
		{
			Utils.DebugLog("Preparing server rpc call for kill notification");
			KillableEnemy component = ((Component)GeneralExtensions.GetValueSafe<ulong, EnemyAI>(KillableEnemyManager.Instance.NetworkObjectIDToEnemyAI, objectKilled_Id)).gameObject.GetComponent<KillableEnemy>();
			string name = ((Object)((Component)component).gameObject).name;
			string playerUsername = Utils.GetPlayerClassFromNetID(playerThatKilled_Id).playerUsername;
			name = name.Replace("Enemy", "");
			name = name.Replace("(Clone)", "");
			name = name.Replace(".prefab", "");
			((Component)StartOfRound.Instance.allPlayerScripts[0]).GetComponent<UIEmitter>().DoNotificationOnKillServerRpc(name, playerUsername, component.Reward, component.isBounty, component.isBounty ? 6 : 4);
		}

		public void PrepareOnBountyServerRPC_Notification(string enemyName, int rewardAmount)
		{
			Utils.DebugLog("Preparing server rpc call for bounty notification");
			((Component)StartOfRound.Instance.allPlayerScripts[0]).GetComponent<UIEmitter>().DoNotificationOnBountyServerRpc(enemyName, rewardAmount, 8);
		}

		public void Initialise()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Expected O, but got Unknown
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)sideNotificationParent))
			{
				GameObject val = new GameObject("SideNotificationParent");
				val.transform.SetParent(GameObject.Find("Systems/UI/Canvas/IngamePlayerHUD/TopLeftCorner/Self").transform, false);
				VerticalLayoutGroup val2 = val.AddComponent<VerticalLayoutGroup>();
				((Component)val2).transform.localPosition = new Vector3(-30f, -75f, 0f);
				((Component)val2).transform.localScale = new Vector3(-0.2f, 0.2f, -0.2f);
				((HorizontalOrVerticalLayoutGroup)val2).spacing = 15f;
				((LayoutGroup)val2).childAlignment = (TextAnchor)4;
				((HorizontalOrVerticalLayoutGroup)val2).reverseArrangement = true;
				((HorizontalOrVerticalLayoutGroup)val2).childControlWidth = false;
				((HorizontalOrVerticalLayoutGroup)val2).childControlHeight = false;
				((HorizontalOrVerticalLayoutGroup)val2).childForceExpandHeight = false;
				((HorizontalOrVerticalLayoutGroup)val2).childForceExpandWidth = false;
				sideNotificationParent = val.transform;
				Utils.DebugLog("sideNotificationParent added " + ((Object)sideNotificationParent).name + ", its parent is " + ((Object)((Component)sideNotificationParent).transform.parent).name);
			}
			if (!Object.op_Implicit((Object)(object)topNotificationParent))
			{
				GameObject val3 = new GameObject("topNotificationParent");
				Transform parent = ((Component)HUDManager.Instance.Inventory.canvasGroup).transform.parent;
				val3.transform.SetParent(parent, false);
				VerticalLayoutGroup val4 = val3.AddComponent<VerticalLayoutGroup>();
				((Component)val4).transform.localPosition = new Vector3(0f, 150f, 0f);
				((Component)val4).transform.localScale = new Vector3(0.3f, 0.3f, 0.3f);
				((HorizontalOrVerticalLayoutGroup)val4).spacing = 15f;
				((LayoutGroup)val4).childAlignment = (TextAnchor)4;
				((HorizontalOrVerticalLayoutGroup)val4).reverseArrangement = true;
				((HorizontalOrVerticalLayoutGroup)val4).childControlWidth = false;
				((HorizontalOrVerticalLayoutGroup)val4).childControlHeight = false;
				((HorizontalOrVerticalLayoutGroup)val4).childForceExpandHeight = false;
				((HorizontalOrVerticalLayoutGroup)val4).childForceExpandWidth = false;
				topNotificationParent = val3.transform;
				Utils.DebugLog("topNotificationParent added " + ((Object)topNotificationParent).name + ", its parent is " + ((Object)((Component)topNotificationParent).transform.parent).name);
			}
		}

		public void ShowEnemyKilledNotfication(string enemyName, string playerThatKilledName, int rewardForKill, bool isBounty, int secondsOnScreen)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)sideNotificationParent))
			{
				Utils.DebugLog("ERROR: UIManager() => sideNotificationParent = NULL");
				return;
			}
			GameObject val = Object.Instantiate<GameObject>(notificationElementObj[0], sideNotificationParent, false);
			if (!Object.op_Implicit((Object)(object)val))
			{
				Utils.DebugLog("ERROR: UIManager() => notificationElement = NULL");
				return;
			}
			val.SetActive(true);
			val.transform.localPosition = new Vector3(0f, 0f, 0f);
			if (!isBounty)
			{
				((Component)val.transform.GetChild(0)).gameObject.SetActive(false);
				((Component)val.transform.GetChild(1)).GetComponent<TMP_Text>().fontSize = 50f;
				((Component)val.transform.GetChild(2)).GetComponent<TMP_Text>().fontSize = 50f;
				((Component)val.transform.GetChild(1)).GetComponent<TMP_Text>().text = playerThatKilledName + " killed " + enemyName;
				((Component)val.transform.GetChild(2)).GetComponent<TMP_Text>().text = "The Company values its tomb at " + rewardForKill;
				((Component)val.transform.GetChild(1)).gameObject.SetActive(true);
				((Component)val.transform.GetChild(2)).gameObject.SetActive(true);
			}
			else
			{
				((Component)val.transform.GetChild(0)).GetComponent<TMP_Text>().fontSize = 55f;
				((Component)val.transform.GetChild(1)).GetComponent<TMP_Text>().fontSize = 45f;
				((Component)val.transform.GetChild(2)).GetComponent<TMP_Text>().fontSize = 38f;
				((Component)val.transform.GetChild(0)).GetComponent<TMP_Text>().text = "BOUNTY " + enemyName.ToUpper() + " KILLED";
				((Component)val.transform.GetChild(1)).GetComponent<TMP_Text>().text = playerThatKilledName + " stompped it 6 feet down!";
				((Component)val.transform.GetChild(2)).GetComponent<TMP_Text>().text = "The Company values it at " + rewardForKill;
				((Component)val.transform.GetChild(0)).gameObject.SetActive(true);
				((Component)val.transform.GetChild(1)).gameObject.SetActive(true);
				((Component)val.transform.GetChild(2)).gameObject.SetActive(true);
			}
			Animator component = val.GetComponent<Animator>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				Utils.DebugLog("ERROR: UIManager() => notificationElementAnimator = NULL");
			}
			else
			{
				val.AddComponent<ElementDespawn>().StartTimer(secondsOnScreen, component);
			}
		}

		public void ShowEnemyBountyNotfication(string enemyName, int rewardForKill, int secondsOnScreen)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)topNotificationParent))
			{
				Utils.DebugLog("ERROR: UIManager() => topNotificationParent = NULL");
				return;
			}
			GameObject val = Object.Instantiate<GameObject>(notificationElementObj[1], topNotificationParent, false);
			if (!Object.op_Implicit((Object)(object)val))
			{
				Utils.DebugLog("ERROR: UIManager() => notificationElement = NULL");
				return;
			}
			val.SetActive(true);
			val.transform.localPosition = new Vector3(0f, 0f, 0f);
			((Component)val.transform.GetChild(0)).GetComponent<TMP_Text>().fontSize = 80f;
			((Component)val.transform.GetChild(1)).GetComponent<TMP_Text>().fontSize = 50f;
			((Component)val.transform.GetChild(2)).GetComponent<TMP_Text>().fontSize = 50f;
			((Component)val.transform.GetChild(0)).GetComponent<TMP_Text>().text = "bounty Has Awoken".ToUpper();
			((Component)val.transform.GetChild(1)).GetComponent<TMP_Text>().text = "Find and kill " + enemyName;
			((Component)val.transform.GetChild(2)).GetComponent<TMP_Text>().text = "The Company will reward with " + rewardForKill + " for its tomb!";
			((Component)val.transform.GetChild(0)).gameObject.SetActive(true);
			((Component)val.transform.GetChild(1)).gameObject.SetActive(true);
			((Component)val.transform.GetChild(2)).gameObject.SetActive(true);
			Animator component = val.GetComponent<Animator>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				Utils.DebugLog("ERROR: UIManager() => notificationElementAnimator = NULL");
			}
			else
			{
				val.AddComponent<ElementDespawn>().StartTimer(secondsOnScreen, component);
			}
		}
	}
}
namespace KillThemAll.Hooks
{
	internal class UnityHook
	{
		private const string modGUID = "KillThemAll.Unity";

		static UnityHook()
		{
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(NetworkManager), "DespawnObject")]
		private static void PrefixDespawn(NetworkSpawnManager __instance, NetworkObject networkObject, bool destroyObject)
		{
			if (Object.op_Implicit((Object)(object)networkObject))
			{
				EnemyAI component = ((Component)networkObject).GetComponent<EnemyAI>();
				if ((Object)(object)component != (Object)null)
				{
					KillableEnemyManager.Instance.EnemyAIToNetworkObjectID.Remove(component);
					KillableEnemyManager.Instance.NetworkObjectIDToEnemyAI.Remove(((NetworkBehaviour)component).NetworkObjectId);
					Utils.DebugLog("Removed " + ((Object)component).name + "'s network object");
				}
			}
		}
	}
	internal class VanillaHook
	{
		private const string modGUID = "KillThemAll.Vanilla";

		static VanillaHook()
		{
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		private static void GameNetworkManagerPostStart(GameNetworkManager __instance)
		{
			KillThemAll.instance.Initialise();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "SaveItemsInShip")]
		private static void SaveItemsInShipPost()
		{
			Utils.DebugLog("Items saved!------------------------");
			if (Utils.isHost)
			{
				KillThemAll.instance.RemoveSavedTombThatDontExist(GameNetworkManager.Instance.currentSaveFileName);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "OnClientConnect")]
		private static void OnClientConnectPostfix(ulong clientId)
		{
			if (!Utils.isHost)
			{
				return;
			}
			List<TombScrap> list = Object.FindObjectsByType<TombScrap>((FindObjectsInactive)0, (FindObjectsSortMode)0).ToList();
			foreach (TombScrap item in list)
			{
				ulong networkObjectId = ((Component)item).GetComponent<NetworkObject>().NetworkObjectId;
				((Component)StartOfRound.Instance.allPlayerScripts[0]).gameObject.GetComponent<TombScrapEmitter>().SendTombDataSaveServerRpc(networkObjectId, item.enemyName, item.playerName, item.meshIndex, item.matIndex);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(DeleteFileButton), "DeleteFile")]
		private static void PrefixDeleteFileButton()
		{
			int fileToDelete = Object.FindAnyObjectByType<DeleteFileButton>().fileToDelete;
			if (1 == 0)
			{
			}
			string text = fileToDelete switch
			{
				0 => "LCSaveFile1", 
				1 => "LCSaveFile2", 
				2 => "LCSaveFile3", 
				_ => "LCSaveFile1", 
			};
			if (1 == 0)
			{
			}
			string text2 = text;
			KillThemAll.instance.OnDeleteGameSave(text2);
			Utils.DebugLog("Delete saved = " + text2);
		}

		[HarmonyPatch(typeof(RoundManager), "Start")]
		[HarmonyPrefix]
		private static void GetHost()
		{
			Utils.isHost = ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost;
			Utils.DebugLog("RoundManager start=> Round Started");
		}

		[HarmonyPatch(typeof(RoundManager), "Update")]
		[HarmonyPrefix]
		private static void OnRoundManagerUpdate()
		{
			if (Object.op_Implicit((Object)(object)StartOfRound.Instance) && Utils.isHost && RoundManager.Instance.isSpawningEnemies && !StartOfRound.Instance.shipIsLeaving)
			{
				BountyManager.Instance.ServerUpdateOnRoundStart();
			}
		}

		[HarmonyPatch(typeof(RoundManager), "DespawnPropsAtEndOfRound")]
		[HarmonyPrefix]
		private static void OnRoundManagerEnd()
		{
			if (Object.op_Implicit((Object)(object)StartOfRound.Instance) && Utils.isHost)
			{
				BountyManager.Instance.ServerUpdateOnRoundEnd();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		private static void PostfixStartPlayer(PlayerControllerB __instance)
		{
			if (Utils.IsLocalPlayer(__instance))
			{
				KillableEnemyManager.Instance.SetupHitmarkerHUD(__instance);
				UIManager.Instance.Initialise();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAI), "Start")]
		private static void PostfixStartEnemy(EnemyAI __instance)
		{
			if (Object.op_Implicit((Object)(object)__instance) && Utils.isHost && !Object.op_Implicit((Object)(object)((Component)__instance).gameObject.GetComponent<KillableEnemy>()))
			{
				KillableEnemyManager.Instance.AssignKillableClassToEnemy(__instance);
				Utils.DebugLog("Assigned values on host?: " + Utils.isHost);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAI), "Update")]
		private static void PostfixUpdateEnemy(EnemyAI __instance)
		{
			if (Object.op_Implicit((Object)(object)__instance) && Utils.isHost && !Object.op_Implicit((Object)(object)((Component)__instance).gameObject.GetComponent<KillableEnemy>()))
			{
				KillableEnemyManager.Instance.AssignKillableClassToEnemy(__instance);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAI), "HitEnemy")]
		private static void HitPostfix(EnemyAI __instance, int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
		{
			if (Object.op_Implicit((Object)(object)playerWhoHit))
			{
				if (Utils.IsLocalPlayer(playerWhoHit))
				{
					KillableEnemyManager.Instance.PlayHitmarkerLocal(playerWhoHit);
				}
				if (Utils.isHost)
				{
					Utils.DebugLog("Hook: OnEnemyHit() Prepare ServerRPC");
					KillableEnemyManager.Instance.OnEnemyHitPrepareServerRPC(((NetworkBehaviour)__instance).NetworkObjectId, ((NetworkBehaviour)playerWhoHit).NetworkObjectId, force);
				}
			}
		}

		[HarmonyPatch(typeof(Terminal), "Start")]
		[HarmonyPostfix]
		private static void GetAllEnemies(ref SelectableLevel[] ___moonsCatalogueList, Terminal __instance)
		{
			SelectableLevel[] array = ___moonsCatalogueList;
			SpawnEnemyManager.Enemy item = default(SpawnEnemyManager.Enemy);
			SelectableLevel[] array2 = array;
			foreach (SelectableLevel level in array2)
			{
				int e;
				for (e = 0; e < level.Enemies.Count; e++)
				{
					if (!SpawnEnemyManager.listOfSpawnableEnemies.Any((SpawnEnemyManager.Enemy x) => x.name == level.Enemies[e].enemyType.enemyName) && !(level.Enemies[e].enemyType.enemyName == "Lasso"))
					{
						item.name = level.Enemies[e].enemyType.enemyName;
						item.prefab = level.Enemies[e].enemyType.enemyPrefab;
						item.isOutside = level.Enemies[e].enemyType.isOutsideEnemy;
						Utils.DebugLog("Terminal start=> Enemy Found: " + item.name);
						SpawnEnemyManager.listOfSpawnableEnemies.Add(item);
					}
				}
				int i;
				for (i = 0; i < level.OutsideEnemies.Count; i++)
				{
					if (!SpawnEnemyManager.listOfSpawnableEnemies.Any((SpawnEnemyManager.Enemy x) => x.name == level.OutsideEnemies[i].enemyType.enemyName) && !(level.Enemies[i].enemyType.enemyName == "Lasso"))
					{
						item.name = level.OutsideEnemies[i].enemyType.enemyName;
						item.prefab = level.OutsideEnemies[i].enemyType.enemyPrefab;
						item.isOutside = level.OutsideEnemies[i].enemyType.isOutsideEnemy;
						Utils.DebugLog("Terminal start=> Enemy Found: " + item.name);
						SpawnEnemyManager.listOfSpawnableEnemies.Add(item);
					}
				}
			}
			BountyManager.Instance.__terminal = __instance;
			Utils.DebugLog("server BountyManager.Instance.__terminal " + (object)BountyManager.Instance.__terminal);
		}
	}
}
namespace KillThemAll.Extras
{
	internal class ElementDespawn : MonoBehaviour
	{
		private float waittimer = 3f;

		private Animator animator;

		private bool isPlayingEnd = false;

		public void StartTimer(float time, Animator animator)
		{
			Utils.DebugLog("StartTimer for despawn ui " + ((Object)this).name);
			waittimer = time;
			this.animator = animator;
		}

		private void Update()
		{
			waittimer -= Time.deltaTime;
			if (waittimer <= 0f && !isPlayingEnd)
			{
				animator.Play("NotificationEnd", 0);
				isPlayingEnd = true;
				waittimer = 1f;
			}
			else if (isPlayingEnd && waittimer <= 0f)
			{
				Utils.DebugLog("Destroying notificationElement");
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}
	}
	public class TombScrap : GrabbableObject
	{
		public bool HasJustSpawned = false;

		public int id = -1;

		public int meshIndex = -1;

		public int matIndex = -1;

		public int scrapVal = -1;

		public string enemyName = "";

		public string playerName = "";

		public void OnSpawnInit(bool saveLoaded = false)
		{
			base.fallTime = 1f;
			base.grabbable = true;
			base.isInFactory = true;
			base.grabbableToEnemies = true;
			if (saveLoaded)
			{
				base.scrapPersistedThroughRounds = true;
				base.isInElevator = true;
				base.isInShipRoom = true;
			}
			if (!Object.op_Implicit((Object)(object)base.itemProperties))
			{
				base.itemProperties = KillableEnemyManager.Instance.enemyTomb;
			}
			base.itemProperties.saveItemVariable = true;
			base.customGrabTooltip = "Grab Tomb : [E]";
			base.mainObjectRenderer = ((Component)this).GetComponent<MeshRenderer>();
			HasJustSpawned = true;
			if (id == -1)
			{
				id = Random.Range(0, 99999);
			}
			UpdateObject();
			((Behaviour)this).enabled = true;
		}

		public override int GetItemDataToSave()
		{
			KillThemAll.instance.SaveTombScrapOnShip(GameNetworkManager.Instance.currentSaveFileName, id, meshIndex, matIndex, enemyName, playerName);
			return id;
		}

		public override void LoadItemSaveData(int saveDataID)
		{
			Tomb tombById = KillThemAll.instance.GetTombById(saveDataID, GameNetworkManager.Instance.currentSaveFileName);
			if (tombById == null)
			{
				if (!Utils.isHost)
				{
					return;
				}
				Utils.DebugLog("not found saved tomb with id of: " + saveDataID);
			}
			enemyName = tombById.enemyName;
			playerName = tombById.playerThatKilled;
			meshIndex = tombById.meshIndex;
			matIndex = tombById.matIndex;
			Utils.DebugLog("Tomb saved loaded: " + saveDataID);
			OnSpawnInit(saveLoaded: true);
		}

		public void LoadItemSaveDataOnJoin(string enemyName, string playerName, int meshIndex, int matIndex)
		{
			if (!(this.enemyName != ""))
			{
				this.enemyName = enemyName;
				this.playerName = playerName;
				this.meshIndex = meshIndex;
				this.matIndex = matIndex;
				Utils.DebugLog("Tomb saved loaded");
				OnSpawnInit(saveLoaded: true);
			}
		}

		public override void Update()
		{
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			if (base.currentUseCooldown >= 0f)
			{
				base.currentUseCooldown -= Time.deltaTime;
			}
			if (((NetworkBehaviour)this).IsOwner)
			{
				if (base.isBeingUsed && base.itemProperties.requiresBattery)
				{
					if (base.insertedBattery.charge > 0f)
					{
						if (!base.itemProperties.itemIsTrigger)
						{
							Battery insertedBattery = base.insertedBattery;
							insertedBattery.charge -= Time.deltaTime / base.itemProperties.batteryUsage;
						}
					}
					else if (!base.insertedBattery.empty)
					{
						base.insertedBattery.empty = true;
						if (base.isBeingUsed)
						{
							Debug.Log((object)"Use up batteries local");
							base.isBeingUsed = false;
							((GrabbableObject)this).UseUpBatteries();
						}
					}
				}
				if (!base.wasOwnerLastFrame)
				{
					base.wasOwnerLastFrame = true;
				}
			}
			else if (base.wasOwnerLastFrame)
			{
				base.wasOwnerLastFrame = false;
			}
			if (base.isHeld || !((Object)(object)base.parentObject == (Object)null))
			{
				return;
			}
			if (base.fallTime < 1f)
			{
				base.reachedFloorTarget = false;
				((GrabbableObject)this).FallWithCurve();
				if (((Component)this).transform.localPosition.y - base.targetFloorPosition.y < 0.1f && !base.hasHitGround)
				{
					((GrabbableObject)this).PlayDropSFX();
					((GrabbableObject)this).OnHitGround();
				}
				return;
			}
			if (!base.reachedFloorTarget)
			{
				base.reachedFloorTarget = true;
				if (base.floorYRot == -1)
				{
				}
				Vector3 val = default(Vector3);
				((Vector3)(ref val))..ctor(((Component)this).transform.position.x, ((Component)this).transform.position.y - 0.5f, ((Component)this).transform.position.z);
				GameObject val2 = Object.Instantiate<GameObject>(KillableEnemyManager.Instance.tombDropEffect, val, KillableEnemyManager.Instance.tombDropEffect.transform.rotation);
				val2.AddComponent<VfxDespawn>();
			}
			((Component)this).transform.localPosition = base.targetFloorPosition;
		}

		public override void FallWithCurve()
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			float num = base.startFallingPosition.y - base.targetFloorPosition.y;
			if (!HasJustSpawned)
			{
				((Component)this).transform.rotation = Quaternion.Euler(base.itemProperties.restingRotation.x, (float)(base.floorYRot + base.itemProperties.floorYOffset) + 90f, base.itemProperties.restingRotation.z);
			}
			if (base.floorYRot == -1)
			{
			}
			if (num > 5f)
			{
				((Component)this).transform.localPosition = Vector3.Lerp(base.startFallingPosition, base.targetFloorPosition, StartOfRound.Instance.objectFallToGroundCurveNoBounce.Evaluate(base.fallTime));
			}
			else
			{
				((Component)this).transform.localPosition = Vector3.Lerp(base.startFallingPosition, base.targetFloorPosition, StartOfRound.Instance.objectFallToGroundCurve.Evaluate(base.fallTime));
			}
			base.fallTime += Mathf.Abs(Time.deltaTime * 6f / num);
		}

		public override void OnHitGround()
		{
			((GrabbableObject)this).OnHitGround();
			if (HasJustSpawned)
			{
				HasJustSpawned = false;
			}
		}

		public void UpdateObject()
		{
			if (scrapVal != -1)
			{
				base.scrapValue = scrapVal;
			}
			((GrabbableObject)this).SetScrapValue(base.scrapValue);
			((Component)this).GetComponent<MeshFilter>().mesh = base.itemProperties.meshVariants[meshIndex];
			((Renderer)((Component)this).GetComponent<MeshRenderer>()).material = base.itemProperties.materialVariants[matIndex];
			Transform transform = ((Component)((Component)((Component)this).transform.GetChild(1)).transform.GetChild(0)).transform;
			((Component)transform.GetChild(0)).GetComponent<TMP_Text>().text = enemyName;
			((Component)transform.GetChild(2)).GetComponent<TMP_Text>().text = playerName;
		}
	}
	[VFXBinder("Transform/TransformBinder")]
	public class TransformBinder : VFXBinderBase
	{
		[VFXPropertyBinding(new string[] { "UnityEditor.VFX.Transform" })]
		[SerializeField]
		[FormerlySerializedAs("m_Parameter")]
		protected ExposedProperty m_Property = ExposedProperty.op_Implicit("Transform");

		public Transform Target = null;

		private ExposedProperty Position;

		private ExposedProperty Angles;

		private ExposedProperty Scale;

		public string Property
		{
			get
			{
				return (string)m_Property;
			}
			set
			{
				m_Property = ExposedProperty.op_Implicit(value);
				UpdateSubProperties();
			}
		}

		protected override void OnEnable()
		{
			((VFXBinderBase)this).OnEnable();
			UpdateSubProperties();
		}

		private void OnValidate()
		{
			UpdateSubProperties();
		}

		private void UpdateSubProperties()
		{
			Position = m_Property + ExposedProperty.op_Implicit("_position");
			Angles = m_Property + ExposedProperty.op_Implicit("_angles");
			Scale = m_Property + ExposedProperty.op_Implicit("_scale");
		}

		public override bool IsValid(VisualEffect component)
		{
			return (Object)(object)Target != (Object)null && component.HasVector3(ExposedProperty.op_Implicit(Position)) && component.HasVector3(ExposedProperty.op_Implicit(Angles)) && component.HasVector3(ExposedProperty.op_Implicit(Scale));
		}

		public override void UpdateBinding(VisualEffect component)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			component.SetVector3(ExposedProperty.op_Implicit(Position), Target.position);
			component.SetVector3(ExposedProperty.op_Implicit(Angles), Target.eulerAngles);
			component.SetVector3(ExposedProperty.op_Implicit(Scale), Target.localScale);
		}

		public override string ToString()
		{
			return string.Format("Transform : '{0}' -> {1}", m_Property, ((Object)(object)Target == (Object)null) ? "(null)" : ((Object)Target).name);
		}
	}
	internal class Utils
	{
		public static bool isHost;

		private static ManualLogSource mls;

		private const string modGUID = "KillThemAll";

		public static void SetupLog()
		{
			mls = Logger.CreateLogSource("KillThemAll");
		}

		public static void DebugLog(string log)
		{
			if (KillableEnemyManager.Instance.debugLog)
			{
				mls.LogInfo((object)("--KillThemAll | " + log));
			}
		}

		public static bool IsLocalPlayer(PlayerControllerB playerControllerClass)
		{
			return (Object)(object)StartOfRound.Instance.localPlayerController == (Object)(object)playerControllerClass;
		}

		internal static void DebugLog(object p)
		{
			throw new NotImplementedException();
		}

		public static PlayerControllerB GetPlayerClassFromNetID(ulong clientID)
		{
			if (clientID < 0 || !Object.op_Implicit((Object)(object)NetworkManager.Singleton) || !Object.op_Implicit((Object)(object)((Component)NetworkManager.Singleton.SpawnManager.SpawnedObjects[clientID]).gameObject))
			{
				return null;
			}
			return ((Component)NetworkManager.Singleton.SpawnManager.SpawnedObjects[clientID]).gameObject.GetComponent<PlayerControllerB>();
		}

		public static EnemyAI GetEnemyAIClassFromNetID(ulong enemyID)
		{
			if (enemyID < 0 || !Object.op_Implicit((Object)(object)NetworkManager.Singleton) || !Object.op_Implicit((Object)(object)((Component)NetworkManager.Singleton.SpawnManager.SpawnedObjects[enemyID]).gameObject))
			{
				return null;
			}
			return ((Component)NetworkManager.Singleton.SpawnManager.SpawnedObjects[enemyID]).gameObject.GetComponent<EnemyAI>();
		}

		public static string GetEnemyName(ulong enemyID)
		{
			if (enemyID < 0 || !Object.op_Implicit((Object)(object)NetworkManager.Singleton) || !Object.op_Implicit((Object)(object)((Component)NetworkManager.Singleton.SpawnManager.SpawnedObjects[enemyID]).gameObject))
			{
				return null;
			}
			EnemyAI component = ((Component)NetworkManager.Singleton.SpawnManager.SpawnedObjects[enemyID]).gameObject.GetComponent<EnemyAI>();
			string name = ((Object)component).name;
			name = name.Replace("Enemy", "");
			name = name.Replace("(Clone)", "");
			name = name.Replace(".prefab", "");
			name = name.Replace("default_", "");
			name = name.Replace("Obj", "");
			name = name.Replace("(", "");
			return name.Replace(")", "");
		}

		public static string GetEnemyName(EnemyAI enemyClass)
		{
			string name = ((Object)enemyClass).name;
			name = name.Replace("Enemy", "");
			name = name.Replace("(Clone)", "");
			name = name.Replace(".prefab", "");
			name = name.Replace("default_", "");
			name = name.Replace("Obj", "");
			name = name.Replace("(", "");
			return name.Replace(")", "");
		}

		public static double SimilarityRatio(string str1, string str2)
		{
			int num = LevenshteinDistance(str1, str2);
			int num2 = Math.Max(str1.Length, str2.Length);
			return 1.0 - (double)num / (double)num2;
		}

		public static int LevenshteinDistance(string str1, string str2)
		{
			int[,] array = new int[str1.Length + 1, str2.Length + 1];
			for (int i = 0; i <= str1.Length; i++)
			{
				for (int j = 0; j <= str2.Length; j++)
				{
					if (i == 0)
					{
						array[i, j] = j;
						continue;
					}
					if (j == 0)
					{
						array[i, j] = i;
						continue;
					}
					int num = ((str1[i - 1] != str2[j - 1]) ? 1 : 0);
					array[i, j] = Math.Min(array[i - 1, j] + 1, Math.Min(array[i, j - 1] + 1, array[i - 1, j - 1] + num));
				}
			}
			return array[str1.Length, str2.Length];
		}

		public static GameObject GetScrapObject(ulong scrapID)
		{
			if (scrapID < 0 || !Object.op_Implicit((Object)(object)NetworkManager.Singleton) || !Object.op_Implicit((Object)(object)((Component)NetworkManager.Singleton.SpawnManager.SpawnedObjects[scrapID]).gameObject))
			{
				DebugLog("Scrap ID: " + scrapID + " Not found or Network Manager does not exist");
				return null;
			}
			return ((Component)NetworkManager.Singleton.SpawnManager.SpawnedObjects[scrapID]).gameObject;
		}

		public static int GetTimeOfRound()
		{
			int num = (int)(TimeOfDay.Instance.normalizedTimeOfDay * (60f * (float)TimeOfDay.Instance.numberOfHours)) + 360;
			return (int)Mathf.Floor((float)(num / 60));
		}
	}
	public class VfxDespawn : MonoBehaviour
	{
		private float waittimer = 3f;

		private void Start()
		{
			waittimer = 3f;
		}

		private void Update()
		{
			waittimer -= Time.deltaTime;
			if (waittimer <= 0f)
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}
	}
}

BepInEx/plugins/americanompany/LCHazardsOutside.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LCHazardsOutside.Abstract;
using LCHazardsOutside.Data;
using LCHazardsOutside.ModCompatibility;
using LCHazardsOutside.Patches;
using LCHazardsOutside.Strategy;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("LCHazardsOutside")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+03924a40eccc82ec032c9bceef2b554cb95c8401")]
[assembly: AssemblyProduct("LCHazardsOutside")]
[assembly: AssemblyTitle("LCHazardsOutside")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LCHazardsOutside
{
	public class LCUtils
	{
		public static readonly Dictionary<string, string[]> CUSTOM_LAYER_MASK = new Dictionary<string, string[]> { 
		{
			VanillaMoon.march.ToString(),
			new string[1] { "Room" }
		} };

		public static readonly Dictionary<string, HazardType> HAZARD_MAP = new Dictionary<string, HazardType>(3)
		{
			{
				"Landmine",
				HazardType.Landmine
			},
			{
				"TurretContainer",
				HazardType.Turret
			},
			{
				"SpikeRoofTrapHazard",
				HazardType.SpikeRoofTrap
			}
		};

		private static readonly Dictionary<SpawnStrategyType, SpawnStrategy> STRATEGY_MAP = new Dictionary<SpawnStrategyType, SpawnStrategy>(3)
		{
			{
				SpawnStrategyType.MainAndFireExit,
				MainAndFireExitSpawnStrategy.GetInstance()
			},
			{
				SpawnStrategyType.MainEntranceOnly,
				MainEntranceOnlySpawnStrategy.GetInstance()
			},
			{
				SpawnStrategyType.FireExitsOnly,
				FireExitsOnlySpawnStrategy.GetInstance()
			}
		};

		public static SpawnStrategy GetSpawnStrategy(string typeString)
		{
			try
			{
				SpawnStrategyType key = (SpawnStrategyType)Enum.Parse(typeof(SpawnStrategyType), typeString);
				if (STRATEGY_MAP.TryGetValue(key, out var value))
				{
					return value;
				}
			}
			catch (Exception)
			{
				Plugin.GetLogger().LogError((object)("Type " + typeString + " could not be parsed into a SpawnStrategyType. Reverting to default..."));
			}
			return MainAndFireExitSpawnStrategy.GetInstance();
		}

		public static string GetNumberlessMoonName(SelectableLevel selectableLevel)
		{
			if ((Object)(object)selectableLevel != (Object)null)
			{
				return new string(selectableLevel.PlanetName.SkipWhile((char c) => !char.IsLetter(c)).ToArray()).ToLower();
			}
			return string.Empty;
		}

		public static bool IsVanillaMoon(string moonName)
		{
			object result;
			return Enum.TryParse(typeof(VanillaMoon), moonName, ignoreCase: true, out result);
		}

		public static bool IsVanillaMoon(SelectableLevel selectableLevel)
		{
			object result;
			return Enum.TryParse(typeof(VanillaMoon), GetNumberlessMoonName(selectableLevel), ignoreCase: true, out result);
		}

		private static float RandomNumberInRadius(float radius, Random randomSeed)
		{
			return ((float)randomSeed.NextDouble() - 0.5f) * radius;
		}

		public static (Vector3, Quaternion) GetRandomGroundPositionAndRotation(Vector3 centerPoint, float radius = 10f, Random randomSeed = null, int layerMask = -1, int maxAttempts = 10)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: 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_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: 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)
			float y = centerPoint.y;
			NavMeshHit val2 = default(NavMeshHit);
			RaycastHit val3 = default(RaycastHit);
			for (int i = 0; i < maxAttempts; i++)
			{
				try
				{
					float num = RandomNumberInRadius(radius, randomSeed);
					float num2 = RandomNumberInRadius(radius, randomSeed);
					float num3 = RandomNumberInRadius(radius, randomSeed);
					Vector3 val = centerPoint + new Vector3(num, num2, num3);
					val.y = y;
					float num4 = Vector3.Distance(centerPoint, val) + 30f;
					if (NavMesh.SamplePosition(val, ref val2, num4, -1))
					{
						if (Physics.Raycast(((NavMeshHit)(ref val2)).position + Vector3.up, Vector3.down, ref val3, 50f, layerMask))
						{
							return (((RaycastHit)(ref val3)).point + Vector3.up * 0.1f, Quaternion.FromToRotation(Vector3.up, ((RaycastHit)(ref val3)).normal));
						}
						Plugin.GetLogger().LogDebug((object)$"Nav hit at: {((NavMeshHit)(ref val2)).position} but ray cast failed.");
					}
				}
				catch (Exception)
				{
				}
			}
			return (Vector3.zero, Quaternion.identity);
		}

		public static void DetermineMinMaxSpawnRates(bool increasedMapHazardSpawnRate, int configMinSpawnRate, int configMaxSpawnRate, MoonMinMax moonMinMax, out int minSpawnRate, out int maxSpawnRate)
		{
			int num = moonMinMax?.Min ?? configMinSpawnRate;
			int num2 = moonMinMax?.Max ?? configMaxSpawnRate;
			minSpawnRate = Mathf.Min(Mathf.Max(num, 0), num2);
			maxSpawnRate = Mathf.Max(Mathf.Min(num2, 100), minSpawnRate);
			if (increasedMapHazardSpawnRate)
			{
				minSpawnRate = Mathf.Max(5, minSpawnRate);
				maxSpawnRate = Mathf.Min(maxSpawnRate * 2, 15);
			}
		}

		public static EntranceContainer FindAllExitPositions()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: 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)
			EntranceTeleport[] array = Object.FindObjectsOfType<EntranceTeleport>(false);
			List<Vector3> list = new List<Vector3>();
			Vector3 mainEntrancePosition = Vector3.zero;
			for (int i = 0; i < array.Length; i++)
			{
				EntranceTeleport val = array[i];
				if (val.isEntranceToBuilding)
				{
					if (val.entranceId == 0)
					{
						mainEntrancePosition = ((Component)val).transform.position;
					}
					else
					{
						list.Add(((Component)array[i]).transform.position);
					}
				}
			}
			return new EntranceContainer(mainEntrancePosition, list);
		}

		public static Dictionary<string, MoonMinMax> ParseMoonString(string moonString)
		{
			if (string.IsNullOrEmpty(moonString))
			{
				return new Dictionary<string, MoonMinMax>();
			}
			Dictionary<string, MoonMinMax> dictionary = new Dictionary<string, MoonMinMax>();
			string[] array = moonString.Trim().ToLower().Split(',');
			string[] array2 = array;
			foreach (string text in array2)
			{
				try
				{
					string[] array3 = text.Trim().Split(':');
					dictionary.TryAdd(array3[0], new MoonMinMax(int.Parse(array3[1]), int.Parse(array3[2])));
				}
				catch (Exception)
				{
					Plugin.GetLogger().LogError((object)("There was an error while parsing the moon string " + text + ". Make sure it has the format moon:min:max."));
				}
			}
			return dictionary;
		}

		public static object GetReflectionField(object obj, string fieldName)
		{
			return AccessTools.Field(obj.GetType(), fieldName).GetValue(obj);
		}
	}
	[BepInPlugin("snake.tech.LCHazardsOutside", "LCHazardsOutside", "1.2.4")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string modGUID = "snake.tech.LCHazardsOutside";

		private const string modName = "LCHazardsOutside";

		private const string modVersion = "1.2.4";

		private readonly Harmony harmony = new Harmony("snake.tech.LCHazardsOutside");

		private readonly AcceptableValueRange<int> acceptableSpawnRange = new AcceptableValueRange<int>(0, 100);

		private readonly AcceptableValueList<string> acceptableSpawnStrategies = new AcceptableValueList<string>(Enum.GetNames(typeof(SpawnStrategyType)));

		public static Plugin instance;

		public bool IsCoroutineRunning = false;

		public HashSet<Type> hazardBlockList = new HashSet<Type>();

		public bool v49CompatibilityEnabled = false;

		public Dictionary<HazardType, HazardConfiguration> hazardConfigMap = new Dictionary<HazardType, HazardConfiguration>();

		public ConfigEntry<int> noHazardSpawnChance;

		private void Awake()
		{
			if ((Object)(object)instance == (Object)null)
			{
				instance = this;
			}
			LoadConfig();
			new LateGameUpgradesHandler().Apply();
			new V49Handler().Apply();
			harmony.PatchAll(typeof(RoundManagerPatch));
			GetLogger().LogInfo((object)"Plugin LCHazardsOutside is loaded!");
		}

		private void LoadConfig()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			ConfigDescription val = new ConfigDescription("This setting dictates how spawn positions are allocated. It has 3 possible options: \"MainAndFireExit\", \"MainEntranceOnly\" and \"FireExitsOnly\".\r\nWhen set to \"MainAndFireExit\", spawn positions are determined based on both the main entrance, the fire exits and the ship.\r\nWhen set to \"MainEntranceOnly\", spawn positions are limited strictly to the area between the ship and the main entrance of the facility, making spawn points more concentrated and fire exits safe.\r\nWhen set to \"FireExitsOnly\", spawn positions are limited strictly to the area between the ship and the fire exits of the facility, making fire exits more punishing while leaving the main entrance hassle-free.", (AcceptableValueBase)(object)acceptableSpawnStrategies, Array.Empty<object>());
			ConfigDescription val2 = new ConfigDescription("Minimum amount to spawn outside.", (AcceptableValueBase)(object)acceptableSpawnRange, Array.Empty<object>());
			ConfigDescription val3 = new ConfigDescription("Maximum amount to spawn outside.", (AcceptableValueBase)(object)acceptableSpawnRange, Array.Empty<object>());
			ConfigDescription val4 = new ConfigDescription("The moon(s) where this hazard can spawn outside in the form of a comma separated list of selectable level names with min/max values in moon:min:max format (e.g. \"experimentation:5:15,rend:0:10,dine:10:15\")\r\n\"NOTE: These must be the internal data names of the levels (for vanilla moons use the names you see on the terminal i.e. vow, march and for modded moons check their description or ask the author).", (AcceptableValueBase)null, Array.Empty<object>());
			noHazardSpawnChance = ((BaseUnityPlugin)this).Config.Bind<int>("0. General", "NoHazardSpawnChance", 0, "A global chance from 0 to 100 in % for NO hazards to spawn outside.\n Use a non-zero chance if you want to make hazards outside more of a surprise.");
			ConfigEntry<bool> val5 = ((BaseUnityPlugin)this).Config.Bind<bool>("1. Landmine", "EnableLandmineOutside", true, "Whether or not to spawn landmines outside.");
			ConfigEntry<int> val6 = ((BaseUnityPlugin)this).Config.Bind<int>("1. Landmine", "LandmineMinSpawnRate", 15, val2);
			ConfigEntry<int> val7 = ((BaseUnityPlugin)this).Config.Bind<int>("1. Landmine", "LandmineMaxSpawnRate", 30, val3);
			ConfigEntry<string> val8 = ((BaseUnityPlugin)this).Config.Bind<string>("1. Landmine", "LandmineMoons", "", val4);
			ConfigEntry<string> val9 = ((BaseUnityPlugin)this).Config.Bind<string>("1. Landmine", "LandmineSpawnStrategy", SpawnStrategyType.MainAndFireExit.ToString(), val);
			Dictionary<string, MoonMinMax> moonMap = LCUtils.ParseMoonString(val8.Value);
			SpawnStrategy spawnStrategy = LCUtils.GetSpawnStrategy(val9.Value);
			hazardConfigMap.Add(HazardType.Landmine, new HazardConfiguration(val5.Value, val6.Value, val7.Value, moonMap, spawnStrategy));
			ConfigEntry<bool> val10 = ((BaseUnityPlugin)this).Config.Bind<bool>("2. Turret", "EnableTurretOutside", false, "Whether or not to spawn turrets outside.");
			ConfigEntry<int> val11 = ((BaseUnityPlugin)this).Config.Bind<int>("2. Turret", "TurretMinSpawnRate", 0, val2);
			ConfigEntry<int> val12 = ((BaseUnityPlugin)this).Config.Bind<int>("2. Turret", "TurretMaxSpawnRate", 1, val3);
			ConfigEntry<string> val13 = ((BaseUnityPlugin)this).Config.Bind<string>("2. Turret", "TurretMoons", "", val4);
			ConfigEntry<string> val14 = ((BaseUnityPlugin)this).Config.Bind<string>("2. Turret", "TurretSpawnStrategy", SpawnStrategyType.MainAndFireExit.ToString(), val);
			Dictionary<string, MoonMinMax> moonMap2 = LCUtils.ParseMoonString(val13.Value);
			SpawnStrategy spawnStrategy2 = LCUtils.GetSpawnStrategy(val14.Value);
			hazardConfigMap.Add(HazardType.Turret, new HazardConfiguration(val10.Value, val11.Value, val12.Value, moonMap2, spawnStrategy2));
			ConfigEntry<bool> val15 = ((BaseUnityPlugin)this).Config.Bind<bool>("3. SpikeRoofTrap", "EnableSpikeRoofTrapOutside", true, "Whether or not to spawn spike roof traps outside.");
			ConfigEntry<int> val16 = ((BaseUnityPlugin)this).Config.Bind<int>("3. SpikeRoofTrap", "SpikeRoofTrapMinSpawnRate", 0, val2);
			ConfigEntry<int> val17 = ((BaseUnityPlugin)this).Config.Bind<int>("3. SpikeRoofTrap", "SpikeRoofTrapMaxSpawnRate", 2, val3);
			ConfigEntry<string> val18 = ((BaseUnityPlugin)this).Config.Bind<string>("3. SpikeRoofTrap", "SpikeRoofTrapMoons", "", val4);
			ConfigEntry<string> val19 = ((BaseUnityPlugin)this).Config.Bind<string>("3. SpikeRoofTrap", "SpikeRoofTrapSpawnStrategy", SpawnStrategyType.MainAndFireExit.ToString(), val);
			Dictionary<string, MoonMinMax> moonMap3 = LCUtils.ParseMoonString(val18.Value);
			SpawnStrategy spawnStrategy3 = LCUtils.GetSpawnStrategy(val19.Value);
			hazardConfigMap.Add(HazardType.SpikeRoofTrap, new HazardConfiguration(val15.Value, val16.Value, val17.Value, moonMap3, spawnStrategy3));
			ConfigEntry<bool> val20 = ((BaseUnityPlugin)this).Config.Bind<bool>("99. Custom", "EnableCustomHazardOutside", false, "Whether or not to spawn modded hazards outside.");
			ConfigEntry<int> val21 = ((BaseUnityPlugin)this).Config.Bind<int>("99. Custom", "CustomHazardMinSpawnRate", 0, val2);
			ConfigEntry<int> val22 = ((BaseUnityPlugin)this).Config.Bind<int>("99. Custom", "CustomHazardMaxSpawnRate", 3, val3);
			ConfigEntry<string> val23 = ((BaseUnityPlugin)this).Config.Bind<string>("99. Custom", "CustomHazardMoons", "", val4);
			ConfigEntry<string> val24 = ((BaseUnityPlugin)this).Config.Bind<string>("99. Custom", "CustomHazardSpawnStrategy", SpawnStrategyType.MainAndFireExit.ToString(), val);
			Dictionary<string, MoonMinMax> moonMap4 = LCUtils.ParseMoonString(val23.Value);
			SpawnStrategy spawnStrategy4 = LCUtils.GetSpawnStrategy(val24.Value);
			hazardConfigMap.Add(HazardType.CustomHazard, new HazardConfiguration(val20.Value, val21.Value, val22.Value, moonMap4, spawnStrategy4));
		}

		public static ManualLogSource GetLogger()
		{
			return ((BaseUnityPlugin)instance).Logger;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LCHazardsOutside";

		public const string PLUGIN_NAME = "LCHazardsOutside";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace LCHazardsOutside.Strategy
{
	internal class FireExitsOnlySpawnStrategy : SpawnStrategy
	{
		private static FireExitsOnlySpawnStrategy instance;

		private FireExitsOnlySpawnStrategy()
		{
		}

		public static FireExitsOnlySpawnStrategy GetInstance()
		{
			if (instance == null)
			{
				instance = new FireExitsOnlySpawnStrategy();
			}
			return instance;
		}

		public override List<SpawnPositionData> CalculateCenterPositions(Vector3 shipLandPosition, Vector3 mainEntrancePosition, List<Vector3> pointsOfInterest, float spawnRadiusMultiplier)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			List<SpawnPositionData> list = new List<SpawnPositionData>();
			foreach (Vector3 item in pointsOfInterest)
			{
				list.Add(CalculateCenterWithSpawnRadius(shipLandPosition, item, spawnRadiusMultiplier));
			}
			return list;
		}
	}
	internal class MainAndFireExitSpawnStrategy : SpawnStrategy
	{
		private static MainAndFireExitSpawnStrategy instance;

		private MainAndFireExitSpawnStrategy()
		{
		}

		public static MainAndFireExitSpawnStrategy GetInstance()
		{
			if (instance == null)
			{
				instance = new MainAndFireExitSpawnStrategy();
			}
			return instance;
		}

		public override List<SpawnPositionData> CalculateCenterPositions(Vector3 shipLandPosition, Vector3 mainEntrancePosition, List<Vector3> pointsOfInterest, float spawnRadiusMultiplier)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			List<SpawnPositionData> list = new List<SpawnPositionData>(1) { CalculateCenterWithSpawnRadius(shipLandPosition, mainEntrancePosition, spawnRadiusMultiplier) };
			foreach (Vector3 item in pointsOfInterest)
			{
				list.Add(CalculateCenterWithSpawnRadius(shipLandPosition, item, spawnRadiusMultiplier));
			}
			return list;
		}
	}
	internal class MainEntranceOnlySpawnStrategy : SpawnStrategy
	{
		private static MainEntranceOnlySpawnStrategy instance;

		private MainEntranceOnlySpawnStrategy()
		{
		}

		public static MainEntranceOnlySpawnStrategy GetInstance()
		{
			if (instance == null)
			{
				instance = new MainEntranceOnlySpawnStrategy();
			}
			return instance;
		}

		public override List<SpawnPositionData> CalculateCenterPositions(Vector3 shipLandPosition, Vector3 mainEntrancePosition, List<Vector3> pointsOfInterest, float spawnRadiusMultiplier)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			SpawnPositionData item = CalculateCenterWithSpawnRadius(shipLandPosition, mainEntrancePosition, spawnRadiusMultiplier);
			return new List<SpawnPositionData>(1) { item };
		}
	}
}
namespace LCHazardsOutside.Patches
{
	[HarmonyPatch(typeof(RoundManager))]
	internal class RoundManagerPatch
	{
		private const string HAZARD_LAYER_NAME = "MapHazards";

		[HarmonyPatch("SpawnOutsideHazards")]
		[HarmonyPrefix]
		private static void SpawnHazardsOutsidePatch(RoundManager __instance)
		{
			if (!__instance.currentLevel.spawnEnemiesAndScrap || !((NetworkBehaviour)__instance).IsServer || !((NetworkBehaviour)__instance).IsHost)
			{
				return;
			}
			Plugin.GetLogger().LogDebug((object)("randomMapSeed: " + StartOfRound.Instance.randomMapSeed));
			Random random = new Random(StartOfRound.Instance.randomMapSeed + 587);
			int value = Plugin.instance.noHazardSpawnChance.Value;
			if (value > 0)
			{
				double num = (double)value / 100.0;
				if (random.NextDouble() < num)
				{
					Plugin.GetLogger().LogInfo((object)"No hazards spawned outside due to global chance.");
					return;
				}
			}
			SpawnableMapObject[] spawnableMapObjects = __instance.currentLevel.spawnableMapObjects;
			if (spawnableMapObjects.Length != 0)
			{
				((MonoBehaviour)__instance).StartCoroutine(SpawnHazardsAfterExitSpawn(__instance, spawnableMapObjects, random));
			}
		}

		private static void SpawnHazardsOutside(RoundManager __instance, SpawnableMapObject[] hazardObjects, EntranceContainer entranceContainer, Random random)
		{
			string numberlessMoonName = LCUtils.GetNumberlessMoonName(__instance.currentLevel);
			Plugin.GetLogger().LogDebug((object)("Planetname: " + numberlessMoonName));
			LCUtils.CUSTOM_LAYER_MASK.TryGetValue(numberlessMoonName, out var value);
			if (value == null)
			{
				value = new string[2] { "Room", "Default" };
			}
			int mask = LayerMask.GetMask(value);
			GameObject[] array = GameObject.FindGameObjectsWithTag("SpawnDenialPoint");
			List<GameObject> list = new List<GameObject>(array.Length);
			list.AddRange(array);
			List<GameObject> spawnDenialPoints = list;
			var array2 = hazardObjects.Select((SpawnableMapObject hazardObject, int index) => new
			{
				HazardObject = hazardObject,
				IsBlacklisted = Plugin.instance.hazardBlockList.Any((Type type) => (Object)(object)hazardObject.prefabToSpawn.GetComponent(type) != (Object)null),
				IsIncreasedSpawnRate = (__instance.increasedMapHazardSpawnRateIndex == index)
			}).ToArray();
			var array3 = array2;
			foreach (var anon in array3)
			{
				Plugin.GetLogger().LogDebug((object)("Current spawnable object: " + ((Object)anon.HazardObject.prefabToSpawn).name));
				if (anon.IsBlacklisted)
				{
					Plugin.GetLogger().LogInfo((object)("Hazard blocked from spawning due to blacklist: " + ((Object)anon.HazardObject.prefabToSpawn).name));
					continue;
				}
				HazardType type2 = HazardType.CustomHazard;
				if (LCUtils.HAZARD_MAP.TryGetValue(((Object)anon.HazardObject.prefabToSpawn).name, out var value2))
				{
					type2 = value2;
				}
				ProcessHazard(type2, __instance, anon.IsIncreasedSpawnRate, anon.HazardObject, spawnDenialPoints, numberlessMoonName, entranceContainer, random, mask);
			}
			Plugin.GetLogger().LogInfo((object)"Outside hazard spawning done.");
		}

		private static void ProcessHazard(HazardType type, RoundManager __instance, bool isIncreasedSpawnRate, SpawnableMapObject hazardObj, List<GameObject> spawnDenialPoints, string moonName, EntranceContainer entranceContainer, Random random, int layerMask)
		{
			Plugin.instance.hazardConfigMap.TryGetValue(type, out var value);
			if (value.Enabled)
			{
				Plugin.GetLogger().LogInfo((object)$"Spawning {type}s outside...");
				value.MoonMap.TryGetValue(moonName, out var value2);
				LCUtils.DetermineMinMaxSpawnRates(isIncreasedSpawnRate, value.MinSpawnRate, value.MaxSpawnRate, value2, out var minSpawnRate, out var maxSpawnRate);
				HazardCalculationContainer hazardCalculationContainer = new HazardCalculationContainer(random, spawnDenialPoints, hazardObj, minSpawnRate, maxSpawnRate, layerMask);
				if (type == HazardType.Turret)
				{
					hazardCalculationContainer.NeedsSafetyZone = true;
					hazardCalculationContainer.SpawnRatioMultiplier = 1.25f;
				}
				if (type == HazardType.SpikeRoofTrap)
				{
					hazardCalculationContainer.NeedsSafetyZone = true;
				}
				CalculateHazardSpawn(__instance, hazardCalculationContainer, entranceContainer, value.SpawnStrategy);
			}
		}

		private static void CalculateHazardSpawn(RoundManager __instance, HazardCalculationContainer hazardCalculationContainer, EntranceContainer entranceContainer, SpawnStrategy spawnStrategy)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: 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_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			Vector3 mainEntrancePosition = entranceContainer.MainEntrancePosition;
			List<Vector3> fireExitPositions = entranceContainer.FireExitPositions;
			Transform[] shipSpawnPathPoints = __instance.shipSpawnPathPoints;
			int num = 0;
			Vector3 position = shipSpawnPathPoints.Last().position;
			int num2 = hazardCalculationContainer.Random.Next(hazardCalculationContainer.MinSpawnRate, hazardCalculationContainer.MaxSpawnRate + 1);
			Plugin.GetLogger().LogDebug((object)("Random spawn rate: " + num2));
			List<SpawnPositionData> list = spawnStrategy.CalculateCenterPositions(position, mainEntrancePosition, fireExitPositions, hazardCalculationContainer.SpawnRatioMultiplier);
			List<GameObject> list2 = new List<GameObject>();
			int layerMask = hazardCalculationContainer.LayerMask;
			int num3 = num2 / list.Count;
			Plugin.GetLogger().LogDebug((object)("Actual spawn rate per position: " + num3));
			foreach (SpawnPositionData item in list)
			{
				for (int i = 0; i < num3; i++)
				{
					var (val, quaternion) = LCUtils.GetRandomGroundPositionAndRotation(item.CenterPosition, item.SpawnRadius, hazardCalculationContainer.Random, layerMask);
					if (val == Vector3.zero)
					{
						Plugin.GetLogger().LogDebug((object)"No NavMesh hit!");
						continue;
					}
					List<Vector3> list3 = new List<Vector3>(1) { position };
					list3.AddRange(hazardCalculationContainer.SpawnDenialPoints.Select((GameObject x) => x.transform.position).ToArray());
					GameObject val2 = GameObject.Find("PlayerShipNavmesh");
					if ((Object)(object)val2 != (Object)null)
					{
						Vector3 position2 = val2.transform.position;
						list3.Add(position2);
					}
					if (IsInvalidSpawnPoint(list3, val, hazardCalculationContainer.NeedsSafetyZone ? 18f : 8f))
					{
						ManualLogSource logger = Plugin.GetLogger();
						Vector3 val3 = val;
						logger.LogDebug((object)("Hazard was too close to denial or safety zone and was therefore deleted: " + ((object)(Vector3)(ref val3)).ToString()));
					}
					else
					{
						list2.Add(InstantiateHazardObject(__instance, hazardCalculationContainer.SpawnableMapObject, val, quaternion));
						num++;
					}
				}
			}
			((MonoBehaviour)__instance).StartCoroutine(SpawnHazardsInBulk(list2));
			Plugin.GetLogger().LogDebug((object)("Total hazard amount: " + num));
		}

		private static GameObject InstantiateHazardObject(RoundManager __instance, SpawnableMapObject spawnableMapObject, Vector3 position, Quaternion quaternion)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: 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_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			ManualLogSource logger = Plugin.GetLogger();
			Vector3 val = position;
			logger.LogDebug((object)("Spawn hazard outside at: " + ((object)(Vector3)(ref val)).ToString()));
			GameObject val2 = Object.Instantiate<GameObject>(spawnableMapObject.prefabToSpawn, position, quaternion, __instance.mapPropsContainer.transform);
			if (spawnableMapObject.spawnFacingAwayFromWall)
			{
				val2.transform.eulerAngles = new Vector3(0f, __instance.YRotationThatFacesTheFarthestFromPosition(position + Vector3.up * 0.2f, 25f, 6), 0f);
			}
			if (!Plugin.instance.v49CompatibilityEnabled)
			{
				if ((bool)LCUtils.GetReflectionField(spawnableMapObject, "spawnFacingWall"))
				{
					val2.transform.eulerAngles = new Vector3(0f, __instance.YRotationThatFacesTheNearestFromPosition(position + Vector3.up * 0.2f, 25f, 6), 0f);
				}
				RaycastHit val3 = default(RaycastHit);
				if ((bool)LCUtils.GetReflectionField(spawnableMapObject, "spawnWithBackToWall") && Physics.Raycast(val2.transform.position, -val2.transform.forward, ref val3, 300f, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))
				{
					RaycastHit val4 = default(RaycastHit);
					if (Physics.Raycast(((RaycastHit)(ref val3)).point + Vector3.up * 0.2f, Vector3.down, ref val4, 50f, StartOfRound.Instance.collidersAndRoomMaskAndDefault))
					{
						val2.transform.position = ((RaycastHit)(ref val4)).point;
					}
					else
					{
						val2.transform.position = ((RaycastHit)(ref val3)).point;
					}
					if ((bool)LCUtils.GetReflectionField(spawnableMapObject, "spawnWithBackFlushAgainstWall"))
					{
						val2.transform.forward = -((RaycastHit)(ref val3)).normal;
						val2.transform.eulerAngles = new Vector3(0f, val2.transform.eulerAngles.y, 0f);
					}
				}
			}
			val2.SetActive(true);
			val2.layer = LayerMask.NameToLayer("MapHazards");
			return val2;
		}

		private static bool IsInvalidSpawnPoint(List<Vector3> spawnDenialPoints, Vector3 randomPosition, float safetyDistance)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			foreach (Vector3 spawnDenialPoint in spawnDenialPoints)
			{
				if (Vector3.Distance(randomPosition, spawnDenialPoint) < safetyDistance)
				{
					return true;
				}
			}
			return false;
		}

		public static IEnumerator SpawnHazardsInBulk(List<GameObject> gameObjects)
		{
			yield return (object)new WaitWhile((Func<bool>)(() => Plugin.instance.IsCoroutineRunning));
			Plugin.instance.IsCoroutineRunning = true;
			Plugin.GetLogger().LogDebug((object)"SpawnHazardsInBulk Coroutine running.");
			for (int i = 0; i < gameObjects.Count; i += 10)
			{
				int range = Mathf.Min(10, gameObjects.Count - i);
				for (int j = 0; j < range; j++)
				{
					GameObject objectToSpawn = gameObjects[i + j];
					try
					{
						if ((Object)(object)objectToSpawn != (Object)null)
						{
							NetworkObject networkObject = objectToSpawn.GetComponent<NetworkObject>();
							if ((Object)(object)networkObject != (Object)null)
							{
								networkObject.Spawn(true);
							}
							else
							{
								Plugin.GetLogger().LogError((object)("Hazard " + ((Object)objectToSpawn).name + " had no network object and cannot be spawned."));
							}
						}
						else
						{
							Plugin.GetLogger().LogError((object)"Hazard object was destroyed before it could spawn. Probably needs compatibility patch.");
						}
					}
					catch (Exception e)
					{
						Plugin.GetLogger().LogError((object)$"NetworkObject {((Object)objectToSpawn).name} could not be spawned: {e}");
					}
				}
				yield return (object)new WaitForSeconds(0.5f);
			}
			Plugin.instance.IsCoroutineRunning = false;
			Plugin.GetLogger().LogDebug((object)"SpawnHazardsInBulk Coroutine done.");
		}

		public static IEnumerator SpawnHazardsAfterExitSpawn(RoundManager __instance, SpawnableMapObject[] hazardObjects, Random random)
		{
			float startTime = Time.timeSinceLevelLoad;
			EntranceContainer entranceContainer = LCUtils.FindAllExitPositions();
			Plugin.GetLogger().LogDebug((object)$"Time since level loaded: {startTime}");
			while (!entranceContainer.IsInitialized() && Time.timeSinceLevelLoad - startTime < 15f)
			{
				Plugin.GetLogger().LogDebug((object)"Waiting for main entrance to load...");
				yield return (object)new WaitForSeconds(1f);
				entranceContainer = LCUtils.FindAllExitPositions();
			}
			SpawnHazardsOutside(__instance, hazardObjects, entranceContainer, random);
		}
	}
}
namespace LCHazardsOutside.ModCompatibility
{
	internal class LateGameUpgradesHandler : AbstractCompatibilityHandler
	{
		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		protected override void DoApply()
		{
			LogApply();
			Assembly targetAssembly = GetTargetAssembly("MoreShipUpgrades");
			if (targetAssembly == null)
			{
				Plugin.GetLogger().LogError((object)"Target assembly 'MoreShipUpgrades' not found.");
				return;
			}
			AddTypeToHazardBlockList(targetAssembly, "MoreShipUpgrades.UpgradeComponents.Items.Wheelbarrow.ScrapWheelbarrow");
			AddContractItemsToBlocklist(targetAssembly);
		}

		private void AddTypeToHazardBlockList(Assembly assembly, string typeName)
		{
			Type type = assembly.GetTypes().FirstOrDefault((Type t) => t.FullName == typeName);
			if (type != null)
			{
				Plugin.instance.hazardBlockList.Add(type);
				Plugin.GetLogger().LogDebug((object)("Added " + typeName + " to hazardBlockList."));
			}
			else
			{
				Plugin.GetLogger().LogWarning((object)("Type " + typeName + " not found in assembly."));
			}
		}

		private void AddContractItemsToBlocklist(Assembly assembly)
		{
			Type baseType = assembly.GetTypes().FirstOrDefault((Type t) => t.Name == "ContractObject");
			if (baseType == null)
			{
				Plugin.GetLogger().LogError((object)"Base type ContractObject not found in assembly.");
				return;
			}
			IEnumerable<Type> enumerable = from t in assembly.GetTypes()
				where t.IsClass && !t.IsAbstract && t.IsSubclassOf(baseType)
				select t;
			foreach (Type item in enumerable)
			{
				Plugin.instance.hazardBlockList.Add(item);
				Plugin.GetLogger().LogDebug((object)("Added " + item.Name + " to hazardBlockList."));
			}
		}

		protected override string GetModGUID()
		{
			return "com.malco.lethalcompany.moreshipupgrades";
		}
	}
	internal class V49Handler : AbstractCompatibilityHandler
	{
		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		protected override void DoApply()
		{
			Assembly targetAssembly = GetTargetAssembly("Assembly-CSharp");
			if (targetAssembly == null)
			{
				Plugin.GetLogger().LogError((object)"Target assembly 'Assembly-CSharp' not found.");
				return;
			}
			Plugin.instance.v49CompatibilityEnabled = !targetAssembly.GetTypes().Any((Type type) => type.Name.Equals("SpikeRoofTrap", StringComparison.OrdinalIgnoreCase));
			if (Plugin.instance.v49CompatibilityEnabled)
			{
				Plugin.GetLogger().LogInfo((object)"Running in v49 compatibility mode.");
			}
		}

		protected override string GetModGUID()
		{
			return "snake.tech.LCHazardsOutside";
		}
	}
}
namespace LCHazardsOutside.Data
{
	public class EntranceContainer
	{
		public Vector3 MainEntrancePosition { get; set; }

		public List<Vector3> FireExitPositions { get; set; }

		public EntranceContainer(Vector3 mainEntrancePosition, List<Vector3> fireExitPositions)
		{
			//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)
			MainEntrancePosition = mainEntrancePosition;
			FireExitPositions = fireExitPositions;
			base..ctor();
		}

		public bool IsInitialized()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return MainEntrancePosition != Vector3.zero && FireExitPositions.All((Vector3 x) => x != Vector3.zero);
		}
	}
	internal class HazardCalculationContainer
	{
		public Random Random { get; set; }

		public List<GameObject> SpawnDenialPoints { get; set; }

		public SpawnableMapObject SpawnableMapObject { get; set; }

		public int MinSpawnRate { get; set; }

		public int MaxSpawnRate { get; set; }

		public bool NeedsSafetyZone { get; set; }

		public float SpawnRatioMultiplier { get; set; }

		public int LayerMask { get; set; }

		public HazardCalculationContainer(Random random, List<GameObject> spawnDenialPoints, SpawnableMapObject spawnableMapObject, int minSpawnRate, int maxSpawnRate, int layerMask)
		{
			Random = random;
			SpawnDenialPoints = spawnDenialPoints;
			SpawnableMapObject = spawnableMapObject;
			MinSpawnRate = minSpawnRate;
			MaxSpawnRate = maxSpawnRate;
			NeedsSafetyZone = false;
			SpawnRatioMultiplier = 1.5f;
			LayerMask = layerMask;
			base..ctor();
		}
	}
	public class HazardConfiguration
	{
		public bool Enabled { get; set; }

		public int MinSpawnRate { get; set; }

		public int MaxSpawnRate { get; set; }

		public Dictionary<string, MoonMinMax> MoonMap { get; set; }

		public SpawnStrategy SpawnStrategy { get; set; }

		public HazardConfiguration(bool enabled, int minSpawnRate, int maxSpawnRate, Dictionary<string, MoonMinMax> moonMap, SpawnStrategy spawnStrategy)
		{
			Enabled = enabled;
			MinSpawnRate = minSpawnRate;
			MaxSpawnRate = maxSpawnRate;
			MoonMap = moonMap;
			SpawnStrategy = spawnStrategy;
			base..ctor();
		}
	}
	public enum HazardType
	{
		Landmine,
		Turret,
		SpikeRoofTrap,
		CustomHazard
	}
	public class MoonMinMax
	{
		public int Min { get; set; }

		public int Max { get; set; }

		public MoonMinMax(int min, int max)
		{
			Min = min;
			Max = max;
			base..ctor();
		}
	}
	public record struct SpawnPositionData
	{
		public Vector3 CenterPosition { get; set; }

		public float SpawnRadius { get; set; }

		public SpawnPositionData(Vector3 centerPosition, float spawnRadius)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			this = default(SpawnPositionData);
			CenterPosition = centerPosition;
			SpawnRadius = spawnRadius;
		}

		[CompilerGenerated]
		private readonly bool PrintMembers(StringBuilder builder)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			builder.Append("CenterPosition = ");
			Vector3 centerPosition = CenterPosition;
			builder.Append(((object)(Vector3)(ref centerPosition)).ToString());
			builder.Append(", SpawnRadius = ");
			builder.Append(SpawnRadius.ToString());
			return true;
		}
	}
	public enum SpawnStrategyType
	{
		MainAndFireExit,
		MainEntranceOnly,
		FireExitsOnly
	}
	internal enum VanillaMoon
	{
		experimentation,
		assurance,
		offense,
		vow,
		march,
		rend,
		dine,
		titan,
		adamance,
		embrion,
		artifice,
		liquidation
	}
}
namespace LCHazardsOutside.Abstract
{
	internal abstract class AbstractCompatibilityHandler
	{
		protected abstract void DoApply();

		protected abstract string GetModGUID();

		private bool IsEnabled()
		{
			return Chainloader.PluginInfos.ContainsKey(GetModGUID());
		}

		public void Apply()
		{
			if (IsEnabled())
			{
				try
				{
					DoApply();
				}
				catch (Exception arg)
				{
					Plugin.GetLogger().LogError((object)$"There was an error in patching {GetModGUID()}. Skipping... \n {arg}\n");
				}
			}
		}

		protected void LogApply()
		{
			Plugin.GetLogger().LogInfo((object)("Applying compatibility fixes for " + GetModGUID() + "."));
		}

		protected Assembly GetTargetAssembly(string assemblyName)
		{
			return AccessTools.AllAssemblies().FirstOrDefault((Assembly assembly) => assembly.GetName().Name.Equals(assemblyName, StringComparison.OrdinalIgnoreCase));
		}
	}
	public abstract class SpawnStrategy
	{
		public abstract List<SpawnPositionData> CalculateCenterPositions(Vector3 shipLandPosition, Vector3 mainEntrancePosition, List<Vector3> pointsOfInterest, float spawnRadiusMultiplier);

		protected SpawnPositionData CalculateCenterWithSpawnRadius(Vector3 shipLandPosition, Vector3 targetPosition, float spawnRadiusMultiplier)
		{
			//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_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: 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)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = (shipLandPosition + targetPosition) / 2f;
			float spawnRadius = Vector3.Distance(targetPosition, val) * spawnRadiusMultiplier;
			val.y = Mathf.Max(shipLandPosition.y, targetPosition.y);
			return new SpawnPositionData(val, spawnRadius);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}

BepInEx/plugins/americanompany/LethalBestiary.dll

Decompiled 2 years ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using GameNetcodeStuff;
using LethalBestiary.Modules;
using LethalBestiary.NetcodePatcher;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using On;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("")]
[assembly: AssemblyCompany("Xilef992")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Lightweight version for Lethal Lib for registering new enemies!")]
[assembly: AssemblyFileVersion("0.0.0.0")]
[assembly: AssemblyInformationalVersion("0.0.0-dev.5+1066fcad873f53ff493f6e79e46189f3bc6bf919")]
[assembly: AssemblyProduct("LethalBestiary")]
[assembly: AssemblyTitle("LethalBestiary")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/FelixAllard/Xilef-LethalBestiary-LC")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalBestiary
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "LethalBestiary";

		public const string PLUGIN_NAME = "LethalBestiary";

		public const string PLUGIN_VERSION = "1.0.0";
	}
	[BepInPlugin("Xilef.LethalBestiary", "LethalBestiary", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGUID = "Xilef.LethalBestiary";

		public const string ModName = "LethalBestiary";

		public const string ModVersion = "1.0.0";

		public static AssetBundle MainAssets;

		public static ManualLogSource logger;

		public static ConfigFile config;

		public static Plugin Instance;

		public static ConfigEntry<bool> extendedLogging;

		private void Awake()
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			config = ((BaseUnityPlugin)this).Config;
			logger = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LethalBestiary Is loading ...");
			extendedLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ExtendedLogging", false, "Enable extended logging");
			new ILHook((MethodBase)typeof(StackTrace).GetMethod("AddFrames", BindingFlags.Instance | BindingFlags.NonPublic), new Manipulator(IlHook));
			Enemies.Init();
			Utilities.Init();
			NetworkPrefabs.Init();
			Utilities.Init();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LethalBestiary Is Loaded");
		}

		private void IlHook(ILContext il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			try
			{
				ILCursor val = new ILCursor(il);
				val.GotoNext(new Func<Instruction, bool>[1]
				{
					(Instruction x) => ILPatternMatchingExt.MatchCallvirt(x, (MethodBase)typeof(StackFrame).GetMethod("GetFileLineNumber", BindingFlags.Instance | BindingFlags.Public))
				});
				val.RemoveRange(2);
				val.EmitDelegate<Func<StackFrame, string>>((Func<StackFrame, string>)GetLineOrIL);
			}
			catch (Exception)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"ILHook already applied! LethalBestiary is skipping Method Patching!");
			}
		}

		private static string GetLineOrIL(StackFrame instance)
		{
			int fileLineNumber = instance.GetFileLineNumber();
			if (fileLineNumber == -1 || fileLineNumber == 0)
			{
				return "IL_" + instance.GetILOffset().ToString("X4");
			}
			return fileLineNumber.ToString();
		}
	}
}
namespace LethalBestiary.Modules
{
	public class Enemies
	{
		public struct EnemyAssetInfo
		{
			public EnemyType EnemyAsset;

			public TerminalKeyword keyword;
		}

		public enum SpawnType
		{
			Default,
			Daytime,
			Outside
		}

		public class SpawnableEnemy
		{
			public EnemyType enemy;

			public SpawnType spawnType;

			public TerminalNode terminalNode;

			public TerminalKeyword infoKeyword;

			public string modName;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public string[] spawnLevelOverrides;

			public Dictionary<string, int> customLevelRarities = new Dictionary<string, int>();

			public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>();

			public SpawnableEnemy(EnemyType enemy, int rarity, Levels.LevelTypes spawnLevels, SpawnType spawnType, string[] spawnLevelOverrides = null)
			{
				this.enemy = enemy;
				this.spawnLevels = spawnLevels;
				this.spawnType = spawnType;
				if (spawnLevelOverrides != null)
				{
					foreach (string levelName in spawnLevelOverrides)
					{
						customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(levelName), rarity);
					}
				}
				if (spawnLevels == Levels.LevelTypes.None)
				{
					return;
				}
				foreach (Levels.LevelTypes value in Enum.GetValues(typeof(Levels.LevelTypes)))
				{
					if (spawnLevels.HasFlag(value))
					{
						levelRarities.Add(value, rarity);
					}
				}
			}

			public SpawnableEnemy(EnemyType enemy, SpawnType spawnType, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null)
			{
				this.enemy = enemy;
				this.spawnType = spawnType;
				if (levelRarities != null)
				{
					this.levelRarities = levelRarities;
				}
				if (customLevelRarities != null)
				{
					this.customLevelRarities = Levels.Compatibility.LLLifyLevelRarityDictionary(customLevelRarities);
				}
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__RegisterLevelEnemies;

			public static hook_Start <1>__Terminal_Start;

			public static hook_Start <2>__QuickMenuManager_Start;

			public static hook_Start <3>__RegisterLevelEnemiesforLLL_RoundManager_Start;

			public static hook_Start <4>__RegisterLevelEnemiesforLE_Terminal_Start;
		}

		private static List<SelectableLevel> levelsAlreadyAddedTo = new List<SelectableLevel>();

		private static bool addedToDebug = false;

		public static Terminal terminal;

		public static List<EnemyAssetInfo> enemyAssetInfos = new List<EnemyAssetInfo>();

		public static List<SpawnableEnemy> spawnableEnemies = new List<SpawnableEnemy>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			object obj = <>O.<0>__RegisterLevelEnemies;
			if (obj == null)
			{
				hook_Awake val = RegisterLevelEnemies;
				<>O.<0>__RegisterLevelEnemies = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__Terminal_Start;
			if (obj2 == null)
			{
				hook_Start val2 = Terminal_Start;
				<>O.<1>__Terminal_Start = val2;
				obj2 = (object)val2;
			}
			Terminal.Start += (hook_Start)obj2;
			object obj3 = <>O.<2>__QuickMenuManager_Start;
			if (obj3 == null)
			{
				hook_Start val3 = QuickMenuManager_Start;
				<>O.<2>__QuickMenuManager_Start = val3;
				obj3 = (object)val3;
			}
			QuickMenuManager.Start += (hook_Start)obj3;
		}

		private static void QuickMenuManager_Start(orig_Start orig, QuickMenuManager self)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			if (addedToDebug)
			{
				orig.Invoke(self);
				return;
			}
			SelectableLevel testAllEnemiesLevel = self.testAllEnemiesLevel;
			List<SpawnableEnemyWithRarity> enemies = testAllEnemiesLevel.Enemies;
			List<SpawnableEnemyWithRarity> daytimeEnemies = testAllEnemiesLevel.DaytimeEnemies;
			List<SpawnableEnemyWithRarity> outsideEnemies = testAllEnemiesLevel.OutsideEnemies;
			foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
			{
				if (enemies.All((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
				{
					continue;
				}
				SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity
				{
					enemyType = spawnableEnemy.enemy,
					rarity = spawnableEnemy.rarity
				};
				switch (spawnableEnemy.spawnType)
				{
				case SpawnType.Default:
					if (!enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
					{
						enemies.Add(item);
					}
					break;
				case SpawnType.Daytime:
					if (!daytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
					{
						daytimeEnemies.Add(item);
					}
					break;
				case SpawnType.Outside:
					if (!outsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
					{
						outsideEnemies.Add(item);
					}
					break;
				}
				if (Plugin.extendedLogging.Value)
				{
					Plugin.logger.LogInfo((object)$"Added {spawnableEnemy.enemy.enemyName} to DebugList [{spawnableEnemy.spawnType}]");
				}
			}
			addedToDebug = true;
			orig.Invoke(self);
		}

		private static void Terminal_Start(orig_Start orig, Terminal self)
		{
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Expected O, but got Unknown
			terminal = self;
			TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			List<string> list = new List<string>();
			foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
			{
				if (list.Contains(spawnableEnemy.enemy.enemyName))
				{
					Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added"));
					continue;
				}
				if ((Object)(object)spawnableEnemy.terminalNode == (Object)null)
				{
					spawnableEnemy.terminalNode = ScriptableObject.CreateInstance<TerminalNode>();
					spawnableEnemy.terminalNode.displayText = spawnableEnemy.enemy.enemyName + "\n\nDanger level: Unknown\n\n[No information about this creature was found.]\n\n";
					spawnableEnemy.terminalNode.clearPreviousText = true;
					spawnableEnemy.terminalNode.maxCharactersToType = 35;
					spawnableEnemy.terminalNode.creatureName = spawnableEnemy.enemy.enemyName;
				}
				if (self.enemyFiles.Any((TerminalNode x) => x.creatureName == spawnableEnemy.terminalNode.creatureName))
				{
					Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added"));
					continue;
				}
				TerminalKeyword keyword2 = (((Object)(object)spawnableEnemy.infoKeyword != (Object)null) ? spawnableEnemy.infoKeyword : TerminalUtils.CreateTerminalKeyword(spawnableEnemy.terminalNode.creatureName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val));
				keyword2.defaultVerb = val;
				List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList();
				if (!list2.Any((TerminalKeyword x) => x.word == keyword2.word))
				{
					list2.Add(keyword2);
					self.terminalNodes.allKeywords = list2.ToArray();
				}
				List<CompatibleNoun> list3 = val.compatibleNouns.ToList();
				if (!list3.Any((CompatibleNoun x) => x.noun.word == keyword2.word))
				{
					list3.Add(new CompatibleNoun
					{
						noun = keyword2,
						result = spawnableEnemy.terminalNode
					});
				}
				val.compatibleNouns = list3.ToArray();
				spawnableEnemy.terminalNode.creatureFileID = self.enemyFiles.Count;
				self.enemyFiles.Add(spawnableEnemy.terminalNode);
				ScanNodeProperties[] componentsInChildren = spawnableEnemy.enemy.enemyPrefab.GetComponentsInChildren<ScanNodeProperties>();
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					componentsInChildren[i].creatureScanID = spawnableEnemy.terminalNode.creatureFileID;
				}
				EnemyAssetInfo enemyAssetInfo = default(EnemyAssetInfo);
				enemyAssetInfo.EnemyAsset = spawnableEnemy.enemy;
				enemyAssetInfo.keyword = keyword2;
				EnemyAssetInfo item = enemyAssetInfo;
				enemyAssetInfos.Add(item);
			}
			orig.Invoke(self);
		}

		private static void RegisterLevelEnemies(orig_Awake orig, StartOfRound self)
		{
			//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_0049: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			orig.Invoke(self);
			RegisterLethalLibEnemiesForAllLevels();
			if (Chainloader.PluginInfos.ContainsKey("imabatby.lethallevelloader") || Chainloader.PluginInfos.ContainsKey("iambatby.lethallevelloader"))
			{
				object obj = <>O.<3>__RegisterLevelEnemiesforLLL_RoundManager_Start;
				if (obj == null)
				{
					hook_Start val = RegisterLevelEnemiesforLLL_RoundManager_Start;
					<>O.<3>__RegisterLevelEnemiesforLLL_RoundManager_Start = val;
					obj = (object)val;
				}
				RoundManager.Start += (hook_Start)obj;
			}
			if (Chainloader.PluginInfos.ContainsKey("LethalExpansion"))
			{
				object obj2 = <>O.<4>__RegisterLevelEnemiesforLE_Terminal_Start;
				if (obj2 == null)
				{
					hook_Start val2 = RegisterLevelEnemiesforLE_Terminal_Start;
					<>O.<4>__RegisterLevelEnemiesforLE_Terminal_Start = val2;
					obj2 = (object)val2;
				}
				Terminal.Start += (hook_Start)obj2;
			}
		}

		private static void RegisterLevelEnemiesforLLL_RoundManager_Start(orig_Start orig, RoundManager self)
		{
			orig.Invoke(self);
			RegisterLethalLibEnemiesForAllLevels();
		}

		private static void RegisterLevelEnemiesforLE_Terminal_Start(orig_Start orig, Terminal self)
		{
			orig.Invoke(self);
			RegisterLethalLibEnemiesForAllLevels();
		}

		private static void RegisterLethalLibEnemiesForAllLevels()
		{
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				if (levelsAlreadyAddedTo.Contains(val))
				{
					continue;
				}
				foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
				{
					AddEnemyToLevel(spawnableEnemy, val);
				}
				levelsAlreadyAddedTo.Add(val);
			}
		}

		private static void AddEnemyToLevel(SpawnableEnemy spawnableEnemy, SelectableLevel level)
		{
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Expected O, but got Unknown
			SpawnableEnemy spawnableEnemy2 = spawnableEnemy;
			string text = ((Object)level).name;
			bool flag = spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.All) || (spawnableEnemy2.customLevelRarities != null && spawnableEnemy2.customLevelRarities.ContainsKey(text));
			if (spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), text))
			{
				flag = true;
			}
			Levels.LevelTypes levelTypes = Levels.LevelTypes.None;
			bool flag2 = false;
			if (Enum.IsDefined(typeof(Levels.LevelTypes), text))
			{
				levelTypes = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), text);
				flag2 = true;
			}
			else
			{
				text = Levels.Compatibility.GetLLLNameOfLevel(text);
			}
			if (!(flag2 || flag))
			{
				return;
			}
			Levels.LevelTypes key = (flag ? Levels.LevelTypes.All : levelTypes);
			if (!flag && !spawnableEnemy2.levelRarities.ContainsKey(key))
			{
				return;
			}
			int num = 0;
			if (flag2 && spawnableEnemy2.levelRarities.ContainsKey(levelTypes))
			{
				num = spawnableEnemy2.levelRarities[levelTypes];
			}
			else if (!flag2 && spawnableEnemy2.customLevelRarities != null && spawnableEnemy2.customLevelRarities.ContainsKey(text))
			{
				num = spawnableEnemy2.customLevelRarities[text];
			}
			else if (!flag2 && spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.Modded))
			{
				num = spawnableEnemy2.levelRarities[Levels.LevelTypes.Modded];
			}
			else if (spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.All))
			{
				num = spawnableEnemy2.levelRarities[Levels.LevelTypes.All];
			}
			SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity
			{
				enemyType = spawnableEnemy2.enemy,
				rarity = num
			};
			switch (spawnableEnemy2.spawnType)
			{
			case SpawnType.Default:
				if (!level.Enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy2.enemy))
				{
					level.Enemies.Add(item);
					if (Plugin.extendedLogging.Value)
					{
						Plugin.logger.LogInfo((object)$"To {text} added {((Object)spawnableEnemy2.enemy).name} with weight {num} and SpawnType [Default]");
					}
				}
				break;
			case SpawnType.Daytime:
				if (!level.DaytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy2.enemy))
				{
					level.DaytimeEnemies.Add(item);
					if (Plugin.extendedLogging.Value)
					{
						Plugin.logger.LogInfo((object)$"To {text} added {((Object)spawnableEnemy2.enemy).name} with weight {num} andSpawnType [Daytime]");
					}
				}
				break;
			case SpawnType.Outside:
				if (!level.OutsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy2.enemy))
				{
					level.OutsideEnemies.Add(item);
					if (Plugin.extendedLogging.Value)
					{
						Plugin.logger.LogInfo((object)$"To {text} added {((Object)spawnableEnemy2.enemy).name} with weight {num} and SpawnType [Outside]");
					}
				}
				break;
			}
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			RegisterEnemy(enemy, rarity, levelFlags, spawnType, null, infoNode, infoKeyword);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyType enemy2 = enemy;
			EnemyNullCheck(enemy2);
			SpawnableEnemy spawnableEnemy = spawnableEnemies.FirstOrDefault((SpawnableEnemy x) => (Object)(object)x.enemy == (Object)(object)enemy2 && x.spawnType == spawnType);
			if (spawnableEnemy != null)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					spawnableEnemy.levelRarities.Add(levelFlags, rarity);
				}
				if (spawnLevelOverrides != null)
				{
					foreach (string levelName in spawnLevelOverrides)
					{
						spawnableEnemy.customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(levelName), rarity);
					}
				}
			}
			else
			{
				spawnableEnemy = new SpawnableEnemy(enemy2, rarity, levelFlags, spawnType, spawnLevelOverrides);
				spawnableEnemy.terminalNode = infoNode;
				spawnableEnemy.infoKeyword = infoKeyword;
				FinalizeRegisterEnemy(spawnableEnemy);
			}
		}

		public static void RegisterEnemy(EnemyType enemy, SpawnType spawnType, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyType enemy2 = enemy;
			EnemyNullCheck(enemy2);
			SpawnableEnemy spawnableEnemy = spawnableEnemies.FirstOrDefault((SpawnableEnemy x) => (Object)(object)x.enemy == (Object)(object)enemy2 && x.spawnType == spawnType);
			if (spawnableEnemy != null)
			{
				if (levelRarities != null)
				{
					foreach (KeyValuePair<Levels.LevelTypes, int> levelRarity in levelRarities)
					{
						spawnableEnemy.levelRarities.Add(levelRarity.Key, levelRarity.Value);
					}
				}
				if (customLevelRarities == null)
				{
					return;
				}
				{
					foreach (KeyValuePair<string, int> customLevelRarity in customLevelRarities)
					{
						spawnableEnemy.customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(customLevelRarity.Key), customLevelRarity.Value);
					}
					return;
				}
			}
			spawnableEnemy = new SpawnableEnemy(enemy2, spawnType, levelRarities, customLevelRarities);
			spawnableEnemy.terminalNode = infoNode;
			spawnableEnemy.infoKeyword = infoKeyword;
			FinalizeRegisterEnemy(spawnableEnemy);
		}

		private static void FinalizeRegisterEnemy(SpawnableEnemy spawnableEnemy)
		{
			string name = Assembly.GetCallingAssembly().GetName().Name;
			spawnableEnemy.modName = name;
			if (spawnableEnemy.enemy.enemyPrefab == null)
			{
				throw new NullReferenceException("Cannot register enemy '" + spawnableEnemy.enemy.enemyName + "', because enemy.enemyPrefab is null!");
			}
			EnemyAICollisionDetect[] componentsInChildren = spawnableEnemy.enemy.enemyPrefab.GetComponentsInChildren<EnemyAICollisionDetect>();
			foreach (EnemyAICollisionDetect val in componentsInChildren)
			{
				if (val.mainScript == null)
				{
					Plugin.logger.LogWarning((object)("An Enemy AI Collision Detect Script on GameObject '" + ((Object)((Component)val).gameObject).name + "' of enemy '" + spawnableEnemy.enemy.enemyName + "' does not reference a 'Main Script', and could cause Null Reference Exceptions."));
				}
			}
			spawnableEnemies.Add(spawnableEnemy);
		}

		private static void EnemyNullCheck(EnemyType enemy)
		{
			if (enemy == null)
			{
				throw new ArgumentNullException("enemy", "The first argument of RegisterEnemy was null!");
			}
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyNullCheck(enemy);
			SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default));
			RegisterEnemy(enemy, rarity, levelFlags, spawnType, null, infoNode, infoKeyword);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyNullCheck(enemy);
			SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default));
			RegisterEnemy(enemy, rarity, levelFlags, spawnType, spawnLevelOverrides, infoNode, infoKeyword);
		}

		public static void RegisterEnemy(EnemyType enemy, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyNullCheck(enemy);
			SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default));
			RegisterEnemy(enemy, spawnType, levelRarities, customLevelRarities, infoNode, infoKeyword);
		}

		public static void RemoveEnemyFromLevels(EnemyType enemyType, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			EnemyType enemyType2 = enemyType;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				if (!Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					name = Levels.Compatibility.GetLLLNameOfLevel(name);
				}
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => Levels.Compatibility.GetLLLNameOfLevel(item).ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					List<SpawnableEnemyWithRarity> enemies = val.Enemies;
					List<SpawnableEnemyWithRarity> daytimeEnemies = val.DaytimeEnemies;
					List<SpawnableEnemyWithRarity> outsideEnemies = val.OutsideEnemies;
					enemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
					daytimeEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
					outsideEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
					if (Plugin.extendedLogging.Value)
					{
						Plugin.logger.LogInfo((object)("Removed Enemy " + ((Object)enemyType2).name + " from Level " + name));
					}
				}
			}
		}
	}
	public class Levels
	{
		[Flags]
		public enum LevelTypes
		{
			None = 1,
			ExperimentationLevel = 4,
			AssuranceLevel = 8,
			VowLevel = 0x10,
			OffenseLevel = 0x20,
			MarchLevel = 0x40,
			RendLevel = 0x80,
			DineLevel = 0x100,
			TitanLevel = 0x200,
			Vanilla = 0x3FC,
			Modded = 0x400,
			All = -1
		}

		internal static class Compatibility
		{
			private const string illegalCharacters = ".,?!@#$%^&*()_+-=';:'\"";

			private static string GetNumberlessPlanetName(string planetName)
			{
				if (planetName != null)
				{
					return new string(planetName.SkipWhile((char c) => !char.IsLetter(c)).ToArray());
				}
				return string.Empty;
			}

			private static string StripSpecialCharacters(string input)
			{
				string text = string.Empty;
				for (int i = 0; i < input.Length; i++)
				{
					char c = input[i];
					if ((!".,?!@#$%^&*()_+-=';:'\"".ToCharArray().Contains(c) && char.IsLetterOrDigit(c)) || c.ToString() == " ")
					{
						text += c;
					}
				}
				return text;
			}

			internal static string GetLLLNameOfLevel(string levelName)
			{
				string text = StripSpecialCharacters(GetNumberlessPlanetName(levelName));
				if (!text.EndsWith("Level"))
				{
					text += "Level";
				}
				return text;
			}

			internal static Dictionary<string, int> LLLifyLevelRarityDictionary(Dictionary<string, int> keyValuePairs)
			{
				Dictionary<string, int> dictionary = new Dictionary<string, int>();
				List<string> list = keyValuePairs.Keys.ToList();
				List<int> list2 = keyValuePairs.Values.ToList();
				for (int i = 0; i < keyValuePairs.Count; i++)
				{
					dictionary.Add(GetLLLNameOfLevel(list[i]), list2[i]);
				}
				return dictionary;
			}
		}
	}
	public class NetworkPrefabs
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Start <0>__GameNetworkManager_Start;
		}

		private static List<GameObject> _networkPrefabs = new List<GameObject>();

		internal static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			object obj = <>O.<0>__GameNetworkManager_Start;
			if (obj == null)
			{
				hook_Start val = GameNetworkManager_Start;
				<>O.<0>__GameNetworkManager_Start = val;
				obj = (object)val;
			}
			GameNetworkManager.Start += (hook_Start)obj;
		}

		public static void RegisterNetworkPrefab(GameObject prefab)
		{
			if (prefab == null)
			{
				throw new ArgumentNullException("prefab", "The given argument for RegisterNetworkPrefab is null!");
			}
			if (!_networkPrefabs.Contains(prefab))
			{
				_networkPrefabs.Add(prefab);
			}
		}

		private static void GameNetworkManager_Start(orig_Start orig, GameNetworkManager self)
		{
			orig.Invoke(self);
			Debug.Log((object)"Registering All Prefabs!");
			foreach (GameObject networkPrefab in _networkPrefabs)
			{
				if (!NetworkManager.Singleton.NetworkConfig.Prefabs.Contains(networkPrefab))
				{
					NetworkManager.Singleton.AddNetworkPrefab(networkPrefab);
				}
			}
		}
	}
	public class PrefabUtils
	{
		internal static Lazy<GameObject> _prefabParent;

		internal static GameObject prefabParent => _prefabParent.Value;

		static PrefabUtils()
		{
			_prefabParent = new Lazy<GameObject>((Func<GameObject>)delegate
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Expected O, but got Unknown
				GameObject val = new GameObject("LethalLibGeneratedPrefabs")
				{
					hideFlags = (HideFlags)61
				};
				val.SetActive(false);
				return val;
			});
		}

		public static GameObject ClonePrefab(GameObject prefabToClone, string newName = null)
		{
			GameObject val = Object.Instantiate<GameObject>(prefabToClone, prefabParent.transform);
			((Object)val).hideFlags = (HideFlags)61;
			if (newName != null)
			{
				((Object)val).name = newName;
			}
			else
			{
				((Object)val).name = ((Object)prefabToClone).name;
			}
			return val;
		}

		public static GameObject CreatePrefab(string name)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			GameObject val = new GameObject(name)
			{
				hideFlags = (HideFlags)61
			};
			val.transform.SetParent(prefabParent.transform);
			return val;
		}
	}
	public class TerminalUtils
	{
		public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, CompatibleNoun[] compatibleNouns = null, TerminalNode specialKeywordResult = null, TerminalKeyword defaultVerb = null, bool accessTerminalObjects = false)
		{
			TerminalKeyword obj = ScriptableObject.CreateInstance<TerminalKeyword>();
			((Object)obj).name = word;
			obj.word = word;
			obj.isVerb = isVerb;
			obj.compatibleNouns = compatibleNouns;
			obj.specialKeywordResult = specialKeywordResult;
			obj.defaultVerb = defaultVerb;
			obj.accessTerminalObjects = accessTerminalObjects;
			return obj;
		}
	}
	public class Utilities
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Start <0>__StartOfRound_Start;

			public static hook_Start <1>__MenuManager_Start;
		}

		public static List<GameObject> prefabsToFix = new List<GameObject>();

		public static List<GameObject> fixedPrefabs = new List<GameObject>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Start;
			if (obj == null)
			{
				hook_Start val = StartOfRound_Start;
				<>O.<0>__StartOfRound_Start = val;
				obj = (object)val;
			}
			StartOfRound.Start += (hook_Start)obj;
			object obj2 = <>O.<1>__MenuManager_Start;
			if (obj2 == null)
			{
				hook_Start val2 = MenuManager_Start;
				<>O.<1>__MenuManager_Start = val2;
				obj2 = (object)val2;
			}
			MenuManager.Start += (hook_Start)obj2;
		}

		private static void StartOfRound_Start(orig_Start orig, StartOfRound self)
		{
			AudioMixer diageticMixer = SoundManager.Instance.diageticMixer;
			if (Plugin.extendedLogging.Value)
			{
				Plugin.logger.LogInfo((object)("Diagetic mixer is " + ((Object)diageticMixer).name));
			}
			Plugin.logger.LogInfo((object)$"Found {prefabsToFix.Count} prefabs to fix");
			List<GameObject> list = new List<GameObject>();
			for (int num = prefabsToFix.Count - 1; num >= 0; num--)
			{
				GameObject val = prefabsToFix[num];
				AudioSource[] componentsInChildren = val.GetComponentsInChildren<AudioSource>();
				foreach (AudioSource val2 in componentsInChildren)
				{
					if ((Object)(object)val2.outputAudioMixerGroup == (Object)null || !(((Object)val2.outputAudioMixerGroup.audioMixer).name == "Diagetic"))
					{
						continue;
					}
					AudioMixerGroup val3 = diageticMixer.FindMatchingGroups(((Object)val2.outputAudioMixerGroup).name)[0];
					if ((Object)(object)val3 != (Object)null)
					{
						val2.outputAudioMixerGroup = val3;
						if (Plugin.extendedLogging.Value)
						{
							Plugin.logger.LogInfo((object)("Set mixer group for " + ((Object)val2).name + " in " + ((Object)val).name + " to Diagetic:" + ((Object)val3).name));
						}
						list.Add(val);
					}
				}
			}
			foreach (GameObject item in list)
			{
				prefabsToFix.Remove(item);
			}
			orig.Invoke(self);
		}

		private static void MenuManager_Start(orig_Start orig, MenuManager self)
		{
			orig.Invoke(self);
			if ((Object)(object)((Component)self).GetComponent<AudioSource>() == (Object)null)
			{
				return;
			}
			AudioMixer audioMixer = ((Component)self).GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer;
			List<GameObject> list = new List<GameObject>();
			for (int num = prefabsToFix.Count - 1; num >= 0; num--)
			{
				GameObject val = prefabsToFix[num];
				AudioSource[] componentsInChildren = val.GetComponentsInChildren<AudioSource>();
				foreach (AudioSource val2 in componentsInChildren)
				{
					if ((Object)(object)val2.outputAudioMixerGroup == (Object)null || !(((Object)val2.outputAudioMixerGroup.audioMixer).name == "NonDiagetic"))
					{
						continue;
					}
					AudioMixerGroup val3 = audioMixer.FindMatchingGroups(((Object)val2.outputAudioMixerGroup).name)[0];
					if ((Object)(object)val3 != (Object)null)
					{
						val2.outputAudioMixerGroup = val3;
						if (Plugin.extendedLogging.Value)
						{
							Plugin.logger.LogInfo((object)("Set mixer group for " + ((Object)val2).name + " in " + ((Object)val).name + " to NonDiagetic:" + ((Object)val3).name));
						}
						list.Add(val);
					}
				}
			}
			foreach (GameObject item in list)
			{
				prefabsToFix.Remove(item);
			}
		}

		public static void FixMixerGroups(GameObject prefab)
		{
			if (!fixedPrefabs.Contains(prefab))
			{
				fixedPrefabs.Add(prefab);
				prefabsToFix.Add(prefab);
			}
		}
	}
}
namespace LethalBestiary.Extras
{
	[CreateAssetMenu(menuName = "ScriptableObjects/DungeonDef")]
	public class DungeonDef : ScriptableObject
	{
		public DungeonFlow dungeonFlow;

		[Range(0f, 300f)]
		public int rarity;

		public AudioClip firstTimeDungeonAudio;
	}
	[CreateAssetMenu(menuName = "ScriptableObjects/DungeonGraphLine")]
	public class DungeonGraphLineDef : ScriptableObject
	{
		public GraphLine graphLine;
	}
	public static class ScriptableObjectExtension
	{
		public static T Clone<T>(this T scriptableObject) where T : ScriptableObject
		{
			if ((Object)(object)scriptableObject == (Object)null)
			{
				Debug.LogError((object)$"ScriptableObject was null. Returning default {typeof(T)} object.");
				return (T)(object)ScriptableObject.CreateInstance(typeof(T));
			}
			T val = Object.Instantiate<T>(scriptableObject);
			((Object)(object)val).name = ((Object)(object)scriptableObject).name;
			return val;
		}
	}
	[CreateAssetMenu(menuName = "ScriptableObjects/GameObjectChance")]
	public class GameObjectChanceDef : ScriptableObject
	{
		public GameObjectChance gameObjectChance;
	}
	[CreateAssetMenu(menuName = "ScriptableObjects/SpawnableMapObject")]
	public class SpawnableMapObjectDef : ScriptableObject
	{
		public SpawnableMapObject spawnableMapObject;
	}
	[CreateAssetMenu(menuName = "ScriptableObjects/SpawnableOutsideObject")]
	public class SpawnableOutsideObjectDef : ScriptableObject
	{
		public SpawnableOutsideObjectWithRarity spawnableMapObject;
	}
}
namespace LethalLib
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "LethalBestiary";

		public const string PLUGIN_NAME = "LethalBestiary";

		public const string PLUGIN_VERSION = "1.2.1";
	}
}
namespace LethalLib.EnemyHelper
{
	public static class FlashLightEnemyHelper
	{
		public static bool CheckIfEnemyFlashed(Vector3 EnemyPosition, float angle = 20f)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB[] allPlayerScripts = RoundManager.Instance.playersManager.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if (!val.HasLineOfSightToPosition(EnemyPosition, 45f, 60, -1f))
				{
					continue;
				}
				GrabbableObject[] itemSlots = val.ItemSlots;
				foreach (GrabbableObject val2 in itemSlots)
				{
					if ((Object)(object)val2 != (Object)null && (Object)(object)((Component)val2).gameObject.GetComponent<FlashlightItem>() != (Object)null && ((GrabbableObject)((Component)val2).gameObject.GetComponent<FlashlightItem>()).isBeingUsed && Vector3.Distance(((Component)val).transform.position, EnemyPosition) < 3f && val.LineOfSightToPositionAngle(EnemyPosition, 60, -1f) < 20f)
					{
						return true;
					}
				}
			}
			return false;
		}

		public static bool CheckIfEnemyFlashedByPlayer(Vector3 EnemyPosition, PlayerControllerB PlayerToCheck, float angle = 20f)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			if (PlayerToCheck.HasLineOfSightToPosition(EnemyPosition, 45f, 60, -1f))
			{
				GrabbableObject[] itemSlots = PlayerToCheck.ItemSlots;
				foreach (GrabbableObject val in itemSlots)
				{
					if ((Object)(object)val != (Object)null && (Object)(object)((Component)val).gameObject.GetComponent<FlashlightItem>() != (Object)null && ((GrabbableObject)((Component)val).gameObject.GetComponent<FlashlightItem>()).isBeingUsed && Vector3.Distance(((Component)PlayerToCheck).transform.position, EnemyPosition) < 3f && PlayerToCheck.LineOfSightToPositionAngle(EnemyPosition, 60, -1f) < angle)
					{
						return true;
					}
				}
			}
			return false;
		}

		public static bool CheckIfPlayerHasFlashlight(PlayerControllerB PlayerToCheck, bool CheckIfOpened)
		{
			GrabbableObject[] itemSlots = PlayerToCheck.ItemSlots;
			foreach (GrabbableObject val in itemSlots)
			{
				if ((Object)(object)val != (Object)null && (Object)(object)((Component)val).gameObject.GetComponent<FlashlightItem>() != (Object)null && CheckIfOpened && ((GrabbableObject)((Component)val).gameObject.GetComponent<FlashlightItem>()).isBeingUsed)
				{
					return true;
				}
			}
			return false;
		}
	}
	public static class TeleportEnemy
	{
		public static void FindValidTeleportPositionRadius(Vector3 position, float MinRadius, float MaxRadius, bool MustHavePath = true)
		{
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace LethalBestiary.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}

BepInEx/plugins/americanompany/LethalLib.dll

Decompiled 2 years ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using LethalLib.Extras;
using LethalLib.Modules;
using LethalLib.NetcodePatcher;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using On;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: AssemblyCompany("Evaisa")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Content-addition API for Lethal Company")]
[assembly: AssemblyFileVersion("0.16.1.0")]
[assembly: AssemblyInformationalVersion("0.16.1+1544246572e61ff167c447c6c4ceee7f9c8c05d5")]
[assembly: AssemblyProduct("LethalLib")]
[assembly: AssemblyTitle("LethalLib")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/EvaisaDev/LethalLib")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalLib
{
	[BepInPlugin("evaisa.lethallib", "LethalLib", "0.16.1")]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGUID = "evaisa.lethallib";

		public const string ModName = "LethalLib";

		public const string ModVersion = "0.16.1";

		public static AssetBundle MainAssets;

		public static ManualLogSource logger;

		public static ConfigFile config;

		public static Plugin Instance;

		public static ConfigEntry<bool> extendedLogging;

		private void Awake()
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			config = ((BaseUnityPlugin)this).Config;
			logger = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LethalLib loaded!!");
			extendedLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ExtendedLogging", false, "Enable extended logging");
			MainAssets = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "lethallib"));
			new ILHook((MethodBase)typeof(StackTrace).GetMethod("AddFrames", BindingFlags.Instance | BindingFlags.NonPublic), new Manipulator(IlHook));
			Enemies.Init();
			Items.Init();
			Unlockables.Init();
			MapObjects.Init();
			Dungeon.Init();
			Weathers.Init();
			Player.Init();
			Utilities.Init();
			NetworkPrefabs.Init();
		}

		private void IlHook(ILContext il)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			ILCursor val = new ILCursor(il);
			MethodInfo getFileLineNumberMethod = typeof(StackFrame).GetMethod("GetFileLineNumber", BindingFlags.Instance | BindingFlags.Public);
			if (val.TryGotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchCallvirt(x, (MethodBase)getFileLineNumberMethod)
			}))
			{
				val.RemoveRange(2);
				val.EmitDelegate<Func<StackFrame, string>>((Func<StackFrame, string>)GetLineOrIL);
			}
		}

		private static string GetLineOrIL(StackFrame instance)
		{
			int fileLineNumber = instance.GetFileLineNumber();
			if (fileLineNumber == -1 || fileLineNumber == 0)
			{
				return "IL_" + instance.GetILOffset().ToString("X4");
			}
			return fileLineNumber.ToString();
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "LethalLib";

		public const string PLUGIN_NAME = "LethalLib";

		public const string PLUGIN_VERSION = "0.16.1";
	}
}
namespace LethalLib.Modules
{
	public class ContentLoader
	{
		public class CustomContent
		{
			private string id = "";

			public string ID => id;

			public CustomContent(string id)
			{
				this.id = id;
			}
		}

		public class CustomItem : CustomContent
		{
			public Action<Item> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal Item item;

			public Item Item => item;

			public CustomItem(string id, string contentPath, Action<Item> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
			}
		}

		public class ShopItem : CustomItem
		{
			public int initPrice;

			public string buyNode1Path;

			public string buyNode2Path;

			public string itemInfoPath;

			public void RemoveFromShop()
			{
				Items.RemoveShopItem(base.Item);
			}

			public void SetPrice(int price)
			{
				Items.UpdateShopItemPrice(base.Item, price);
			}

			public ShopItem(string id, string contentPath, int price = 0, string buyNode1Path = null, string buyNode2Path = null, string itemInfoPath = null, Action<Item> registryCallback = null)
				: base(id, contentPath, registryCallback)
			{
				initPrice = price;
				this.buyNode1Path = buyNode1Path;
				this.buyNode2Path = buyNode2Path;
				this.itemInfoPath = itemInfoPath;
			}
		}

		public class ScrapItem : CustomItem
		{
			public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>();

			public Dictionary<string, int> customLevelRarities = new Dictionary<string, int>();

			public int Rarity => 0;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags)
			{
				Items.RemoveScrapFromLevels(base.Item, levelFlags);
			}

			public ScrapItem(string id, string contentPath, int rarity, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Action<Item> registryCallback = null)
				: base(id, contentPath, registryCallback)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					levelRarities.Add(levelFlags, rarity);
				}
				else if (levelOverrides != null)
				{
					foreach (string key in levelOverrides)
					{
						customLevelRarities.Add(key, rarity);
					}
				}
			}

			public ScrapItem(string id, string contentPath, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, Action<Item> registryCallback = null)
				: base(id, contentPath, registryCallback)
			{
				if (levelRarities != null)
				{
					this.levelRarities = levelRarities;
				}
				if (customLevelRarities != null)
				{
					this.customLevelRarities = customLevelRarities;
				}
			}
		}

		public class Unlockable : CustomContent
		{
			public Action<UnlockableItem> registryCallback = delegate
			{
			};

			internal UnlockableItem unlockable;

			public string contentPath = "";

			public int initPrice;

			public string buyNode1Path;

			public string buyNode2Path;

			public string itemInfoPath;

			public StoreType storeType;

			public UnlockableItem UnlockableItem => unlockable;

			public void RemoveFromShop()
			{
				Unlockables.DisableUnlockable(UnlockableItem);
			}

			public void SetPrice(int price)
			{
				Unlockables.UpdateUnlockablePrice(UnlockableItem, price);
			}

			public Unlockable(string id, string contentPath, int price = 0, string buyNode1Path = null, string buyNode2Path = null, string itemInfoPath = null, StoreType storeType = StoreType.None, Action<UnlockableItem> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				initPrice = price;
				this.buyNode1Path = buyNode1Path;
				this.buyNode2Path = buyNode2Path;
				this.itemInfoPath = itemInfoPath;
				this.storeType = storeType;
			}
		}

		public class CustomEnemy : CustomContent
		{
			public Action<EnemyType> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal EnemyType enemy;

			public string infoNodePath;

			public string infoKeywordPath;

			public int rarity;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides;

			public Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1);

			public EnemyType Enemy => enemy;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags)
			{
				Enemies.RemoveEnemyFromLevels(Enemy, levelFlags);
			}

			public CustomEnemy(string id, string contentPath, int rarity = 0, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1), string[] levelOverrides = null, string infoNodePath = null, string infoKeywordPath = null, Action<EnemyType> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				this.infoNodePath = infoNodePath;
				this.infoKeywordPath = infoKeywordPath;
				this.rarity = rarity;
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnType = spawnType;
			}
		}

		public class MapHazard : CustomContent
		{
			public Action<SpawnableMapObjectDef> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal SpawnableMapObjectDef hazard;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides;

			public SpawnableMapObjectDef Hazard => hazard;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
			{
				MapObjects.RemoveMapObject(Hazard, levelFlags, levelOverrides);
			}

			public MapHazard(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableMapObjectDef> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnRateFunction = spawnRateFunction;
			}
		}

		public class OutsideObject : CustomContent
		{
			public Action<SpawnableOutsideObjectDef> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal SpawnableOutsideObjectDef mapObject;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides;

			public SpawnableOutsideObjectDef MapObject => mapObject;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
			{
				MapObjects.RemoveOutsideObject(MapObject, levelFlags, levelOverrides);
			}

			public OutsideObject(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableOutsideObjectDef> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnRateFunction = spawnRateFunction;
			}
		}

		public PluginInfo modInfo;

		private AssetBundle modBundle;

		public Action<CustomContent, GameObject> prefabCallback = delegate
		{
		};

		public Dictionary<string, CustomContent> LoadedContent { get; } = new Dictionary<string, CustomContent>();


		public string modName => modInfo.Metadata.Name;

		public string modVersion => modInfo.Metadata.Version.ToString();

		public string modGUID => modInfo.Metadata.GUID;

		public ContentLoader(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null)
		{
			this.modInfo = modInfo;
			this.modBundle = modBundle;
			if (prefabCallback != null)
			{
				this.prefabCallback = prefabCallback;
			}
		}

		public ContentLoader Create(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null)
		{
			return new ContentLoader(modInfo, modBundle, prefabCallback);
		}

		public void Register(CustomContent content)
		{
			if (LoadedContent.ContainsKey(content.ID))
			{
				Debug.LogError((object)("[LethalLib] " + modName + " tried to register content with ID " + content.ID + " but it already exists!"));
				return;
			}
			if (content is CustomItem customItem)
			{
				Item val = (customItem.item = modBundle.LoadAsset<Item>(customItem.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
				Utilities.FixMixerGroups(val.spawnPrefab);
				prefabCallback(customItem, val.spawnPrefab);
				customItem.registryCallback(val);
				if (content is ShopItem shopItem)
				{
					TerminalNode buyNode = null;
					TerminalNode buyNode2 = null;
					TerminalNode itemInfo = null;
					if (shopItem.buyNode1Path != null)
					{
						buyNode = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode1Path);
					}
					if (shopItem.buyNode2Path != null)
					{
						buyNode2 = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode2Path);
					}
					if (shopItem.itemInfoPath != null)
					{
						itemInfo = modBundle.LoadAsset<TerminalNode>(shopItem.itemInfoPath);
					}
					Items.RegisterShopItem(val, buyNode, buyNode2, itemInfo, shopItem.initPrice);
				}
				else if (content is ScrapItem scrapItem)
				{
					Items.RegisterScrap(val, scrapItem.levelRarities, scrapItem.customLevelRarities);
				}
				else
				{
					Items.RegisterItem(val);
				}
			}
			else if (content is Unlockable unlockable)
			{
				UnlockableItemDef unlockableItemDef = modBundle.LoadAsset<UnlockableItemDef>(unlockable.contentPath);
				if ((Object)(object)unlockableItemDef.unlockable.prefabObject != (Object)null)
				{
					NetworkPrefabs.RegisterNetworkPrefab(unlockableItemDef.unlockable.prefabObject);
					prefabCallback(content, unlockableItemDef.unlockable.prefabObject);
					Utilities.FixMixerGroups(unlockableItemDef.unlockable.prefabObject);
				}
				unlockable.unlockable = unlockableItemDef.unlockable;
				unlockable.registryCallback(unlockableItemDef.unlockable);
				TerminalNode buyNode3 = null;
				TerminalNode buyNode4 = null;
				TerminalNode itemInfo2 = null;
				if (unlockable.buyNode1Path != null)
				{
					buyNode3 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode1Path);
				}
				if (unlockable.buyNode2Path != null)
				{
					buyNode4 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode2Path);
				}
				if (unlockable.itemInfoPath != null)
				{
					itemInfo2 = modBundle.LoadAsset<TerminalNode>(unlockable.itemInfoPath);
				}
				Unlockables.RegisterUnlockable(unlockableItemDef, unlockable.storeType, buyNode3, buyNode4, itemInfo2, unlockable.initPrice);
			}
			else if (content is CustomEnemy customEnemy)
			{
				EnemyType val2 = modBundle.LoadAsset<EnemyType>(customEnemy.contentPath);
				NetworkPrefabs.RegisterNetworkPrefab(val2.enemyPrefab);
				Utilities.FixMixerGroups(val2.enemyPrefab);
				customEnemy.enemy = val2;
				prefabCallback(content, val2.enemyPrefab);
				customEnemy.registryCallback(val2);
				TerminalNode infoNode = null;
				TerminalKeyword infoKeyword = null;
				if (customEnemy.infoNodePath != null)
				{
					infoNode = modBundle.LoadAsset<TerminalNode>(customEnemy.infoNodePath);
				}
				if (customEnemy.infoKeywordPath != null)
				{
					infoKeyword = modBundle.LoadAsset<TerminalKeyword>(customEnemy.infoKeywordPath);
				}
				if (customEnemy.spawnType == (Enemies.SpawnType)(-1))
				{
					Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.levelOverrides, infoNode, infoKeyword);
				}
				else
				{
					Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.spawnType, customEnemy.levelOverrides, infoNode, infoKeyword);
				}
			}
			else if (content is MapHazard mapHazard)
			{
				SpawnableMapObjectDef spawnableMapObjectDef = (mapHazard.hazard = modBundle.LoadAsset<SpawnableMapObjectDef>(mapHazard.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				Utilities.FixMixerGroups(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				prefabCallback(content, spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				mapHazard.registryCallback(spawnableMapObjectDef);
				MapObjects.RegisterMapObject(spawnableMapObjectDef, mapHazard.LevelTypes, mapHazard.levelOverrides, mapHazard.spawnRateFunction);
			}
			else if (content is OutsideObject outsideObject)
			{
				SpawnableOutsideObjectDef spawnableOutsideObjectDef = (outsideObject.mapObject = modBundle.LoadAsset<SpawnableOutsideObjectDef>(outsideObject.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				Utilities.FixMixerGroups(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				prefabCallback(content, spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				outsideObject.registryCallback(spawnableOutsideObjectDef);
				MapObjects.RegisterOutsideObject(spawnableOutsideObjectDef, outsideObject.LevelTypes, outsideObject.levelOverrides, outsideObject.spawnRateFunction);
			}
			LoadedContent.Add(content.ID, content);
		}

		public void RegisterAll(CustomContent[] content)
		{
			Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Length} content items!");
			foreach (CustomContent content2 in content)
			{
				Register(content2);
			}
		}

		public void RegisterAll(List<CustomContent> content)
		{
			Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Count} content items!");
			foreach (CustomContent item in content)
			{
				Register(item);
			}
		}
	}
	public class Dungeon
	{
		public class CustomDungeonArchetype
		{
			public DungeonArchetype archeType;

			public Levels.LevelTypes LevelTypes;

			public int lineIndex = -1;
		}

		public class CustomGraphLine
		{
			public GraphLine graphLine;

			public Levels.LevelTypes LevelTypes;
		}

		public class CustomDungeon
		{
			public int rarity;

			public DungeonFlow dungeonFlow;

			public Levels.LevelTypes LevelTypes;

			public string[] levelOverrides;

			public int dungeonIndex = -1;

			public AudioClip firstTimeDungeonAudio;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_GenerateNewFloor <0>__RoundManager_GenerateNewFloor;

			public static hook_Start <1>__RoundManager_Start;
		}

		public static List<CustomDungeonArchetype> customDungeonArchetypes = new List<CustomDungeonArchetype>();

		public static List<CustomGraphLine> customGraphLines = new List<CustomGraphLine>();

		public static Dictionary<string, TileSet> extraTileSets = new Dictionary<string, TileSet>();

		public static Dictionary<string, GameObjectChance> extraRooms = new Dictionary<string, GameObjectChance>();

		public static List<CustomDungeon> customDungeons = new List<CustomDungeon>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			object obj = <>O.<0>__RoundManager_GenerateNewFloor;
			if (obj == null)
			{
				hook_GenerateNewFloor val = RoundManager_GenerateNewFloor;
				<>O.<0>__RoundManager_GenerateNewFloor = val;
				obj = (object)val;
			}
			RoundManager.GenerateNewFloor += (hook_GenerateNewFloor)obj;
			object obj2 = <>O.<1>__RoundManager_Start;
			if (obj2 == null)
			{
				hook_Start val2 = RoundManager_Start;
				<>O.<1>__RoundManager_Start = val2;
				obj2 = (object)val2;
			}
			RoundManager.Start += (hook_Start)obj2;
		}

		private static void RoundManager_Start(orig_Start orig, RoundManager self)
		{
			orig.Invoke(self);
		}

		private static void RoundManager_GenerateNewFloor(orig_GenerateNewFloor orig, RoundManager self)
		{
			string name = ((Object)self.currentLevel).name;
			if (Enum.IsDefined(typeof(Levels.LevelTypes), name))
			{
				Levels.LevelTypes levelEnum = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name);
				int index = 0;
				self.dungeonGenerator.Generator.DungeonFlow.Lines.ForEach(delegate(GraphLine line)
				{
					foreach (CustomDungeonArchetype customDungeonArchetype in customDungeonArchetypes)
					{
						if (customDungeonArchetype.LevelTypes.HasFlag(levelEnum) && !line.DungeonArchetypes.Contains(customDungeonArchetype.archeType) && (customDungeonArchetype.lineIndex == -1 || customDungeonArchetype.lineIndex == index))
						{
							line.DungeonArchetypes.Add(customDungeonArchetype.archeType);
							if (Plugin.extendedLogging.Value)
							{
								Plugin.logger.LogInfo((object)("Added " + ((Object)customDungeonArchetype.archeType).name + " to " + name));
							}
						}
					}
					foreach (DungeonArchetype dungeonArchetype in line.DungeonArchetypes)
					{
						string name2 = ((Object)dungeonArchetype).name;
						if (extraTileSets.ContainsKey(name2))
						{
							TileSet val4 = extraTileSets[name2];
							if (!dungeonArchetype.TileSets.Contains(val4))
							{
								dungeonArchetype.TileSets.Add(val4);
								if (Plugin.extendedLogging.Value)
								{
									Plugin.logger.LogInfo((object)("Added " + ((Object)val4).name + " to " + name));
								}
							}
						}
						foreach (TileSet tileSet in dungeonArchetype.TileSets)
						{
							string name3 = ((Object)tileSet).name;
							if (extraRooms.ContainsKey(name3))
							{
								GameObjectChance item = extraRooms[name3];
								if (!tileSet.TileWeights.Weights.Contains(item))
								{
									tileSet.TileWeights.Weights.Add(item);
								}
							}
						}
					}
					index++;
				});
				foreach (CustomGraphLine customGraphLine in customGraphLines)
				{
					if (customGraphLine.LevelTypes.HasFlag(levelEnum) && !self.dungeonGenerator.Generator.DungeonFlow.Lines.Contains(customGraphLine.graphLine))
					{
						self.dungeonGenerator.Generator.DungeonFlow.Lines.Add(customGraphLine.graphLine);
					}
				}
			}
			orig.Invoke(self);
			NetworkManager val = Object.FindObjectOfType<NetworkManager>();
			RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>();
			foreach (RandomMapObject val2 in array)
			{
				for (int j = 0; j < val2.spawnablePrefabs.Count; j++)
				{
					string prefabName = ((Object)val2.spawnablePrefabs[j]).name;
					NetworkPrefab val3 = ((IEnumerable<NetworkPrefab>)val.NetworkConfig.Prefabs.m_Prefabs).FirstOrDefault((Func<NetworkPrefab, bool>)((NetworkPrefab x) => ((Object)x.Prefab).name == prefabName));
					if (val3 != null && (Object)(object)val3.Prefab != (Object)(object)val2.spawnablePrefabs[j])
					{
						val2.spawnablePrefabs[j] = val3.Prefab;
					}
					else if (val3 == null)
					{
						Plugin.logger.LogError((object)("DungeonGeneration - Could not find network prefab (" + prefabName + ")! Make sure your assigned prefab is registered with the network manager, or named identically to the vanilla prefab you are referencing."));
					}
				}
			}
		}

		public static void AddArchetype(DungeonArchetype archetype, Levels.LevelTypes levelFlags, int lineIndex = -1)
		{
			CustomDungeonArchetype customDungeonArchetype = new CustomDungeonArchetype();
			customDungeonArchetype.archeType = archetype;
			customDungeonArchetype.LevelTypes = levelFlags;
			customDungeonArchetype.lineIndex = lineIndex;
			customDungeonArchetypes.Add(customDungeonArchetype);
		}

		public static void AddLine(GraphLine line, Levels.LevelTypes levelFlags)
		{
			CustomGraphLine customGraphLine = new CustomGraphLine();
			customGraphLine.graphLine = line;
			customGraphLine.LevelTypes = levelFlags;
			customGraphLines.Add(customGraphLine);
		}

		public static void AddLine(DungeonGraphLineDef line, Levels.LevelTypes levelFlags)
		{
			AddLine(line.graphLine, levelFlags);
		}

		public static void AddTileSet(TileSet set, string archetypeName)
		{
			extraTileSets.Add(archetypeName, set);
		}

		public static void AddRoom(GameObjectChance room, string tileSetName)
		{
			extraRooms.Add(tileSetName, room);
		}

		public static void AddRoom(GameObjectChanceDef room, string tileSetName)
		{
			AddRoom(room.gameObjectChance, tileSetName);
		}

		public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags)
		{
			AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, dungeon.firstTimeDungeonAudio);
		}

		public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags, string[] levelOverrides)
		{
			AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, levelOverrides, dungeon.firstTimeDungeonAudio);
		}

		public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, AudioClip firstTimeDungeonAudio = null)
		{
			customDungeons.Add(new CustomDungeon
			{
				dungeonFlow = dungeon,
				rarity = rarity,
				LevelTypes = levelFlags,
				firstTimeDungeonAudio = firstTimeDungeonAudio
			});
		}

		public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, string[] levelOverrides = null, AudioClip firstTimeDungeonAudio = null)
		{
			customDungeons.Add(new CustomDungeon
			{
				dungeonFlow = dungeon,
				rarity = rarity,
				LevelTypes = levelFlags,
				firstTimeDungeonAudio = firstTimeDungeonAudio,
				levelOverrides = levelOverrides
			});
		}
	}
	public class Enemies
	{
		public struct EnemyAssetInfo
		{
			public EnemyType EnemyAsset;

			public TerminalKeyword keyword;
		}

		public enum SpawnType
		{
			Default,
			Daytime,
			Outside
		}

		public class SpawnableEnemy
		{
			public EnemyType enemy;

			public SpawnType spawnType;

			public TerminalNode terminalNode;

			public TerminalKeyword infoKeyword;

			public string modName;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public string[] spawnLevelOverrides;

			public Dictionary<string, int> customLevelRarities = new Dictionary<string, int>();

			public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>();

			public SpawnableEnemy(EnemyType enemy, int rarity, Levels.LevelTypes spawnLevels, SpawnType spawnType, string[] spawnLevelOverrides = null)
			{
				this.enemy = enemy;
				this.spawnLevels = spawnLevels;
				this.spawnType = spawnType;
				if (spawnLevelOverrides != null)
				{
					foreach (string levelName in spawnLevelOverrides)
					{
						customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(levelName), rarity);
					}
				}
				if (spawnLevels == Levels.LevelTypes.None)
				{
					return;
				}
				foreach (Levels.LevelTypes value in Enum.GetValues(typeof(Levels.LevelTypes)))
				{
					if (spawnLevels.HasFlag(value))
					{
						levelRarities.Add(value, rarity);
					}
				}
			}

			public SpawnableEnemy(EnemyType enemy, SpawnType spawnType, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null)
			{
				this.enemy = enemy;
				this.spawnType = spawnType;
				if (levelRarities != null)
				{
					this.levelRarities = levelRarities;
				}
				if (customLevelRarities != null)
				{
					this.customLevelRarities = Levels.Compatibility.LLLifyLevelRarityDictionary(customLevelRarities);
				}
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__RegisterLevelEnemies;

			public static hook_Start <1>__Terminal_Start;

			public static hook_Start <2>__QuickMenuManager_Start;

			public static hook_Start <3>__RegisterLevelEnemiesforLLL_RoundManager_Start;

			public static hook_Start <4>__RegisterLevelEnemiesforLE_Terminal_Start;
		}

		private static List<SelectableLevel> levelsAlreadyAddedTo = new List<SelectableLevel>();

		private static bool addedToDebug = false;

		public static Terminal terminal;

		public static List<EnemyAssetInfo> enemyAssetInfos = new List<EnemyAssetInfo>();

		public static List<SpawnableEnemy> spawnableEnemies = new List<SpawnableEnemy>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			object obj = <>O.<0>__RegisterLevelEnemies;
			if (obj == null)
			{
				hook_Awake val = RegisterLevelEnemies;
				<>O.<0>__RegisterLevelEnemies = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__Terminal_Start;
			if (obj2 == null)
			{
				hook_Start val2 = Terminal_Start;
				<>O.<1>__Terminal_Start = val2;
				obj2 = (object)val2;
			}
			Terminal.Start += (hook_Start)obj2;
			object obj3 = <>O.<2>__QuickMenuManager_Start;
			if (obj3 == null)
			{
				hook_Start val3 = QuickMenuManager_Start;
				<>O.<2>__QuickMenuManager_Start = val3;
				obj3 = (object)val3;
			}
			QuickMenuManager.Start += (hook_Start)obj3;
		}

		private static void QuickMenuManager_Start(orig_Start orig, QuickMenuManager self)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			if (addedToDebug)
			{
				orig.Invoke(self);
				return;
			}
			SelectableLevel testAllEnemiesLevel = self.testAllEnemiesLevel;
			List<SpawnableEnemyWithRarity> enemies = testAllEnemiesLevel.Enemies;
			List<SpawnableEnemyWithRarity> daytimeEnemies = testAllEnemiesLevel.DaytimeEnemies;
			List<SpawnableEnemyWithRarity> outsideEnemies = testAllEnemiesLevel.OutsideEnemies;
			foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
			{
				if (enemies.All((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
				{
					continue;
				}
				SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity
				{
					enemyType = spawnableEnemy.enemy,
					rarity = spawnableEnemy.rarity
				};
				switch (spawnableEnemy.spawnType)
				{
				case SpawnType.Default:
					if (!enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
					{
						enemies.Add(item);
					}
					break;
				case SpawnType.Daytime:
					if (!daytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
					{
						daytimeEnemies.Add(item);
					}
					break;
				case SpawnType.Outside:
					if (!outsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
					{
						outsideEnemies.Add(item);
					}
					break;
				}
				if (Plugin.extendedLogging.Value)
				{
					Plugin.logger.LogInfo((object)$"Added {spawnableEnemy.enemy.enemyName} to DebugList [{spawnableEnemy.spawnType}]");
				}
			}
			addedToDebug = true;
			orig.Invoke(self);
		}

		private static void Terminal_Start(orig_Start orig, Terminal self)
		{
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Expected O, but got Unknown
			terminal = self;
			TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			List<string> list = new List<string>();
			foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
			{
				if (list.Contains(spawnableEnemy.enemy.enemyName))
				{
					Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added"));
					continue;
				}
				if ((Object)(object)spawnableEnemy.terminalNode == (Object)null)
				{
					spawnableEnemy.terminalNode = ScriptableObject.CreateInstance<TerminalNode>();
					spawnableEnemy.terminalNode.displayText = spawnableEnemy.enemy.enemyName + "\n\nDanger level: Unknown\n\n[No information about this creature was found.]\n\n";
					spawnableEnemy.terminalNode.clearPreviousText = true;
					spawnableEnemy.terminalNode.maxCharactersToType = 35;
					spawnableEnemy.terminalNode.creatureName = spawnableEnemy.enemy.enemyName;
				}
				if (self.enemyFiles.Any((TerminalNode x) => x.creatureName == spawnableEnemy.terminalNode.creatureName))
				{
					Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added"));
					continue;
				}
				TerminalKeyword keyword2 = (((Object)(object)spawnableEnemy.infoKeyword != (Object)null) ? spawnableEnemy.infoKeyword : TerminalUtils.CreateTerminalKeyword(spawnableEnemy.terminalNode.creatureName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val));
				keyword2.defaultVerb = val;
				List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList();
				if (!list2.Any((TerminalKeyword x) => x.word == keyword2.word))
				{
					list2.Add(keyword2);
					self.terminalNodes.allKeywords = list2.ToArray();
				}
				List<CompatibleNoun> list3 = val.compatibleNouns.ToList();
				if (!list3.Any((CompatibleNoun x) => x.noun.word == keyword2.word))
				{
					list3.Add(new CompatibleNoun
					{
						noun = keyword2,
						result = spawnableEnemy.terminalNode
					});
				}
				val.compatibleNouns = list3.ToArray();
				spawnableEnemy.terminalNode.creatureFileID = self.enemyFiles.Count;
				self.enemyFiles.Add(spawnableEnemy.terminalNode);
				ScanNodeProperties[] componentsInChildren = spawnableEnemy.enemy.enemyPrefab.GetComponentsInChildren<ScanNodeProperties>();
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					componentsInChildren[i].creatureScanID = spawnableEnemy.terminalNode.creatureFileID;
				}
				EnemyAssetInfo enemyAssetInfo = default(EnemyAssetInfo);
				enemyAssetInfo.EnemyAsset = spawnableEnemy.enemy;
				enemyAssetInfo.keyword = keyword2;
				EnemyAssetInfo item = enemyAssetInfo;
				enemyAssetInfos.Add(item);
			}
			orig.Invoke(self);
		}

		private static void RegisterLevelEnemies(orig_Awake orig, StartOfRound self)
		{
			//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_0049: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			orig.Invoke(self);
			RegisterLethalLibEnemiesForAllLevels();
			if (Chainloader.PluginInfos.ContainsKey("imabatby.lethallevelloader") || Chainloader.PluginInfos.ContainsKey("iambatby.lethallevelloader"))
			{
				object obj = <>O.<3>__RegisterLevelEnemiesforLLL_RoundManager_Start;
				if (obj == null)
				{
					hook_Start val = RegisterLevelEnemiesforLLL_RoundManager_Start;
					<>O.<3>__RegisterLevelEnemiesforLLL_RoundManager_Start = val;
					obj = (object)val;
				}
				RoundManager.Start += (hook_Start)obj;
			}
			if (Chainloader.PluginInfos.ContainsKey("LethalExpansion"))
			{
				object obj2 = <>O.<4>__RegisterLevelEnemiesforLE_Terminal_Start;
				if (obj2 == null)
				{
					hook_Start val2 = RegisterLevelEnemiesforLE_Terminal_Start;
					<>O.<4>__RegisterLevelEnemiesforLE_Terminal_Start = val2;
					obj2 = (object)val2;
				}
				Terminal.Start += (hook_Start)obj2;
			}
		}

		private static void RegisterLevelEnemiesforLLL_RoundManager_Start(orig_Start orig, RoundManager self)
		{
			orig.Invoke(self);
			RegisterLethalLibEnemiesForAllLevels();
		}

		private static void RegisterLevelEnemiesforLE_Terminal_Start(orig_Start orig, Terminal self)
		{
			orig.Invoke(self);
			RegisterLethalLibEnemiesForAllLevels();
		}

		private static void RegisterLethalLibEnemiesForAllLevels()
		{
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				if (levelsAlreadyAddedTo.Contains(val))
				{
					continue;
				}
				foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
				{
					AddEnemyToLevel(spawnableEnemy, val);
				}
				levelsAlreadyAddedTo.Add(val);
			}
		}

		private static void AddEnemyToLevel(SpawnableEnemy spawnableEnemy, SelectableLevel level)
		{
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Expected O, but got Unknown
			SpawnableEnemy spawnableEnemy2 = spawnableEnemy;
			string text = ((Object)level).name;
			bool flag = spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.All) || spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.Vanilla) || (spawnableEnemy2.customLevelRarities != null && spawnableEnemy2.customLevelRarities.ContainsKey(text));
			if (spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), text))
			{
				flag = true;
			}
			Levels.LevelTypes levelTypes = Levels.LevelTypes.None;
			bool flag2 = false;
			if (Enum.IsDefined(typeof(Levels.LevelTypes), text))
			{
				levelTypes = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), text);
				flag2 = true;
			}
			else
			{
				text = Levels.Compatibility.GetLLLNameOfLevel(text);
			}
			if (!(flag2 || flag))
			{
				return;
			}
			Levels.LevelTypes key = (flag ? Levels.LevelTypes.All : levelTypes);
			if (!flag && !spawnableEnemy2.levelRarities.ContainsKey(key))
			{
				return;
			}
			int num = 0;
			if (flag2 && spawnableEnemy2.levelRarities.ContainsKey(levelTypes))
			{
				num = spawnableEnemy2.levelRarities[levelTypes];
			}
			else if (flag2 && spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.Vanilla))
			{
				num = spawnableEnemy2.levelRarities[Levels.LevelTypes.Vanilla];
			}
			else if (!flag2 && spawnableEnemy2.customLevelRarities != null && spawnableEnemy2.customLevelRarities.ContainsKey(text))
			{
				num = spawnableEnemy2.customLevelRarities[text];
			}
			else if (!flag2 && spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.Modded))
			{
				num = spawnableEnemy2.levelRarities[Levels.LevelTypes.Modded];
			}
			else if (spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.All))
			{
				num = spawnableEnemy2.levelRarities[Levels.LevelTypes.All];
			}
			SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity
			{
				enemyType = spawnableEnemy2.enemy,
				rarity = num
			};
			switch (spawnableEnemy2.spawnType)
			{
			case SpawnType.Default:
				if (!level.Enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy2.enemy))
				{
					level.Enemies.Add(item);
					if (Plugin.extendedLogging.Value)
					{
						Plugin.logger.LogInfo((object)$"To {text} added {((Object)spawnableEnemy2.enemy).name} with weight {num} and SpawnType [Default]");
					}
				}
				break;
			case SpawnType.Daytime:
				if (!level.DaytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy2.enemy))
				{
					level.DaytimeEnemies.Add(item);
					if (Plugin.extendedLogging.Value)
					{
						Plugin.logger.LogInfo((object)$"To {text} added {((Object)spawnableEnemy2.enemy).name} with weight {num} andSpawnType [Daytime]");
					}
				}
				break;
			case SpawnType.Outside:
				if (!level.OutsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy2.enemy))
				{
					level.OutsideEnemies.Add(item);
					if (Plugin.extendedLogging.Value)
					{
						Plugin.logger.LogInfo((object)$"To {text} added {((Object)spawnableEnemy2.enemy).name} with weight {num} and SpawnType [Outside]");
					}
				}
				break;
			}
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			RegisterEnemy(enemy, rarity, levelFlags, spawnType, null, infoNode, infoKeyword);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyType enemy2 = enemy;
			EnemyNullCheck(enemy2);
			SpawnableEnemy spawnableEnemy = spawnableEnemies.FirstOrDefault((SpawnableEnemy x) => (Object)(object)x.enemy == (Object)(object)enemy2 && x.spawnType == spawnType);
			if (spawnableEnemy != null)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					spawnableEnemy.levelRarities.Add(levelFlags, rarity);
				}
				if (spawnLevelOverrides != null)
				{
					foreach (string levelName in spawnLevelOverrides)
					{
						spawnableEnemy.customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(levelName), rarity);
					}
				}
			}
			else
			{
				spawnableEnemy = new SpawnableEnemy(enemy2, rarity, levelFlags, spawnType, spawnLevelOverrides);
				spawnableEnemy.terminalNode = infoNode;
				spawnableEnemy.infoKeyword = infoKeyword;
				FinalizeRegisterEnemy(spawnableEnemy);
			}
		}

		public static void RegisterEnemy(EnemyType enemy, SpawnType spawnType, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyType enemy2 = enemy;
			EnemyNullCheck(enemy2);
			SpawnableEnemy spawnableEnemy = spawnableEnemies.FirstOrDefault((SpawnableEnemy x) => (Object)(object)x.enemy == (Object)(object)enemy2 && x.spawnType == spawnType);
			if (spawnableEnemy != null)
			{
				if (levelRarities != null)
				{
					foreach (KeyValuePair<Levels.LevelTypes, int> levelRarity in levelRarities)
					{
						spawnableEnemy.levelRarities.Add(levelRarity.Key, levelRarity.Value);
					}
				}
				if (customLevelRarities == null)
				{
					return;
				}
				{
					foreach (KeyValuePair<string, int> customLevelRarity in customLevelRarities)
					{
						spawnableEnemy.customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(customLevelRarity.Key), customLevelRarity.Value);
					}
					return;
				}
			}
			spawnableEnemy = new SpawnableEnemy(enemy2, spawnType, levelRarities, customLevelRarities);
			spawnableEnemy.terminalNode = infoNode;
			spawnableEnemy.infoKeyword = infoKeyword;
			FinalizeRegisterEnemy(spawnableEnemy);
		}

		private static void FinalizeRegisterEnemy(SpawnableEnemy spawnableEnemy)
		{
			string name = Assembly.GetCallingAssembly().GetName().Name;
			spawnableEnemy.modName = name;
			if (spawnableEnemy.enemy.enemyPrefab == null)
			{
				throw new NullReferenceException("Cannot register enemy '" + spawnableEnemy.enemy.enemyName + "', because enemy.enemyPrefab is null!");
			}
			EnemyAICollisionDetect[] componentsInChildren = spawnableEnemy.enemy.enemyPrefab.GetComponentsInChildren<EnemyAICollisionDetect>();
			foreach (EnemyAICollisionDetect val in componentsInChildren)
			{
				if (val.mainScript == null)
				{
					Plugin.logger.LogWarning((object)("An Enemy AI Collision Detect Script on GameObject '" + ((Object)((Component)val).gameObject).name + "' of enemy '" + spawnableEnemy.enemy.enemyName + "' does not reference a 'Main Script', and could cause Null Reference Exceptions."));
				}
			}
			spawnableEnemies.Add(spawnableEnemy);
		}

		private static void EnemyNullCheck(EnemyType enemy)
		{
			if (enemy == null)
			{
				throw new ArgumentNullException("enemy", "The first argument of RegisterEnemy was null!");
			}
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyNullCheck(enemy);
			SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default));
			RegisterEnemy(enemy, rarity, levelFlags, spawnType, null, infoNode, infoKeyword);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyNullCheck(enemy);
			SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default));
			RegisterEnemy(enemy, rarity, levelFlags, spawnType, spawnLevelOverrides, infoNode, infoKeyword);
		}

		public static void RegisterEnemy(EnemyType enemy, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			EnemyNullCheck(enemy);
			SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default));
			RegisterEnemy(enemy, spawnType, levelRarities, customLevelRarities, infoNode, infoKeyword);
		}

		public static void RemoveEnemyFromLevels(EnemyType enemyType, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			EnemyType enemyType2 = enemyType;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				if (!Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					name = Levels.Compatibility.GetLLLNameOfLevel(name);
				}
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => Levels.Compatibility.GetLLLNameOfLevel(item).ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					List<SpawnableEnemyWithRarity> enemies = val.Enemies;
					List<SpawnableEnemyWithRarity> daytimeEnemies = val.DaytimeEnemies;
					List<SpawnableEnemyWithRarity> outsideEnemies = val.OutsideEnemies;
					enemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
					daytimeEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
					outsideEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
					if (Plugin.extendedLogging.Value)
					{
						Plugin.logger.LogInfo((object)("Removed Enemy " + ((Object)enemyType2).name + " from Level " + name));
					}
				}
			}
		}
	}
	public class Items
	{
		public struct ItemSaveOrderData
		{
			public int itemId;

			public string itemName;

			public string assetName;
		}

		public struct BuyableItemAssetInfo
		{
			public Item itemAsset;

			public TerminalKeyword keyword;
		}

		public class ScrapItem
		{
			public Item item;

			public Item origItem;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public string[] spawnLevelOverrides;

			public string modName = "Unknown";

			public Dictionary<string, int> customLevelRarities = new Dictionary<string, int>();

			public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>();

			public ScrapItem(Item item, int rarity, Levels.LevelTypes spawnLevels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null)
			{
				//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
				origItem = item;
				if (!item.isScrap)
				{
					item = item.Clone<Item>();
					item.isScrap = true;
					if (item.maxValue == 0 && item.minValue == 0)
					{
						item.minValue = 40;
						item.maxValue = 100;
					}
					else if (item.maxValue == 0)
					{
						item.maxValue = item.minValue * 2;
					}
					else if (item.minValue == 0)
					{
						item.minValue = item.maxValue / 2;
					}
					GameObject val = NetworkPrefabs.CloneNetworkPrefab(item.spawnPrefab);
					if ((Object)(object)val.GetComponent<GrabbableObject>() != (Object)null)
					{
						val.GetComponent<GrabbableObject>().itemProperties = item;
					}
					if ((Object)(object)val.GetComponentInChildren<ScanNodeProperties>() == (Object)null)
					{
						GameObject obj = Object.Instantiate<GameObject>(scanNodePrefab, val.transform);
						((Object)obj).name = "ScanNode";
						obj.transform.localPosition = new Vector3(0f, 0f, 0f);
						obj.GetComponent<ScanNodeProperties>().headerText = item.itemName;
					}
					item.spawnPrefab = val;
				}
				this.item = item;
				if (spawnLevelOverrides != null)
				{
					foreach (string levelName in spawnLevelOverrides)
					{
						customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(levelName), rarity);
					}
				}
				if (spawnLevels == Levels.LevelTypes.None)
				{
					return;
				}
				foreach (Levels.LevelTypes value in Enum.GetValues(typeof(Levels.LevelTypes)))
				{
					if (spawnLevels.HasFlag(value))
					{
						levelRarities.Add(value, rarity);
					}
				}
			}

			public ScrapItem(Item item, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null)
			{
				//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
				origItem = item;
				if (!item.isScrap)
				{
					item = item.Clone<Item>();
					item.isScrap = true;
					if (item.maxValue == 0 && item.minValue == 0)
					{
						item.minValue = 40;
						item.maxValue = 100;
					}
					else if (item.maxValue == 0)
					{
						item.maxValue = item.minValue * 2;
					}
					else if (item.minValue == 0)
					{
						item.minValue = item.maxValue / 2;
					}
					GameObject val = NetworkPrefabs.CloneNetworkPrefab(item.spawnPrefab);
					if ((Object)(object)val.GetComponent<GrabbableObject>() != (Object)null)
					{
						val.GetComponent<GrabbableObject>().itemProperties = item;
					}
					if ((Object)(object)val.GetComponentInChildren<ScanNodeProperties>() == (Object)null)
					{
						GameObject obj = Object.Instantiate<GameObject>(scanNodePrefab, val.transform);
						((Object)obj).name = "ScanNode";
						obj.transform.localPosition = new Vector3(0f, 0f, 0f);
						obj.GetComponent<ScanNodeProperties>().headerText = item.itemName;
					}
					item.spawnPrefab = val;
				}
				this.item = item;
				if (customLevelRarities != null)
				{
					this.customLevelRarities = Levels.Compatibility.LLLifyLevelRarityDictionary(customLevelRarities);
				}
				if (levelRarities != null)
				{
					this.levelRarities = levelRarities;
				}
			}
		}

		public class PlainItem
		{
			public Item item;

			public string modName;

			public PlainItem(Item item)
			{
				this.item = item;
			}
		}

		public class ShopItem
		{
			public Item item;

			public Item origItem;

			public TerminalNode buyNode1;

			public TerminalNode buyNode2;

			public TerminalNode itemInfo;

			public bool wasRemoved;

			public int price;

			public string modName;

			public ShopItem(Item item, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = 0)
			{
				origItem = item;
				this.item = item;
				this.price = price;
				if ((Object)(object)buyNode1 != (Object)null)
				{
					this.buyNode1 = buyNode1;
				}
				if ((Object)(object)buyNode2 != (Object)null)
				{
					this.buyNode2 = buyNode2;
				}
				if ((Object)(object)itemInfo != (Object)null)
				{
					this.itemInfo = itemInfo;
				}
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Start <0>__StartOfRound_Start;

			public static hook_Awake <1>__Terminal_Awake;

			public static hook_TextPostProcess <2>__Terminal_TextPostProcess;

			public static hook_Start <3>__RegisterLevelScrapforLLL_RoundManager_Start;

			public static hook_Start <4>__RegisterLevelScrapforLE_Terminal_Start;
		}

		public static ConfigEntry<bool> useSavedataFix;

		public static GameObject scanNodePrefab;

		private static List<SelectableLevel> levelsAlreadyAddedTo = new List<SelectableLevel>();

		public static List<Item> LethalLibItemList = new List<Item>();

		public static List<BuyableItemAssetInfo> buyableItemAssetInfos = new List<BuyableItemAssetInfo>();

		public static Terminal terminal;

		public static List<ScrapItem> scrapItems = new List<ScrapItem>();

		public static List<ShopItem> shopItems = new List<ShopItem>();

		public static List<PlainItem> plainItems = new List<PlainItem>();

		public static void Init()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			useSavedataFix = Plugin.config.Bind<bool>("Items", "EnableItemSaveFix", false, "Allow for LethalLib to store/reorder the item list, which should fix issues where items get reshuffled when loading an old save. This is experimental and may cause save corruptions occasionally.");
			scanNodePrefab = Plugin.MainAssets.LoadAsset<GameObject>("Assets/Custom/ItemScanNode.prefab");
			object obj = <>O.<0>__StartOfRound_Start;
			if (obj == null)
			{
				hook_Start val = StartOfRound_Start;
				<>O.<0>__StartOfRound_Start = val;
				obj = (object)val;
			}
			StartOfRound.Start += (hook_Start)obj;
			object obj2 = <>O.<1>__Terminal_Awake;
			if (obj2 == null)
			{
				hook_Awake val2 = Terminal_Awake;
				<>O.<1>__Terminal_Awake = val2;
				obj2 = (object)val2;
			}
			Terminal.Awake += (hook_Awake)obj2;
			object obj3 = <>O.<2>__Terminal_TextPostProcess;
			if (obj3 == null)
			{
				hook_TextPostProcess val3 = Terminal_TextPostProcess;
				<>O.<2>__Terminal_TextPostProcess = val3;
				obj3 = (object)val3;
			}
			Terminal.TextPostProcess += (hook_TextPostProcess)obj3;
		}

		private static string Terminal_TextPostProcess(orig_TextPostProcess orig, Terminal self, string modifiedDisplayText, TerminalNode node)
		{
			List<Item> list = self.buyableItemsList.ToList();
			List<Item> list2 = self.buyableItemsList.ToList();
			list2.RemoveAll((Item x) => shopItems.FirstOrDefault((ShopItem item) => (Object)(object)item.origItem == (Object)(object)x || (Object)(object)item.item == (Object)(object)x)?.wasRemoved ?? false);
			self.buyableItemsList = list2.ToArray();
			string result = orig.Invoke(self, modifiedDisplayText, node);
			self.buyableItemsList = list.ToArray();
			return result;
		}

		private static void StartOfRound_Start(orig_Start orig, StartOfRound self)
		{
			if (useSavedataFix.Value && ((NetworkBehaviour)self).IsHost)
			{
				Plugin.logger.LogInfo((object)"Fixing Item savedata!!");
				List<ItemSaveOrderData> itemList = new List<ItemSaveOrderData>();
				StartOfRound.Instance.allItemsList.itemsList.ForEach(delegate(Item item)
				{
					itemList.Add(new ItemSaveOrderData
					{
						itemId = item.itemId,
						itemName = item.itemName,
						assetName = ((Object)item).name
					});
				});
				if (ES3.KeyExists("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName))
				{
					itemList = ES3.Load<List<ItemSaveOrderData>>("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName);
				}
				List<Item> itemsList = StartOfRound.Instance.allItemsList.itemsList;
				List<Item> list = new List<Item>();
				foreach (ItemSaveOrderData item2 in itemList)
				{
					Item val = ((IEnumerable<Item>)itemsList).FirstOrDefault((Func<Item, bool>)((Item x) => x.itemId == item2.itemId && x.itemName == item2.itemName && item2.assetName == ((Object)x).name));
					if ((Object)(object)val != (Object)null)
					{
						list.Add(val);
					}
					else
					{
						list.Add(ScriptableObject.CreateInstance<Item>());
					}
				}
				foreach (Item item3 in itemsList)
				{
					if (!list.Contains(item3))
					{
						list.Add(item3);
					}
				}
				StartOfRound.Instance.allItemsList.itemsList = list;
				ES3.Save<List<ItemSaveOrderData>>("LethalLibAllItemsList", itemList, GameNetworkManager.Instance.currentSaveFileName);
			}
			orig.Invoke(self);
		}

		private static void RegisterLevelScrapforLLL_RoundManager_Start(orig_Start orig, RoundManager self)
		{
			orig.Invoke(self);
			RegisterLethalLibScrapItemsForAllLevels();
		}

		private static void RegisterLevelScrapforLE_Terminal_Start(orig_Start orig, Terminal self)
		{
			orig.Invoke(self);
			RegisterLethalLibScrapItemsForAllLevels();
		}

		private static void RegisterLethalLibScrapItemsForAllLevels()
		{
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				if (levelsAlreadyAddedTo.Contains(val))
				{
					continue;
				}
				foreach (ScrapItem scrapItem in scrapItems)
				{
					AddScrapItemToLevel(scrapItem, val);
				}
				levelsAlreadyAddedTo.Add(val);
			}
		}

		private static void AddScrapItemToLevel(ScrapItem scrapItem, SelectableLevel level)
		{
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Expected O, but got Unknown
			ScrapItem scrapItem2 = scrapItem;
			string text = ((Object)level).name;
			bool flag = scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.All) || scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.Vanilla) || (scrapItem2.customLevelRarities != null && scrapItem2.customLevelRarities.ContainsKey(text));
			if (scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), text))
			{
				flag = true;
			}
			Levels.LevelTypes key = Levels.LevelTypes.None;
			bool flag2 = false;
			if (Enum.IsDefined(typeof(Levels.LevelTypes), text))
			{
				key = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), text);
				flag2 = true;
			}
			else
			{
				text = Levels.Compatibility.GetLLLNameOfLevel(text);
			}
			if (!(flag2 || flag))
			{
				return;
			}
			Levels.LevelTypes key2 = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), text)));
			if (!flag && !scrapItem2.levelRarities.ContainsKey(key2))
			{
				return;
			}
			int rarity = 0;
			if (flag2 && scrapItem2.levelRarities.ContainsKey(key))
			{
				rarity = scrapItem2.levelRarities[key];
			}
			else if (flag2 && scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.Vanilla))
			{
				rarity = scrapItem2.levelRarities[Levels.LevelTypes.Vanilla];
			}
			else if (!flag2 && scrapItem2.customLevelRarities != null && scrapItem2.customLevelRarities.ContainsKey(text))
			{
				rarity = scrapItem2.customLevelRarities[text];
			}
			else if (!flag2 && scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.Modded))
			{
				rarity = scrapItem2.levelRarities[Levels.LevelTypes.Modded];
			}
			else if (scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.All))
			{
				rarity = scrapItem2.levelRarities[Levels.LevelTypes.All];
			}
			SpawnableItemWithRarity item = new SpawnableItemWithRarity
			{
				spawnableItem = scrapItem2.item,
				rarity = rarity
			};
			if (!level.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem2.item))
			{
				level.spawnableScrap.Add(item);
				if (Plugin.extendedLogging.Value)
				{
					Plugin.logger.LogInfo((object)("To " + text + " added " + ((Object)scrapItem2.item).name));
				}
			}
		}

		private static void RegisterScrapAsItem(StartOfRound startOfRound)
		{
			foreach (ScrapItem scrapItem in scrapItems)
			{
				if (startOfRound.allItemsList.itemsList.Contains(scrapItem.item))
				{
					continue;
				}
				if (Plugin.extendedLogging.Value)
				{
					if (scrapItem.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(scrapItem.modName + " registered scrap item: " + scrapItem.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered scrap item: " + scrapItem.item.itemName));
					}
				}
				LethalLibItemList.Add(scrapItem.item);
				startOfRound.allItemsList.itemsList.Add(scrapItem.item);
			}
		}

		private static void Terminal_Awake(orig_Awake orig, Terminal self)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			//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_0079: Expected O, but got Unknown
			//IL_0579: Unknown result type (might be due to invalid IL or missing references)
			//IL_057e: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05bc: Expected O, but got Unknown
			//IL_05be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0600: Expected O, but got Unknown
			//IL_0663: Unknown result type (might be due to invalid IL or missing references)
			//IL_0668: Unknown result type (might be due to invalid IL or missing references)
			//IL_0670: Unknown result type (might be due to invalid IL or missing references)
			//IL_067d: Expected O, but got Unknown
			//IL_070a: Unknown result type (might be due to invalid IL or missing references)
			//IL_070f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0717: Unknown result type (might be due to invalid IL or missing references)
			//IL_0724: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			RegisterLethalLibScrapItemsForAllLevels();
			if (Chainloader.PluginInfos.ContainsKey("imabatby.lethallevelloader") || Chainloader.PluginInfos.ContainsKey("iambatby.lethallevelloader"))
			{
				object obj = <>O.<3>__RegisterLevelScrapforLLL_RoundManager_Start;
				if (obj == null)
				{
					hook_Start val = RegisterLevelScrapforLLL_RoundManager_Start;
					<>O.<3>__RegisterLevelScrapforLLL_RoundManager_Start = val;
					obj = (object)val;
				}
				RoundManager.Start += (hook_Start)obj;
			}
			if (Chainloader.PluginInfos.ContainsKey("LethalExpansion"))
			{
				object obj2 = <>O.<4>__RegisterLevelScrapforLE_Terminal_Start;
				if (obj2 == null)
				{
					hook_Start val2 = RegisterLevelScrapforLE_Terminal_Start;
					<>O.<4>__RegisterLevelScrapforLE_Terminal_Start = val2;
					obj2 = (object)val2;
				}
				Terminal.Start += (hook_Start)obj2;
			}
			RegisterScrapAsItem(instance);
			foreach (ShopItem shopItem in shopItems)
			{
				if (instance.allItemsList.itemsList.Contains(shopItem.item))
				{
					continue;
				}
				if (Plugin.extendedLogging.Value)
				{
					if (shopItem.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(shopItem.modName + " registered shop item: " + shopItem.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered shop item: " + shopItem.item.itemName));
					}
				}
				LethalLibItemList.Add(shopItem.item);
				instance.allItemsList.itemsList.Add(shopItem.item);
			}
			foreach (PlainItem plainItem in plainItems)
			{
				if (instance.allItemsList.itemsList.Contains(plainItem.item))
				{
					continue;
				}
				if (Plugin.extendedLogging.Value)
				{
					if (plainItem.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(plainItem.modName + " registered item: " + plainItem.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered item: " + plainItem.item.itemName));
					}
				}
				LethalLibItemList.Add(plainItem.item);
				instance.allItemsList.itemsList.Add(plainItem.item);
			}
			terminal = self;
			List<Item> list = self.buyableItemsList.ToList();
			TerminalKeyword val3 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			TerminalNode result = val3.compatibleNouns[0].result.terminalOptions[1].result;
			TerminalKeyword val4 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			Plugin.logger.LogInfo((object)$"Adding {shopItems.Count} items to terminal");
			foreach (ShopItem item in shopItems)
			{
				if (list.Any((Item x) => x.itemName == item.item.itemName) && !item.wasRemoved)
				{
					Plugin.logger.LogInfo((object)("Item " + item.item.itemName + " already exists in terminal, skipping"));
					continue;
				}
				item.wasRemoved = false;
				if (item.price == -1)
				{
					item.price = item.item.creditsWorth;
				}
				else
				{
					item.item.creditsWorth = item.price;
				}
				int num = -1;
				if (!list.Any((Item x) => (Object)(object)x == (Object)(object)item.item))
				{
					list.Add(item.item);
				}
				else
				{
					num = list.IndexOf(item.item);
				}
				int buyItemIndex = ((num == -1) ? (list.Count - 1) : num);
				string itemName = item.item.itemName;
				_ = itemName[itemName.Length - 1];
				string text = itemName;
				TerminalNode val5 = item.buyNode2;
				if ((Object)(object)val5 == (Object)null)
				{
					val5 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val5).name = itemName.Replace(" ", "-") + "BuyNode2";
					val5.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n";
					val5.clearPreviousText = true;
					val5.maxCharactersToType = 15;
				}
				val5.buyItemIndex = buyItemIndex;
				val5.isConfirmationNode = false;
				val5.itemCost = item.price;
				val5.playSyncedClip = 0;
				TerminalNode val6 = item.buyNode1;
				if ((Object)(object)val6 == (Object)null)
				{
					val6 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val6).name = itemName.Replace(" ", "-") + "BuyNode1";
					val6.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n";
					val6.clearPreviousText = true;
					val6.maxCharactersToType = 35;
				}
				val6.buyItemIndex = buyItemIndex;
				val6.isConfirmationNode = true;
				val6.overrideOptions = true;
				val6.itemCost = item.price;
				val6.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2]
				{
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"),
						result = val5
					},
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"),
						result = result
					}
				};
				TerminalKeyword val7 = TerminalUtils.CreateTerminalKeyword(itemName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val3);
				List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList();
				list2.Add(val7);
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list3 = val3.compatibleNouns.ToList();
				list3.Add(new CompatibleNoun
				{
					noun = val7,
					result = val6
				});
				val3.compatibleNouns = list3.ToArray();
				TerminalNode val8 = item.itemInfo;
				if ((Object)(object)val8 == (Object)null)
				{
					val8 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val8).name = itemName.Replace(" ", "-") + "InfoNode";
					val8.displayText = "[No information about this object was found.]\n\n";
					val8.clearPreviousText = true;
					val8.maxCharactersToType = 25;
				}
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list4 = val4.compatibleNouns.ToList();
				list4.Add(new CompatibleNoun
				{
					noun = val7,
					result = val8
				});
				val4.compatibleNouns = list4.ToArray();
				BuyableItemAssetInfo buyableItemAssetInfo = default(BuyableItemAssetInfo);
				buyableItemAssetInfo.itemAsset = item.item;
				buyableItemAssetInfo.keyword = val7;
				BuyableItemAssetInfo item2 = buyableItemAssetInfo;
				buyableItemAssetInfos.Add(item2);
				if (Plugin.extendedLogging.Value)
				{
					Plugin.logger.LogInfo((object)$"Added {itemName} to terminal (Item price: {val6.itemCost}, Item Index: {val6.buyItemIndex}, Terminal keyword: {val7.word})");
				}
			}
			self.buyableItemsList = list.ToArray();
			orig.Invoke(self);
		}

		public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					scrapItem.levelRarities.Add(levelFlags, rarity);
				}
			}
			else
			{
				scrapItem = new ScrapItem(spawnableItem2, rarity, levelFlags);
				string name = Assembly.GetCallingAssembly().GetName().Name;
				scrapItem.modName = name;
				scrapItems.Add(scrapItem);
			}
		}

		public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					scrapItem.levelRarities.Add(levelFlags, rarity);
				}
				if (levelOverrides != null)
				{
					foreach (string levelName in levelOverrides)
					{
						scrapItem.customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(levelName), rarity);
					}
				}
			}
			else
			{
				scrapItem = new ScrapItem(spawnableItem2, rarity, levelFlags, levelOverrides);
				string name = Assembly.GetCallingAssembly().GetName().Name;
				scrapItem.modName = name;
				scrapItems.Add(scrapItem);
			}
		}

		public static void RegisterScrap(Item spawnableItem, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelRarities != null)
				{
					foreach (KeyValuePair<Levels.LevelTypes, int> levelRarity in levelRarities)
					{
						scrapItem.levelRarities.Add(levelRarity.Key, levelRarity.Value);
					}
				}
				if (customLevelRarities == null)
				{
					return;
				}
				{
					foreach (KeyValuePair<string, int> customLevelRarity in customLevelRarities)
					{
						scrapItem.customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(customLevelRarity.Key), customLevelRarity.Value);
					}
					return;
				}
			}
			scrapItem = new ScrapItem(spawnableItem2, levelRarities, customLevelRarities);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			scrapItem.modName = name;
			scrapItems.Add(scrapItem);
		}

		public static void RegisterShopItem(Item shopItem, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1)
		{
			ShopItem shopItem2 = new ShopItem(shopItem, buyNode1, buyNode2, itemInfo, price);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			shopItem2.modName = name;
			shopItems.Add(shopItem2);
		}

		public static void RegisterShopItem(Item shopItem, int price = -1)
		{
			ShopItem shopItem2 = new ShopItem(shopItem, null, null, null, price);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			shopItem2.modName = name;
			shopItems.Add(shopItem2);
		}

		public static void RegisterItem(Item plainItem)
		{
			PlainItem plainItem2 = new PlainItem(plainItem);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			plainItem2.modName = name;
			plainItems.Add(plainItem2);
		}

		public static void RemoveScrapFromLevels(Item scrapItem, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			Item scrapItem2 = scrapItem;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				if (!Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					name = Levels.Compatibility.GetLLLNameOfLevel(name);
				}
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => Levels.Compatibility.GetLLLNameOfLevel(item).ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (!flag && !levelFlags.HasFlag(levelTypes))
				{
					continue;
				}
				ScrapItem actualItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)scrapItem2 || (Object)(object)x.item == (Object)(object)scrapItem2);
				SpawnableItemWithRarity val2 = ((IEnumerable<SpawnableItemWithRarity>)val.spawnableScrap).FirstOrDefault((Func<SpawnableItemWithRarity, bool>)((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)actualItem.item));
				if (val2 != null)
				{
					if (Plugin.extendedLogging.Value)
					{
						Plugin.logger.LogInfo((object)("Removed Item " + ((Object)val2.spawnableItem).name + " from Level " + name));
					}
					val.spawnableScrap.Remove(val2);
				}
			}
		}

		public static void RemoveShopItem(Item shopItem)
		{
			Item shopItem2 = shopItem;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem2 || (Object)(object)x.item == (Object)(object)shopItem2);
			actualItem.wasRemoved = true;
			List<TerminalKeyword> list = terminal.terminalNodes.allKeywords.ToList();
			TerminalKeyword obj = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			TerminalKeyword val = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			List<CompatibleNoun> list2 = val.compatibleNouns.ToList();
			List<CompatibleNoun> list3 = obj.compatibleNouns.ToList();
			if (buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item))
			{
				BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item);
				list.Remove(asset.keyword);
				list2.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
				list3.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
			}
			terminal.terminalNodes.allKeywords = list.ToArray();
			val.compatibleNouns = list2.ToArray();
			obj.compatibleNouns = list3.ToArray();
		}

		public static void UpdateShopItemPrice(Item shopItem, int price)
		{
			Item shopItem2 = shopItem;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem2 || (Object)(object)x.item == (Object)(object)shopItem2);
			actualItem.item.creditsWorth = price;
			TerminalKeyword obj = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			_ = obj.compatibleNouns[0].result.terminalOptions[1].result;
			List<CompatibleNoun> source = obj.compatibleNouns.ToList();
			if (!buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item))
			{
				return;
			}
			BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item);
			if (!source.Any((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword))
			{
				return;
			}
			TerminalNode result = source.First((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword).result;
			result.itemCost = price;
			if (result.terminalOptions.Length == 0)
			{
				return;
			}
			CompatibleNoun[] terminalOptions = result.terminalOptions;
			foreach (CompatibleNoun val in terminalOptions)
			{
				if ((Object)(object)val.result != (Object)null && val.result.buyItemIndex != -1)
				{
					val.result.itemCost = price;
				}
			}
		}
	}
	public class Levels
	{
		[Flags]
		public enum LevelTypes
		{
			None = 1,
			ExperimentationLevel = 4,
			AssuranceLevel = 8,
			VowLevel = 0x10,
			OffenseLevel = 0x20,
			MarchLevel = 0x40,
			RendLevel = 0x80,
			DineLevel = 0x100,
			TitanLevel = 0x200,
			AdamanceLevel = 0x800,
			ArtificeLevel = 0x1000,
			EmbrionLevel = 0x2000,
			Vanilla = 0x3BFC,
			Modded = 0x400,
			All = -1
		}

		internal static class Compatibility
		{
			private const string illegalCharacters = ".,?!@#$%^&*()_+-=';:'\"";

			private static string GetNumberlessPlanetName(string planetName)
			{
				if (planetName != null)
				{
					return new string(planetName.SkipWhile((char c) => !char.IsLetter(c)).ToArray());
				}
				return string.Empty;
			}

			private static string StripSpecialCharacters(string input)
			{
				string text = string.Empty;
				for (int i = 0; i < input.Length; i++)
				{
					char c = input[i];
					if ((!".,?!@#$%^&*()_+-=';:'\"".ToCharArray().Contains(c) && char.IsLetterOrDigit(c)) || c.ToString() == " ")
					{
						text += c;
					}
				}
				return text;
			}

			internal static string GetLLLNameOfLevel(string levelName)
			{
				string text = StripSpecialCharacters(GetNumberlessPlanetName(levelName));
				if (!text.EndsWith("Level"))
				{
					text += "Level";
				}
				return text;
			}

			internal static Dictionary<string, int> LLLifyLevelRarityDictionary(Dictionary<string, int> keyValuePairs)
			{
				Dictionary<string, int> dictionary = new Dictionary<string, int>();
				List<string> list = keyValuePairs.Keys.ToList();
				List<int> list2 = keyValuePairs.Values.ToList();
				for (int i = 0; i < keyValuePairs.Count; i++)
				{
					dictionary.Add(GetLLLNameOfLevel(list[i]), list2[i]);
				}
				return dictionary;
			}
		}
	}
	public class MapObjects
	{
		public class RegisteredMapObject
		{
			public SpawnableMapObject mapObject;

			public SpawnableOutsideObjectWithRarity outsideObject;

			public Levels.LevelTypes levels;

			public string[] spawnLevelOverrides;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__StartOfRound_Awake;

			public static hook_SpawnMapObjects <1>__RoundManager_SpawnMapObjects;
		}

		public static List<RegisteredMapObject> mapObjects = new List<RegisteredMapObject>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__RoundManager_SpawnMapObjects;
			if (obj2 == null)
			{
				hook_SpawnMapObjects val2 = RoundManager_SpawnMapObjects;
				<>O.<1>__RoundManager_SpawnMapObjects = val2;
				obj2 = (object)val2;
			}
			RoundManager.SpawnMapObjects += (hook_SpawnMapObjects)obj2;
		}

		private static void RoundManager_SpawnMapObjects(orig_SpawnMapObjects orig, RoundManager self)
		{
			RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>();
			foreach (RandomMapObject val in array)
			{
				foreach (RegisteredMapObject mapObject in mapObjects)
				{
					if (mapObject.mapObject != null && !val.spawnablePrefabs.Any((GameObject prefab) => (Object)(object)prefab == (Object)(object)mapObject.mapObject.prefabToSpawn))
					{
						val.spawnablePrefabs.Add(mapObject.mapObject.prefabToSpawn);
					}
				}
			}
			orig.Invoke(self);
		}

		private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self)
		{
			orig.Invoke(self);
			foreach (RegisteredMapObject mapObject in mapObjects)
			{
				SelectableLevel[] levels = self.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = mapObject.levels.HasFlag(Levels.LevelTypes.All) || (mapObject.spawnLevelOverrides != null && mapObject.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (mapObject.levels.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
					{
						flag = true;
					}
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (!flag && !mapObject.levels.HasFlag(levelTypes))
					{
						continue;
					}
					if (mapObject.mapObject != null)
					{
						if (val.spawnableMapObjects.Any((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn))
						{
							List<SpawnableMapObject> list = val.spawnableMapObjects.ToList();
							list.RemoveAll((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn);
							val.spawnableMapObjects = list.ToArray();
						}
						SpawnableMapObject mapObject2 = mapObject.mapObject;
						if (mapObject.spawnRateFunction != null)
						{
							mapObject2.numberToSpawn = mapObject.spawnRateFunction(val);
						}
						List<SpawnableMapObject> list2 = val.spawnableMapObjects.ToList();
						list2.Add(mapObject2);
						val.spawnableMapObjects = list2.ToArray();
						if (Plugin.extendedLogging.Value)
						{
							Plugin.logger.LogInfo((object)("Added " + ((Object)mapObject2.prefabToSpawn).name + " to " + name));
						}
					}
					else
					{
						if (mapObject.outsideObject == null)
						{
							continue;
						}
						if (val.spawnableOutsideObjects.Any((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn))
						{
							List<SpawnableOutsideObjectWithRarity> list3 = val.spawnableOutsideObjects.ToList();
							list3.RemoveAll((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn);
							val.spawnableOutsideObjects = list3.ToArray();
						}
						SpawnableOutsideObjectWithRarity outsideObject = mapObject.outsideObject;
						if (mapObject.spawnRateFunction != null)
						{
							outsideObject.randomAmount = mapObject.spawnRateFunction(val);
						}
						List<SpawnableOutsideObjectWithRarity> list4 = val.spawnableOutsideObjects.ToList();
						list4.Add(outsideObject);
						val.spawnableOutsideObjects = list4.ToArray();
						if (Plugin.extendedLogging.Value)
						{
							Plugin.logger.LogInfo((object)("Added " + ((Object)outsideObject.spawnableObject.prefabToSpawn).name + " to " + name));
						}
					}
				}
			}
		}

		public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterMapObject(mapObject.spawnableMapObject, levels, spawnRateFunction);
		}

		public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterMapObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction);
		}

		public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				mapObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction
			});
		}

		public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				mapObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction,
				spawnLevelOverrides = levelOverrides
			});
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterOutsideObject(mapObject.spawnableMapObject, levels, spawnRateFunction);
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterOutsideObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction);
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				outsideObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction
			});
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				outsideObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction,
				spawnLevelOverrides = levelOverrides
			});
		}

		public static void RemoveMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			RemoveMapObject(mapObject.spawnableMapObject, levelFlags, levelOverrides);
		}

		public static void RemoveMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			SpawnableMapObject mapObject2 = mapObject;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					val.spawnableMapObjects = val.spawnableMapObjects.Where((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn != (Object)(object)mapObject2.prefabToSpawn).ToArray();
				}
			}
		}

		public static void RemoveOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			RemoveOutsideObject(mapObject.spawnableMapObject, levelFlags, levelOverrides);
		}

		public static void RemoveOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			SpawnableOutsideObjectWithRarity mapObject2 = mapObject;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					val.spawnableOutsideObjects = val.spawnableOutsideObjects.Where((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn != (Object)(object)mapObject2.spawnableObject.prefabToSpawn).ToArray();
				}
			}
		}
	}
	public class NetworkPrefabs
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Start <0>__GameNetworkManager_Start;
		}

		private static List<GameObject> _networkPrefabs = new List<GameObject>();

		internal static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			object obj = <>O.<0>__GameNetworkManager_Start;
			if (obj == null)
			{
				hook_Start val = GameNetworkManager_Start;
				<>O.<0>__GameNetworkManager_Start = val;
				obj = (object)val;
			}
			GameNetworkManager.Start += (hook_Start)obj;
		}

		public static void RegisterNetworkPrefab(GameObject prefab)
		{
			if (prefab == null)
			{
				throw new ArgumentNullException("prefab", "The given argument for RegisterNetworkPrefab is null!");
			}
			if (!_networkPrefabs.Contains(prefab))
			{
				_networkPrefabs.Add(prefab);
			}
		}

		public static GameObject CreateNetworkPrefab(string name)
		{
			GameObject obj = PrefabUtils.CreatePrefab(name);
			obj.AddComponent<NetworkObject>();
			byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetCallingAssembly().GetName().Name + name));
			obj.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0);
			RegisterNetworkPrefab(obj);
			return obj;
		}

		public static GameObject CloneNetworkPrefab(GameObject prefabToClone, string newName = null)
		{
			GameObject val = PrefabUtils.ClonePrefab(prefabToClone, newName);
			byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetCallingAssembly().GetName().Name + ((Object)val).name));
			val.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0);
			RegisterNetworkPrefab(val);
			return val;
		}

		private static void GameNetworkManager_Start(orig_Start orig, GameNetworkManager self)
		{
			orig.Invoke(self);
			foreach (GameObject networkPrefab in _networkPrefabs)
			{
				if (!NetworkManager.Singleton.NetworkConfig.Prefabs.Contains(networkPrefab))
				{
					NetworkManager.Singleton.AddNetworkPrefab(networkPrefab);
				}
			}
		}
	}
	public class Player
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__StartOfRound_Awake;
		}

		public static Dictionary<string, GameObject> ragdollRefs = new Dictionary<string, GameObject>();

		public static Dictionary<string, int> ragdollIndexes = new Dictionary<string, int>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
		}

		private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self)
		{
			orig.Invoke(self);
			foreach (KeyValuePair<string, GameObject> ragdollRef in ragdollRefs)
			{
				if (!self.playerRagdolls.Contains(ragdollRef.Value))
				{
					self.playerRagdolls.Add(ragdollRef.Value);
					int value = self.playerRagdolls.Count - 1;
					if (ragdollIndexes.ContainsKey(ragdollRef.Key))
					{
						ragdollIndexes[ragdollRef.Key] = value;
					}
					else
					{
						ragdollIndexes.Add(ragdollRef.Key, value);
					}
				}
			}
		}

		public static int GetRagdollIndex(string id)
		{
			return ragdollIndexes[id];
		}

		public static GameObject GetRagdoll(string id)
		{
			return ragdollRefs[id];
		}

		public static void RegisterPlayerRagdoll(string id, GameObject ragdoll)
		{
			Plugin.logger.LogInfo((object)("Registering player ragdoll " + id));
			ragdollRefs.Add(id, ragdoll);
		}
	}
	public class PrefabUtils
	{
		internal static Lazy<GameObject> _prefabParent;

		internal static GameObject prefabParent => _prefabParent.Value;

		static PrefabUtils()
		{
			_prefabParent = new Lazy<GameObject>((Func<GameObject>)delegate
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Expected O, but got Unknown
				GameObject val = new GameObject("LethalLibGeneratedPrefabs")
				{
					hideFlags = (HideFlags)61
				};
				val.SetActive(false);
				return val;
			});
		}

		public static GameObject ClonePrefab(GameObject prefabToClone, string newName = null)
		{
			GameObject val = Object.Instantiate<GameObjec

BepInEx/plugins/americanompany/LetMeLookDown.dll

Decompiled 2 years ago
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using GameNetcodeStuff;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("LetMeLookDown")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LetMeLookDown")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("a9c88d54-8f01-44a7-be0d-bd61d38aadcb")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace LetMeLookDown
{
	[BepInPlugin("FlipMods.LetMeLookDown", "LetMeLookDown", "1.0.2")]
	public class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		private static Plugin instance;

		public static float maxAngle = 80f;

		private void Awake()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			_harmony = new Harmony("LetMeLookDown");
			_harmony.PatchAll();
			instance = this;
			Log("LetMeLookDown mod loaded");
		}

		public static void Log(string message)
		{
			((BaseUnityPlugin)instance).Logger.LogInfo((object)message);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FlipMods.LetMeLookDown";

		public const string PLUGIN_NAME = "LetMeLookDown";

		public const string PLUGIN_VERSION = "1.0.2";
	}
}
namespace LetMeLookDown.Patches
{
	[HarmonyPatch]
	internal class AdjustSmoothLookingPatcher
	{
		[HarmonyPatch(typeof(PlayerControllerB), "CalculateSmoothLookingInput")]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 60f)
				{
					list[i].operand = Plugin.maxAngle;
					break;
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch]
	internal class AdjustNormalLookingPatcher
	{
		[HarmonyPatch(typeof(PlayerControllerB), "CalculateNormalLookingInput")]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 60f)
				{
					list[i].operand = Plugin.maxAngle;
					break;
				}
			}
			return list.AsEnumerable();
		}
	}
}

BepInEx/plugins/americanompany/LocalFlashlight.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using LethalConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using LocalFlashlight.NetcodePatcher;
using LocalFlashlight.Networking;
using Microsoft.CodeAnalysis;
using TMPro;
using TerminalApi;
using TerminalApi.Classes;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.InputSystem;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LocalFlashlight")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+0b1e44eae724efbb9a787ce025ca3bc0af57ca0d")]
[assembly: AssemblyProduct("LocalFlashlight")]
[assembly: AssemblyTitle("LocalFlashlight")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
public enum BatteryDisplayOptions
{
	Disabled,
	Bar,
	Percentage,
	VerticalBar,
	CircularBar,
	All
}
public enum TextDisplayOptions
{
	Percent,
	AccuratePercent,
	Time,
	All
}
public enum SoundOptions
{
	OriginalLightSounds,
	InGameFlashlight,
	OtherwordlyLight
}
public enum RechargeOptions
{
	Time,
	Shake,
	Dynamo,
	ShipRecharge,
	FacilityPowered
}
public enum GlobalFlashlightOptions
{
	CrewUpgrade,
	Unrestricted
}
namespace LocalFlashlight
{
	internal class LightScript : MonoBehaviour
	{
		private PlayerControllerB player_controller;

		public ulong clientId;

		private GameObject player;

		private GameObject cameraObject;

		private GameObject dynamoLightObj;

		private static GameObject lightObject;

		public static AudioClip[] flashlightClips = (AudioClip[])(object)new AudioClip[25];

		public static int[] activeClips = new int[15];

		private static AudioSource flashSource;

		private static AudioSource dynamoAudioSource;

		private Light localLight;

		private bool flashState;

		public static bool publicFlashState;

		private bool canToggle = true;

		private SoundOptions selectedSoundOption;

		private RechargeOptions selectedRechargeOption;

		private float playerMovementSpeed;

		public static float UIHideTime;

		public static float maxBatteryTime;

		public static float BatteryPercent;

		public static float truePercentBattery;

		public static float BatteryClamped;

		public static float batteryTime = maxBatteryTime;

		private float batteryRegen;

		private float regenCool;

		private float batteryCooldown;

		private float burnOutCooldown;

		private float shakeCool;

		private float soundCool;

		private float lastShakeTime = 0f;

		private bool rechargeKeyHeld = false;

		private float targetVolume = 0f;

		private float targetPitch = 0f;

		private float windRechargeMult = 0f;

		public static Color flashColor;

		private int toggleAmount = 0;

		private float flashOnTime = 0f;

		private int timesCommandUsed = 0;

		private void Start()
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			Plugin.mls.LogInfo((object)"Mod script started, setting mod values and making light...");
			FindLocalPlayer();
			if (!(((Object)(object)player == (Object)null) | ((Object)(object)cameraObject == (Object)null)))
			{
				SetModValues();
				SetFlashlightSounds();
				MakeLocalLight();
				if (Plugin.enableNetworking.Value)
				{
					LFNetworkHandler.Instance.RequestAllLightsUpdateServerRpc();
				}
				((Behaviour)localLight).enabled = false;
				TerminalApi.AddCommand("LocalFlashlight", new CommandInfo
				{
					Category = "other",
					Description = (Plugin.enableNetworking.Value ? "Shows the state of the flashlight upgrade if you already have it unlocked. If not, use \"LocalFlashlight buy\" to buy it instead!" : "Displays statistics about the flashlight's usage"),
					DisplayTextSupplier = onCommandParse
				}, (string)null, true);
			}
		}

		public void Update()
		{
			if (((Object)(object)player == (Object)null) | ((Object)(object)player_controller == (Object)null) | ((Object)(object)cameraObject == (Object)null) | ((Object)(object)lightObject == (Object)null))
			{
				return;
			}
			try
			{
				UpdateModValues();
				if (batteryTime > maxBatteryTime)
				{
					batteryTime = maxBatteryTime;
					if (selectedRechargeOption == RechargeOptions.Time)
					{
						PlayNoise(activeClips[3], 0.7f, playForWorld: true);
					}
				}
				if (flashState)
				{
					batteryTime -= Time.deltaTime;
					flashOnTime += Time.deltaTime;
					if (batteryTime < 0f)
					{
						if (Plugin.flickerOnBatteryBurn.Value)
						{
							((MonoBehaviour)this).StartCoroutine(FlickerAndStop());
						}
						else
						{
							Toggle();
						}
					}
				}
				if (((double)BatteryPercent <= 99.75) | flashState)
				{
					UIHideTime = Plugin.HideUIDelay.Value;
				}
				if ((double)BatteryPercent > 99.75 && !flashState)
				{
					UIHideTime -= Time.deltaTime;
				}
				UpdateBatteryValues();
				if (Plugin.flashlightToggleInstance.toggleKey.triggered)
				{
					if (player_controller.quickMenuManager.isMenuOpen | player_controller.isPlayerDead | player_controller.inTerminalMenu | player_controller.isTypingChat | player_controller.inSpecialInteractAnimation | ((Object)(object)localLight == (Object)null))
					{
						return;
					}
					if (batteryTime > 0f)
					{
						if (flashState)
						{
							Toggle();
						}
						else if (!flashState && canToggle)
						{
							Toggle();
						}
						else if (Patches.isFlashlightHeld)
						{
							PlayNoise(22, 0.3f, playForWorld: false);
						}
					}
					else
					{
						PlayNoise(22, 0.7f, playForWorld: false);
					}
				}
				if (Plugin.flashlightToggleInstance.switchLightPosKey.triggered && !(player_controller.quickMenuManager.isMenuOpen | player_controller.isPlayerDead | player_controller.inTerminalMenu | player_controller.isTypingChat | player_controller.inSpecialInteractAnimation | ((Object)(object)localLight == (Object)null)))
				{
					ChangeLightPosition();
				}
			}
			catch (Exception arg)
			{
				Plugin.mls.LogError((object)$"something went wrong in the update script!! might be either from battery update, mod value update, or whatever else there is in this script:\n{arg}");
			}
		}

		private void Toggle()
		{
			if ((Object)(object)player == (Object)null || (Object)(object)cameraObject == (Object)null)
			{
				return;
			}
			flashState = !flashState;
			publicFlashState = flashState;
			((Behaviour)localLight).enabled = flashState;
			if (Plugin.enableNetworking.Value)
			{
				LFNetworkHandler.Instance.ToggleLightServerRpc(player_controller.playerClientId, flashState);
			}
			if (flashState)
			{
				PlayNoise(activeClips[0], 0.3f, playForWorld: true);
				toggleAmount++;
				return;
			}
			if (batteryTime <= 0f && Plugin.BatteryBurnOut.Value)
			{
				regenCool = burnOutCooldown;
			}
			else
			{
				regenCool = batteryCooldown;
				toggleAmount++;
			}
			if (batteryTime <= 0f)
			{
				PlayNoise(activeClips[2], 0.5f, playForWorld: true);
			}
			else
			{
				PlayNoise(activeClips[1], 0.6f, playForWorld: true);
			}
		}

		private void ChangeLightPosition()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			float x = lightObject.transform.localPosition.x;
			float y = lightObject.transform.localRotation.y;
			lightObject.transform.localPosition = new Vector3(0f - x, -0.55f, 0.5f);
			lightObject.transform.localRotation = Quaternion.Euler(-10f, 0f - y, 0f);
			PlayNoise(21, 0.3f, playForWorld: false);
		}

		public static void PlayNoise(int clipIndex, float volume, bool playForWorld)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			AudioSource obj = flashSource;
			if (obj != null)
			{
				obj.PlayOneShot(flashlightClips[clipIndex]);
			}
			if (playForWorld)
			{
				Object.FindObjectOfType<RoundManager>().PlayAudibleNoise(lightObject.transform.position, 8f, volume, 0, StartOfRound.Instance.localPlayerController.isInHangarShipRoom && StartOfRound.Instance.hangarDoorsClosed, 0);
				if (Plugin.enableNetworking.Value)
				{
					LFNetworkHandler.Instance.PlayNetworkedSoundServerRpc(StartOfRound.Instance.localPlayerController.playerClientId, clipIndex);
				}
			}
		}

		private void holdCallback(CallbackContext context)
		{
			if (!((selectedRechargeOption != RechargeOptions.Dynamo) | player_controller.quickMenuManager.isMenuOpen | player_controller.isPlayerDead | player_controller.inTerminalMenu | player_controller.isTypingChat))
			{
				targetVolume = (float)Plugin.FlashVolume.Value / 200f;
				targetPitch = 1f;
				if ((Object)(object)dynamoAudioSource != (Object)null)
				{
					dynamoAudioSource.loop = true;
					dynamoAudioSource.clip = flashlightClips[activeClips[5]];
					dynamoAudioSource.Play();
				}
				rechargeKeyHeld = true;
			}
		}

		private void releaseCallback(CallbackContext context)
		{
			if (selectedRechargeOption == RechargeOptions.Dynamo)
			{
				targetVolume = 0f;
				targetPitch = 0f;
				if ((Object)(object)dynamoAudioSource != (Object)null)
				{
					dynamoAudioSource.loop = false;
				}
				soundCool = 0.25f;
				rechargeKeyHeld = false;
			}
		}

		private void SetFlashlightSounds()
		{
			try
			{
				selectedSoundOption = Plugin.soundOption.Value;
				flashlightClips[0] = Plugin.bundle.LoadAsset<AudioClip>("lighton");
				flashlightClips[1] = Plugin.bundle.LoadAsset<AudioClip>("lighton1");
				flashlightClips[2] = Plugin.bundle.LoadAsset<AudioClip>("lighton2");
				flashlightClips[3] = Plugin.bundle.LoadAsset<AudioClip>("lightoff");
				flashlightClips[4] = Plugin.bundle.LoadAsset<AudioClip>("lighton1");
				flashlightClips[5] = Plugin.bundle.LoadAsset<AudioClip>("lighton2");
				flashlightClips[6] = Plugin.bundle.LoadAsset<AudioClip>("lowtoggle");
				flashlightClips[7] = Plugin.bundle.LoadAsset<AudioClip>("lowtoggle2");
				flashlightClips[8] = Plugin.bundle.LoadAsset<AudioClip>("lowtoggle1");
				flashlightClips[9] = Plugin.bundle.LoadAsset<AudioClip>("recharged");
				flashlightClips[10] = Plugin.bundle.LoadAsset<AudioClip>("recharged1");
				flashlightClips[11] = Plugin.bundle.LoadAsset<AudioClip>("recharged2");
				flashlightClips[12] = Plugin.bundle.LoadAsset<AudioClip>("reloadlight");
				flashlightClips[13] = Plugin.bundle.LoadAsset<AudioClip>("reloadlight");
				flashlightClips[14] = Plugin.bundle.LoadAsset<AudioClip>("reloadlight");
				flashlightClips[15] = Plugin.bundle.LoadAsset<AudioClip>("dynamo");
				flashlightClips[16] = Plugin.bundle.LoadAsset<AudioClip>("dynamo1");
				flashlightClips[17] = Plugin.bundle.LoadAsset<AudioClip>("dynamo2");
				flashlightClips[18] = Plugin.bundle.LoadAsset<AudioClip>("flashDown");
				flashlightClips[19] = Plugin.bundle.LoadAsset<AudioClip>("flashDown1");
				flashlightClips[20] = Plugin.bundle.LoadAsset<AudioClip>("flashDown2");
				flashlightClips[21] = Plugin.bundle.LoadAsset<AudioClip>("changepos.ogg");
				flashlightClips[22] = Plugin.bundle.LoadAsset<AudioClip>("denytoggle");
				Plugin.mls.LogDebug((object)"loaded assets...");
				switch (selectedSoundOption)
				{
				case SoundOptions.OriginalLightSounds:
					activeClips[0] = 0;
					activeClips[1] = 3;
					activeClips[2] = 6;
					activeClips[3] = 9;
					activeClips[4] = 12;
					activeClips[5] = 16;
					activeClips[6] = 19;
					break;
				case SoundOptions.OtherwordlyLight:
					activeClips[0] = 1;
					activeClips[1] = 4;
					activeClips[2] = 7;
					activeClips[3] = 11;
					activeClips[4] = 13;
					activeClips[5] = 17;
					activeClips[6] = 18;
					break;
				case SoundOptions.InGameFlashlight:
					activeClips[0] = 2;
					activeClips[1] = 5;
					activeClips[2] = 8;
					activeClips[3] = 10;
					activeClips[4] = 14;
					activeClips[5] = 15;
					activeClips[6] = 20;
					break;
				}
			}
			catch (Exception arg)
			{
				Plugin.mls.LogError((object)$"error while setting localflashlight mod sounds:\n{arg}");
			}
		}

		private void SetModValues()
		{
			try
			{
				flashState = false;
				canToggle = true;
				rechargeKeyHeld = false;
				maxBatteryTime = Plugin.BatteryLife.Value;
				batteryTime = maxBatteryTime;
				batteryRegen = Plugin.RechargeMult.Value;
				burnOutCooldown = Plugin.BurnOutCool.Value;
				batteryCooldown = Plugin.BatteryCool.Value;
				UIHideTime = 2f + Plugin.HideUIDelay.Value;
				selectedRechargeOption = Plugin.rechargeOption.Value;
				shakeCool = Plugin.shakeActionCooldown.Value;
				playerMovementSpeed = player_controller.movementSpeed;
				ColorUtility.TryParseHtmlString(Plugin.flashlightColorHex.Value, ref flashColor);
			}
			catch (Exception arg)
			{
				Plugin.mls.LogError((object)$"error while setting initial localflashlight mod values:\n{arg}");
			}
		}

		private void FindLocalPlayer()
		{
			if ((Object)(object)player != (Object)null)
			{
				return;
			}
			try
			{
				Plugin.mls.LogInfo((object)"Attempting to find local player controller!");
				player = ((Component)GameNetworkManager.Instance.localPlayerController).gameObject;
				if ((Object)(object)player != (Object)null)
				{
					player_controller = player.GetComponent<PlayerControllerB>();
					cameraObject = ((Component)player_controller.gameplayCamera).gameObject;
					clientId = GameNetworkManager.Instance.localPlayerController.playerClientId;
				}
			}
			catch (Exception arg)
			{
				Plugin.mls.LogError((object)$"error while finding the local player controller! it may be null or the mod just can't find it for whatever reason\n{arg}");
			}
		}

		private void MakeLocalLight()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Expected O, but got Unknown
			if ((Object)(object)player == (Object)null)
			{
				Plugin.mls.LogError((object)"no player!!!!!!!");
				return;
			}
			try
			{
				AudioMixerGroup outputAudioMixerGroup = ((Component)GameNetworkManager.Instance.localPlayerController.itemAudio).GetComponent<AudioSource>().outputAudioMixerGroup;
				lightObject = new GameObject();
				lightObject.transform.SetParent(cameraObject.transform, false);
				((Object)lightObject).name = "lightObject (LOCAL)";
				localLight = lightObject.AddComponent<Light>();
				localLight.type = (LightType)0;
				localLight.shape = (LightShape)0;
				localLight.color = flashColor;
				localLight.intensity = Plugin.Intensity.Value;
				localLight.range = Plugin.Range.Value;
				localLight.shadows = (LightShadows)1;
				localLight.spotAngle = Plugin.Angle.Value;
				flashSource = lightObject.AddComponent<AudioSource>();
				flashSource.loop = false;
				flashSource.playOnAwake = false;
				flashSource.volume = (float)Plugin.FlashVolume.Value / 100f;
				flashSource.priority = 0;
				flashSource.spatialize = true;
				flashSource.outputAudioMixerGroup = outputAudioMixerGroup;
				lightObject.transform.localPosition = new Vector3(-0.15f, -0.55f, 0.5f);
				lightObject.transform.Rotate(new Vector3(-12f, 3f, 0f));
				if (selectedRechargeOption == RechargeOptions.Dynamo)
				{
					dynamoLightObj = new GameObject("DynamoAudioSource (ONLY USED FOR DYNAMO RECHARGE)");
					dynamoLightObj.transform.SetParent(lightObject.transform, false);
					dynamoAudioSource = dynamoLightObj.AddComponent<AudioSource>();
					((Object)dynamoAudioSource).name = "yeah no idea why this happens but every time its a nullreferenceexception per frame if i dont keep this, nevermind i fixed it";
					dynamoAudioSource.loop = true;
					dynamoAudioSource.priority = 0;
					dynamoAudioSource.spatialize = true;
					dynamoAudioSource.outputAudioMixerGroup = outputAudioMixerGroup;
				}
				if (Plugin.ShadowsEnabled.Value)
				{
					HDAdditionalLightData val = lightObject.AddComponent<HDAdditionalLightData>();
					val.EnableShadows(true);
					val.SetShadowNearPlane(0.35f);
				}
				lightObject.SetActive(true);
				Plugin.mls.LogInfo((object)"light up and working!");
			}
			catch (Exception arg)
			{
				Plugin.mls.LogError((object)$"error while creating the light object:\n{arg}");
			}
		}

		private void UpdateModValues()
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			regenCool -= Time.deltaTime;
			BatteryPercent = (int)Math.Ceiling(batteryTime / maxBatteryTime * 100f);
			BatteryClamped = batteryTime / maxBatteryTime;
			truePercentBattery = BatteryClamped * 100f;
			ColorUtility.TryParseHtmlString(Plugin.flashlightColorHex.Value, ref flashColor);
			localLight.color = flashColor;
			localLight.range = Plugin.Range.Value;
			localLight.spotAngle = Plugin.Angle.Value;
			flashSource.volume = (float)Plugin.FlashVolume.Value / 100f;
			if (selectedRechargeOption == RechargeOptions.Dynamo && (Object)(object)dynamoAudioSource != (Object)null)
			{
				dynamoAudioSource.volume = Mathf.Lerp(dynamoAudioSource.volume, targetVolume, Time.deltaTime * 6f);
				dynamoAudioSource.pitch = Mathf.Lerp(dynamoAudioSource.pitch, targetPitch, Time.deltaTime * 6f);
			}
			canToggle = !Plugin.flashlightToggleModSynergyquestionmark.Value || (!((Behaviour)player_controller.helmetLight).enabled && !Patches.isFlashlightPocketed && !Patches.isFlashlightHeld);
			if (player_controller.isPlayerDead)
			{
				flashState = false;
				((Behaviour)localLight).enabled = false;
				batteryTime = maxBatteryTime;
				regenCool = 0f;
				canToggle = true;
				rechargeKeyHeld = false;
			}
			float val = Mathf.Lerp(0f, 1f, BatteryClamped);
			val = Math.Max(val, (float)Plugin.flashlightStopDimBatteryValue.Value / 100f);
			if (FlashlightItem.globalFlashlightInterferenceLevel >= 1)
			{
				localLight.intensity = Plugin.Intensity.Value * ((selectedRechargeOption == RechargeOptions.FacilityPowered) ? Plugin.apparaticeFlashlightIntensityMult.Value : 1f) * Patches.randomLightInterferenceMultiplier;
			}
			else
			{
				localLight.intensity = (Plugin.dimEnabled.Value ? (Plugin.Intensity.Value * val) : Plugin.Intensity.Value);
			}
		}

		private void UpdateBatteryValues()
		{
			switch (selectedRechargeOption)
			{
			case RechargeOptions.Time:
				if (!flashState && (double)batteryTime <= (double)maxBatteryTime - 0.001 && regenCool < 0f)
				{
					batteryTime += batteryRegen * Time.deltaTime;
				}
				break;
			case RechargeOptions.Shake:
				if (Plugin.flashlightToggleInstance.rechargeKey.triggered && Time.time - lastShakeTime > shakeCool && !player_controller.quickMenuManager.isMenuOpen && !player_controller.isPlayerDead && !player_controller.inTerminalMenu && !player_controller.isTypingChat)
				{
					if (player_controller.sprintMeter > 0.25f)
					{
						batteryTime += maxBatteryTime * 0.07f * batteryRegen;
						PlayNoise(activeClips[4], 0.6f, playForWorld: true);
						PlayerControllerB obj = player_controller;
						obj.sprintMeter -= (float)Plugin.shakeStaminaConsume.Value / 100f;
						lastShakeTime = Time.time;
					}
					else
					{
						PlayNoise(22, 0.7f, playForWorld: false);
					}
				}
				break;
			case RechargeOptions.Dynamo:
				if (!player_controller.quickMenuManager.isMenuOpen || !player_controller.isPlayerDead || !player_controller.isTypingChat || !player_controller.inSpecialInteractAnimation)
				{
					Plugin.flashlightToggleInstance.rechargeKey.performed += holdCallback;
					Plugin.flashlightToggleInstance.rechargeKey.canceled += releaseCallback;
				}
				else
				{
					Plugin.flashlightToggleInstance.rechargeKey.performed -= holdCallback;
				}
				if (rechargeKeyHeld)
				{
					WindUpFlashlight();
					windRechargeMult += Time.deltaTime * 3f;
				}
				else if (windRechargeMult > 0f)
				{
					windRechargeMult -= Time.deltaTime * 5f;
				}
				batteryTime += Time.deltaTime * batteryRegen * windRechargeMult;
				windRechargeMult = Mathf.Clamp(windRechargeMult, 0f, 1.5f);
				player_controller.movementSpeed = (rechargeKeyHeld ? (playerMovementSpeed * Plugin.dynamoUseMoveMult.Value) : playerMovementSpeed);
				break;
			case RechargeOptions.FacilityPowered:
				if (Patches.isFacilityPowered)
				{
					batteryTime = maxBatteryTime;
				}
				break;
			case RechargeOptions.ShipRecharge:
				batteryTime = (player_controller.isInHangarShipRoom ? maxBatteryTime : batteryTime);
				break;
			}
		}

		private void WindUpFlashlight()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			if (selectedRechargeOption == RechargeOptions.Dynamo)
			{
				PlayerControllerB obj = player_controller;
				obj.sprintMeter -= Time.deltaTime * 0.03f;
				if (soundCool < 0f)
				{
					Object.FindObjectOfType<RoundManager>().PlayAudibleNoise(((Component)player_controller).transform.position, 8f, 0.5f, 0, player_controller.isInHangarShipRoom && StartOfRound.Instance.hangarDoorsClosed, 0);
					soundCool = 0.4f;
				}
				soundCool -= Time.deltaTime;
			}
		}

		private IEnumerator FlickerAndStop()
		{
			regenCool = 0.3f + (Plugin.BatteryBurnOut.Value ? burnOutCooldown : batteryCooldown);
			flashState = false;
			publicFlashState = flashState;
			PlayNoise(8, 0.6f, playForWorld: true);
			if (Plugin.enableNetworking.Value)
			{
				LFNetworkHandler.Instance.FlickerOutServerRpc(player_controller.playerClientId);
			}
			((Behaviour)localLight).enabled = false;
			yield return (object)new WaitForSeconds(0.1f);
			((Behaviour)localLight).enabled = true;
			yield return (object)new WaitForSeconds(0.1f);
			((Behaviour)localLight).enabled = false;
		}

		private string onCommandParse()
		{
			//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_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			string text = null;
			text += "the command isn't fully implemented, nor is the upgrade system, so here's some stats from your entire game session up to this point\n\n";
			text = text + "Flashlight toggle count: " + toggleAmount + "\n";
			text = text + "Time spent using the light: " + $"{flashOnTime:.00}" + " seconds\n";
			text = text + "Flashlight recharge method: " + selectedRechargeOption.ToString() + "\n";
			timesCommandUsed++;
			text = text + "Times you used this command: " + timesCommandUsed + "\n";
			if (timesCommandUsed <= 1)
			{
				text += "\nsadly these stats will get reset when starting up the game again but i'll try making it an actual mini-save file if it turns out to be a good feature to add in\n";
			}
			if (Plugin.enableNetworking.Value)
			{
				TerminalApi.AddCommand("Localflashlight sayhi", new CommandInfo
				{
					DisplayTextSupplier = terminalSayHi,
					Category = null
				}, (string)null, true);
			}
			return text;
		}

		private string terminalSayHi()
		{
			LFNetworkHandler.Instance.SayHiServerRpc(player_controller.playerClientId);
			return "Said hello to all the people in the server!\n\nhow'd you find this anyway?\n";
		}
	}
	internal class Patches : MonoBehaviour
	{
		private static GameObject UIContainer;

		private static GameObject frameObj;

		private static GameObject meterObj;

		private static GameObject textObj;

		private static GameObject warningObj;

		private static TextMeshProUGUI textmesh;

		private static Image frameImage;

		private static Image meterImage;

		private static Image warningImage;

		private static Sprite frame;

		private static Sprite meter;

		private static readonly Sprite warning = Plugin.bundle.LoadAsset<Sprite>("warning");

		public static Color UIColorHex;

		private static bool warningEnabled = Plugin.UIDisabledLowBatteryWarning.Value;

		private static float warningPercent = Plugin.LowBatteryWarningPercentage.Value;

		private static BatteryDisplayOptions selectedStyle;

		private static TextDisplayOptions selectedText;

		private static RechargeOptions selectedRecharge;

		private static float elemScale;

		public static bool isFlashlightHeld = false;

		public static bool isFlashlightPocketed = false;

		public static bool isFacilityPowered = true;

		public static float randomLightInterferenceMultiplier;

		private static float targetAlpha;

		private static float soundCd = 1f;

		private static float lastSoundTime = 0f;

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		internal static void MakeLightController()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			GameObject val = new GameObject("LightController");
			val.transform.SetParent(((Component)StartOfRound.Instance.localPlayerController).transform, false);
			val.AddComponent<LightScript>();
			StartOfRound.Instance.localPlayerController.nightVision.intensity = StartOfRound.Instance.localPlayerController.nightVision.intensity * ((float)Plugin.DarkVisionMult.Value / 100f);
		}

		[HarmonyPatch(typeof(GameNetworkManager), "Disconnect")]
		[HarmonyPostfix]
		internal static void DestroyLightController()
		{
			GameObject val = GameObject.Find("LightController");
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)val);
			}
			TerminalApi.DeleteKeyword("LocalFlashlight");
		}

		[HarmonyPatch(typeof(HUDManager), "Awake")]
		[HarmonyPostfix]
		internal static void GetBatteryUI(ref HUDManager __instance)
		{
			selectedStyle = Plugin.BatteryDisplay.Value;
			selectedText = Plugin.TextDisplay.Value;
			warningEnabled = Plugin.UIDisabledLowBatteryWarning.Value;
			warningPercent = Plugin.LowBatteryWarningPercentage.Value;
			elemScale = Plugin.UIScale.Value;
			selectedRecharge = Plugin.rechargeOption.Value;
			isFacilityPowered = true;
			ColorUtility.TryParseHtmlString(Plugin.HUDColorHex.Value, ref UIColorHex);
			MakeIndicator(__instance);
		}

		[HarmonyPatch(typeof(HUDManager), "Update")]
		[HarmonyPostfix]
		internal static void UpdateBatteryInfo(ref HUDManager __instance)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)UIContainer == (Object)null)
			{
				MakeIndicator(__instance);
				return;
			}
			try
			{
				float batteryTime = LightScript.batteryTime;
				float num = Mathf.FloorToInt(batteryTime / 60f);
				float num2 = Mathf.FloorToInt(batteryTime % 60f);
				UIContainer.transform.localPosition = Vector2.op_Implicit(new Vector2(Plugin.UIPositionX.Value, Plugin.UIPositionY.Value));
				elemScale = Plugin.UIScale.Value;
				UIContainer.transform.localScale = new Vector3(elemScale, elemScale, elemScale);
				UIContainer.GetComponent<CanvasGroup>().alpha = Mathf.Lerp(UIContainer.GetComponent<CanvasGroup>().alpha, targetAlpha, Time.deltaTime * 6f);
				if ((selectedStyle == BatteryDisplayOptions.Percentage) | (selectedStyle == BatteryDisplayOptions.Bar) | (selectedStyle == BatteryDisplayOptions.VerticalBar) | (selectedStyle == BatteryDisplayOptions.CircularBar) | (selectedStyle == BatteryDisplayOptions.All))
				{
					targetAlpha = ((!Plugin.HideUI.Value) ? 1f : ((LightScript.UIHideTime < 0f) ? Plugin.UIHiddenAlpha.Value : 1f));
					if (selectedStyle != BatteryDisplayOptions.Percentage)
					{
						meterImage.fillAmount = LightScript.BatteryClamped;
					}
				}
				if (selectedStyle == BatteryDisplayOptions.Disabled)
				{
					UIContainer.SetActive(warningEnabled && LightScript.truePercentBattery <= warningPercent);
				}
				ColorUtility.TryParseHtmlString(Plugin.HUDColorHex.Value, ref UIColorHex);
				if ((Object)(object)frameObj != (Object)null && selectedStyle == BatteryDisplayOptions.Bar)
				{
					((Graphic)frameImage).color = UIColorHex;
				}
				if ((Object)(object)meterObj != (Object)null)
				{
					((Graphic)meterImage).color = UIColorHex;
				}
				if ((Object)(object)warningObj != (Object)null)
				{
					((Graphic)warningImage).color = UIColorHex;
					warningPercent = Plugin.LowBatteryWarningPercentage.Value;
					warningEnabled = Plugin.UIDisabledLowBatteryWarning.Value;
				}
				if ((Object)(object)textObj != (Object)null)
				{
					((Graphic)textmesh).color = UIColorHex;
				}
				if (!((selectedStyle == BatteryDisplayOptions.All) | (selectedStyle == BatteryDisplayOptions.Percentage)) || (Object)(object)textmesh == (Object)null)
				{
					return;
				}
				switch (selectedText)
				{
				case TextDisplayOptions.Percent:
					if (LightScript.batteryTime > 0f || LightScript.batteryTime < LightScript.maxBatteryTime)
					{
						((TMP_Text)textmesh).text = LightScript.BatteryPercent + "%";
					}
					if (LightScript.batteryTime <= 0f)
					{
						((TMP_Text)textmesh).text = "0%";
					}
					if (LightScript.batteryTime >= LightScript.maxBatteryTime)
					{
						((TMP_Text)textmesh).text = "100%";
					}
					break;
				case TextDisplayOptions.AccuratePercent:
					if (LightScript.batteryTime > 0f || LightScript.batteryTime < LightScript.maxBatteryTime)
					{
						((TMP_Text)textmesh).text = LightScript.truePercentBattery.ToString("0.0") + "%";
					}
					if (LightScript.batteryTime <= 0f)
					{
						((TMP_Text)textmesh).text = "0.0%";
					}
					if (LightScript.batteryTime >= LightScript.maxBatteryTime)
					{
						((TMP_Text)textmesh).text = "100.0%";
					}
					break;
				case TextDisplayOptions.Time:
					if (LightScript.batteryTime > 0f || LightScript.batteryTime < LightScript.maxBatteryTime)
					{
						((TMP_Text)textmesh).text = $"{num:0}:{num2:00}";
					}
					if (LightScript.batteryTime <= 0f)
					{
						((TMP_Text)textmesh).text = "0:00";
					}
					if (LightScript.batteryTime >= LightScript.maxBatteryTime)
					{
						((TMP_Text)textmesh).text = $"{Mathf.FloorToInt(LightScript.maxBatteryTime / 60f):0}:{Mathf.RoundToInt(LightScript.maxBatteryTime % 60f):00}";
					}
					break;
				case TextDisplayOptions.All:
					if (LightScript.batteryTime > 0f || LightScript.batteryTime < LightScript.maxBatteryTime)
					{
						((TMP_Text)textmesh).text = LightScript.truePercentBattery.ToString("0.0") + "%" + $" | {num:0}:{num2:00}";
					}
					if (LightScript.batteryTime <= 0f)
					{
						((TMP_Text)textmesh).text = "0.0% | 0:00";
					}
					if (LightScript.batteryTime >= LightScript.maxBatteryTime)
					{
						((TMP_Text)textmesh).text = "100.0%" + $" | {Mathf.FloorToInt(LightScript.maxBatteryTime / 60f):0}:{Mathf.RoundToInt(LightScript.maxBatteryTime % 60f):00}";
					}
					break;
				}
			}
			catch (Exception arg)
			{
				Plugin.mls.LogError((object)$"error while updating hud!! is the light script even there?? is the hud even there????\n{arg}");
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "ShipHasLeft")]
		[HarmonyPostfix]
		internal static void ReDisableHUD()
		{
			if (selectedRecharge == RechargeOptions.FacilityPowered)
			{
				UIContainer.SetActive(false);
			}
			isFacilityPowered = true;
			if (StartOfRound.Instance.localPlayerController.isPlayerDead)
			{
				StartOfRound.Instance.localPlayerController.pocketedFlashlight = null;
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "openingDoorsSequence")]
		[HarmonyPostfix]
		internal static void FixValues()
		{
			isFlashlightHeld = false;
			isFlashlightPocketed = false;
			randomLightInterferenceMultiplier = Random.Range(0.1f, 0.4f);
		}

		[HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")]
		[HarmonyPostfix]
		internal static void PocketedFlashlightChecks()
		{
			try
			{
				PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
				if ((!((NetworkBehaviour)localPlayerController).IsOwner || !localPlayerController.isPlayerControlled || (((NetworkBehaviour)localPlayerController).IsServer && !localPlayerController.isHostPlayerObject)) && !localPlayerController.isTestingPlayer)
				{
					return;
				}
				if (!localPlayerController.isPlayerDead)
				{
					if (localPlayerController.currentlyHeldObjectServer is FlashlightItem && (Object)(object)localPlayerController.currentlyHeldObjectServer != (Object)(object)localPlayerController.pocketedFlashlight)
					{
						localPlayerController.pocketedFlashlight = localPlayerController.currentlyHeldObjectServer;
					}
					if (!((Object)(object)localPlayerController.pocketedFlashlight == (Object)null))
					{
						if (localPlayerController.currentlyHeldObjectServer is FlashlightItem && localPlayerController.isHoldingObject && !localPlayerController.pocketedFlashlight.insertedBattery.empty)
						{
							isFlashlightHeld = true;
						}
						else
						{
							isFlashlightHeld = false;
						}
						if (localPlayerController.pocketedFlashlight is FlashlightItem && localPlayerController.pocketedFlashlight.isHeld && !localPlayerController.pocketedFlashlight.insertedBattery.empty)
						{
							isFlashlightPocketed = true;
						}
						else
						{
							isFlashlightPocketed = false;
						}
					}
				}
				else
				{
					localPlayerController.pocketedFlashlight = null;
					isFlashlightHeld = false;
					isFlashlightPocketed = false;
				}
			}
			catch
			{
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
		[HarmonyPostfix]
		internal static void ClearLightA(ref PlayerControllerB __instance)
		{
			__instance.pocketedFlashlight = null;
			isFlashlightHeld = false;
			isFlashlightPocketed = false;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		internal static void ClearLightB()
		{
			isFlashlightHeld = false;
			isFlashlightPocketed = false;
		}

		[HarmonyPatch(typeof(RoundManager), "PowerSwitchOnClientRpc")]
		[HarmonyPostfix]
		private static void TurnOnFlashlightPower()
		{
			isFacilityPowered = true;
			if (selectedRecharge == RechargeOptions.FacilityPowered)
			{
				UIContainer.SetActive(!isFacilityPowered);
			}
			lastSoundTime = Time.time;
		}

		[HarmonyPatch(typeof(RoundManager), "PowerSwitchOffClientRpc")]
		[HarmonyPostfix]
		private static void TurnOffFlashlightPower()
		{
			isFacilityPowered = false;
			if (selectedRecharge == RechargeOptions.FacilityPowered)
			{
				UIContainer.SetActive(!isFacilityPowered);
				if (Time.time - lastSoundTime > soundCd)
				{
					LightScript.PlayNoise(LightScript.activeClips[6], 0.2f, playForWorld: false);
				}
			}
		}

		private static void MakeIndicator(HUDManager hudManager)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Expected O, but got Unknown
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_08e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_08f1: Expected O, but got Unknown
			//IL_094f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0964: Unknown result type (might be due to invalid IL or missing references)
			//IL_0969: Unknown result type (might be due to invalid IL or missing references)
			//IL_0988: Unknown result type (might be due to invalid IL or missing references)
			//IL_098d: Unknown result type (might be due to invalid IL or missing references)
			//IL_09bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_09c7: Expected O, but got Unknown
			//IL_0a11: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a3e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a43: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a62: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a67: Unknown result type (might be due to invalid IL or missing references)
			//IL_06bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c6: Expected O, but got Unknown
			//IL_0724: Unknown result type (might be due to invalid IL or missing references)
			//IL_0739: Unknown result type (might be due to invalid IL or missing references)
			//IL_073e: Unknown result type (might be due to invalid IL or missing references)
			//IL_075d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0762: Unknown result type (might be due to invalid IL or missing references)
			//IL_0792: Unknown result type (might be due to invalid IL or missing references)
			//IL_079c: Expected O, but got Unknown
			//IL_07e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_082b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0830: Unknown result type (might be due to invalid IL or missing references)
			//IL_084f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0854: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cf: Expected O, but got Unknown
			//IL_042c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0431: Unknown result type (might be due to invalid IL or missing references)
			//IL_0459: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cb: Expected O, but got Unknown
			//IL_0529: Unknown result type (might be due to invalid IL or missing references)
			//IL_053e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0543: Unknown result type (might be due to invalid IL or missing references)
			//IL_0562: Unknown result type (might be due to invalid IL or missing references)
			//IL_0567: Unknown result type (might be due to invalid IL or missing references)
			//IL_0597: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a1: Expected O, but got Unknown
			//IL_05eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0618: Unknown result type (might be due to invalid IL or missing references)
			//IL_061d: Unknown result type (might be due to invalid IL or missing references)
			//IL_063c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0641: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ae1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aeb: Expected O, but got Unknown
			//IL_0b2a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b59: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				UIContainer = new GameObject("LocalFlashlightHUDElements", new Type[2]
				{
					typeof(RectTransform),
					typeof(CanvasGroup)
				});
				UIContainer.transform.SetParent(hudManager.HUDContainer.transform, false);
				UIContainer.transform.localPosition = Vector2.op_Implicit(new Vector2(Plugin.UIPositionX.Value, Plugin.UIPositionY.Value));
				UIContainer.transform.localScale = new Vector3(elemScale, elemScale, elemScale);
				switch (selectedStyle)
				{
				case BatteryDisplayOptions.Bar:
					frame = Plugin.bundle.LoadAsset<Sprite>("frame.png");
					meter = Plugin.bundle.LoadAsset<Sprite>("meter.png");
					frameObj = new GameObject("FrameHUD", new Type[2]
					{
						typeof(RectTransform),
						typeof(Image)
					});
					frameObj.transform.SetParent(UIContainer.transform, false);
					frameObj.GetComponent<RectTransform>();
					frameImage = frameObj.GetComponent<Image>();
					frameImage.sprite = frame;
					((Graphic)frameImage).color = UIColorHex;
					frameObj.transform.localPosition = Vector2.op_Implicit(Vector2.zero);
					frameObj.transform.localScale = Vector2.op_Implicit(new Vector2(1.5f, 1.25f));
					meterObj = new GameObject("MeterHUD", new Type[2]
					{
						typeof(RectTransform),
						typeof(Image)
					});
					meterObj.transform.SetParent(UIContainer.transform, false);
					meterObj.GetComponent<RectTransform>();
					meterImage = meterObj.GetComponent<Image>();
					meterImage.sprite = meter;
					((Graphic)meterImage).color = UIColorHex;
					meterImage.type = (Type)3;
					meterImage.fillMethod = (FillMethod)0;
					meterObj.transform.localPosition = Vector2.op_Implicit(Vector2.zero);
					meterObj.transform.localScale = Vector2.op_Implicit(new Vector2(1.5f, 1.25f));
					UIContainer.SetActive(selectedRecharge != RechargeOptions.FacilityPowered || !isFacilityPowered);
					frameObj.SetActive(true);
					meterObj.SetActive(true);
					break;
				case BatteryDisplayOptions.Percentage:
				{
					textmesh = UIContainer.AddComponent<TextMeshProUGUI>();
					RectTransform rectTransform = ((TMP_Text)textmesh).rectTransform;
					((Transform)rectTransform).SetParent(UIContainer.transform, false);
					((TMP_Text)textmesh).font = ((TMP_Text)hudManager.controlTipLines[0]).font;
					((Graphic)textmesh).color = UIColorHex;
					((TMP_Text)textmesh).fontSize = 23f;
					((TMP_Text)textmesh).overflowMode = (TextOverflowModes)0;
					((Behaviour)textmesh).enabled = true;
					((TMP_Text)textmesh).text = "";
					UIContainer.SetActive(selectedRecharge != RechargeOptions.FacilityPowered || !isFacilityPowered);
					break;
				}
				case BatteryDisplayOptions.All:
				{
					frame = Plugin.bundle.LoadAsset<Sprite>("meter.png");
					meter = Plugin.bundle.LoadAsset<Sprite>("meter.png");
					textObj = new GameObject("TextHUD", new Type[2]
					{
						typeof(RectTransform),
						typeof(TextMeshProUGUI)
					});
					textObj.transform.SetParent(UIContainer.transform, false);
					textObj.GetComponent<RectTransform>();
					textmesh = textObj.GetComponent<TextMeshProUGUI>();
					RectTransform rectTransform2 = ((TMP_Text)textmesh).rectTransform;
					((Transform)rectTransform2).SetParent(textObj.transform, false);
					((Transform)rectTransform2).localPosition = Vector2.op_Implicit(new Vector2(15f, 0f));
					((TMP_Text)textmesh).font = ((TMP_Text)hudManager.controlTipLines[0]).font;
					((Graphic)textmesh).color = UIColorHex;
					((TMP_Text)textmesh).fontSize = 20f;
					((TMP_Text)textmesh).overflowMode = (TextOverflowModes)0;
					((Behaviour)textmesh).enabled = true;
					((TMP_Text)textmesh).text = "";
					frameObj = new GameObject("FrameHUD", new Type[2]
					{
						typeof(RectTransform),
						typeof(Image)
					});
					frameObj.transform.SetParent(UIContainer.transform, false);
					frameObj.GetComponent<RectTransform>();
					frameImage = frameObj.GetComponent<Image>();
					frameImage.sprite = frame;
					((Graphic)frameImage).color = new Color(0f, 0f, 0f, 0.5f);
					frameObj.transform.localPosition = Vector2.op_Implicit(Vector2.zero);
					frameObj.transform.localScale = Vector2.op_Implicit(new Vector2(2.625f, 0.875f));
					meterObj = new GameObject("MeterHUD", new Type[2]
					{
						typeof(RectTransform),
						typeof(Image)
					});
					meterObj.transform.SetParent(UIContainer.transform, false);
					meterObj.GetComponent<RectTransform>();
					meterImage = meterObj.GetComponent<Image>();
					meterImage.sprite = meter;
					((Graphic)meterImage).color = UIColorHex;
					meterImage.type = (Type)3;
					meterImage.fillMethod = (FillMethod)0;
					meterObj.transform.localPosition = Vector2.op_Implicit(Vector2.zero);
					meterObj.transform.localScale = Vector2.op_Implicit(new Vector2(2.625f, 0.875f));
					UIContainer.SetActive(selectedRecharge != RechargeOptions.FacilityPowered || !isFacilityPowered);
					break;
				}
				case BatteryDisplayOptions.CircularBar:
					frame = Plugin.bundle.LoadAsset<Sprite>("meter2.png");
					meter = Plugin.bundle.LoadAsset<Sprite>("meter2.png");
					frameObj = new GameObject("FrameHUD", new Type[2]
					{
						typeof(RectTransform),
						typeof(Image)
					});
					frameObj.transform.SetParent(UIContainer.transform, false);
					frameObj.GetComponent<RectTransform>();
					frameImage = frameObj.GetComponent<Image>();
					frameImage.sprite = frame;
					((Graphic)frameImage).color = new Color(0f, 0f, 0f, 0.3f);
					frameObj.transform.localPosition = Vector2.op_Implicit(Vector2.zero);
					frameObj.transform.localScale = Vector2.op_Implicit(new Vector2(0.7f, 0.7f));
					meterObj = new GameObject("MeterHUD", new Type[2]
					{
						typeof(RectTransform),
						typeof(Image)
					});
					meterObj.transform.SetParent(UIContainer.transform, false);
					meterObj.GetComponent<RectTransform>();
					meterImage = meterObj.GetComponent<Image>();
					meterImage.sprite = meter;
					((Graphic)meterImage).color = UIColorHex;
					meterImage.type = (Type)3;
					meterImage.fillMethod = (FillMethod)4;
					meterImage.fillClockwise = false;
					meterImage.fillOrigin = 2;
					meterObj.transform.localPosition = Vector2.op_Implicit(Vector2.zero);
					meterObj.transform.localScale = Vector2.op_Implicit(new Vector2(0.7f, 0.7f));
					UIContainer.SetActive(selectedRecharge != RechargeOptions.FacilityPowered || !isFacilityPowered);
					frameObj.SetActive(true);
					meterObj.SetActive(true);
					break;
				case BatteryDisplayOptions.VerticalBar:
					frame = Plugin.bundle.LoadAsset<Sprite>("meter3.png");
					meter = Plugin.bundle.LoadAsset<Sprite>("meter3.png");
					frameObj = new GameObject("FrameHUD", new Type[2]
					{
						typeof(RectTransform),
						typeof(Image)
					});
					frameObj.transform.SetParent(UIContainer.transform, false);
					frameObj.GetComponent<RectTransform>();
					frameImage = frameObj.GetComponent<Image>();
					frameImage.sprite = frame;
					((Graphic)frameImage).color = new Color(0f, 0f, 0f, 0.5f);
					frameObj.transform.localPosition = Vector2.op_Implicit(Vector2.zero);
					frameObj.transform.localScale = Vector2.op_Implicit(new Vector2(1.25f, 3f));
					meterObj = new GameObject("MeterHUD", new Type[2]
					{
						typeof(RectTransform),
						typeof(Image)
					});
					meterObj.transform.SetParent(UIContainer.transform, false);
					meterObj.GetComponent<RectTransform>();
					meterImage = meterObj.GetComponent<Image>();
					meterImage.sprite = meter;
					((Graphic)meterImage).color = UIColorHex;
					meterImage.type = (Type)3;
					meterImage.fillMethod = (FillMethod)1;
					meterObj.transform.localPosition = Vector2.op_Implicit(Vector2.zero);
					meterObj.transform.localScale = Vector2.op_Implicit(new Vector2(1.25f, 3f));
					UIContainer.SetActive(selectedRecharge != RechargeOptions.FacilityPowered || !isFacilityPowered);
					frameObj.SetActive(true);
					meterObj.SetActive(true);
					break;
				case BatteryDisplayOptions.Disabled:
					if (warningEnabled)
					{
						warningObj = new GameObject("WarningHUD", new Type[2]
						{
							typeof(RectTransform),
							typeof(Image)
						});
						warningObj.transform.SetParent(UIContainer.transform, false);
						warningObj.GetComponent<RectTransform>();
						warningObj.transform.localScale = new Vector3(0.7f, 0.7f, 0.7f);
						warningImage = warningObj.GetComponent<Image>();
						warningImage.sprite = warning;
						((Graphic)warningImage).color = UIColorHex;
					}
					UIContainer.SetActive(false);
					break;
				}
			}
			catch (Exception arg)
			{
				Plugin.mls.LogError((object)$"error while making the hud?\n{arg}");
			}
		}
	}
	public class ToggleButton : LcInputActions
	{
		[InputAction("<Keyboard>/f", Name = "Toggle key")]
		public InputAction toggleKey { get; set; }

		[InputAction("<Keyboard>/h", Name = "Position and angle switch key")]
		public InputAction switchLightPosKey { get; set; }

		[InputAction("<Keyboard>/q", Name = "Recharge key")]
		public InputAction rechargeKey { get; set; }
	}
	[BepInPlugin("command.localFlashlight", "LocalFlashlight", "1.4.13")]
	[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 VERSION = "1.4.13";

		public const string GUID = "command.localFlashlight";

		public const string NAME = "LocalFlashlight";

		public static AssetBundle bundle;

		internal static ToggleButton flashlightToggleInstance = new ToggleButton();

		private readonly Harmony har = new Harmony("command.localFlashlight");

		private static string sceneName;

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

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

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

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

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

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

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

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

		public static ConfigEntry<BatteryDisplayOptions> BatteryDisplay { get; private set; }

		public static ConfigEntry<TextDisplayOptions> TextDisplay { get; private set; }

		public static ConfigEntry<SoundOptions> soundOption { get; private set; }

		public static ConfigEntry<RechargeOptions> rechargeOption { get; private set; }

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

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

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

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

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

		public static ConfigEntry<int> LowBatteryWarningPercentage { get; private set; }

		public static ConfigEntry<int> FlashVolume { get; private set; }

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

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

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

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

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

		public static ConfigEntry<int> shakeStaminaConsume { get; private set; }

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

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

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

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

		public static ConfigEntry<int> flashlightStopDimBatteryValue { get; private set; }

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

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

		public static ConfigEntry<string> flashlightColorHex { get; private set; }

		public static ConfigEntry<string> HUDColorHex { get; private set; }

		public static ConfigEntry<int> DarkVisionMult { get; private set; }

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

		public static ManualLogSource mls { get; private set; }

		private void Awake()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Expected O, but got Unknown
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Expected O, but got Unknown
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Expected O, but got Unknown
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Expected O, but got Unknown
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Expected O, but got Unknown
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Expected O, but got Unknown
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Expected O, but got Unknown
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Expected O, but got Unknown
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Expected O, but got Unknown
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Expected O, but got Unknown
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Expected O, but got Unknown
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Expected O, but got Unknown
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Expected O, but got Unknown
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Expected O, but got Unknown
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Expected O, but got Unknown
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Expected O, but got Unknown
			//IL_031a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0324: Expected O, but got Unknown
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0369: Expected O, but got Unknown
			//IL_0364: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Expected O, but got Unknown
			//IL_038f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0399: Expected O, but got Unknown
			//IL_03a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bc: Expected O, but got Unknown
			//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c8: Expected O, but got Unknown
			//IL_03ce: Expected O, but got Unknown
			//IL_03c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d3: Expected O, but got Unknown
			//IL_0402: Unknown result type (might be due to invalid IL or missing references)
			//IL_040c: Expected O, but got Unknown
			//IL_0417: Unknown result type (might be due to invalid IL or missing references)
			//IL_041c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0424: Unknown result type (might be due to invalid IL or missing references)
			//IL_042f: Expected O, but got Unknown
			//IL_0430: Unknown result type (might be due to invalid IL or missing references)
			//IL_043b: Expected O, but got Unknown
			//IL_0441: Expected O, but got Unknown
			//IL_043c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0446: Expected O, but got Unknown
			//IL_0475: Unknown result type (might be due to invalid IL or missing references)
			//IL_047f: Expected O, but got Unknown
			//IL_048a: Unknown result type (might be due to invalid IL or missing references)
			//IL_048f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0497: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a2: Expected O, but got Unknown
			//IL_04a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ae: Expected O, but got Unknown
			//IL_04b4: Expected O, but got Unknown
			//IL_04af: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b9: Expected O, but got Unknown
			//IL_04e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f2: Expected O, but got Unknown
			//IL_04fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0502: Unknown result type (might be due to invalid IL or missing references)
			//IL_050a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0515: Expected O, but got Unknown
			//IL_0516: Unknown result type (might be due to invalid IL or missing references)
			//IL_0521: Expected O, but got Unknown
			//IL_0527: Expected O, but got Unknown
			//IL_0522: Unknown result type (might be due to invalid IL or missing references)
			//IL_052c: Expected O, but got Unknown
			//IL_055b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0565: Expected O, but got Unknown
			//IL_0570: Unknown result type (might be due to invalid IL or missing references)
			//IL_0575: Unknown result type (might be due to invalid IL or missing references)
			//IL_057d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0588: Expected O, but got Unknown
			//IL_0589: Unknown result type (might be due to invalid IL or missing references)
			//IL_0594: Expected O, but got Unknown
			//IL_059a: Expected O, but got Unknown
			//IL_0595: Unknown result type (might be due to invalid IL or missing references)
			//IL_059f: Expected O, but got Unknown
			//IL_05c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d8: Expected O, but got Unknown
			//IL_05d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05dd: Expected O, but got Unknown
			//IL_0602: Unknown result type (might be due to invalid IL or missing references)
			//IL_060c: Expected O, but got Unknown
			//IL_0617: Unknown result type (might be due to invalid IL or missing references)
			//IL_061c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0624: Unknown result type (might be due to invalid IL or missing references)
			//IL_062b: Expected O, but got Unknown
			//IL_062c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0634: Expected O, but got Unknown
			//IL_063a: Expected O, but got Unknown
			//IL_0635: Unknown result type (might be due to invalid IL or missing references)
			//IL_063f: Expected O, but got Unknown
			//IL_0660: Unknown result type (might be due to invalid IL or missing references)
			//IL_066a: Expected O, but got Unknown
			//IL_0675: Unknown result type (might be due to invalid IL or missing references)
			//IL_067c: Expected O, but got Unknown
			//IL_068e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0698: Expected O, but got Unknown
			//IL_069b: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a5: Expected O, but got Unknown
			//IL_06c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d0: Expected O, but got Unknown
			//IL_06db: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ed: Expected O, but got Unknown
			//IL_06e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f2: Expected O, but got Unknown
			//IL_0719: Unknown result type (might be due to invalid IL or missing references)
			//IL_071e: Unknown result type (might be due to invalid IL or missing references)
			//IL_072b: Expected O, but got Unknown
			//IL_0726: Unknown result type (might be due to invalid IL or missing references)
			//IL_0730: Expected O, but got Unknown
			//IL_0755: Unknown result type (might be due to invalid IL or missing references)
			//IL_075f: Expected O, but got Unknown
			//IL_076a: Unknown result type (might be due to invalid IL or missing references)
			//IL_076f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0777: Unknown result type (might be due to invalid IL or missing references)
			//IL_077e: Expected O, but got Unknown
			//IL_077f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0787: Expected O, but got Unknown
			//IL_078d: Expected O, but got Unknown
			//IL_0788: Unknown result type (might be due to invalid IL or missing references)
			//IL_0792: Expected O, but got Unknown
			//IL_07b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_07bf: Expected O, but got Unknown
			//IL_07cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_07d9: Expected O, but got Unknown
			//IL_080c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0813: Expected O, but got Unknown
			//IL_0825: Unknown result type (might be due to invalid IL or missing references)
			//IL_082f: Expected O, but got Unknown
			//IL_0832: Unknown result type (might be due to invalid IL or missing references)
			//IL_083c: Expected O, but got Unknown
			//IL_0863: Unknown result type (might be due to invalid IL or missing references)
			//IL_0869: Expected O, but got Unknown
			//IL_0879: Unknown result type (might be due to invalid IL or missing references)
			//IL_0883: Expected O, but got Unknown
			//IL_08b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_08bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_08c8: Expected O, but got Unknown
			//IL_08c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_08cd: Expected O, but got Unknown
			//IL_08f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_08fc: Expected O, but got Unknown
			//IL_0907: Unknown result type (might be due to invalid IL or missing references)
			//IL_090e: Expected O, but got Unknown
			//IL_0920: Unknown result type (might be due to invalid IL or missing references)
			//IL_092a: Expected O, but got Unknown
			//IL_0940: Unknown result type (might be due to invalid IL or missing references)
			//IL_094a: Expected O, but got Unknown
			//IL_0971: Unknown result type (might be due to invalid IL or missing references)
			//IL_0978: Expected O, but got Unknown
			//IL_098a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0994: Expected O, but got Unknown
			//IL_0997: Unknown result type (might be due to invalid IL or missing references)
			//IL_09a1: Expected O, but got Unknown
			//IL_09c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_09cf: Expected O, but got Unknown
			//IL_09e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_09eb: Expected O, but got Unknown
			//IL_09ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_09f8: Expected O, but got Unknown
			//IL_0a1d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a27: Expected O, but got Unknown
			//IL_0a32: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a37: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a3f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a46: Expected O, but got Unknown
			//IL_0a47: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a4f: Expected O, but got Unknown
			//IL_0a55: Expected O, but got Unknown
			//IL_0a50: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a5a: Expected O, but got Unknown
			//IL_0a81: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a88: Expected O, but got Unknown
			//IL_0a9a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aa4: Expected O, but got Unknown
			//IL_0aa7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ab1: Expected O, but got Unknown
			//IL_0adc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ae1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ae9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0af4: Expected O, but got Unknown
			//IL_0af5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b00: Expected O, but got Unknown
			//IL_0b06: Expected O, but got Unknown
			//IL_0b01: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b0b: Expected O, but got Unknown
			//IL_0b36: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b3b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b43: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b4e: Expected O, but got Unknown
			//IL_0b4f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b5a: Expected O, but got Unknown
			//IL_0b60: Expected O, but got Unknown
			//IL_0b5b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b65: Expected O, but got Unknown
			//IL_0b90: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b95: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b9d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ba8: Expected O, but got Unknown
			//IL_0ba9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bb4: Expected O, but got Unknown
			//IL_0bba: Expected O, but got Unknown
			//IL_0bb5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bbf: Expected O, but got Unknown
			//IL_0bdc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0be6: Expected O, but got Unknown
			//IL_0bf1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bf6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bfe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c05: Expected O, but got Unknown
			//IL_0c06: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c0e: Expected O, but got Unknown
			//IL_0c14: Expected O, but got Unknown
			//IL_0c0f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c19: Expected O, but got Unknown
			//IL_0c44: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c49: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c51: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c5c: Expected O, but got Unknown
			//IL_0c5d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c68: Expected O, but got Unknown
			//IL_0c6e: Expected O, but got Unknown
			//IL_0c69: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c73: Expected O, but got Unknown
			//IL_0c9e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ca4: Expected O, but got Unknown
			//IL_0cb4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cbe: Expected O, but got Unknown
			//IL_0cd8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ce2: Expected O, but got Unknown
			//IL_0d09: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d10: Expected O, but got Unknown
			//IL_0d22: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d2c: Expected O, but got Unknown
			//IL_0d2f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d39: Expected O, but got Unknown
			mls = ((BaseUnityPlugin)this).Logger;
			Intensity = ((BaseUnityPlugin)this).Config.Bind<float>("Flashlight", "Light intensity", 350f, new ConfigDescription("The intensity of the light (in lumens, i think)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 5000f), Array.Empty<object>()));
			ConfigEntry<float> intensity = Intensity;
			FloatInputFieldOptions val = new FloatInputFieldOptions();
			((BaseOptions)val).RequiresRestart = false;
			((BaseOptions)val).CanModifyCallback = new CanModifyDelegate(modifySpecialConfig);
			((BaseRangeOptions<float>)(object)val).Min = 10f;
			((BaseRangeOptions<float>)(object)val).Max = 5000f;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(intensity, val));
			Range = ((BaseUnityPlugin)this).Config.Bind<float>("Flashlight", "Light range", 17f, new ConfigDescription("The range of the light (in units)", (AcceptableValueBase)null, Array.Empty<object>()));
			ConfigEntry<float> range = Range;
			val = new FloatInputFieldOptions();
			((BaseOptions)val).RequiresRestart = false;
			((BaseOptions)val).CanModifyCallback = new CanModifyDelegate(modifySpecialConfig);
			((BaseRangeOptions<float>)(object)val).Min = 1f;
			((BaseRangeOptions<float>)(object)val).Max = float.PositiveInfinity;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(range, val));
			Angle = ((BaseUnityPlugin)this).Config.Bind<float>("Flashlight", "Light angle", 55f, new ConfigDescription("The size of the light's circle (Spot angle)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 120f), Array.Empty<object>()));
			ConfigEntry<float> angle = Angle;
			val = new FloatInputFieldOptions();
			((BaseOptions)val).RequiresRestart = false;
			((BaseOptions)val).CanModifyCallback = new CanModifyDelegate(modifySpecialConfig);
			((BaseRangeOptions<float>)(object)val).Min = 1f;
			((BaseRangeOptions<float>)(object)val).Max = 120f;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(angle, val));
			BatteryLife = ((BaseUnityPlugin)this).Config.Bind<float>("Battery", "Battery life", 12f, new ConfigDescription("The battery life of the flashlight (in seconds)", (AcceptableValueBase)null, Array.Empty<object>()));
			ConfigEntry<float> batteryLife = BatteryLife;
			val = new FloatInputFieldOptions();
			((BaseOptions)val).RequiresRestart = false;
			((BaseOptions)val).CanModifyCallback = new CanModifyDelegate(modifyConfig);
			((BaseRangeOptions<float>)(object)val).Min = 1f;
			((BaseRangeOptions<float>)(object)val).Max = float.PositiveInfinity;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(batteryLife, val));
			RechargeMult = ((BaseUnityPlugin)this).Config.Bind<float>("Battery", "Recharge Multiplier", 0.8f, new ConfigDescription("The flashlight's battery recharge multiplier (For instance, setting it to 1 will make it recharge at about the same rate that it is depleted when using the Time recharge method, however this config also applies to other recharge methods)", (AcceptableValueBase)null, Array.Empty<object>()));
			ConfigEntry<float> rechargeMult = RechargeMult;
			val = new FloatInputFieldOptions();
			((BaseOptions)val).RequiresRestart = false;
			((BaseOptions)val).CanModifyCallback = new CanModifyDelegate(modifyConfig);
			((BaseRangeOptions<float>)(object)val).Min = 0f;
			((BaseRangeOptions<float>)(object)val).Max = float.PositiveInfinity;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(rechargeMult, val));
			BatteryDisplay = ((BaseUnityPlugin)this).Config.Bind<BatteryDisplayOptions>("Indicator", "Battery Details", BatteryDisplayOptions.Bar, "How the indicator displays the flashlight's remaining battery time");
			ConfigEntry<BatteryDisplayOptions> batteryDisplay = BatteryDisplay;
			EnumDropDownOptions val2 = new EnumDropDownOptions();
			((BaseOptions)val2).RequiresRestart = false;
			((BaseOptions)val2).CanModifyCallback = new CanModifyDelegate(modifyConfig);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)new EnumDropDownConfigItem<BatteryDisplayOptions>(batteryDisplay, val2));
			TextDisplay = ((BaseUnityPlugin)this).Config.Bind<TextDisplayOptions>("Indicator", "Battery text display", TextDisplayOptions.Percent, "(Only applies to \"Text\" and \"All\" indicator display options) Wherether the mod should display the battery information text in percents, accurate percents or time left");
			ConfigEntry<TextDisplayOptions> textDisplay = TextDisplay;
			val2 = new EnumDropDownOptions();
			((BaseOptions)val2).RequiresRestart = false;
			((BaseOptions)val2).CanModifyCallback = new CanModifyDelegate(modifyConfig);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)new EnumDropDownConfigItem<TextDisplayOptions>(textDisplay, val2));
			HideUI = ((BaseUnityPlugin)this).Config.Bind<bool>("Indicator", "Indicator fading", true, "When true, the indicator will hide after a while of not using the flashlight");
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(HideUI, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}));
			HideUIDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Indicator", "Battery indicator fade delay", 1.5f, new ConfigDescription("The delay before fading out the indicator (in seconds)", (AcceptableValueBase)null, Array.Empty<object>()));
			ConfigEntry<float> hideUIDelay = HideUIDelay;
			FloatInputFieldOptions val3 = new FloatInputFieldOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<float>)val3).Min = 0f;
			((BaseRangeOptions<float>)val3).Max = float.PositiveInfinity;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(hideUIDelay, val3));
			UIHiddenAlpha = ((BaseUnityPlugin)this).Config.Bind<float>("Indicator", "Indicator faded out opacity", 0.2f, new ConfigDescription("The opacity of the indicator when the indicator is faded out", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			ConfigEntry<float> uIHiddenAlpha = UIHiddenAlpha;
			FloatInputFieldOptions val4 = new FloatInputFieldOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<float>)val4).Min = 0f;
			((BaseRangeOptions<float>)val4).Max = 1f;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(uIHiddenAlpha, val4));
			UIScale = ((BaseUnityPlugin)this).Config.Bind<float>("Indicator", "Indicator scale", 1f, new ConfigDescription("The scale of the indicator, updates in-game", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1f), Array.Empty<object>()));
			ConfigEntry<float> uIScale = UIScale;
			FloatInputFieldOptions val5 = new FloatInputFieldOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<float>)val5).Min = 0.1f;
			((BaseRangeOptions<float>)val5).Max = float.PositiveInfinity;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(uIScale, val5));
			UIPositionX = ((BaseUnityPlugin)this).Config.Bind<float>("Indicator", "IndicatorPositionX", 350f, new ConfigDescription("The position of the UI on the X axis, updates in-game", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-450f, 450f), Array.Empty<object>()));
			ConfigEntry<float> uIPositionX = UIPositionX;
			FloatSliderOptions val6 = new FloatSliderOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<float>)val6).Min = -450f;
			((BaseRangeOptions<float>)val6).Max = 450f;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatSliderConfigItem(uIPositionX, val6));
			UIPositionY = ((BaseUnityPlugin)this).Config.Bind<float>("Indicator", "IndicatorPositionY", -150f, new ConfigDescription("The position of the UI on the Y axis, updates in-game", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-280f, 280f), Array.Empty<object>()));
			ConfigEntry<float> uIPositionY = UIPositionY;
			FloatSliderOptions val7 = new FloatSliderOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<float>)val7).Min = -280f;
			((BaseRangeOptions<float>)val7).Max = 280f;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatSliderConfigItem(uIPositionY, val7));
			UIDisabledLowBatteryWarning = ((BaseUnityPlugin)this).Config.Bind<bool>("Indicator", "Low Battery Warning Toggle", true, "(Only applies to when the indicator is disabled) When true, shows a warning on the HUD when the battery reaches a certain percentage");
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(UIDisabledLowBatteryWarning, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}));
			LowBatteryWarningPercentage = ((BaseUnityPlugin)this).Config.Bind<int>("Indicator", "Low Battery Warning Percentage", 30, new ConfigDescription("(Only applies when the indicator is disabled) The percentage at which the low battery warning shows up", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			ConfigEntry<int> lowBatteryWarningPercentage = LowBatteryWarningPercentage;
			IntInputFieldOptions val8 = new IntInputFieldOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<int>)val8).Min = 0;
			((BaseRangeOptions<int>)val8).Max = 100;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new IntInputFieldConfigItem(lowBatteryWarningPercentage, val8));
			flashlightColorHex = ((BaseUnityPlugin)this).Config.Bind<string>("Colors", "Flashlight Color (Hex)", "#FFFFFF", new ConfigDescription("very important, add the # before the hex! if it breaks or doesn't work, try resetting the config and typing the code in manually", (AcceptableValueBase)null, Array.Empty<object>()));
			ConfigEntry<string> obj = flashlightColorHex;
			TextInputFieldOptions val9 = new TextInputFieldOptions();
			((BaseOptions)val9).RequiresRestart = false;
			((BaseOptions)val9).CanModifyCallback = new CanModifyDelegate(modifySpecialConfig);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new TextInputFieldConfigItem(obj, val9));
			HUDColorHex = ((BaseUnityPlugin)this).Config.Bind<string>("Colors", "Indicator Color (Hex)", "#FFFFFF", new ConfigDescription("very important, add the # before the hex! if it breaks or doesn't work, try resetting the config and typing the code in manually", (AcceptableValueBase)null, Array.Empty<object>()));
			LethalConfigManager.AddConfigItem((BaseConfigItem)new TextInputFieldConfigItem(HUDColorHex, new TextInputFieldOptions
			{
				RequiresRestart = false
			}));
			flashlightToggleModSynergyquestionmark = ((BaseUnityPlugin)this).Config.Bind<bool>("Other", "Prioritize flashlights in player inventory", true, "Setting this to true will prevent the light turning on while you have a flashlight in your inventory, however the local flashlight can still be turned off in case you picked up an active flashlight");
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(flashlightToggleModSynergyquestionmark, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}));
			FlashVolume = ((BaseUnityPlugin)this).Config.Bind<int>("Other", "Flashlight volume", 50, new ConfigDescription("Volume of all of the sounds that the flashlight makes. Does not apply to how well others can hear it.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			ConfigEntry<int> flashVolume = FlashVolume;
			IntSliderOptions val10 = new IntSliderOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<int>)val10).Min = 0;
			((BaseRangeOptions<int>)val10).Max = 100;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new IntSliderConfigItem(flashVolume, val10));
			soundOption = ((BaseUnityPlugin)this).Config.Bind<SoundOptions>("Other", "Sound options", SoundOptions.InGameFlashlight, "The flashlight has different sounds depending on what you chose. Does not apply to other players if you have networking enabled.");
			ConfigEntry<SoundOptions> obj2 = soundOption;
			val2 = new EnumDropDownOptions();
			((BaseOptions)val2).RequiresRestart = false;
			((BaseOptions)val2).CanModifyCallback = new CanModifyDelegate(modifyConfig);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)new EnumDropDownConfigItem<SoundOptions>(obj2, val2));
			ShadowsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Other", "Enable shadows", true, "When set to true, the light will also emit shadows");
			ConfigEntry<bool> shadowsEnabled = ShadowsEnabled;
			BoolCheckBoxOptions val11 = new BoolCheckBoxOptions();
			((BaseOptions)val11).RequiresRestart = false;
			((BaseOptions)val11).CanModifyCallback = new CanModifyDelegate(modifyConfig);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(shadowsEnabled, val11));
			rechargeOption = ((BaseUnityPlugin)this).Config.Bind<RechargeOptions>("Other", "Recharge method", RechargeOptions.Time, "The way that the flashlight can be recharged. Time, Shake and Dynamo are intended for shorter battery times while FacilityPowered and ShipRecharge are intended for longer battery times");
			ConfigEntry<RechargeOptions> obj3 = rechargeOption;
			val2 = new EnumDropDownOptions();
			((BaseOptions)val2).RequiresRestart = false;
			((BaseOptions)val2).CanModifyCallback = new CanModifyDelegate(modifyConfig);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)new EnumDropDownConfigItem<RechargeOptions>(obj3, val2));
			rechargeInOrbit = ((BaseUnityPlugin)this).Config.Bind<bool>("Other", "Fully recharge in orbit", true, "When set to true, fully recharges the flashlight when reaching orbit (when the round ends)");
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(rechargeInOrbit, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}));
			DarkVisionMult = ((BaseUnityPlugin)this).Config.Bind<int>("Other", "Ambient light intensity multiplier", 100, new ConfigDescription("Sets the multiplier of the ambient light. Useful if you feel like forcing yourself to use the flashlight more", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			ConfigEntry<int> darkVisionMult = DarkVisionMult;
			IntSliderOptions val12 = new IntSliderOptions();
			((BaseOptions)val12).RequiresRestart = false;
			((BaseOptions)val12).CanModifyCallback = new CanModifyDelegate(modifyConfig);
			((BaseRangeOptions<int>)(object)val12).Min = 0;
			((BaseRangeOptions<int>)(object)val12).Max = 100;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new IntSliderConfigItem(darkVisionMult, val12));
			flickerOnBatteryBurn = ((BaseUnityPlugin)this).Config.Bind<bool>("Other", "Enable light flickering", true, "When true, the flashlight attempts to flicker like the in-game flashlights, and also flickers when its battery runs out");
			ConfigEntry<bool> obj4 = flickerOnBatteryBurn;
			val11 = new BoolCheckBoxOptions();
			((BaseOptions)val11).RequiresRestart = false;
			((BaseOptions)val11).CanModifyCallback = new CanModifyDelegate(modifyConfig);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(obj4, val11));
			dimEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Other", "Enable light dimming", false, "When true, the intensity of the light dims down to a certain point");
			ConfigEntry<bool> obj5 = dimEnabled;
			val11 = new BoolCheckBoxOptions();
			((BaseOptions)val11).RequiresRestart = false;
			((BaseOptions)val11).CanModifyCallback = new CanModifyDelegate(modifyConfig);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(obj5, val11));
			flashlightStopDimBatteryValue = ((BaseUnityPlugin)this).Config.Bind<int>("Other", "Minimum battery amount dim", 15, new ConfigDescription("The battery percentage at which the light stops dimming", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			ConfigEntry<int> obj6 = flashlightStopDimBatteryValue;
			IntInputFieldOptions val13 = new IntInputFieldOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<int>)val13).Min = 0;
			((BaseRangeOptions<int>)val13).Max = 100;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new IntInputFieldConfigItem(obj6, val13));
			BatteryBurnOut = ((BaseUnityPlugin)this).Config.Bind<bool>("Time battery recharge configs", "Battery burnout", true, "When true, if the flashlight turns off with no battery left, the cooldown before starting to recharge lasts longer");
			ConfigEntry<bool> batteryBurnOut = BatteryBurnOut;
			val11 = new BoolCheckBoxOptions();
			((BaseOptions)val11).RequiresRestart = false;
			((BaseOptions)val11).CanModifyCallback = new CanModifyDelegate(modifyConfig);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(batteryBurnOut, val11));
			BatteryCool = ((BaseUnityPlugin)this).Config.Bind<float>("Time battery recharge configs", "Battery recharge cooldown", 1f, "The cooldown before the battery starts recharging normally");
			ConfigEntry<float> batteryCool = BatteryCool;
			FloatInputFieldOptions val14 = new FloatInputFieldOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<float>)val14).Min = 0f;
			((BaseRangeOptions<float>)val14).Max = float.PositiveInfinity;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(batteryCool, val14));
			BurnOutCool = ((BaseUnityPlugin)this).Config.Bind<float>("Time battery recharge configs", "Battery recharge cooldown (no battery)", 3f, "The cooldown before the battery starts recharging when it is fully depleted");
			ConfigEntry<float> burnOutCool = BurnOutCool;
			FloatInputFieldOptions val15 = new FloatInputFieldOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<float>)val15).Min = 0f;
			((BaseRangeOptions<float>)val15).Max = float.PositiveInfinity;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(burnOutCool, val15));
			shakeActionCooldown = ((BaseUnityPlugin)this).Config.Bind<float>("Shake battery recharge configs", "Shake cooldown", 0.2f, "The time needed to wait before you can recharge the flashlight again via shaking it");
			ConfigEntry<float> obj7 = shakeActionCooldown;
			FloatInputFieldOptions val16 = new FloatInputFieldOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<float>)val16).Min = 0f;
			((BaseRangeOptions<float>)val16).Max = float.PositiveInfinity;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(obj7, val16));
			shakeStaminaConsume = ((BaseUnityPlugin)this).Config.Bind<int>("Shake battery recharge configs", "Consumed stamina amount", 3, new ConfigDescription("The amount of stamina shaking the flashlight consumes", (AcceptableValueBase)null, Array.Empty<object>()));
			ConfigEntry<int> obj8 = shakeStaminaConsume;
			IntInputFieldOptions val17 = new IntInputFieldOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<int>)val17).Min = 0;
			((BaseRangeOptions<int>)val17).Max = 100;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new IntInputFieldConfigItem(obj8, val17));
			dynamoUseMoveMult = ((BaseUnityPlugin)this).Config.Bind<float>("Dynamo battery recharge configs", "Movespeed multiplier when recharging", 0.75f, "The multiplier of the player's normal movement speed while recharging the flashlight");
			ConfigEntry<float> obj9 = dynamoUseMoveMult;
			FloatInputFieldOptions val18 = new FloatInputFieldOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<float>)val18).Min = 0f;
			((BaseRangeOptions<float>)val18).Max = 1f;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(obj9, val18));
			apparaticeFlashlightIntensityMult = ((BaseUnityPlugin)this).Config.Bind<float>("Facility powered battery recharge configs", "Light intensity multiplier", 0.5f, "The multiplier of the light intensity when using the Facility Powered recharge option");
			ConfigEntry<float> obj10 = apparaticeFlashlightIntensityMult;
			val = new FloatInputFieldOptions();
			((BaseOptions)val).RequiresRestart = false;
			((BaseOptions)val).CanModifyCallback = new CanModifyDelegate(modifySpecialConfig);
			((BaseRangeOptions<float>)(object)val).Min = 0f;
			((BaseRangeOptions<float>)(object)val).Max = 1f;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatInputFieldConfigItem(obj10, val));
			enableNetworking = ((BaseUnityPlugin)this).Config.Bind<bool>("Networking", "(EXPERIMENTAL) Enable networking", false, "Enables networking. While this is enabled, you cannot join other servers without this mod and its networking also enabled. However, you can see other players' lights (alongside the intensity, range, angle and color they set) and hear their flashlight sounds");
			ConfigEntry<bool> obj11 = enableNetworking;
			val11 = new BoolCheckBoxOptions();
			((BaseOptions)val11).RequiresRestart = true;
			((BaseOptions)val11).CanModifyCallback = new CanModifyDelegate(denyNetworkConfigModify);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(obj11, val11));
			string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			string text = Path.Combine(directoryName, "localbundle");
			bundle = AssetBundle.LoadFromFile(text);
			if ((Object)(object)bundle == (Object)null)
			{
				mls.LogError((object)"failed to get mod assets!");
			}
			SceneManager.activeSceneChanged += SceneManager_activeSceneChanged;
			har.PatchAll(typeof(Patches));
			if (enableNetworking.Value)
			{
				mls.LogWarning((object)"NETWORKING ENABLED!!!! this is EXPERIMENTAL territory, and you're pretty much stuck joining servers where the host has LocalFlashlight and also has networking enabled! you may also encounter many many bugs!!!!! if you didn't mean to have this enabled, go back to the mod manager of your choice, disable the enable networking config that resides in the Networking category, and then restart the game.");
				har.PatchAll(typeof(NetworkingPatches));
				NetcodePatcher();
			}
			else
			{
				mls.LogInfo((object)"Networking disabled");
			}
		}

		private static void SceneManager_activeSceneChanged(Scene arg0, Scene arg1)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			Scene activeScene = SceneManager.GetActiveScene();
			sceneName = ((Scene)(ref activeScene)).name;
		}

		private static CanModifyResult modifyConfig()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			return CanModifyResult.op_Implicit((sceneName == "MainMenu", "This setting cannot be changed while in a lobby."));
		}

		private static CanModifyResult denyNetworkConfigModify()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: 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)
			return CanModifyResult.op_Implicit((false, "Enabling or disabling networking cannot be done while the game is open.\nEdit it from your mod manager of choice instead."));
		}

		private static CanModifyResult modifySpecialConfig()
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (enableNetworking.Value)
			{
				return CanModifyResult.op_Implicit((sceneName == "MainMenu", "Setting cannot be changed while in a lobby when networking is enabled."));
			}
			return CanModifyResult.op_Implicit((true, "?"));
		}

		private static void NetcodePatcher()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}
	}
}
namespace LocalFlashlight.Networking
{
	public class LFNetworkHandler : NetworkBehaviour
	{
		public static LFNetworkHandler Instance { get; private set; }

		public override void OnNetworkSpawn()
		{
			if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
			{
				LFNetworkHandler instance = Instance;
				if (instance != null)
				{
					((Component)instance).gameObject.GetComponent<NetworkObject>().Despawn(true);
				}
			}
			Instance = this;
			((NetworkBehaviour)this).OnNetworkSpawn();
		}

		[ServerRpc(RequireOwnership = false)]
		public void RequestAllLightsUpdateServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(4188426817u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 4188426817u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					Plugin.mls.LogInfo((object)"Recieved request to update lights on all clients!!");
					AcceptAllLightUpdateRequestClientRpc();
				}
			}
		}

		[ClientRpc]
		public void AcceptAllLightUpdateRequestClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(4106604540u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4106604540u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Plugin.mls.LogInfo((object)"Updating local light for all clients!");
					Color color = default(Color);
					ColorUtility.TryParseHtmlString(Plugin.flashlightColorHex.Value, ref color);
					MakeLightServerRpc(StartOfRound.Instance.localPlayerController.playerClientId, color, Plugin.Intensity.Value, Plugin.Range.Value, Plugin.Angle.Value, LightScript.publicFlashState);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void MakeLightServerRpc(ulong clientId, Color color, float intensity, float range, float angle, bool currentState)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be du

BepInEx/plugins/americanompany/Locker.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLib.Modules;
using Locker.MonoBehaviours;
using Locker.NetcodePatcher;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.VFX;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Locker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Locker")]
[assembly: AssemblyCopyright("Copyright © zealsprince 2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("335007C9-7068-4DF7-85B3-B406E9795203")]
[assembly: AssemblyFileVersion("1.2.6")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.6.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Locker
{
	internal class Assets
	{
		public enum LoadStatusCode : ushort
		{
			Success,
			Failed,
			Exists
		}

		public static AssetBundle Bundle;

		public static Dictionary<string, GameObject> Prefabs = new Dictionary<string, GameObject>();

		public static readonly Dictionary<string, string> Manifest = new Dictionary<string, string>
		{
			{ "locker", "assets/exported/locker/enemies/locker.prefab" },
			{ "lockerenemy", "assets/exported/locker/enemies/lockerenemy.asset" }
		};

		public static LoadStatusCode Load()
		{
			if ((Object)(object)Bundle != (Object)null)
			{
				return LoadStatusCode.Exists;
			}
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Locker");
			Bundle = AssetBundle.LoadFromFile(text);
			if ((Object)(object)Bundle == (Object)null)
			{
				Plugin.logger.LogInfo((object)("Failed to load asset bundle from path: " + text));
				return LoadStatusCode.Failed;
			}
			Plugin.logger.LogInfo((object)("Loaded asset bundle from path: " + text));
			string[] allAssetNames = Bundle.GetAllAssetNames();
			foreach (string text2 in allAssetNames)
			{
				Plugin.logger.LogDebug((object)("Found asset: " + text2));
			}
			foreach (KeyValuePair<string, string> item in Manifest)
			{
				Prefabs.Add(item.Key, Bundle.LoadAsset<GameObject>(item.Value));
			}
			return LoadStatusCode.Success;
		}

		public static GameObject SpawnPrefab(string name, Vector3 position)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (Prefabs.ContainsKey(name))
				{
					Plugin.logger.LogDebug((object)("Loading prefab '" + name + "'"));
					return Object.Instantiate<GameObject>(Prefabs[name], position, Quaternion.identity);
				}
				Plugin.logger.LogWarning((object)("Prefab " + name + " not found!"));
			}
			catch (Exception ex) when (ex is ArgumentException || ex is NullReferenceException)
			{
				Plugin.logger.LogError((object)ex.Message);
			}
			return null;
		}

		public static GameObject Get(string name)
		{
			if (Prefabs.ContainsKey(name))
			{
				return Prefabs[name];
			}
			return null;
		}
	}
	public class Config
	{
		public static ConfigEntry<int> LockerSpawnWeight;

		public static ConfigEntry<float> LockerSpawnPower;

		public static ConfigEntry<int> LockerSpawnMax;

		public static ConfigEntry<string> LockerSpawnLevelsSet;

		public static ConfigEntry<string> LockerSpawnLevelsWithWeight;

		public static ConfigEntry<float> LockerVolumeAdjustment;

		public static ConfigEntry<float> LockerMechanicsReactivationChance;

		public static void Load()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			LockerMechanicsReactivationChance = Plugin.config.Bind<float>("Mechanics", "LockerMechanicsReactivationChance", 50f, new ConfigDescription("Chance for the Locker to reactivate after a chase and begin another lunge at the closest player (rolls a value 0-100 and if below the given value will reactivate)", (AcceptableValueBase)null, Array.Empty<object>()));
			LockerSpawnWeight = Plugin.config.Bind<int>("Spawn", "LockerSpawnWeight", 50, new ConfigDescription("What is the chance of the Locker spawning - higher values make it more common (this is like adding tickets to a lottery - it doesn't guarantee getting picked but it vastly increases the chances)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 99999), Array.Empty<object>()));
			LockerSpawnPower = Plugin.config.Bind<float>("Spawn", "LockerSpawnPower", 1f, new ConfigDescription("What's the spawn power of a Locker? How much does it subtract from the moon power pool on spawn?", (AcceptableValueBase)null, Array.Empty<object>()));
			LockerSpawnMax = Plugin.config.Bind<int>("Spawn", "LockerSpawnMax", 3, new ConfigDescription("What's the maximum amount of Lockers that can spawn on a given moon?", (AcceptableValueBase)null, Array.Empty<object>()));
			LockerSpawnLevelsSet = Plugin.config.Bind<string>("Spawn", "LockerSpawnLevelsSet", "all", new ConfigDescription("Which set of levels should by default let the Locker spawn on them? (Options are: all/none/modded/vanilla)", (AcceptableValueBase)null, Array.Empty<object>()));
			LockerSpawnLevelsWithWeight = Plugin.config.Bind<string>("Spawn", "LockerSpawnLevels", "experimentation:25, assurance:75, vow:0, march:0, offense:100", new ConfigDescription("Which specific moons/levels can the Locker spawn on and with what weight? (This takes priority over the level set config option - names are matched leniently and case insensitive)", (AcceptableValueBase)null, Array.Empty<object>()));
			LockerVolumeAdjustment = Plugin.config.Bind<float>("Volume", "LockerVolumeAdjustment", 1f, new ConfigDescription("Client side volume adjustment - values are a percentage i.e. 50% volume is 0.5", (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[BepInPlugin("com.zealsprince.locker", "Locker", "1.2.6")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGUID = "com.zealsprince.locker";

		public const string ModName = "Locker";

		public const string ModVersion = "1.2.6";

		public static ManualLogSource logger;

		public static ConfigFile config;

		private readonly Harmony harmony = new Harmony("com.zealsprince.locker");

		public void Awake()
		{
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			logger = ((BaseUnityPlugin)this).Logger;
			config = ((BaseUnityPlugin)this).Config;
			Config.Load();
			if (Assets.Load() != 0)
			{
				return;
			}
			EnemyType val = Assets.Bundle.LoadAsset<EnemyType>("assets/exported/locker/enemies/lockerenemy.asset");
			TerminalNode val2 = Assets.Bundle.LoadAsset<TerminalNode>("assets/exported/locker/enemies/lockerterminalnode.asset");
			TerminalKeyword val3 = Assets.Bundle.LoadAsset<TerminalKeyword>("assets/exported/locker/enemies/lockerterminalkeyword.asset");
			NetworkPrefabs.RegisterNetworkPrefab(val.enemyPrefab);
			val.PowerLevel = Config.LockerSpawnPower.Value;
			val.MaxCount = Config.LockerSpawnMax.Value;
			string[] source = new string[4] { "all", "modded", "vanilla", "none" };
			string text = source.FirstOrDefault((string s) => new string((from c in Config.LockerSpawnLevelsSet.Value.ToLower().ToCharArray()
				where !char.IsWhiteSpace(c)
				select c).ToArray()).Contains(s));
			LevelTypes val4 = (LevelTypes)1;
			switch (text)
			{
			case "all":
				val4 = (LevelTypes)(-1);
				break;
			case "modded":
				val4 = (LevelTypes)1024;
				break;
			case "vanilla":
				val4 = (LevelTypes)1020;
				break;
			}
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			string text2 = new string((from c in Config.LockerSpawnLevelsWithWeight.Value.ToLower().ToCharArray()
				where !char.IsWhiteSpace(c)
				select c).ToArray());
			string[] array = text2.Split(new char[1] { ',' });
			foreach (string text3 in array)
			{
				string[] array2 = text3.Split(new char[1] { ':' });
				if (array2.Length == 1)
				{
					dictionary.Add(array2[0], Config.LockerSpawnWeight.Value);
				}
				else
				{
					if (array2.Length != 2)
					{
						continue;
					}
					int num = 0;
					try
					{
						num = int.Parse(array2[1]);
					}
					catch (Exception ex)
					{
						if (ex is ArgumentException || ex is FormatException || ex is OverflowException)
						{
							logger.LogError((object)$"Failed to parse level/moon weight value: {ex}");
						}
						continue;
					}
					dictionary.Add(array2[0], num);
				}
			}
			Enemies.RegisterEnemy(val, Config.LockerSpawnWeight.Value, (LevelTypes)1, (SpawnType)0, val2, val3);
			Enemies.RemoveEnemyFromLevels(val, (LevelTypes)1, (string[])null);
			Enemies.RegisterEnemy(val, (SpawnType)0, new Dictionary<LevelTypes, int> { [val4] = Config.LockerSpawnWeight.Value }, dictionary, val2, val3);
			try
			{
				Type[] types = Assembly.GetExecutingAssembly().GetTypes();
				Type[] array3 = types;
				foreach (Type type in array3)
				{
					MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
					MethodInfo[] array4 = methods;
					foreach (MethodInfo methodInfo in array4)
					{
						object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
						if (customAttributes.Length != 0)
						{
							methodInfo.Invoke(null, null);
						}
					}
				}
			}
			catch (Exception ex2)
			{
				logger.LogError((object)ex2);
			}
			harmony.PatchAll();
		}
	}
	internal class Utilities
	{
		public static void ApplyLocalPlayerScreenshake(Vector3 position, float minDistance = 14f, float maxDistance = 25f, bool onlySmall = false)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			float num = Vector3.Distance(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, position);
			if (num < minDistance && !onlySmall)
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)1);
			}
			else if (num < maxDistance)
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)0);
			}
		}

		public static void Explode(Vector3 position, float minRange = 5f, float maxRange = 6f, float damage = 25f, int enemyDamage = 6)
		{
			//IL_005a: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: 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_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			Transform val = null;
			if ((Object)(object)RoundManager.Instance != (Object)null && (Object)(object)RoundManager.Instance.mapPropsContainer != (Object)null && (Object)(object)RoundManager.Instance.mapPropsContainer.transform != (Object)null)
			{
				val = RoundManager.Instance.mapPropsContainer.transform;
			}
			Object.Instantiate<GameObject>(StartOfRound.Instance.explosionPrefab, position, Quaternion.Euler(-90f, 0f, 0f), val).SetActive(true);
			ApplyLocalPlayerScreenshake(position);
			Collider[] array = Physics.OverlapSphere(position, maxRange, 2621448, (QueryTriggerInteraction)2);
			for (int i = 0; i < array.Length; i++)
			{
				float num = Vector3.Distance(position, ((Component)array[i]).transform.position);
				if (num > 4f && Physics.Linecast(position, ((Component)array[i]).transform.position + Vector3.up * 0.3f, 256, (QueryTriggerInteraction)1))
				{
					continue;
				}
				if (((Component)array[i]).gameObject.layer == 3)
				{
					PlayerControllerB component = ((Component)array[i]).gameObject.GetComponent<PlayerControllerB>();
					if ((Object)(object)component != (Object)null && ((NetworkBehaviour)component).IsOwner)
					{
						float num2 = 1f - Mathf.Clamp01((num - minRange) / (maxRange - minRange));
						component.DamagePlayer((int)(damage * num2), true, true, (CauseOfDeath)3, 0, false, default(Vector3));
					}
				}
				else if (((Component)array[i]).gameObject.layer == 21)
				{
					Landmine componentInChildren = ((Component)array[i]).gameObject.GetComponentInChildren<Landmine>();
					if ((Object)(object)componentInChildren != (Object)null && !componentInChildren.hasExploded && num < 6f)
					{
						componentInChildren.Detonate();
					}
				}
				else if (((Component)array[i]).gameObject.layer == 19)
				{
					EnemyAICollisionDetect componentInChildren2 = ((Component)array[i]).gameObject.GetComponentInChildren<EnemyAICollisionDetect>();
					if ((Object)(object)componentInChildren2 != (Object)null && ((NetworkBehaviour)componentInChildren2.mainScript).IsOwner && num < 4.5f)
					{
						componentInChildren2.mainScript.HitEnemyOnLocalClient(enemyDamage, default(Vector3), (PlayerControllerB)null, false, -1);
					}
				}
			}
			int num3 = ~LayerMask.GetMask(new string[1] { "Room" });
			num3 = ~LayerMask.GetMask(new string[1] { "Colliders" });
			array = Physics.OverlapSphere(position, 10f, num3);
			for (int j = 0; j < array.Length; j++)
			{
				Rigidbody component2 = ((Component)array[j]).GetComponent<Rigidbody>();
				if (component2 != null)
				{
					component2.AddExplosionForce(70f, position, 10f);
				}
			}
		}
	}
}
namespace Locker.Patches
{
	[HarmonyPatch(typeof(HUDManager))]
	internal class HUDManagerPatches
	{
		[HarmonyPostfix]
		[HarmonyPatch("PingScan_performed")]
		private static void NotifyScanLockers()
		{
			if (!((Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null))
			{
				return;
			}
			foreach (LockerAI activeLocker in LockerAI.activeLockers)
			{
				activeLocker?.PlayerScan(GameNetworkManager.Instance.localPlayerController);
			}
		}
	}
}
namespace Locker.MonoBehaviours
{
	public class LockerAI : EnemyAI
	{
		public enum State
		{
			Dormant,
			Activating,
			Chasing,
			Reactivating,
			Resetting,
			Consuming,
			Debug
		}

		public static readonly int CreatureID = 176;

		private static readonly Color eyeColorDormant = Color.black;

		private static readonly Color eyeColorScan = Color.cyan;

		private static readonly Color eyeColorDetect = new Color(1f, 0.4f, 0f);

		private static readonly Color eyeColorChase = Color.red;

		private AudioSource audioSource;

		private Animator animationController;

		private Material eyeMaterial;

		private Light internalLight;

		private List<Light> scrapeLights;

		private DoorLock[] doors = Array.Empty<DoorLock>();

		private VisualEffect[] visualEffects;

		private static VFXExposedProperty chaseVFXBeginTrigger;

		private static VFXExposedProperty chaseVFXEndTrigger;

		private static readonly string chaseVFXBeginTriggerName = "BeginChase";

		private static readonly string chaseVFXEndTriggerName = "EndChase";

		private static VFXExposedProperty consumeVFXBeginTrigger;

		private static VFXExposedProperty consumeVFXEndTrigger;

		private static readonly string consumeVFXBeginTriggerName = "BeginConsume";

		private static readonly string consumeVFXEndTriggerName = "EndConsume";

		private int observedState;

		private Vector3 targetPosition;

		private Quaternion targetRotation;

		private float currentRotationSpeed = 0f;

		private readonly float maxRotationSpeed = 90f;

		private Color currentEyeColor = eyeColorDormant;

		private float currentEyeIntensity = 0f;

		private float activationTimer = 0f;

		private readonly float activationDuration = 1.5f;

		private readonly float activationSpinWindup = 0.45f;

		private float reactivationTimer = 0f;

		private readonly float reactivationDuration = 1f;

		private float consumeTimer = 0f;

		private readonly float consumeDuration = 2.2f;

		private readonly float consumeBloodWindup = 1f;

		private bool consumeBloodTriggered = false;

		private float resetTimer = 0f;

		private readonly float resetDuration = 1f;

		private PlayerControllerB playerScanning;

		private bool playerScanned = false;

		private float playerScannedTimer = 0f;

		private float playerScannedDuration = 0f;

		private float lastTargetTime;

		private readonly float touchOvershoot = 1.75f;

		private readonly float scanOvershoot = 1f;

		private readonly float reactivationOvershoot = 1.25f;

		private Vector3 lastChasePosition = Vector3.zero;

		private float chaseMovementAverage = 0f;

		private readonly float chaseMovementSpeed = 30f;

		private readonly float chaseMovementAverageInitial = 100f;

		private readonly float chaseMovementAverageMinimum = 0.01f;

		private readonly float lastTargetTimeframe = 0.2f;

		private readonly float explosionDamage = 100f;

		private readonly float explosionMinRange = 5f;

		private readonly float explosionMaxRange = 6f;

		private readonly int explosionEnemyDamage = 6;

		[Header("Locker")]
		public bool DebugToCamera = false;

		public AudioClip AudioClipPing;

		public AudioClip AudioClipActivate;

		public AudioClip AudioClipChase;

		public AudioClip AudioClipReactivate;

		public AudioClip AudioClipReset;

		public AudioClip AudioClipConsume;

		private LineRenderer debugLine;

		public static List<LockerAI> activeLockers = new List<LockerAI>();

		public override void OnDestroy()
		{
			((EnemyAI)this).OnDestroy();
			activeLockers.Remove(this);
		}

		public override void Start()
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			((EnemyAI)this).Start();
			activeLockers.Add(this);
			audioSource = ((Component)this).GetComponent<AudioSource>();
			animationController = ((Component)this).GetComponent<Animator>();
			SkinnedMeshRenderer componentInChildren = ((Component)this).gameObject.GetComponentInChildren<SkinnedMeshRenderer>();
			Material[] materials = ((Renderer)componentInChildren).materials;
			foreach (Material val in materials)
			{
				if (((Object)val).name.ToLower().Contains("eye"))
				{
					eyeMaterial = val;
					eyeMaterial.SetColor("_EmissiveColor", currentEyeColor);
					break;
				}
			}
			scrapeLights = new List<Light>();
			Light[] componentsInChildren = ((Component)this).gameObject.GetComponentsInChildren<Light>();
			Light[] array = componentsInChildren;
			foreach (Light val2 in array)
			{
				if (((Object)((Component)val2).gameObject).name == "InternalLight")
				{
					internalLight = val2;
					continue;
				}
				scrapeLights.Add(val2);
				((Behaviour)val2).enabled = false;
			}
			internalLight.intensity = 0f;
			((Behaviour)internalLight).enabled = true;
			targetPosition = Vector3.zero;
			visualEffects = ((Component)this).gameObject.GetComponentsInChildren<VisualEffect>();
			chaseVFXBeginTrigger.name = chaseVFXBeginTriggerName;
			chaseVFXEndTrigger.name = chaseVFXEndTriggerName;
			consumeVFXBeginTrigger.name = consumeVFXBeginTriggerName;
			consumeVFXEndTrigger.name = consumeVFXEndTriggerName;
			doors = Object.FindObjectsOfType(typeof(DoorLock)) as DoorLock[];
			debugLine = ((Component)this).GetComponent<LineRenderer>();
			SwitchState(State.Dormant);
		}

		public IEnumerator DrawPath()
		{
			if (((Behaviour)base.agent).enabled)
			{
				yield return (object)new WaitForEndOfFrame();
				debugLine.positionCount = base.agent.path.corners.Length;
				debugLine.SetPosition(0, ((Component)base.agent).transform.position);
				for (int i = 1; i < base.agent.path.corners.Length; i++)
				{
					debugLine.SetPosition(i, base.agent.path.corners[i]);
				}
			}
		}

		public override void DoAIInterval()
		{
			((EnemyAI)this).DoAIInterval();
			if (!base.isEnemyDead && !StartOfRound.Instance.allPlayersDead)
			{
				if (base.debugEnemyAI)
				{
					((Renderer)debugLine).enabled = true;
					((MonoBehaviour)this).StartCoroutine(DrawPath());
				}
				else
				{
					((Renderer)debugLine).enabled = false;
				}
			}
		}

		public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false, int hitID = -1)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)playerWhoHit != (Object)null)
			{
				TargetServerRpc(playerWhoHit.playerClientId, ((Component)playerWhoHit).transform.position);
			}
		}

		public override void Update()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Unknown result type (might be due to invalid IL or missing references)
			//IL_037d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0404: Unknown result type (might be due to invalid IL or missing references)
			//IL_0414: Unknown result type (might be due to invalid IL or missing references)
			//IL_0421: Unknown result type (might be due to invalid IL or missing references)
			//IL_0426: Unknown result type (might be due to invalid IL or missing references)
			//IL_0430: Unknown result type (might be due to invalid IL or missing references)
			//IL_0435: Unknown result type (might be due to invalid IL or missing references)
			((EnemyAI)this).Update();
			if (base.isEnemyDead)
			{
				return;
			}
			if (DebugToCamera)
			{
				DebugToCamera = false;
				TargetServerRpc(0uL, ((Component)Camera.main).transform.position);
			}
			switch (base.currentBehaviourStateIndex)
			{
			case 0:
				currentEyeColor = Color.Lerp(currentEyeColor, eyeColorDormant, Time.deltaTime);
				currentEyeIntensity = Mathf.Lerp(currentEyeIntensity, 0f, Time.deltaTime);
				internalLight.intensity = Mathf.Lerp(internalLight.intensity, 0f, Time.deltaTime * 8f);
				break;
			case 1:
				if (activationTimer > activationSpinWindup)
				{
					currentRotationSpeed = Mathf.Lerp(currentRotationSpeed, maxRotationSpeed, Time.deltaTime / Mathf.Abs(maxRotationSpeed - currentRotationSpeed));
					((Component)this).transform.rotation = Quaternion.Slerp(((Component)this).transform.rotation, targetRotation, Time.deltaTime * currentRotationSpeed * 4f);
				}
				currentEyeColor = Color.Lerp(currentEyeColor, eyeColorDetect, Time.deltaTime);
				currentEyeIntensity = Mathf.Lerp(currentEyeIntensity, 100000f, Time.deltaTime);
				internalLight.intensity = Mathf.Lerp(internalLight.intensity, 40000f, Time.deltaTime / 4f);
				break;
			case 2:
				currentEyeColor = Color.Lerp(currentEyeColor, eyeColorChase, Time.deltaTime);
				currentEyeIntensity = Mathf.Lerp(currentEyeIntensity, 500000f, Time.deltaTime * 2f);
				if (((Component)this).transform.position != lastChasePosition)
				{
					Quaternion val2 = Quaternion.LookRotation(((Component)this).transform.position - lastChasePosition) * Quaternion.Euler(Vector3.up * 90f) * Quaternion.Euler(Vector3.back * 8f);
					((Component)this).transform.rotation = Quaternion.Slerp(((Component)this).transform.rotation, val2, Time.deltaTime * 4f);
				}
				internalLight.intensity = Mathf.Lerp(internalLight.intensity, 20000f, Time.deltaTime);
				foreach (Light scrapeLight in scrapeLights)
				{
					scrapeLight.intensity = Mathf.Lerp(scrapeLight.intensity + (float)Random.Range(-3000, 3000), 4000f, Time.deltaTime * 2f);
				}
				break;
			case 3:
				currentRotationSpeed = Mathf.Lerp(currentRotationSpeed, maxRotationSpeed, Time.deltaTime / Mathf.Abs(maxRotationSpeed - currentRotationSpeed));
				((Component)this).transform.rotation = Quaternion.Slerp(((Component)this).transform.rotation, targetRotation, Time.deltaTime * currentRotationSpeed * 6f);
				break;
			case 5:
				if (consumeTimer > consumeBloodWindup && !consumeBloodTriggered)
				{
					VisualEffect[] array = visualEffects;
					foreach (VisualEffect val in array)
					{
						val.SendEvent(consumeVFXBeginTrigger.name);
					}
					consumeBloodTriggered = true;
				}
				((Component)this).transform.rotation = Quaternion.Slerp(((Component)this).transform.rotation, targetRotation, Time.deltaTime * 8f);
				currentEyeColor = Color.Lerp(currentEyeColor, eyeColorChase, Time.deltaTime);
				currentEyeIntensity = Mathf.Lerp(currentEyeIntensity, 0f, Time.deltaTime);
				internalLight.intensity = Mathf.Lerp(internalLight.intensity, 0f, Time.deltaTime * 2f);
				foreach (Light scrapeLight2 in scrapeLights)
				{
					scrapeLight2.intensity = Mathf.Lerp(scrapeLight2.intensity, 0f, Time.deltaTime * 8f);
				}
				break;
			}
			eyeMaterial.SetColor("_EmissiveColor", currentEyeColor * currentEyeIntensity);
		}

		public void FixedUpdate()
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_0630: Unknown result type (might be due to invalid IL or missing references)
			//IL_063c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0641: Unknown result type (might be due to invalid IL or missing references)
			//IL_0646: Unknown result type (might be due to invalid IL or missing references)
			//IL_0657: Unknown result type (might be due to invalid IL or missing references)
			//IL_065e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0669: Unknown result type (might be due to invalid IL or missing references)
			//IL_066e: Unknown result type (might be due to invalid IL or missing references)
			//IL_038c: Unknown result type (might be due to invalid IL or missing references)
			//IL_039c: Unknown result type (might be due to invalid IL or missing references)
			//IL_032d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Unknown result type (might be due to invalid IL or missing references)
			//IL_034e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0521: Unknown result type (might be due to invalid IL or missing references)
			//IL_052c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0549: Unknown result type (might be due to invalid IL or missing references)
			//IL_054e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0569: Unknown result type (might be due to invalid IL or missing references)
			//IL_056f: Unknown result type (might be due to invalid IL or missing references)
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0485: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ac: Unknown result type (might be due to invalid IL or missing references)
			ObserveState();
			PlayerControllerB val2 = null;
			try
			{
				val2 = ((EnemyAI)this).GetClosestPlayer(false, true, true);
			}
			catch (Exception ex)
			{
				if (!(ex is NullReferenceException))
				{
				}
			}
			switch (base.currentBehaviourStateIndex)
			{
			case 0:
				if ((Object)(object)val2 != (Object)null && Mathf.Abs(((Component)val2).transform.position.y - ((Component)this).transform.position.y) + 2f > 2f && (double)Vector3.Distance(((Component)val2).transform.position, ((Component)this).transform.position) < 1.5)
				{
					Vector3 val3 = ((Component)this).transform.position - ((Component)val2).transform.position;
					TargetServerRpc(val2.playerClientId, ((Component)val2).transform.position - ((Vector3)(ref val3)).normalized * touchOvershoot);
					break;
				}
				if (IsLocalPlayerClosestWithLight())
				{
					TargetServerRpc(StartOfRound.Instance.localPlayerController.playerClientId, ((Component)StartOfRound.Instance.localPlayerController).transform.position);
				}
				if (playerScanned)
				{
					playerScannedTimer += Time.fixedDeltaTime;
					if (playerScannedTimer > playerScannedDuration)
					{
						currentEyeColor = eyeColorScan;
						audioSource.PlayOneShot(AudioClipPing, 1.5f * Config.LockerVolumeAdjustment.Value);
						playerScanning.JumpToFearLevel(0.2f, true);
						Vector3 val4 = ((Component)this).transform.position - ((Component)playerScanning).transform.position;
						TargetServerRpc(playerScanning.playerClientId, ((Component)playerScanning).transform.position - ((Vector3)(ref val4)).normalized * scanOvershoot);
						playerScanned = false;
						playerScannedTimer = 0f;
						playerScannedDuration = 0f;
					}
				}
				break;
			case 1:
				activationTimer += Time.fixedDeltaTime;
				if (activationTimer > activationDuration)
				{
					SwitchState(State.Chasing);
				}
				break;
			case 2:
			{
				if (IsLocalPlayerClosestWithLight())
				{
					TargetServerRpc(StartOfRound.Instance.localPlayerController.playerClientId, ((Component)StartOfRound.Instance.localPlayerController).transform.position);
				}
				if (playerScanned)
				{
					playerScannedTimer += Time.fixedDeltaTime;
					if (playerScannedTimer > playerScannedDuration)
					{
						audioSource.PlayOneShot(AudioClipPing, 1.5f * Config.LockerVolumeAdjustment.Value);
						playerScanning.JumpToFearLevel(0.5f, true);
						currentEyeColor = eyeColorScan;
						TargetServerRpc(playerScanning.playerClientId, ((Component)playerScanning).transform.position);
						playerScanned = false;
						playerScannedTimer = 0f;
						playerScannedDuration = 0f;
					}
				}
				if ((Object)(object)val2 != (Object)null && Mathf.Abs(((Component)val2).transform.position.y - ((Component)this).transform.position.y) + 2f > 2f && Vector3.Distance(((Component)val2).transform.position, ((Component)this).transform.position) < 2f)
				{
					ConsumeServerRpc(val2.playerClientId);
					break;
				}
				DoorLock[] array = doors;
				foreach (DoorLock door in array)
				{
					if (!Object.op_Implicit((Object)(object)door))
					{
						doors = doors.Where((DoorLock val) => (Object)(object)val != (Object)(object)door).ToArray();
						break;
					}
					if (!Object.op_Implicit((Object)(object)((Component)door).GetComponent<Rigidbody>()) && Vector3.Distance(((Component)door).transform.position, ((Component)this).transform.position) < 3f)
					{
						Utilities.Explode(((Component)door).transform.position, 2f, 4f, 100f, 0);
						Object.Destroy((Object)(object)((Component)((Component)door).transform.parent).gameObject);
						doors = doors.Where((DoorLock val) => (Object)(object)val != (Object)(object)door).ToArray();
					}
				}
				chaseMovementAverage = (chaseMovementAverage + Vector3.Distance(lastChasePosition, ((Component)this).transform.position)) / 2f;
				lastChasePosition = ((Component)this).transform.position;
				if (((NetworkBehaviour)this).IsServer && (Vector3.Distance(((Component)this).transform.position, targetPosition) <= 0.5f || chaseMovementAverage < chaseMovementAverageMinimum))
				{
					if (chaseMovementAverage > chaseMovementAverageMinimum && Random.Range(0f, 100f) < Config.LockerMechanicsReactivationChance.Value)
					{
						ReactivateServerRpc();
					}
					else
					{
						ResetServerRpc();
					}
				}
				break;
			}
			case 3:
				reactivationTimer += Time.fixedDeltaTime;
				if (reactivationTimer > reactivationDuration)
				{
					PlayerControllerB closestPlayer = ((EnemyAI)this).GetClosestPlayer(true, false, false);
					if (Object.op_Implicit((Object)(object)closestPlayer))
					{
						Vector3 val5 = ((Component)this).transform.position - ((Component)closestPlayer).transform.position;
						TargetServerRpc(closestPlayer.playerClientId, ((Component)closestPlayer).transform.position - ((Vector3)(ref val5)).normalized * reactivationOvershoot);
					}
					else
					{
						ResetServerRpc();
					}
				}
				break;
			case 5:
				consumeTimer += Time.fixedDeltaTime;
				if (consumeTimer > consumeDuration)
				{
					SwitchState(State.Dormant);
				}
				break;
			case 4:
				resetTimer += Time.fixedDeltaTime;
				if (resetTimer > resetDuration)
				{
					SwitchState(State.Dormant);
				}
				break;
			}
		}

		public override void KillEnemy(bool destroy = false)
		{
			((EnemyAI)this).KillEnemy(destroy);
			if (((NetworkBehaviour)this).IsServer)
			{
				ExplodeServerRpc();
			}
		}

		public override void OnCollideWithEnemy(Collider other, EnemyAI enemy)
		{
			((EnemyAI)this).OnCollideWithEnemy(other, enemy);
			int currentBehaviourStateIndex = base.currentBehaviourStateIndex;
			int num = currentBehaviourStateIndex;
			if (num == 2)
			{
				if (enemy.enemyType.canDie && !enemy.isEnemyDead)
				{
					enemy.KillEnemy(false);
				}
				if ((Object)(object)enemy.enemyType == (Object)(object)base.enemyType)
				{
					((EnemyAI)this).KillEnemy(false);
				}
			}
		}

		public void OnTriggerEnter(Collider collider)
		{
			int currentBehaviourStateIndex = base.currentBehaviourStateIndex;
			int num = currentBehaviourStateIndex;
			if (num == 2)
			{
				PlayerControllerB component = ((Component)collider).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component != (Object)null)
				{
					ConsumeServerRpc(component.playerClientId);
				}
			}
		}

		public void SwitchState(State state)
		{
			((EnemyAI)this).SwitchToBehaviourState((int)state);
		}

		public void ObserveState()
		{
			//IL_0351: Unknown result type (might be due to invalid IL or missing references)
			//IL_0356: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_036a: 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_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0402: Unknown result type (might be due to invalid IL or missing references)
			//IL_0424: Unknown result type (might be due to invalid IL or missing references)
			if (base.currentBehaviourStateIndex == observedState)
			{
				return;
			}
			activationTimer = 0f;
			reactivationTimer = 0f;
			consumeTimer = 0f;
			resetTimer = 0f;
			switch (base.currentBehaviourStateIndex)
			{
			case 6:
				TargetServerRpc(0uL, new Vector3((float)Random.Range(-25, 25), ((Component)this).transform.position.y, (float)Random.Range(-25, 25)));
				break;
			case 0:
			{
				audioSource.loop = false;
				currentRotationSpeed = 0f;
				foreach (Light scrapeLight in scrapeLights)
				{
					scrapeLight.intensity = 0f;
					((Behaviour)scrapeLight).enabled = false;
				}
				animationController.SetTrigger("Deactivate");
				animationController.SetBool("Chasing", false);
				VisualEffect[] array2 = visualEffects;
				foreach (VisualEffect val2 in array2)
				{
					val2.SendEvent(consumeVFXEndTrigger.name);
					val2.SendEvent(chaseVFXEndTrigger.name);
				}
				consumeBloodTriggered = false;
				break;
			}
			case 1:
				audioSource.PlayOneShot(AudioClipActivate, Config.LockerVolumeAdjustment.Value);
				animationController.SetTrigger("Activate");
				break;
			case 2:
			{
				if (((NetworkBehaviour)this).IsServer && base.agent.isOnNavMesh)
				{
					((EnemyAI)this).SetDestinationToPosition(targetPosition, true);
				}
				base.agent.speed = chaseMovementSpeed;
				lastChasePosition = ((Component)this).transform.position;
				chaseMovementAverage = chaseMovementAverageInitial;
				audioSource.pitch = 1f;
				audioSource.clip = AudioClipChase;
				audioSource.loop = true;
				audioSource.volume = Config.LockerVolumeAdjustment.Value;
				audioSource.Play();
				animationController.SetTrigger("OpenDoors");
				foreach (Light scrapeLight2 in scrapeLights)
				{
					((Behaviour)scrapeLight2).enabled = true;
				}
				animationController.SetTrigger("Chase");
				animationController.SetBool("Chasing", true);
				VisualEffect[] array3 = visualEffects;
				foreach (VisualEffect val3 in array3)
				{
					val3.SendEvent(chaseVFXBeginTrigger.name);
				}
				break;
			}
			case 3:
			case 4:
			case 5:
			{
				base.agent.speed = 0f;
				currentRotationSpeed = 0f;
				audioSource.Stop();
				audioSource.loop = false;
				((Component)this).transform.rotation = ((Component)this).transform.rotation * Quaternion.Euler(Vector3.forward * 10f);
				animationController.SetBool("Chasing", false);
				animationController.SetTrigger("CloseDoors");
				VisualEffect[] array = visualEffects;
				foreach (VisualEffect val in array)
				{
					val.SendEvent(chaseVFXEndTrigger.name);
				}
				if ((Object)(object)StartOfRound.Instance != (Object)null)
				{
					PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
					float num = Vector3.Distance(((Component)this).transform.position, ((Component)localPlayerController).transform.position);
					if (num < 7f)
					{
						Utilities.ApplyLocalPlayerScreenshake(((Component)this).transform.position, 4f, 7f);
						if (num < 4f)
						{
							if (base.currentBehaviourStateIndex == 5)
							{
								localPlayerController.JumpToFearLevel(1f, true);
							}
							else
							{
								localPlayerController.JumpToFearLevel(0.7f, true);
							}
						}
					}
				}
				if (base.currentBehaviourStateIndex == 5)
				{
					audioSource.PlayOneShot(AudioClipConsume, Config.LockerVolumeAdjustment.Value);
				}
				else if (base.currentBehaviourStateIndex == 3)
				{
					audioSource.PlayOneShot(AudioClipReactivate, Config.LockerVolumeAdjustment.Value);
				}
				else
				{
					audioSource.PlayOneShot(AudioClipReset, Config.LockerVolumeAdjustment.Value);
				}
				break;
			}
			}
			observedState = base.currentBehaviourStateIndex;
		}

		private bool IsLocalPlayerClosestWithLight()
		{
			//IL_0053: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB val = null;
			float num = float.PositiveInfinity;
			PlayerControllerB[] allPlayersInLineOfSight = ((EnemyAI)this).GetAllPlayersInLineOfSight(360f, 15, (Transform)null, -1f, -1);
			if (allPlayersInLineOfSight == null || allPlayersInLineOfSight.Length == 0)
			{
				return false;
			}
			PlayerControllerB[] array = allPlayersInLineOfSight;
			foreach (PlayerControllerB val2 in array)
			{
				bool flag = false;
				Vector3 val3 = ((Component)this).transform.position - ((Component)val2).transform.position;
				float num2 = Vector3.Angle(((Component)val2).transform.forward, val3);
				if ((Object)(object)val2.pocketedFlashlight != (Object)null && val2.pocketedFlashlight.isBeingUsed && Mathf.Abs(num2) < 30f)
				{
					flag = true;
				}
				GrabbableObject currentlyHeldObjectServer = val2.currentlyHeldObjectServer;
				if (!flag && val2.isHoldingObject && (Object)(object)currentlyHeldObjectServer != (Object)null)
				{
					bool flag2 = ((object)currentlyHeldObjectServer).GetType() == typeof(FlashlightItem);
					Light[] componentsInChildren = ((Component)currentlyHeldObjectServer).gameObject.GetComponentsInChildren<Light>();
					Light[] array2 = componentsInChildren;
					foreach (Light val4 in array2)
					{
						if (!((Behaviour)val4).enabled || !(val4.intensity > 0f) || !(val4.range > 0f))
						{
							continue;
						}
						if (flag2)
						{
							if (Mathf.Abs(num2) < 30f)
							{
								flag = true;
							}
						}
						else
						{
							flag = true;
						}
					}
				}
				if (flag)
				{
					float num3 = Vector3.Distance(((Component)val2).transform.position, ((Component)this).transform.position);
					if (num3 < num)
					{
						num = num3;
						val = val2;
					}
				}
			}
			if ((Object)(object)val != (Object)null && (Object)(object)val == (Object)(object)StartOfRound.Instance.localPlayerController)
			{
				return true;
			}
			return false;
		}

		public PlayerControllerB GetClosestVisiblePlayer()
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB[] allPlayersInLineOfSight = ((EnemyAI)this).GetAllPlayersInLineOfSight(360f, 30, (Transform)null, -1f, -1);
			float num = float.PositiveInfinity;
			PlayerControllerB result = null;
			if (allPlayersInLineOfSight != null)
			{
				if (allPlayersInLineOfSight.Length != 0)
				{
					PlayerControllerB[] array = allPlayersInLineOfSight;
					foreach (PlayerControllerB val in array)
					{
						float num2 = Vector3.Distance(((Component)this).transform.position, ((Component)val).transform.position);
						if (num2 < num)
						{
							num = num2;
							result = val;
						}
					}
				}
				return result;
			}
			return null;
		}

		[ServerRpc(RequireOwnership = false)]
		public void TargetServerRpc(ulong clientId, Vector3 position)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1408573431u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, clientId);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref position);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1408573431u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					TargetClientRpc(clientId, position);
				}
			}
		}

		[ClientRpc]
		public void TargetClientRpc(ulong clientId, Vector3 position)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: 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_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: 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)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1018811517u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, clientId);
				((FastBufferWriter)(ref val2)).WriteValueSafe(ref position);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1018811517u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost) || !(Time.time - lastTargetTimeframe > lastTargetTime) || (base.currentBehaviourStateIndex != 0 && base.currentBehaviourStateIndex != 6 && (base.currentBehaviourStateIndex != 2 || clientId != base.targetPlayer.playerClientId) && base.currentBehaviourStateIndex != 3))
			{
				return;
			}
			position.y = ((Component)this).transform.position.y;
			targetPosition = position;
			targetRotation = Quaternion.LookRotation(targetPosition - ((Component)this).transform.position);
			targetRotation *= Quaternion.Euler(Vector3.up * 90f);
			lastTargetTime = Time.time;
			base.targetPlayer = StartOfRound.Instance.allPlayerScripts[clientId];
			if (base.currentBehaviourStateIndex == 0 || base.currentBehaviourStateIndex == 6)
			{
				SwitchState(State.Activating);
			}
			else if ((base.currentBehaviourStateIndex == 2 || base.currentBehaviourStateIndex == 3) && base.currentBehaviourStateIndex == 3)
			{
				if (((NetworkBehaviour)this).IsServer && base.agent.isOnNavMesh)
				{
					((EnemyAI)this).SetDestinationToPosition(targetPosition, true);
				}
				SwitchState(State.Chasing);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void ReactivateServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1126862929u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1126862929u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				targetPosition = ((Component)this).transform.position;
				if (((NetworkBehaviour)this).IsServer && base.agent.isOnNavMesh)
				{
					((EnemyAI)this).SetDestinationToPosition(targetPosition, true);
				}
				ReactivateClientRpc();
			}
		}

		[ClientRpc]
		public void ReactivateClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1648224205u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1648224205u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				PlayerControllerB closestVisiblePlayer = GetClosestVisiblePlayer();
				if ((Object)(object)closestVisiblePlayer != (Object)null)
				{
					currentRotationSpeed = 0f;
					targetRotation = Quaternion.LookRotation(((Component)closestVisiblePlayer).transform.position - ((Component)this).transform.position);
					targetRotation *= Quaternion.Euler(Vector3.up * 90f);
				}
				SwitchState(State.Reactivating);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void ConsumeServerRpc(ulong clientid)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2082259863u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, clientid);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2082259863u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				targetPosition = ((Component)this).transform.position;
				if (((NetworkBehaviour)this).IsServer && base.agent.isOnNavMesh)
				{
					((EnemyAI)this).SetDestinationToPosition(targetPosition, false);
				}
				ConsumeClientRpc(clientid);
			}
		}

		[ClientRpc]
		public void ConsumeClientRpc(ulong id)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2705739593u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, id);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2705739593u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					((MonoBehaviour)this).StartCoroutine(KillPlayer(id));
					SwitchState(State.Consuming);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void ResetServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3735075229u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3735075229u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).IsServer && base.agent.isOnNavMesh)
				{
					targetPosition = ((Component)this).transform.position;
					((EnemyAI)this).SetDestinationToPosition(targetPosition, false);
				}
				ResetClientRpc();
			}
		}

		[ClientRpc]
		public void ResetClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3355973848u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3355973848u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					SwitchState(State.Resetting);
				}
			}
		}

		[ServerRpc(RequireOwnership = true)]
		public void ExplodeServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Invalid comparison between Unknown and I4
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2667453085u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2667453085u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ExplodeClientRpc();
			}
		}

		[ClientRpc]
		public void ExplodeClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(707895878u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 707895878u, val, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Utilities.Explode(((Component)this).transform.position, explosionMinRange, explosionMaxRange, explosionDamage, explosionEnemyDamage);
					Object.Destroy((Object)(object)((Component)this).gameObject);
				}
			}
		}

		public IEnumerator KillPlayer(ulong id)
		{
			PlayerControllerB player = StartOfRound.Instance.allPlayerScripts[id];
			if ((Object)(object)player != (Object)null)
			{
				player.bleedingHeavily = true;
				yield return (object)new WaitForSeconds(0.1f);
				player.KillPlayer(Vector3.zero, true, (CauseOfDeath)8, 1, default(Vector3));
				float startTime = Time.timeSinceLevelLoad;
				yield return (object)new WaitUntil((Func<bool>)(() => (Object)(object)player.deadBody != (Object)null || Time.timeSinceLevelLoad - startTime > 3f));
				if ((Object)(object)player.deadBody != (Object)null)
				{
					player.deadBody.attachedTo = ((Component)base.eye).transform;
					player.deadBody.attachedLimb = player.deadBody.bodyParts[5];
					player.deadBody.matchPositionExactly = true;
				}
				yield return (object)new WaitUntil((Func<bool>)(() => (double)(Time.timeSinceLevelLoad - startTime) > (double)consumeDuration * 0.75));
				if ((Object)(object)player.deadBody != (Object)null)
				{
					player.deadBody.attachedTo = null;
					player.deadBody.attachedLimb = null;
					player.deadBody.matchPositionExactly = false;
					((Component)player.deadBody).gameObject.SetActive(false);
					player.deadBody = null;
				}
			}
		}

		public void PlayerScan(PlayerControllerB player)
		{
			//IL_002c: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: 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_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: 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_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			if (base.currentBehaviourStateIndex != 0 && base.currentBehaviourStateIndex != 6 && base.currentBehaviourStateIndex != 2)
			{
				return;
			}
			float num = Vector3.Distance(((Component)this).transform.position, ((Component)player).transform.position);
			if ((!(num < 2f) || !(Mathf.Abs(((Component)player).transform.position.y - ((Component)this).transform.position.y) + 2f > 2f)) && num < 90f && !Physics.Linecast(((Component)this).transform.position + Vector3.up * 2f + Vector3.right * 0.2f, ((Component)player).transform.position + Vector3.up * 2f + Vector3.right * 0.2f, StartOfRound.Instance.collidersAndRoomMask))
			{
				playerScanning = player;
				if (!playerScanned)
				{
					playerScanned = true;
					playerScannedTimer = 0f;
					playerScannedDuration = num / 30f;
				}
				else if (playerScannedDuration - playerScannedTimer < num / 30f)
				{
					playerScannedDuration = num / 30f;
				}
			}
		}

		protected override void __initializeVariables()
		{
			((EnemyAI)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_LockerAI()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(1408573431u, new RpcReceiveHandler(__rpc_handler_1408573431));
			NetworkManager.__rpc_func_table.Add(1018811517u, new RpcReceiveHandler(__rpc_handler_1018811517));
			NetworkManager.__rpc_func_table.Add(1126862929u, new RpcReceiveHandler(__rpc_handler_1126862929));
			NetworkManager.__rpc_func_table.Add(1648224205u, new RpcReceiveHandler(__rpc_handler_1648224205));
			NetworkManager.__rpc_func_table.Add(2082259863u, new RpcReceiveHandler(__rpc_handler_2082259863));
			NetworkManager.__rpc_func_table.Add(2705739593u, new RpcReceiveHandler(__rpc_handler_2705739593));
			NetworkManager.__rpc_func_table.Add(3735075229u, new RpcReceiveHandler(__rpc_handler_3735075229));
			NetworkManager.__rpc_func_table.Add(3355973848u, new RpcReceiveHandler(__rpc_handler_3355973848));
			NetworkManager.__rpc_func_table.Add(2667453085u, new RpcReceiveHandler(__rpc_handler_2667453085));
			NetworkManager.__rpc_func_table.Add(707895878u, new RpcReceiveHandler(__rpc_handler_707895878));
		}

		private static void __rpc_handler_1408573431(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ulong clientId = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref clientId);
				Vector3 position = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref position);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((LockerAI)(object)target).TargetServerRpc(clientId, position);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1018811517(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ulong clientId = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref clientId);
				Vector3 position = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref position);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((LockerAI)(object)target).TargetClientRpc(clientId, position);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1126862929(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((LockerAI)(object)target).ReactivateServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1648224205(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((LockerAI)(object)target).ReactivateClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2082259863(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ulong clientid = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref clientid);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((LockerAI)(object)target).ConsumeServerRpc(clientid);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2705739593(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ulong id = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref id);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((LockerAI)(object)target).ConsumeClientRpc(id);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3735075229(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((LockerAI)(object)target).ResetServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3355973848(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((LockerAI)(object)target).ResetClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2667453085(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Invalid comparison between Unknown and I4
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
			}
			else
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((LockerAI)(object)target).ExplodeServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_707895878(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((LockerAI)(object)target).ExplodeClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "LockerAI";
		}
	}
}
namespace Locker.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}

BepInEx/plugins/americanompany/magico13.TurretWhacker.dll

Decompiled 2 years ago
using System;
using System.Collections;
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 HarmonyLib;
using Microsoft.CodeAnalysis;
using TurretWhacker.Config;
using TurretWhacker.Patches;
using UnityEngine;

[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("magico13.TurretWhacker")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+b5a1f909292187ad3e67b88fe1db0c3e8c0c5857")]
[assembly: AssemblyProduct("TurretWhacker")]
[assembly: AssemblyTitle("magico13.TurretWhacker")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TurretWhacker
{
	[BepInPlugin("magico13.TurretWhacker", "TurretWhacker", "1.0.0")]
	public class TurretWhacker : BaseUnityPlugin
	{
		public static TurretWhacker Instance { get; private set; }

		internal static PluginConfig PluginConfig { get; private set; }

		internal static ManualLogSource Logger { get; private set; }

		internal static Harmony? Harmony { get; set; }

		private void Awake()
		{
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			PluginConfig = new PluginConfig(((BaseUnityPlugin)this).Config);
			Patch();
			Logger.LogDebug((object)"magico13.TurretWhacker v1.0.0 has loaded!");
		}

		internal static void Patch()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony = new Harmony("magico13.TurretWhacker");
			}
			Logger.LogDebug((object)"Patching...");
			Harmony.CreateAndPatchAll(typeof(TurretPatch), (string)null);
			Logger.LogDebug((object)"Finished patching!");
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "magico13.TurretWhacker";

		public const string PLUGIN_NAME = "TurretWhacker";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace TurretWhacker.Patches
{
	public class TurretPatch
	{
		[HarmonyPatch(typeof(Turret), "IHittable.Hit")]
		[HarmonyPrefix]
		public static bool Hit(Turret __instance, ref bool __result)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			if ((int)__instance.turretMode == 3 || !__instance.turretActive)
			{
				return true;
			}
			float num = Random.Range(0f, 1f);
			float value = TurretWhacker.PluginConfig.NoEffectChance.Value;
			float value2 = TurretWhacker.PluginConfig.SuccessChance.Value;
			float value3 = TurretWhacker.PluginConfig.CriticalSuccessChance.Value;
			TerminalAccessibleObject component = ((Component)__instance).GetComponent<TerminalAccessibleObject>();
			string objectCode = component.objectCode;
			float num2 = 0f;
			if (num < (num2 += value))
			{
				TurretWhacker.Logger.LogDebug((object)$"Turret {objectCode} has been hit! Random value: {num}. No effect.");
			}
			else if (num < (num2 += value2))
			{
				TurretWhacker.Logger.LogDebug((object)$"Turret {objectCode} has been hit! Random value: {num}. Turret is being disabled.");
				((MonoBehaviour)__instance).StartCoroutine(DisableTurretFromTerminal(__instance, component));
			}
			else
			{
				if (!(num < (num2 += value3)))
				{
					TurretWhacker.Logger.LogDebug((object)$"Turret {objectCode} has been hit! Random value: {num}. Turret is beserk.");
					return true;
				}
				TurretWhacker.Logger.LogDebug((object)$"Turret {objectCode} has been hit! Random value: {num}. Turret is being permanently disabled.");
				((MonoBehaviour)__instance).StartCoroutine(DisableTurretPermanently(__instance));
			}
			__result = true;
			return false;
		}

		public static IEnumerator DisableTurretFromTerminal(Turret turret, TerminalAccessibleObject terminalObject)
		{
			turret.SwitchTurretMode(0);
			turret.SetToModeClientRpc(0);
			yield return 0;
			terminalObject.CallFunctionFromTerminal();
		}

		public static IEnumerator DisableTurretPermanently(Turret turret)
		{
			turret.SwitchTurretMode(0);
			turret.SetToModeClientRpc(0);
			yield return 0;
			turret.ToggleTurretEnabled(false);
		}
	}
}
namespace TurretWhacker.Config
{
	public class PluginConfig
	{
		public ConfigEntry<float> NoEffectChance { get; }

		public ConfigEntry<float> SuccessChance { get; }

		public ConfigEntry<float> CriticalSuccessChance { get; }

		public PluginConfig(ConfigFile config)
		{
			config.SaveOnConfigSet = false;
			NoEffectChance = config.Bind<float>("General", "NoEffectChance", 0.1f, "The chance that nothing at all happens when a turret it hit.");
			SuccessChance = config.Bind<float>("General", "SuccessChance", 0.8f, "The chance that the turret is disabled when hit.");
			CriticalSuccessChance = config.Bind<float>("General", "CriticalSuccessChance", 0.01f, "The chance that the turret is permanently disabled when hit.");
			config.Save();
			config.SaveOnConfigSet = true;
		}
	}
}

BepInEx/plugins/americanompany/MaskedEnemyRework.dll

Decompiled 2 years 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.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using MaskedEnemyRework.Patches;
using Microsoft.CodeAnalysis;
using MoreCompany;
using MoreCompany.Cosmetics;
using UnityEngine;

[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("MaskedEnemyRework")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Lethal Company Mod")]
[assembly: AssemblyFileVersion("3.3.0.0")]
[assembly: AssemblyInformationalVersion("3.3.0")]
[assembly: AssemblyProduct("MaskedEnemyRework")]
[assembly: AssemblyTitle("MaskedEnemyRework")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("3.3.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MaskedEnemyRework
{
	public class PluginConfig
	{
		public bool RemoveMasks = Cfg("General", "Remove Mask From Masked Enemy", defaultVal: true, "Whether or not the Masked Enemy has a mask on.");

		public bool RevealMasks = Cfg("General", "Reveal Mask When Attacking", defaultVal: false, "The enemy would reveal their mask permanently after trying to attack someone. Mask would be off until the attempt to attack is made");

		public bool RemoveZombieArms = Cfg("General", "Remove Zombie Arms", defaultVal: true, "Remove the animation where the Masked raise arms like a zombie.");

		public bool TriggerMines = Cfg("General", "Masked Trigger Mines", defaultVal: true, "Masked go KABOOM when walking over a mine.");

		public int Health = Cfg("General", "Masked Health", 4, "Number of shovel hits required to kill a Masked.");

		public bool UseVanillaSpawns = Cfg("General", "Use Vanilla Spawns", defaultVal: false, "Disables all spawning rules from this mod. Only uses the above settings from this config. Will not spawn on all moons. will ignore EVERYTHING in the config below this point.");

		public bool DontTouchMimickingPlayer = Cfg("General", "Dont Touch MaskedPlayerEnemy.mimickingPlayer", defaultVal: false, "Experimental. Give control to other mods (like qwbarch-Mirage) to set which players are impersonated.");

		public bool ShowMaskedNames = Cfg("General", "Show Masked Usernames", defaultVal: false, "[UNUSED FOR NOW] Will show username of player being mimicked.");

		public bool UseSpawnRarity = Cfg("Spawns", "Use Spawn Rarity", defaultVal: false, "Use custom spawn rate from config. If this is false, the masked spawns at the same rate as the Bracken. If true, will spawn at whatever rarity is given in Spawn Rarity config option");

		public int SpawnRarity = Cfg("Spawns", "Spawn Rarity", 15, "The rarity for the Masked Enemy to spawn. The higher the number, the more likely to spawn. Can go to 1000000000, any higher will break. Use Spawn Rarity must be set to True");

		public bool CanSpawnOutside = Cfg("Spawns", "Allow Masked To Spawn Outside", defaultVal: false, "Whether the Masked Enemy can spawn outside the building");

		public int MaxSpawnCount = Cfg("Spawns", "Max Number of Masked", 3, "Vents will stop spawning Masked when this limit is hit. Masked can still spawn through other means, like players getting possessed.");

		public float PowerLevel = Cfg("Spawns", "Masked Power Level", 1f, "How much of the moon's Power Level each Masked consumes. Higher = Less entities");

		public bool BoostMoonPowerLevel = Cfg("Spawns", "Boost Moon Power Level", defaultVal: false, "Increase moon indoor max power level by (Max Masked * Masked Power Level). Allows more Masked and other monsters to spawn. Original MEO behavior.");

		public bool ZombieApocalypseMode = Cfg("Zombie Apocalypse Mode", "Always Zombie Apocalypse", defaultVal: false, "Only spawns Masked! Make sure to crank up the Max Spawn Count in this config! Would also recommend bringing a gun (mod), a shovel works fine too though.... This mode does not play nice with other mods that affect spawn rates. Disable those before playing for best results");

		public int ZombieApocalypeRandomChance = Cfg("Zombie Apocalypse Mode", "Random Zombie Apocalypse", -1, "[Must Be Whole Number] The percent chance from 1 to 100 that a day could contain a zombie apocalypse. Put at -1 to never have the chance arise and don't have Only Spawn Masked turned on");

		public int MaxZombies = Cfg("Zombie Apocalypse Mode", "Max Zombies", 6, "Max Masked for Zombie Apocalypse. Vents will stop spawning Masked when this limit is hit.");

		public float ZombiePowerLevel = Cfg("Zombie Apocalypse Mode", "Zombie Power Level", 2f, "Masked power level during Zombie Apocalypse. Higher = Less Zombies. This can limit max zombies by moon difficulty, even if it's lower than what the 'Max Zombies' option allows. Set to 0 to use Max Zombies for all moons. Moon Indoor Power Levels for reference: [Experimentation: 4, Offense: 12, Titan: 18]");

		public bool UseZombieSpawnCurve = Cfg("Zombie Apocalypse Mode", "Use Spawn Curves", defaultVal: false, "[BUGGED: This likely permanently modifies the level spawning options until the game is restarted] Edit level spawn curves during a Zombie Apocalypse; options below. Original MEO behavior.");

		public float InsideEnemySpawnCurve = Cfg("Zombie Apocalypse Mode", "StartOfDay Inside Masked Spawn Curve", 0.1f, "Spawn curve for masked inside, start of the day. Crank this way up for immediate action. More info in the readme");

		public float MiddayInsideEnemySpawnCurve = Cfg("Zombie Apocalypse Mode", "Midday Inside Masked Spawn Curve", 500f, "Spawn curve for masked inside, midday.");

		public float StartOutsideEnemySpawnCurve = Cfg("Zombie Apocalypse Mode", "StartOfDay Masked Outside Spawn Curve", -30f, "Spawn curve for outside masked, start of the day.");

		public float MidOutsideEnemySpawnCurve = Cfg("Zombie Apocalypse Mode", "Midday Outside Masked Spawn Curve", -30f, "Spawn curve for outside masked, midday.");

		public float EndOutsideEnemySpawnCurve = Cfg("Zombie Apocalypse Mode", "EOD Outside Masked Spawn Curve", 10f, "Spawn curve for outside masked, end of day");

		public static List<ConfigEntryBase> entries = new List<ConfigEntryBase>();

		public static T Cfg<T>(string category, string name, T defaultVal, string description)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<T>(category, name, defaultVal, description);
			entries.Add((ConfigEntryBase)(object)val);
			return val.Value;
		}
	}
	[BepInPlugin("MaskedEnemyRework", "MaskedEnemyRework", "3.3.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("MaskedEnemyRework");

		public static Plugin Instance;

		public static ManualLogSource logger;

		public static PluginConfig cfg;

		public static List<int> PlayerMimicList;

		public static int PlayerMimicIndex;

		public static int InitialPlayerCount;

		public static SpawnableEnemyWithRarity maskedPrefab;

		public static SpawnableEnemyWithRarity flowerPrefab;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			PlayerMimicList = new List<int>();
			PlayerMimicIndex = 0;
			InitialPlayerCount = 0;
			cfg = new PluginConfig();
			logger = Logger.CreateLogSource("MaskedEnemyRework");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MaskedEnemyRework is loaded! Woohoo!");
			harmony.PatchAll(typeof(Plugin));
			harmony.PatchAll(typeof(GetMaskedPrefabForLaterUse));
			harmony.PatchAll(typeof(MaskedVisualRework));
			harmony.PatchAll(typeof(MaskedSpawnSettings));
			if (cfg.TriggerMines)
			{
				harmony.PatchAll(typeof(LandmineVsMasked));
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "MaskedEnemyRework";

		public const string PLUGIN_NAME = "MaskedEnemyRework";

		public const string PLUGIN_VERSION = "3.3.0";
	}
}
namespace MaskedEnemyRework.Patches
{
	[HarmonyPatch]
	internal class GetMaskedPrefabForLaterUse
	{
		[HarmonyPatch(typeof(Terminal), "Start")]
		[HarmonyPostfix]
		private static void SavesPrefabForLaterUse(ref SelectableLevel[] ___moonsCatalogueList)
		{
			ManualLogSource val = Logger.CreateLogSource("MaskedEnemyRework");
			SelectableLevel[] array = ___moonsCatalogueList;
			for (int i = 0; i < array.Length; i++)
			{
				foreach (SpawnableEnemyWithRarity enemy in array[i].Enemies)
				{
					if (enemy.enemyType.enemyName == "Masked")
					{
						val.LogInfo((object)"Found Masked!");
						Plugin.maskedPrefab = enemy;
					}
					else if (enemy.enemyType.enemyName == "Flowerman")
					{
						Plugin.flowerPrefab = enemy;
						val.LogInfo((object)"Found Flowerman!");
					}
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SetHoverTipAndCurrentInteractTrigger")]
		[HarmonyPrefix]
		private static void LookingAtMasked(ref PlayerControllerB __instance)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.cfg.ShowMaskedNames)
			{
				return;
			}
			Ray val = default(Ray);
			((Ray)(ref val))..ctor(((Component)__instance.gameplayCamera).transform.position, ((Component)__instance.gameplayCamera).transform.forward);
			LayerMask val2 = LayerMask.op_Implicit(524288);
			RaycastHit val3 = default(RaycastHit);
			if (!__instance.isFreeCamera && Physics.Raycast(val, ref val3, 5f, LayerMask.op_Implicit(val2)))
			{
				EnemyAICollisionDetect component = ((Component)((RaycastHit)(ref val3)).collider).gameObject.GetComponent<EnemyAICollisionDetect>();
				if (Object.op_Implicit((Object)(object)component))
				{
					((Component)component.mainScript).gameObject.GetComponent<MaskedPlayerEnemy>();
				}
			}
		}
	}
	[HarmonyPatch(typeof(Landmine))]
	internal class LandmineVsMasked
	{
		[HarmonyPatch("OnTriggerEnter")]
		[HarmonyPostfix]
		private static void OnTriggerEnter(Collider other, Landmine __instance, ref bool ___hasExploded, ref float ___pressMineDebounceTimer)
		{
			if (!___hasExploded && !(___pressMineDebounceTimer > 0f) && ((Component)other).CompareTag("Player") && ((Object)other).name.StartsWith("Masked"))
			{
				___pressMineDebounceTimer = 0.5f;
				__instance.PressMineServerRpc();
			}
		}

		[HarmonyPatch("OnTriggerExit")]
		[HarmonyPostfix]
		private static void OnTriggerExit(Collider other, Landmine __instance, ref bool ___hasExploded, ref bool ___mineActivated)
		{
			if (!___hasExploded && ___mineActivated && ((Component)other).CompareTag("Player") && ((Object)other).name.StartsWith("Masked"))
			{
				typeof(Landmine).GetMethod("TriggerMineOnLocalClientByExiting", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(__instance, null);
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	internal class MaskedSpawnSettings
	{
		private static Predicate<SpawnableEnemyWithRarity> isMasked = (SpawnableEnemyWithRarity enemy) => enemy.enemyType.enemyName == "Masked";

		private static Predicate<SpawnableEnemyWithRarity> isFlowerman = (SpawnableEnemyWithRarity enemy) => enemy.enemyType.enemyName == "Flowerman";

		private static FieldInfo powerLevelField = typeof(EnemyType).GetField("PowerLevel");

		private static FieldInfo currentMaxInsidePowerField = typeof(RoundManager).GetField("currentMaxInsidePower");

		public static bool isZombieApocalypse = false;

		public static T StupidGet<T>(object obj, FieldInfo field)
		{
			return (T)Convert.ChangeType(field.GetValue(obj), typeof(T));
		}

		[HarmonyPatch("BeginEnemySpawning")]
		[HarmonyPrefix]
		private static void UpdateSpawnRates(ref SelectableLevel ___currentLevel)
		{
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Expected O, but got Unknown
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Expected O, but got Unknown
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Expected O, but got Unknown
			PluginConfig cfg = Plugin.cfg;
			if (cfg.UseVanillaSpawns)
			{
				return;
			}
			ManualLogSource logger = Plugin.logger;
			logger.LogInfo((object)"Starting Round Manager");
			SpawnableEnemyWithRarity maskedPrefab = Plugin.maskedPrefab;
			SpawnableEnemyWithRarity val = ___currentLevel.Enemies.Find(isFlowerman) ?? Plugin.flowerPrefab;
			isZombieApocalypse = cfg.ZombieApocalypseMode || StartOfRound.Instance.randomMapSeed % 100 < cfg.ZombieApocalypeRandomChance;
			try
			{
				maskedPrefab.enemyType.enemyPrefab.GetComponent<EnemyAI>().enemyHP = cfg.Health;
				float num = 0f;
				foreach (SpawnableEnemyWithRarity item in ___currentLevel.Enemies.FindAll(isMasked))
				{
					num -= (float)item.enemyType.MaxCount * StupidGet<float>(item.enemyType, powerLevelField);
				}
				___currentLevel.Enemies.RemoveAll(isMasked);
				___currentLevel.Enemies.Add(maskedPrefab);
				if (cfg.CanSpawnOutside)
				{
					___currentLevel.OutsideEnemies.RemoveAll(isMasked);
					___currentLevel.OutsideEnemies.Add(maskedPrefab);
					___currentLevel.DaytimeEnemies.RemoveAll(isMasked);
					___currentLevel.DaytimeEnemies.Add(maskedPrefab);
				}
				float num2 = (isZombieApocalypse ? cfg.ZombiePowerLevel : cfg.PowerLevel);
				powerLevelField.SetValue(maskedPrefab.enemyType, Convert.ChangeType(num2, powerLevelField.FieldType));
				maskedPrefab.enemyType.probabilityCurve = val.enemyType.probabilityCurve;
				maskedPrefab.enemyType.isOutsideEnemy = cfg.CanSpawnOutside;
				if (isZombieApocalypse)
				{
					logger.LogInfo((object)"ZOMBIE APOCALYPSE");
					maskedPrefab.enemyType.MaxCount = cfg.MaxZombies;
					maskedPrefab.rarity = 1000000;
					if (cfg.UseZombieSpawnCurve)
					{
						___currentLevel.enemySpawnChanceThroughoutDay = new AnimationCurve((Keyframe[])(object)new Keyframe[2]
						{
							new Keyframe(0f, cfg.InsideEnemySpawnCurve),
							new Keyframe(0.5f, cfg.MiddayInsideEnemySpawnCurve)
						});
						___currentLevel.daytimeEnemySpawnChanceThroughDay = new AnimationCurve((Keyframe[])(object)new Keyframe[2]
						{
							new Keyframe(0f, 7f),
							new Keyframe(0.5f, 7f)
						});
						___currentLevel.outsideEnemySpawnChanceThroughDay = new AnimationCurve((Keyframe[])(object)new Keyframe[3]
						{
							new Keyframe(0f, cfg.StartOutsideEnemySpawnCurve),
							new Keyframe(20f, cfg.MidOutsideEnemySpawnCurve),
							new Keyframe(21f, cfg.EndOutsideEnemySpawnCurve)
						});
					}
				}
				else
				{
					logger.LogInfo((object)"no zombies :(");
					maskedPrefab.enemyType.MaxCount = cfg.MaxSpawnCount;
					maskedPrefab.rarity = (cfg.UseSpawnRarity ? cfg.SpawnRarity : val.rarity);
				}
				num += (float)maskedPrefab.enemyType.MaxCount * num2;
				if (cfg.BoostMoonPowerLevel)
				{
					logger.LogInfo((object)$"Adjusting power levels: [maxEnemyPowerCount: {___currentLevel.maxEnemyPowerCount}+{num}, maxDaytimeEnemyPowerCount: {___currentLevel.maxDaytimeEnemyPowerCount}+{num}, maxOutsideEnemyPowerCount: {___currentLevel.maxOutsideEnemyPowerCount}+{num}]");
					SelectableLevel obj = ___currentLevel;
					obj.maxEnemyPowerCount += (int)num;
					SelectableLevel obj2 = ___currentLevel;
					obj2.maxDaytimeEnemyPowerCount += (int)num;
					SelectableLevel obj3 = ___currentLevel;
					obj3.maxOutsideEnemyPowerCount += (int)num;
				}
			}
			catch (Exception ex)
			{
				logger.LogInfo((object)ex);
			}
		}

		[HarmonyPatch("AssignRandomEnemyToVent")]
		[HarmonyPrefix]
		private static bool ZombieVent(EnemyVent vent, float spawnTime, ref RoundManager __instance, ref bool __result, ref SelectableLevel ___currentLevel, ref TimeOfDay ___timeScript, ref bool ___cannotSpawnMoreInsideEnemies, ref bool ___firstTimeSpawningEnemies, ref int ___currentEnemyPower, ref int ___currentHour)
		{
			if (Plugin.cfg.UseVanillaSpawns || !isZombieApocalypse)
			{
				return true;
			}
			if (___firstTimeSpawningEnemies)
			{
				foreach (SpawnableEnemyWithRarity enemy in ___currentLevel.Enemies)
				{
					enemy.enemyType.numberSpawned = 0;
				}
			}
			___firstTimeSpawningEnemies = false;
			ManualLogSource logger = Plugin.logger;
			int num = ___currentLevel.Enemies.FindIndex(isMasked);
			SpawnableEnemyWithRarity val = ___currentLevel.Enemies[num];
			if (num == -1)
			{
				logger.LogInfo((object)"No masked found in enemy list?");
				return true;
			}
			if (val.enemyType.numberSpawned >= val.enemyType.MaxCount)
			{
				__result = false;
				___cannotSpawnMoreInsideEnemies = true;
				logger.LogInfo((object)"Max masked spawned");
				return false;
			}
			float num2 = StupidGet<float>(val.enemyType, powerLevelField);
			float num3 = StupidGet<float>(__instance, currentMaxInsidePowerField) - (float)___currentEnemyPower;
			logger.LogInfo((object)("available inside power: " + num3));
			if (num2 > num3)
			{
				__result = false;
				___cannotSpawnMoreInsideEnemies = true;
				logger.LogInfo((object)"Max power");
				return false;
			}
			___currentEnemyPower += (int)num2;
			vent.enemyType = val.enemyType;
			vent.enemyTypeIndex = num;
			vent.occupied = true;
			vent.spawnTime = spawnTime;
			if (___timeScript.hour - ___currentHour > 0)
			{
				logger.LogInfo((object)"Round manager catching up to time yada yada UvU.");
			}
			else
			{
				vent.SyncVentSpawnTimeClientRpc((int)spawnTime, num);
			}
			EnemyType enemyType = val.enemyType;
			enemyType.numberSpawned++;
			logger.LogInfo((object)"Spawned a masked");
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(MaskedPlayerEnemy))]
	internal class MaskedVisualRework
	{
		private static IEnumerator coroutine;

		[HarmonyPatch("Start")]
		[HarmonyBefore(new string[] { "AdvancedCompany" })]
		[HarmonyPostfix]
		private static void ReformVisuals(ref MaskedPlayerEnemy __instance)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			ManualLogSource val = Logger.CreateLogSource("MaskedEnemyRework");
			if (!Plugin.cfg.DontTouchMimickingPlayer)
			{
				PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
				int num = StartOfRound.Instance.ClientPlayerList.Count;
				if (num == 0)
				{
					num = 1;
					val.LogError((object)"Player count was zero");
				}
				if (Plugin.PlayerMimicList.Count <= 1 || Plugin.InitialPlayerCount != num)
				{
					Plugin.InitialPlayerCount = num;
					State state = Random.state;
					Random.InitState(1234);
					for (int i = 0; i < 50; i++)
					{
						Plugin.PlayerMimicList.Add(Random.Range(0, num));
					}
					Random.state = state;
				}
				int num2 = Plugin.PlayerMimicList[Plugin.PlayerMimicIndex % 50] % num;
				Plugin.PlayerMimicIndex++;
				if ((Object)(object)__instance.mimickingPlayer == (Object)null)
				{
					__instance.mimickingPlayer = allPlayerScripts[num2];
				}
				__instance.SetSuit(__instance.mimickingPlayer.currentSuitID);
			}
			if (Plugin.cfg.RemoveMasks || Plugin.cfg.RevealMasks)
			{
				((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskComedy")).gameObject.SetActive(false);
				((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskTragedy")).gameObject.SetActive(false);
			}
			if (Chainloader.PluginInfos.ContainsKey("me.swipez.melonloader.morecompany") && !Chainloader.PluginInfos.ContainsKey("com.potatoepet.AdvancedCompany"))
			{
				MoreCompanyPatch.ApplyCosmetics(__instance);
			}
		}

		[HarmonyPatch("SetHandsOutClientRpc")]
		[HarmonyPrefix]
		private static void MaskAndArmsReveal(ref bool setOut, ref MaskedPlayerEnemy __instance)
		{
			GameObject gameObject = ((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskComedy")).gameObject;
			if (Plugin.cfg.RevealMasks && !gameObject.activeSelf && ((EnemyAI)__instance).currentBehaviourStateIndex == 1)
			{
				Logger.CreateLogSource("MaskedEnemyRework");
				IEnumerator enumerator = FadeInAndOut(gameObject, fadeIn: true, 1f);
				((MonoBehaviour)__instance).StartCoroutine(enumerator);
			}
			if (Plugin.cfg.RemoveZombieArms)
			{
				setOut = false;
			}
		}

		[HarmonyPatch("SetEnemyOutside")]
		[HarmonyPostfix]
		[HarmonyPriority(300)]
		private static void HideCosmeticsIfMarked(ref MaskedPlayerEnemy __instance)
		{
			if (Chainloader.PluginInfos.ContainsKey("me.swipez.melonloader.morecompany") && !Chainloader.PluginInfos.ContainsKey("com.potatoepet.AdvancedCompany"))
			{
				MoreCompanyPatch.ApplyCosmetics(__instance);
			}
		}

		[HarmonyPatch("DoAIInterval")]
		[HarmonyPostfix]
		private static void HideRevealedMask(ref MaskedPlayerEnemy __instance)
		{
			if (Plugin.cfg.RevealMasks && (Object)(object)((EnemyAI)__instance).targetPlayer == (Object)null)
			{
				GameObject gameObject = ((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskComedy")).gameObject;
				if (gameObject.activeSelf)
				{
					IEnumerator enumerator = FadeInAndOut(gameObject, fadeIn: false, 1f);
					((MonoBehaviour)__instance).StartCoroutine(enumerator);
				}
			}
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdateMaskName(ref MaskedPlayerEnemy __instance)
		{
		}

		private static IEnumerator FadeInAndOut(GameObject mask, bool fadeIn, float duration)
		{
			float counter = 0f;
			mask.SetActive(true);
			float startLoc;
			float endLoc;
			if (fadeIn)
			{
				startLoc = 0.095f;
				endLoc = 0.215f;
			}
			else
			{
				startLoc = 0.215f;
				endLoc = 0.095f;
			}
			while (counter < duration)
			{
				counter += Time.deltaTime;
				float num = Mathf.Lerp(startLoc, endLoc, counter / duration);
				mask.transform.localPosition = new Vector3(-0.009f, 0.143f, num);
				yield return null;
			}
			if (!fadeIn)
			{
				mask.SetActive(false);
			}
		}
	}
	internal class MoreCompanyPatch
	{
		public static void ApplyCosmetics(MaskedPlayerEnemy masked)
		{
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			if (MainClass.playerIdsAndCosmetics.Count == 0)
			{
				return;
			}
			FieldInfo field = typeof(MainClass).GetField("showCosmetics");
			FieldInfo field2 = typeof(MainClass).GetField("cosmeticsSyncOther");
			if (field != null)
			{
				if (!(bool)field.GetValue(null))
				{
					return;
				}
			}
			else if (!(field2 != null) || !((ConfigEntry<bool>)field2.GetValue(null)).Value)
			{
				return;
			}
			Transform val = ((Component)masked).transform.Find("ScavengerModel").Find("metarig");
			CosmeticApplication component = ((Component)val).GetComponent<CosmeticApplication>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.ClearCosmetics();
				Object.Destroy((Object)(object)component);
				((EnemyAI)masked).skinnedMeshRenderers = ((Component)masked).gameObject.GetComponentsInChildren<SkinnedMeshRenderer>();
				((EnemyAI)masked).meshRenderers = ((Component)masked).gameObject.GetComponentsInChildren<MeshRenderer>();
			}
			List<string> list = MainClass.playerIdsAndCosmetics[(int)masked.mimickingPlayer.playerClientId];
			component = ((Component)val).gameObject.AddComponent<CosmeticApplication>();
			foreach (string item in list)
			{
				component.ApplyCosmetic(item, true);
			}
			foreach (CosmeticInstance spawnedCosmetic in component.spawnedCosmetics)
			{
				Transform transform = ((Component)spawnedCosmetic).transform;
				transform.localScale *= 0.38f;
			}
		}
	}
	internal class RemoveZombieArms
	{
		[HarmonyPatch(typeof(MaskedPlayerEnemy), "SetHandsOutClientRpc")]
		[HarmonyPrefix]
		private static void RemoveArms(ref bool setOut)
		{
			if (Plugin.cfg.RemoveZombieArms)
			{
				setOut = false;
			}
		}
	}
}

BepInEx/plugins/americanompany/MissileTurret.dll

Decompiled 2 years ago
using System;
using System.Diagnostics;
using System.IO;
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 GameNetcodeStuff;
using JetBrains.Annotations;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using MissileTurret.NetcodePatcher;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MissileTurret")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MissileTurret")]
[assembly: AssemblyTitle("MissileTurret")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MissileTurret
{
	public class MissileAI : NetworkBehaviour
	{
		public Transform player;

		private float _speed = 0f;

		private float _currentLaunchTime;

		private readonly float launchTimeSeconds = 0.4f;

		private float _aliveTimeSeconds;

		private Rigidbody _rigidbody;

		public static float MaxTurnSpeed = 1f;

		public static float MaxSpeed = 0.7f;

		public static float Acceleration = 0.001f;

		public static float KillRange = 1f;

		public static float DamageRange = 5f;

		private void Awake()
		{
			_rigidbody = ((Component)this).GetComponent<Rigidbody>();
			_currentLaunchTime = launchTimeSeconds;
		}

		private void Update()
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = ((Component)this).transform;
			Vector3 forward = transform.forward;
			_aliveTimeSeconds += Time.deltaTime;
			if (_currentLaunchTime > 0f)
			{
				_currentLaunchTime -= Time.deltaTime;
				transform.position += transform.up * (_speed * 1.5f);
				_speed += 0.0004f * Time.deltaTime;
			}
			else if (_speed < MaxSpeed)
			{
				_speed += Acceleration * Time.deltaTime;
			}
			_rigidbody.MovePosition(transform.position + forward * (_speed * Time.deltaTime));
			if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
			{
				Vector3 val = player.position + Vector3.up - transform.position;
				Quaternion val2 = Quaternion.LookRotation(val);
				transform.rotation = Quaternion.Lerp(transform.rotation, val2, ((Vector3)(ref val)).magnitude * (MaxTurnSpeed * Time.deltaTime));
			}
			if (_aliveTimeSeconds > 10f)
			{
				EndIt();
			}
		}

		private void OnCollisionEnter(Collision other)
		{
			EndIt();
		}

		private void EndIt()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
			{
				ExplodeClientRpc(((Component)this).transform.position, KillRange, DamageRange);
				NetworkObject component = ((Component)this).GetComponent<NetworkObject>();
				if (component != null && component.IsSpawned)
				{
					component.Despawn(true);
				}
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}

		[ClientRpc]
		public void ExplodeClientRpc(Vector3 position, float killRange, float damageRange)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: 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_00ab: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1416639908u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref position);
					((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref killRange, default(ForPrimitives));
					((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref damageRange, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1416639908u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Landmine.SpawnExplosion(position, true, killRange, damageRange, 50, 0f, (GameObject)null, false);
				}
			}
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_MissileAI()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(1416639908u, new RpcReceiveHandler(__rpc_handler_1416639908));
		}

		private static void __rpc_handler_1416639908(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Vector3 position = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref position);
				float killRange = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref killRange, default(ForPrimitives));
				float damageRange = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref damageRange, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((MissileAI)(object)target).ExplodeClientRpc(position, killRange, damageRange);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		protected internal override string __getTypeName()
		{
			return "MissileAI";
		}
	}
	public class MissileTurretAI : NetworkBehaviour
	{
		private enum MissileTurretState
		{
			SEARCHING,
			FIRING,
			CHARGING,
			DISABLED
		}

		public Transform rod;

		public Transform rail;

		public GameObject missile;

		public GameObject laser;

		public static float RotationRange;

		public static float RotationSpeed;

		private float _currentRotationSpeed;

		private MissileTurretState _state;

		private MissileTurretState _lastState;

		[CanBeNull]
		private PlayerControllerB _targetPlayer;

		private RaycastHit _lastHit;

		private float _currentReloadTime;

		public static float ReloadTimeSeconds;

		private float _currentChargeTime;

		public static float ChargeTimeSeconds;

		public AudioSource acquireTargetAudio;

		public AudioSource disableAudio;

		public AudioSource enableAudio;

		private float _currentDisableTime = 0f;

		public static float DisableTimeSeconds = 8f;

		private void Awake()
		{
			_currentReloadTime = ReloadTimeSeconds;
			_currentChargeTime = ChargeTimeSeconds;
			_currentRotationSpeed = RotationSpeed;
			_currentDisableTime = DisableTimeSeconds;
			TerminalAccessibleObject component = ((Component)this).GetComponent<TerminalAccessibleObject>();
			((UnityEventBase)component.terminalCodeEvent).AddListener((object)this, typeof(MissileTurretAI).GetMethod("DisableTurret"));
			laser.SetActive(false);
			ToggleLaserClientRpc(active: false);
		}

		private void Update()
		{
			//IL_0033: 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_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_030c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0311: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_048b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0490: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0537: Unknown result type (might be due to invalid IL or missing references)
			//IL_053c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0550: Unknown result type (might be due to invalid IL or missing references)
			//IL_055e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0563: Unknown result type (might be due to invalid IL or missing references)
			//IL_0577: Unknown result type (might be due to invalid IL or missing references)
			//IL_0580: Unknown result type (might be due to invalid IL or missing references)
			//IL_0582: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0383: Unknown result type (might be due to invalid IL or missing references)
			//IL_0388: Unknown result type (might be due to invalid IL or missing references)
			//IL_038d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0398: Unknown result type (might be due to invalid IL or missing references)
			//IL_039d: Unknown result type (might be due to invalid IL or missing references)
			MissileTurretState? missileTurretState = null;
			RaycastHit lastHit = default(RaycastHit);
			switch (_state)
			{
			case MissileTurretState.SEARCHING:
				if (Physics.Raycast(rod.position + rod.up, rod.up, ref lastHit, 30f, 1051400, (QueryTriggerInteraction)1) && ((Component)((RaycastHit)(ref lastHit)).transform).CompareTag("Player"))
				{
					if ((Object)(object)((RaycastHit)(ref lastHit)).collider != (Object)(object)((RaycastHit)(ref _lastHit)).collider)
					{
						_targetPlayer = ((Component)((RaycastHit)(ref lastHit)).transform).GetComponent<PlayerControllerB>();
						_lastHit = lastHit;
					}
					missileTurretState = MissileTurretState.CHARGING;
				}
				else
				{
					_targetPlayer = null;
					missileTurretState = MissileTurretState.SEARCHING;
				}
				if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
				{
					rod.Rotate(Vector3.forward, _currentRotationSpeed * Time.deltaTime);
					float z = rod.localEulerAngles.z;
					if ((z > RotationRange && z <= 180f && _currentRotationSpeed > 0f) || (z < 360f - RotationRange && z > 180f && _currentRotationSpeed < 0f))
					{
						_currentRotationSpeed = 0f - _currentRotationSpeed;
					}
					SetYawClientRpc(z);
				}
				break;
			case MissileTurretState.CHARGING:
				if (_lastState != MissileTurretState.CHARGING)
				{
					acquireTargetAudio.Play();
					if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
					{
						ToggleLaserClientRpc(active: true);
					}
				}
				if (_currentChargeTime <= 0f)
				{
					_currentChargeTime = ChargeTimeSeconds;
					missileTurretState = MissileTurretState.FIRING;
					if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
					{
						ToggleLaserClientRpc(active: false);
					}
				}
				else
				{
					_currentChargeTime -= Time.deltaTime;
				}
				break;
			case MissileTurretState.FIRING:
				if (_targetPlayer == null)
				{
					missileTurretState = MissileTurretState.SEARCHING;
					break;
				}
				if (_lastState != MissileTurretState.FIRING)
				{
					if ((!Physics.Raycast(rod.position + rod.forward, ((Component)_targetPlayer).transform.position - rod.position, ref lastHit, 30f, 1051400, (QueryTriggerInteraction)1) || !((Component)((RaycastHit)(ref lastHit)).transform).CompareTag("Player")) && (!Physics.Raycast(rod.position + rod.forward, ((Component)_targetPlayer).transform.position - rod.position, ref lastHit, 30f, 1051400, (QueryTriggerInteraction)1) || !((Component)((RaycastHit)(ref lastHit)).transform).CompareTag("Player")))
					{
						missileTurretState = MissileTurretState.SEARCHING;
						break;
					}
					if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
					{
						MissileAI component = Object.Instantiate<GameObject>(Plugin.MissilePrefab, rod.position + Vector3.up, Quaternion.LookRotation(rod.up)).GetComponent<MissileAI>();
						component.player = ((Component)_targetPlayer).transform;
						((Component)component).GetComponent<NetworkObject>().Spawn(true);
						ToggleMissileClientRpc(active: false);
					}
				}
				if (_currentReloadTime <= 0f)
				{
					if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
					{
						ToggleMissileClientRpc(active: true);
					}
					_currentReloadTime = ReloadTimeSeconds;
					missileTurretState = MissileTurretState.SEARCHING;
				}
				else
				{
					_currentReloadTime -= Time.deltaTime;
				}
				break;
			case MissileTurretState.DISABLED:
				if (_lastState != MissileTurretState.DISABLED)
				{
					disableAudio.Play();
					if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
					{
						Vector3 localEulerAngles = rail.localEulerAngles;
						localEulerAngles.x = -30f;
						rail.localEulerAngles = localEulerAngles;
						Vector3 localPosition = rail.localPosition;
						localPosition.y = -0.67f;
						rail.localPosition = localPosition;
						SetRailClientRpc(localEulerAngles, localPosition);
					}
				}
				if (_currentDisableTime <= 0f)
				{
					_currentDisableTime = DisableTimeSeconds;
					enableAudio.Play();
					if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
					{
						Vector3 localEulerAngles2 = rail.localEulerAngles;
						localEulerAngles2.x = 0f;
						rail.localEulerAngles = localEulerAngles2;
						Vector3 localPosition2 = rail.localPosition;
						localPosition2.y = 0f;
						rail.localPosition = localPosition2;
						SetRailClientRpc(localEulerAngles2, localPosition2);
					}
					missileTurretState = MissileTurretState.SEARCHING;
				}
				else
				{
					_currentDisableTime -= Time.deltaTime;
				}
				break;
			}
			_lastState = _state;
			if (missileTurretState.HasValue && missileTurretState != _state && (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer))
			{
				_state = missileTurretState.Value;
				SetStateClientRpc(_state, _lastState);
			}
		}

		public void DisableTurret(PlayerControllerB pc)
		{
			if (pc != null)
			{
				_lastState = _state;
				_state = MissileTurretState.DISABLED;
				SetStateClientRpc(_state, _lastState);
			}
		}

		[ClientRpc]
		private void SetStateClientRpc(MissileTurretState state, MissileTurretState lastState)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3177718372u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<MissileTurretState>(ref state, default(ForEnums));
					((FastBufferWriter)(ref val2)).WriteValueSafe<MissileTurretState>(ref lastState, default(ForEnums));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3177718372u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					_state = state;
					_lastState = lastState;
				}
			}
		}

		[ClientRpc]
		private void SetYawClientRpc(float yaw)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2936333528u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref yaw, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2936333528u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Vector3 localEulerAngles = rod.localEulerAngles;
					localEulerAngles.z = yaw;
					rod.localEulerAngles = localEulerAngles;
				}
			}
		}

		[ClientRpc]
		private void SetRailClientRpc(Vector3 localEulers, Vector3 localPos)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3970896126u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref localEulers);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref localPos);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3970896126u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					rail.localPosition = localPos;
					rail.localEulerAngles = localEulers;
				}
			}
		}

		[ClientRpc]
		private void ToggleMissileClientRpc(bool active)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1599590863u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref active, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1599590863u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					missile.SetActive(active);
				}
			}
		}

		[ClientRpc]
		private void ToggleLaserClientRpc(bool active)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1199733162u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref active, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1199733162u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					laser.SetActive(active);
				}
			}
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_MissileTurretAI()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(3177718372u, new RpcReceiveHandler(__rpc_handler_3177718372));
			NetworkManager.__rpc_func_table.Add(2936333528u, new RpcReceiveHandler(__rpc_handler_2936333528));
			NetworkManager.__rpc_func_table.Add(3970896126u, new RpcReceiveHandler(__rpc_handler_3970896126));
			NetworkManager.__rpc_func_table.Add(1599590863u, new RpcReceiveHandler(__rpc_handler_1599590863));
			NetworkManager.__rpc_func_table.Add(1199733162u, new RpcReceiveHandler(__rpc_handler_1199733162));
		}

		private static void __rpc_handler_3177718372(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				MissileTurretState state = default(MissileTurretState);
				((FastBufferReader)(ref reader)).ReadValueSafe<MissileTurretState>(ref state, default(ForEnums));
				MissileTurretState lastState = default(MissileTurretState);
				((FastBufferReader)(ref reader)).ReadValueSafe<MissileTurretState>(ref lastState, default(ForEnums));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((MissileTurretAI)(object)target).SetStateClientRpc(state, lastState);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2936333528(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				float yawClientRpc = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref yawClientRpc, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((MissileTurretAI)(object)target).SetYawClientRpc(yawClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3970896126(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Vector3 localEulers = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref localEulers);
				Vector3 localPos = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref localPos);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((MissileTurretAI)(object)target).SetRailClientRpc(localEulers, localPos);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1599590863(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool active = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref active, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((MissileTurretAI)(object)target).ToggleMissileClientRpc(active);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1199733162(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool active = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref active, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((MissileTurretAI)(object)target).ToggleLaserClientRpc(active);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		protected internal override string __getTypeName()
		{
			return "MissileTurretAI";
		}
	}
	[BepInPlugin("Finnerex.MissileTurret", "MissileTurret", "1.3.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static SpawnableMapObject MissileTurretMapObj;

		public static GameObject MissileTurretPrefab;

		public static GameObject MissilePrefab;

		public static ManualLogSource TheLogger;

		public int MaxTurrets;

		public int MinTurrets;

		private void Awake()
		{
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Expected O, but got Unknown
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Expected O, but got Unknown
			TheLogger = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Missile Turret Loading???");
			Configure();
			InitializeNetworkBehaviours();
			string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			AssetBundle val = AssetBundle.LoadFromFile(Path.Combine(directoryName, "missileturretassetbundle"));
			if (val == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Failed to load assets");
				return;
			}
			MissileTurretPrefab = val.LoadAsset<GameObject>("MissileTurret");
			MissilePrefab = val.LoadAsset<GameObject>("Missile");
			MissileTurretAI missileTurretAI = MissileTurretPrefab.AddComponent<MissileTurretAI>();
			missileTurretAI.rod = MissileTurretPrefab.transform.Find("missileTurret/Mount/Rod");
			missileTurretAI.rail = missileTurretAI.rod.Find("Rod.001");
			missileTurretAI.missile = ((Component)missileTurretAI.rail.Find("Cylinder")).gameObject;
			missileTurretAI.acquireTargetAudio = ((Component)missileTurretAI.rod).GetComponent<AudioSource>();
			missileTurretAI.disableAudio = ((Component)missileTurretAI.rod.Find("DisableSound")).GetComponent<AudioSource>();
			missileTurretAI.enableAudio = ((Component)missileTurretAI.rod.Find("EnableSound")).GetComponent<AudioSource>();
			missileTurretAI.laser = ((Component)missileTurretAI.rod.Find("LaserLight")).gameObject;
			MissilePrefab.AddComponent<MissileAI>();
			Utilities.FixMixerGroups(MissileTurretPrefab);
			Utilities.FixMixerGroups(MissilePrefab);
			NetworkPrefabs.RegisterNetworkPrefab(MissileTurretPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(MissilePrefab);
			AnimationCurve curve = new AnimationCurve((Keyframe[])(object)new Keyframe[2]
			{
				new Keyframe(0f, (float)MinTurrets, 0.267f, 0.267f, 0f, 0.246f),
				new Keyframe(1f, (float)MaxTurrets, 61f, 61f, 0.015f * (float)MaxTurrets, 0f)
			});
			MissileTurretMapObj = new SpawnableMapObject
			{
				prefabToSpawn = MissileTurretPrefab,
				spawnFacingAwayFromWall = true,
				numberToSpawn = curve
			};
			MapObjects.RegisterMapObject(MissileTurretMapObj, (LevelTypes)(-1), (Func<SelectableLevel, AnimationCurve>)((SelectableLevel _) => curve));
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Missile Turret Loaded!!!");
		}

		private static void InitializeNetworkBehaviours()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}

		private void Configure()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_002d: Expected O, but got Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_0063: Expected O, but got Unknown
			//IL_007d: 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)
			//IL_009c: Expected O, but got Unknown
			//IL_009c: Expected O, but got Unknown
			//IL_00bc: 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_00db: Expected O, but got Unknown
			//IL_00db: Expected O, but got Unknown
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			//IL_0114: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Expected O, but got Unknown
			//IL_0153: Expected O, but got Unknown
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Expected O, but got Unknown
			//IL_018c: Expected O, but got Unknown
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Expected O, but got Unknown
			//IL_01c5: Expected O, but got Unknown
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Expected O, but got Unknown
			//IL_01fe: Expected O, but got Unknown
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Expected O, but got Unknown
			//IL_023d: Expected O, but got Unknown
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Expected O, but got Unknown
			//IL_0276: Expected O, but got Unknown
			MaxTurrets = ((BaseUnityPlugin)this).Config.Bind<int>(new ConfigDefinition("Spawn Options", "Max Turrets"), 6, new ConfigDescription("Maximum number of turrets that can be spawned", (AcceptableValueBase)null, Array.Empty<object>())).Value;
			MinTurrets = ((BaseUnityPlugin)this).Config.Bind<int>(new ConfigDefinition("Spawn Options", "Min Turrets"), 0, new ConfigDescription("Minimum number of turrets that can be spawned", (AcceptableValueBase)null, Array.Empty<object>())).Value;
			MissileAI.MaxSpeed = ((BaseUnityPlugin)this).Config.Bind<float>(new ConfigDefinition("Missile Options", "Max Speed"), 0.7f, new ConfigDescription("Maximum speed of a missile", (AcceptableValueBase)null, Array.Empty<object>())).Value * 100f;
			MissileAI.MaxTurnSpeed = ((BaseUnityPlugin)this).Config.Bind<float>(new ConfigDefinition("Missile Options", "Turn Rate"), 0.6f, new ConfigDescription("How fast the missile can turn", (AcceptableValueBase)null, Array.Empty<object>())).Value;
			MissileAI.Acceleration = ((BaseUnityPlugin)this).Config.Bind<float>(new ConfigDefinition("Missile Options", "Acceleration"), 0.6f, new ConfigDescription("Acceleration of the missile", (AcceptableValueBase)null, Array.Empty<object>())).Value * 100f;
			MissileAI.KillRange = ((BaseUnityPlugin)this).Config.Bind<float>(new ConfigDefinition("Missile Options", "Explosive Kill Range"), 1f, new ConfigDescription("Distance from explosion to kill", (AcceptableValueBase)null, Array.Empty<object>())).Value;
			MissileAI.DamageRange = ((BaseUnityPlugin)this).Config.Bind<float>(new ConfigDefinition("Missile Options", "Explosive Damage Range"), 5f, new ConfigDescription("Distance from explosion to damage", (AcceptableValueBase)null, Array.Empty<object>())).Value;
			MissileTurretAI.RotationRange = ((BaseUnityPlugin)this).Config.Bind<float>(new ConfigDefinition("Missile Turret Options", "Rotation Range"), 45f, new ConfigDescription("The angle the turret's search is restricted to in degrees left & right", (AcceptableValueBase)null, Array.Empty<object>())).Value;
			MissileTurretAI.RotationSpeed = ((BaseUnityPlugin)this).Config.Bind<float>(new ConfigDefinition("Missile Turret Options", "Rotation Rate"), 0.25f, new ConfigDescription("The speed at which the turret rotates", (AcceptableValueBase)null, Array.Empty<object>())).Value * 100f;
			MissileTurretAI.ReloadTimeSeconds = ((BaseUnityPlugin)this).Config.Bind<float>(new ConfigDefinition("Missile Turret Options", "Reload Time"), 6f, new ConfigDescription("The time it takes for the turret to reload in seconds", (AcceptableValueBase)null, Array.Empty<object>())).Value;
			MissileTurretAI.ChargeTimeSeconds = ((BaseUnityPlugin)this).Config.Bind<float>(new ConfigDefinition("Missile Turret Options", "Charge Time"), 0.5f, new ConfigDescription("The time it takes for the turret to shoot at a target in seconds", (AcceptableValueBase)null, Array.Empty<object>())).Value;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "MissileTurret";

		public const string PLUGIN_NAME = "MissileTurret";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace MissileTurret.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}

BepInEx/plugins/americanompany/MolesterLootBug.dll

Decompiled 2 years ago
using System;
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.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalCompanyTemplate
{
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "MolesterLootBug";

		public const string PLUGIN_NAME = "MolesterLootBug";

		public const string PLUGIN_VERSION = "1.0.1";
	}
}
namespace MolesterLootBug
{
	[BepInPlugin("EvilLootBugByOwen.1.10", "Molester Loot Bug", "0.2")]
	public class Plugin : BaseUnityPlugin
	{
		public class BeingHeldData : MonoBehaviour
		{
			public bool isHeld = false;

			public HoarderBugAI HoarderInstance = null;

			public PlayerControllerB player = null;

			public float holdTimeRemaining = bugHoldTime;
		}

		public class HoldingData : MonoBehaviour
		{
			public bool isHoldingPlayer = false;

			public PlayerControllerB HeldPlayer = null;

			public float CanHoldTime = bugHoldTime;
		}

		private const string PLUGIN_GUID = "EvilLootBugByOwen.1.10";

		private const string PLUGIN_NAME = "Molester Loot Bug";

		private const string PLUGIN_VERSION = "0.2";

		private readonly Harmony harmony = new Harmony("EvilLootBugByOwen.1.10");

		private static Plugin Instance;

		internal static ManualLogSource mls;

		internal static Random random = new Random();

		private static float bugHoldTime = 8f;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("EvilLootBugByOwen.1.10");
			mls.LogInfo((object)"Mod Awake OWEN GOATED");
			harmony.PatchAll(typeof(Plugin));
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Awake")]
		[HarmonyPostfix]
		private static void AwakeUpdate(PlayerControllerB __instance)
		{
			mls.LogInfo((object)"Attempting to Load instance Data, Player Awake Patch");
			((Component)__instance).gameObject.AddComponent<BeingHeldData>();
			BeingHeldData component = ((Component)__instance).gameObject.GetComponent<BeingHeldData>();
			component.player = __instance;
			mls.LogInfo((object)$"Is Being Held ON AWAKE? {component.isHeld}");
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void PlayerUpdate(PlayerControllerB __instance, ref Vector3 ___serverPlayerPosition, ref bool ___snapToServerPosition)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: 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_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			BeingHeldData component = ((Component)__instance).gameObject.GetComponent<BeingHeldData>();
			if (!component.isHeld)
			{
				return;
			}
			Vector3 serverPosition = ((EnemyAI)component.HoarderInstance).serverPosition;
			Vector3 position = ((Component)__instance).gameObject.transform.position;
			Vector3 val = serverPosition - position;
			__instance.thisController.SimpleMove(val * 6f);
			mls.LogInfo((object)$"PlayerServer Pos at {__instance.serverPlayerPosition}");
			mls.LogInfo((object)$"Local Pos at {__instance.serverPlayerPosition}");
			mls.LogInfo((object)$"Loot Pos at {((EnemyAI)component.HoarderInstance).serverPosition}");
			mls.LogInfo((object)$"Bug Holding Player. Time left: {component.holdTimeRemaining}");
			component.holdTimeRemaining -= Time.deltaTime;
			mls.LogInfo((object)$"Is Being Held? {component.isHeld}");
			if (component.holdTimeRemaining <= 0f || __instance.isPlayerDead || ((EnemyAI)component.HoarderInstance).isEnemyDead)
			{
				component.isHeld = false;
				component.holdTimeRemaining = bugHoldTime;
				((Component)component.HoarderInstance).gameObject.GetComponent<HoldingData>().CanHoldTime = bugHoldTime;
				HoldingData component2 = ((Component)component.HoarderInstance).gameObject.GetComponent<HoldingData>();
				if ((Object)(object)component2 != (Object)null)
				{
					component2.isHoldingPlayer = false;
				}
			}
		}

		[HarmonyPatch(typeof(HoarderBugAI), "Start")]
		[HarmonyPostfix]
		private static void BugStart(HoarderBugAI __instance)
		{
			((Component)__instance).gameObject.AddComponent<HoldingData>();
		}

		[HarmonyPatch(typeof(HoarderBugAI), "OnCollideWithPlayer")]
		[HarmonyPostfix]
		private static void BugOnCollide(HoarderBugAI __instance, Collider other)
		{
			HoldingData component = ((Component)__instance).gameObject.GetComponent<HoldingData>();
			if (!component.isHoldingPlayer && random.Next(0, 2) == 0 && !((EnemyAI)__instance).isEnemyDead && component.CanHoldTime <= 0f)
			{
				PlayerControllerB component2 = ((Component)other).GetComponent<PlayerControllerB>();
				if ((Object)(object)component2 != (Object)null)
				{
					((Component)component2).gameObject.GetComponent<BeingHeldData>().isHeld = true;
					((Component)component2).gameObject.GetComponent<BeingHeldData>().HoarderInstance = __instance;
					((Component)__instance).gameObject.GetComponent<HoldingData>().isHoldingPlayer = true;
					((Component)__instance).gameObject.GetComponent<HoldingData>().HeldPlayer = component2;
				}
			}
		}

		[HarmonyPatch(typeof(HoarderBugAI), "Update")]
		[HarmonyPostfix]
		private static void BugUpdate(HoarderBugAI __instance)
		{
			HoldingData component = ((Component)__instance).gameObject.GetComponent<HoldingData>();
			if (component.isHoldingPlayer)
			{
				mls.LogInfo((object)"Bug Holding Player.");
				__instance.angryTimer -= 2f * Time.deltaTime;
				__instance.angryAtPlayer = null;
				__instance.timeSinceHittingPlayer = -5f;
				if (((EnemyAI)__instance).isEnemyDead)
				{
					component.isHoldingPlayer = false;
					BeingHeldData component2 = ((Component)component.HeldPlayer).gameObject.GetComponent<BeingHeldData>();
					component2.isHeld = false;
				}
			}
			else
			{
				component.CanHoldTime -= Time.deltaTime;
			}
		}
	}
}
namespace MolesterLootBug.Patches
{
	[HarmonyPatch(typeof(HoarderBugAI))]
	internal class LootBugPatch
	{
	}
	internal class PlayerControllerBPatch
	{
	}
}

BepInEx/plugins/americanompany/NoShotgunMisfire.dll

Decompiled 2 years ago
using System;
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.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("NoShotgunMisfire")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright © 2024 MegaPiggy")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+de03bd2735d14ec5e61f253b6602806c4ce89ece")]
[assembly: AssemblyProduct("NoShotgunMisfire")]
[assembly: AssemblyTitle("NoShotgunMisfire")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace NoShotgunMisfire
{
	[BepInPlugin("MegaPiggy.NoShotgunMisfire", "No Shotgun Misfire", "1.0.0")]
	public class Main : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(ShotgunItem))]
		internal static class ShotgunItemPatch
		{
			[HarmonyPatch("Update")]
			[HarmonyPrefix]
			public static void Update(ShotgunItem __instance)
			{
				__instance.hasHitGroundWithSafetyOff = true;
				__instance.misfireTimer = 6624f;
			}
		}

		public const string ModGUID = "MegaPiggy.NoShotgunMisfire";

		public const string ModName = "No Shotgun Misfire";

		public const string ModVersion = "1.0.0";

		private readonly Harmony harmony = new Harmony("MegaPiggy.NoShotgunMisfire");

		private static Main instance;

		internal static Main Instance => instance;

		internal static ManualLogSource LoggerInstance => ((BaseUnityPlugin)Instance).Logger;

		private void Awake()
		{
			if ((Object)(object)instance == (Object)null)
			{
				Object.DontDestroyOnLoad((Object)(object)this);
				instance = this;
			}
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin No Shotgun Misfire is loaded with version 1.0.0!");
		}
	}
}

BepInEx/plugins/americanompany/PiggyVarietyMod.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using MoreEmotes.Patch;
using PiggyVarietyMod.Patches;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("RadiationIsCool")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RadiationIsCool")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("8ee335db-0cbe-470c-8fbc-69263f01b35a")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public class AxeItem : GrabbableObject
{
	public int shovelHitForce = 1;

	public bool reelingUp;

	public bool isHoldingButton;

	private RaycastHit rayHit;

	private Coroutine reelingUpCoroutine;

	private RaycastHit[] objectsHitByShovel;

	private List<RaycastHit> objectsHitByShovelList = new List<RaycastHit>();

	public AudioClip reelUp;

	public AudioClip swing;

	public AudioClip[] hitSFX;

	public AudioSource shovelAudio;

	private PlayerControllerB previousPlayerHeldBy;

	private int shovelMask = 11012424;

	public override void ItemActivate(bool used, bool buttonDown = true)
	{
		if ((Object)(object)base.playerHeldBy == (Object)null)
		{
			return;
		}
		Debug.Log((object)$"Is player pressing down button?: {buttonDown}");
		isHoldingButton = buttonDown;
		Debug.Log((object)("PLAYER ACTIVATED ITEM TO HIT WITH SHOVEL. Who sent this log: " + ((Object)((Component)GameNetworkManager.Instance.localPlayerController).gameObject).name));
		if (!reelingUp && buttonDown)
		{
			reelingUp = true;
			previousPlayerHeldBy = base.playerHeldBy;
			Debug.Log((object)$"Set previousPlayerHeldBy: {previousPlayerHeldBy}");
			if (reelingUpCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(reelingUpCoroutine);
			}
			reelingUpCoroutine = ((MonoBehaviour)this).StartCoroutine(reelUpShovel());
		}
	}

	private IEnumerator reelUpShovel()
	{
		base.playerHeldBy.activatingItem = true;
		base.playerHeldBy.twoHanded = true;
		base.playerHeldBy.playerBodyAnimator.ResetTrigger("shovelHit");
		base.playerHeldBy.playerBodyAnimator.SetBool("reelingUp", true);
		shovelAudio.PlayOneShot(reelUp);
		ReelUpSFXServerRpc();
		yield return (object)new WaitForSeconds(0.35f);
		yield return (object)new WaitUntil((Func<bool>)(() => !isHoldingButton || !base.isHeld));
		SwingShovel(!base.isHeld);
		yield return (object)new WaitForSeconds(0.13f);
		yield return (object)new WaitForEndOfFrame();
		HitShovel(!base.isHeld);
		yield return (object)new WaitForSeconds(0.3f);
		reelingUp = false;
		reelingUpCoroutine = null;
	}

	[ServerRpc]
	public void ReelUpSFXServerRpc()
	{
		ReelUpSFXClientRpc();
	}

	[ClientRpc]
	public void ReelUpSFXClientRpc()
	{
		if (!((NetworkBehaviour)this).IsOwner)
		{
			shovelAudio.PlayOneShot(reelUp);
		}
	}

	public override void DiscardItem()
	{
		if ((Object)(object)base.playerHeldBy != (Object)null)
		{
			base.playerHeldBy.activatingItem = false;
		}
		((GrabbableObject)this).DiscardItem();
	}

	public void SwingShovel(bool cancel = false)
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		previousPlayerHeldBy.playerBodyAnimator.SetBool("reelingUp", false);
		if (!cancel)
		{
			shovelAudio.PlayOneShot(swing);
			previousPlayerHeldBy.UpdateSpecialAnimationValue(true, (short)((Component)previousPlayerHeldBy).transform.localEulerAngles.y, 0.4f, false);
		}
	}

	public void HitShovel(bool cancel = false)
	{
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_052c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Unknown result type (might be due to invalid IL or missing references)
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0125: Unknown result type (might be due to invalid IL or missing references)
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0173: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_0229: Unknown result type (might be due to invalid IL or missing references)
		//IL_022e: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01de: Unknown result type (might be due to invalid IL or missing references)
		//IL_0194: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_024c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0251: Unknown result type (might be due to invalid IL or missing references)
		//IL_0315: Unknown result type (might be due to invalid IL or missing references)
		//IL_031a: Unknown result type (might be due to invalid IL or missing references)
		//IL_027d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0282: Unknown result type (might be due to invalid IL or missing references)
		//IL_0214: Unknown result type (might be due to invalid IL or missing references)
		//IL_0337: Unknown result type (might be due to invalid IL or missing references)
		//IL_033c: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_035f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0364: Unknown result type (might be due to invalid IL or missing references)
		//IL_0368: Unknown result type (might be due to invalid IL or missing references)
		//IL_036d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0389: Unknown result type (might be due to invalid IL or missing references)
		//IL_0396: Unknown result type (might be due to invalid IL or missing references)
		//IL_039b: Unknown result type (might be due to invalid IL or missing references)
		//IL_039f: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_042f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0434: Unknown result type (might be due to invalid IL or missing references)
		//IL_0464: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)previousPlayerHeldBy == (Object)null)
		{
			Debug.LogError((object)"Previousplayerheldby is null on this client when HitShovel is called.");
			return;
		}
		previousPlayerHeldBy.activatingItem = false;
		bool flag = false;
		bool flag2 = false;
		bool flag3 = false;
		int num = -1;
		if (!cancel)
		{
			previousPlayerHeldBy.twoHanded = false;
			objectsHitByShovel = Physics.SphereCastAll(((Component)previousPlayerHeldBy.gameplayCamera).transform.position + ((Component)previousPlayerHeldBy.gameplayCamera).transform.right * -0.35f, 0.8f, ((Component)previousPlayerHeldBy.gameplayCamera).transform.forward, 1.5f, shovelMask, (QueryTriggerInteraction)2);
			objectsHitByShovelList = objectsHitByShovel.OrderBy((RaycastHit x) => ((RaycastHit)(ref x)).distance).ToList();
			List<EnemyAI> list = new List<EnemyAI>();
			IHittable val2 = default(IHittable);
			RaycastHit val3 = default(RaycastHit);
			for (int i = 0; i < objectsHitByShovelList.Count; i++)
			{
				Vector3 forward = ((Component)previousPlayerHeldBy.gameplayCamera).transform.forward;
				RaycastHit val = objectsHitByShovelList[i];
				if (((Component)((RaycastHit)(ref val)).transform).TryGetComponent<IHittable>(ref val2))
				{
					val = objectsHitByShovelList[i];
					if (!((Object)(object)((RaycastHit)(ref val)).transform == (Object)(object)((Component)previousPlayerHeldBy).transform))
					{
						val = objectsHitByShovelList[i];
						if (!(((RaycastHit)(ref val)).point == Vector3.zero))
						{
							Vector3 position = ((Component)previousPlayerHeldBy.gameplayCamera).transform.position;
							val = objectsHitByShovelList[i];
							if (Physics.Linecast(position, ((RaycastHit)(ref val)).point, ref val3, StartOfRound.Instance.walkableSurfacesMask, (QueryTriggerInteraction)1))
							{
								goto IL_0221;
							}
						}
						val = objectsHitByShovelList[i];
						TerrainObstacleTrigger componentInChildren = ((Component)((RaycastHit)(ref val)).collider).GetComponentInChildren<TerrainObstacleTrigger>();
						if ((Object)(object)componentInChildren != (Object)null && ((NetworkBehaviour)this).IsOwner)
						{
							RoundManager.Instance.DestroyTreeOnLocalClient(((Component)componentInChildren).transform.position);
						}
					}
				}
				goto IL_0221;
				IL_0221:
				val = objectsHitByShovelList[i];
				if (((Component)((RaycastHit)(ref val)).transform).gameObject.layer != 8)
				{
					val = objectsHitByShovelList[i];
					if (((Component)((RaycastHit)(ref val)).transform).gameObject.layer != 11)
					{
						val = objectsHitByShovelList[i];
						if (!((Component)((RaycastHit)(ref val)).transform).TryGetComponent<IHittable>(ref val2))
						{
							continue;
						}
						val = objectsHitByShovelList[i];
						if ((Object)(object)((RaycastHit)(ref val)).transform == (Object)(object)((Component)previousPlayerHeldBy).transform)
						{
							continue;
						}
						val = objectsHitByShovelList[i];
						if (!(((RaycastHit)(ref val)).point == Vector3.zero))
						{
							Vector3 position2 = ((Component)previousPlayerHeldBy.gameplayCamera).transform.position;
							val = objectsHitByShovelList[i];
							if (Physics.Linecast(position2, ((RaycastHit)(ref val)).point, ref val3, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))
							{
								continue;
							}
						}
						flag = true;
						try
						{
							val = objectsHitByShovelList[i];
							EnemyAICollisionDetect component = ((Component)((RaycastHit)(ref val)).collider).GetComponent<EnemyAICollisionDetect>();
							if ((Object)(object)component != (Object)null)
							{
								if ((Object)(object)component.mainScript == (Object)null || list.Contains(component.mainScript))
								{
									continue;
								}
								goto IL_045c;
							}
							val = objectsHitByShovelList[i];
							if (!((Object)(object)((Component)((RaycastHit)(ref val)).transform).GetComponent<PlayerControllerB>() != (Object)null))
							{
								goto IL_045c;
							}
							if (flag3)
							{
								continue;
							}
							flag3 = true;
							goto IL_045c;
							IL_045c:
							bool flag4 = val2.Hit(shovelHitForce, forward, previousPlayerHeldBy, true, 1);
							if (flag4 && (Object)(object)component != (Object)null)
							{
								list.Add(component.mainScript);
							}
							if (!flag2)
							{
								flag2 = flag4;
							}
						}
						catch (Exception arg)
						{
							Debug.Log((object)$"Exception caught when hitting object with shovel from player #{previousPlayerHeldBy.playerClientId}: {arg}");
						}
						continue;
					}
				}
				val = objectsHitByShovelList[i];
				if (((RaycastHit)(ref val)).collider.isTrigger)
				{
					continue;
				}
				flag = true;
				val = objectsHitByShovelList[i];
				string tag = ((Component)((RaycastHit)(ref val)).collider).gameObject.tag;
				for (int j = 0; j < StartOfRound.Instance.footstepSurfaces.Length; j++)
				{
					if (StartOfRound.Instance.footstepSurfaces[j].surfaceTag == tag)
					{
						num = j;
						break;
					}
				}
			}
		}
		if (flag)
		{
			RoundManager.PlayRandomClip(shovelAudio, hitSFX, true, 1f, 0, 1000);
			Object.FindObjectOfType<RoundManager>().PlayAudibleNoise(((Component)this).transform.position, 17f, 0.8f, 0, false, 0);
			if (!flag2 && num != -1)
			{
				shovelAudio.PlayOneShot(StartOfRound.Instance.footstepSurfaces[num].hitSurfaceSFX);
				WalkieTalkie.TransmitOneShotAudio(shovelAudio, StartOfRound.Instance.footstepSurfaces[num].hitSurfaceSFX, 1f);
			}
			base.playerHeldBy.playerBodyAnimator.SetTrigger("shovelHit");
			HitShovelServerRpc(num);
		}
	}

	[ServerRpc]
	public void HitShovelServerRpc(int hitSurfaceID)
	{
		HitShovelClientRpc(hitSurfaceID);
	}

	[ClientRpc]
	public void HitShovelClientRpc(int hitSurfaceID)
	{
		if (!((NetworkBehaviour)this).IsOwner)
		{
			RoundManager.PlayRandomClip(shovelAudio, hitSFX, true, 1f, 0, 1000);
			if (hitSurfaceID != -1)
			{
				HitSurfaceWithShovel(hitSurfaceID);
			}
		}
	}

	private void HitSurfaceWithShovel(int hitSurfaceID)
	{
		shovelAudio.PlayOneShot(StartOfRound.Instance.footstepSurfaces[hitSurfaceID].hitSurfaceSFX);
		WalkieTalkie.TransmitOneShotAudio(shovelAudio, StartOfRound.Instance.footstepSurfaces[hitSurfaceID].hitSurfaceSFX, 1f);
	}
}
namespace PiggyVarietyMod
{
	[BepInPlugin("Piggy.PiggyVarietyMod", "PiggyVarietyMod", "1.3.14")]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "Piggy.PiggyVarietyMod";

		private const string modName = "PiggyVarietyMod";

		private const string modVersion = "1.3.14";

		private readonly Harmony harmony = new Harmony("Piggy.PiggyVarietyMod");

		private static Plugin Instance;

		public static ManualLogSource mls;

		public static AssetBundle Bundle;

		public static GameObject teslaGateSpawn;

		public static GameObject teslaGatePrefab;

		public static AudioClip teslaIdleStart;

		public static AudioClip teslaIdle;

		public static AudioClip teslaIdleEnd;

		public static AudioClip teslaCrack;

		public static AudioClip teslaBeep;

		public static AudioClip teslaWindUp;

		public static AudioClip teslaUnderbass;

		public static AudioClip teslaClimax;

		public static AudioClip flashlightShake;

		public static AudioClip gummylightClick;

		public static AudioClip gummylightOutage;

		public static AudioClip flashFlicker;

		public static Material flashlightBulb;

		public static Material blackRubber;

		public static GameObject gummylightPrefab;

		public static GameObject m4Prefab;

		public static GameObject axePrefab;

		public static Item revolverItem;

		public static Item revolverAmmoItem;

		public static Item gummyFlashlight;

		public static Item arItem;

		public static Item arMagItem;

		public static Item axeItem;

		public static Item bulbItem;

		public static Item chemicalItem;

		public static int revolverRarity;

		public static int revolverAmmoRarity;

		public static int revolverMaxPlayerDamage;

		public static int revolverMaxMonsterDamage;

		public static int rifleMaxPlayerDamage;

		public static int rifleMonsterDamage;

		public static bool customGunInfinityAmmo;

		public static int revolverPrice;

		public static int revolverAmmoPrice;

		public static int riflePrice;

		public static int rifleMagPrice;

		public static int rifleRarity;

		public static int rifleMagRarity;

		public static bool twoHandedRifle;

		public static int bulbRarity;

		public static int chemicalRarity;

		public static float teslaSpawnWeight;

		public static float teslaSoundVolume;

		public static bool teslaShake;

		public static bool translateKorean;

		public static AudioClip revolverAmmoInsert;

		public static AudioClip revolverCylinderOpen;

		public static AudioClip revolverCylinderClose;

		public static AudioClip revolverDryFire;

		public static AudioClip revolverBlast1;

		public static AudioClip revolverBlast2;

		public static AudioClip m4FireClip;

		public static AudioClip m4ReloadClip;

		public static AudioClip m4InspectClip;

		public static AudioClip m4TriggerClip;

		public static RuntimeAnimatorController playerAnimator;

		public static RuntimeAnimatorController otherPlayerAnimator;

		public static bool foundMoreEmotes;

		public static string PluginDirectory;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			PluginDirectory = ((BaseUnityPlugin)this).Info.Location;
			LoadAssets();
			mls = Logger.CreateLogSource("Piggy.PiggyVarietyMod");
			mls.LogInfo((object)"Piggy's Variety Mod is loaded");
			teslaSoundVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Generic", "TeslaGateVolume", 1f, "(Default 1) Sets the sound volume for Tesla Gate.").Value;
			teslaShake = ((BaseUnityPlugin)this).Config.Bind<bool>("Generic", "TeslaGateShake", false, "(Experimental, Default false) Shake the screen when near Tesla Gate.").Value;
			revolverMaxPlayerDamage = ((BaseUnityPlugin)this).Config.Bind<int>("Generic", "RevolverMaxPlayerDamage", 70, "(Default 70) Sets the maximum amount of damage the Revolver can deals on the player.").Value;
			revolverMaxMonsterDamage = ((BaseUnityPlugin)this).Config.Bind<int>("Generic", "RevolverMaxMonsterDamage", 4, "(Default 4) Sets the maximum amount of damage the Revolver can deals on the monster.").Value;
			rifleMaxPlayerDamage = ((BaseUnityPlugin)this).Config.Bind<int>("Generic", "RifleMaxPlayerDamage", 22, "(Default 22) Sets the maximum amount of damage the Rifle can deals on the player.").Value;
			rifleMonsterDamage = ((BaseUnityPlugin)this).Config.Bind<int>("Generic", "RifleMonsterDamage", 1, "(Default 1) Sets the amount of damage the Rifle deals to monsters.").Value;
			customGunInfinityAmmo = ((BaseUnityPlugin)this).Config.Bind<bool>("Generic", "CustomGunInfinityAmmo", false, "(Default false) If true, reloading custom guns will no longer require ammo.").Value;
			twoHandedRifle = ((BaseUnityPlugin)this).Config.Bind<bool>("Generic", "TwoHandedRifle", false, "(Default false) If true, changes the rifle to a two-handed item.").Value;
			teslaSpawnWeight = ((BaseUnityPlugin)this).Config.Bind<float>("Spawn", "TeslaGateWeight", 1f, "(Default 1) Sets the spawn weight for the Tesla Gate.").Value;
			revolverRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "RevolverRarity", 20, "(Default 20) Sets the spawn rarity for the Revolver.").Value;
			revolverAmmoRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "RevolverAmmoRarity", 60, "(Default 60) Sets the spawn rarity for the Revolver ammo.").Value;
			revolverPrice = ((BaseUnityPlugin)this).Config.Bind<int>("Store", "RevolverPrice", -1, "(Recommended -1 or 550) Set the price of the Revolver. If -1, removes the item from the store list.").Value;
			revolverAmmoPrice = ((BaseUnityPlugin)this).Config.Bind<int>("Store", "RevolverAmmoPrice", -1, "(Recommended -1 or 30) Set the price of the Revolver ammo. If -1, removes the item from the store list.").Value;
			riflePrice = ((BaseUnityPlugin)this).Config.Bind<int>("Store", "RiflePrice", -1, "(Recommended -1 or 1,000~) Set the price of the Rifle (M4A1). If -1, removes the item from the store list.").Value;
			rifleMagPrice = ((BaseUnityPlugin)this).Config.Bind<int>("Store", "RifleMagPrice", -1, "(Recommended -1 or 400~) Set the price of the Rifle magazine. If -1, removes the item from the store list.").Value;
			rifleRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "RifleRarity", 20, "(Default 20) Sets the spawn rarity for the Rifle.").Value;
			rifleMagRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "RifleMagRarity", 60, "(Default 60) Sets the spawn rarity for the Rifle magazine.").Value;
			bulbRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "BulbRarity", 30, "(Default 30) Sets the spawn rarity for the Bulb.").Value;
			chemicalRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "ChemicalRarity", 30, "(Default 30) Sets the spawn rarity for the Chemical.").Value;
			translateKorean = ((BaseUnityPlugin)this).Config.Bind<bool>("Translation", "Enable Korean", false, "Set language to Korean.").Value;
			NetworkPrefabs.RegisterNetworkPrefab(teslaGatePrefab);
			NetworkPrefabs.RegisterNetworkPrefab(revolverItem.spawnPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(revolverAmmoItem.spawnPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(gummyFlashlight.spawnPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(arItem.spawnPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(arMagItem.spawnPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(axeItem.spawnPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(bulbItem.spawnPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(chemicalItem.spawnPrefab);
			Utilities.FixMixerGroups(revolverItem.spawnPrefab);
			Utilities.FixMixerGroups(revolverAmmoItem.spawnPrefab);
			Utilities.FixMixerGroups(gummyFlashlight.spawnPrefab);
			Utilities.FixMixerGroups(arItem.spawnPrefab);
			Utilities.FixMixerGroups(arMagItem.spawnPrefab);
			Utilities.FixMixerGroups(axeItem.spawnPrefab);
			Utilities.FixMixerGroups(bulbItem.spawnPrefab);
			Utilities.FixMixerGroups(chemicalItem.spawnPrefab);
			Items.RegisterItem(revolverItem);
			Items.RegisterItem(revolverAmmoItem);
			Items.RegisterItem(gummyFlashlight);
			Items.RegisterItem(arItem);
			Items.RegisterItem(arMagItem);
			Items.RegisterItem(axeItem);
			Items.RegisterItem(bulbItem);
			Items.RegisterItem(chemicalItem);
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				BepInPlugin metadata = pluginInfo.Value.Metadata;
				if (metadata.GUID.Equals("MoreEmotes", StringComparison.OrdinalIgnoreCase) || metadata.GUID.Equals("BetterEmotes", StringComparison.OrdinalIgnoreCase))
				{
					foundMoreEmotes = true;
					mls.LogInfo((object)"[Piggys Variety Mod] Detected More Emotes / Better Emotes!");
					mls.LogInfo((object)"[Piggys Variety Mod] More Emotes / Better Emotes may not be compatible!");
				}
			}
			if (translateKorean)
			{
				Translate();
			}
			CreateShopItem();
			Items.RegisterScrap(revolverItem, revolverRarity, (LevelTypes)(-1));
			Items.RegisterScrap(revolverAmmoItem, revolverAmmoRarity, (LevelTypes)(-1));
			Items.RegisterScrap(arItem, rifleRarity, (LevelTypes)(-1));
			Items.RegisterScrap(arMagItem, rifleMagRarity, (LevelTypes)(-1));
			Items.RegisterScrap(bulbItem, bulbRarity, (LevelTypes)(-1));
			Items.RegisterScrap(chemicalItem, chemicalRarity, (LevelTypes)(-1));
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		}

		private void LoadAssets()
		{
			try
			{
				Bundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(PluginDirectory), "piggyvarietymod"));
			}
			catch (Exception ex)
			{
				mls.LogError((object)("Couldn't load asset bundle: " + ex.Message));
				return;
			}
			try
			{
				teslaGateSpawn = Bundle.LoadAsset<GameObject>("TeslaGateSpawn.prefab");
				teslaGatePrefab = Bundle.LoadAsset<GameObject>("TeslaGate.prefab");
				teslaGatePrefab.AddComponent<TeslaGate>();
				teslaCrack = Bundle.LoadAsset<AudioClip>("Tesla_Crack.ogg");
				teslaBeep = Bundle.LoadAsset<AudioClip>("Tesla_Beeps.ogg");
				teslaWindUp = Bundle.LoadAsset<AudioClip>("Tesla_WindUp.ogg");
				teslaUnderbass = Bundle.LoadAsset<AudioClip>("Tesla_Underbass.ogg");
				teslaClimax = Bundle.LoadAsset<AudioClip>("Tesla_Climax.ogg");
				teslaIdleStart = Bundle.LoadAsset<AudioClip>("Tesla_IdleStarts.ogg");
				teslaIdle = Bundle.LoadAsset<AudioClip>("Tesla_IdleLoop.ogg");
				teslaIdleEnd = Bundle.LoadAsset<AudioClip>("Tesla_IdleEnd.ogg");
				flashlightShake = Bundle.LoadAsset<AudioClip>("FlashlightShake.wav");
				gummylightClick = Bundle.LoadAsset<AudioClip>("GummyFlashlightClick.wav");
				gummylightOutage = Bundle.LoadAsset<AudioClip>("GummylightBatteryOutage.wav");
				flashFlicker = Bundle.LoadAsset<AudioClip>("FlashlightFlicker.ogg");
				flashlightBulb = Bundle.LoadAsset<Material>("FlashlightBulb1.mat");
				blackRubber = Bundle.LoadAsset<Material>("BlackRubber1.mat");
				Plugin.revolverItem = Bundle.LoadAsset<Item>("Revolver.asset");
				revolverAmmoItem = Bundle.LoadAsset<Item>("RevolverAmmo.asset");
				arItem = Bundle.LoadAsset<Item>("M4A1.asset");
				arMagItem = Bundle.LoadAsset<Item>("Magazine.asset");
				Plugin.axeItem = Bundle.LoadAsset<Item>("Axe.asset");
				gummyFlashlight = Bundle.LoadAsset<Item>("GummyFlashlight.asset");
				chemicalItem = Bundle.LoadAsset<Item>("Chemical.asset");
				bulbItem = Bundle.LoadAsset<Item>("Bulb.asset");
				gummylightPrefab = Bundle.LoadAsset<GameObject>("GummylightItem.prefab");
				m4Prefab = Bundle.LoadAsset<GameObject>("M4Item.prefab");
				axePrefab = Bundle.LoadAsset<GameObject>("AxeItem.prefab");
				revolverAmmoInsert = Bundle.LoadAsset<AudioClip>("RevolverReload.wav");
				revolverCylinderOpen = Bundle.LoadAsset<AudioClip>("RevolverCylinderOpen.wav");
				revolverCylinderClose = Bundle.LoadAsset<AudioClip>("RevolverCylinderClose.wav");
				revolverDryFire = Bundle.LoadAsset<AudioClip>("RevolverDryFire.wav");
				revolverBlast1 = Bundle.LoadAsset<AudioClip>("RevolverBlast1.wav");
				revolverBlast2 = Bundle.LoadAsset<AudioClip>("RevolverBlast2.wav");
				m4FireClip = Bundle.LoadAsset<AudioClip>("M4Fire1.wav");
				m4InspectClip = Bundle.LoadAsset<AudioClip>("InspectM4v2.wav");
				m4TriggerClip = Bundle.LoadAsset<AudioClip>("M4Trigger.wav");
				m4ReloadClip = Bundle.LoadAsset<AudioClip>("M4Reload.wav");
				playerAnimator = Bundle.LoadAsset<RuntimeAnimatorController>("PlayerAnimator.controller");
				otherPlayerAnimator = Bundle.LoadAsset<RuntimeAnimatorController>("OtherPlayerAnimator.controller");
				RevolverItem revolverItem = Plugin.revolverItem.spawnPrefab.AddComponent<RevolverItem>();
				((GrabbableObject)revolverItem).grabbable = true;
				((GrabbableObject)revolverItem).grabbableToEnemies = true;
				revolverItem.gunReloadSFX = revolverAmmoInsert;
				revolverItem.cylinderOpenSFX = revolverCylinderOpen;
				revolverItem.cylinderCloseSFX = revolverCylinderClose;
				revolverItem.gunShootSFX.Add(revolverBlast1);
				revolverItem.gunShootSFX.Add(revolverBlast2);
				revolverItem.noAmmoSFX = revolverDryFire;
				revolverItem.gunSafetySFX = revolverDryFire;
				revolverItem.switchSafetyOffSFX = revolverDryFire;
				revolverItem.switchSafetyOnSFX = revolverDryFire;
				revolverItem.gunAudio = ((Component)revolverItem).gameObject.GetComponent<AudioSource>();
				revolverItem.gunShootAudio = ((Component)((Component)revolverItem).gameObject.transform.GetChild(1)).GetComponent<AudioSource>();
				revolverItem.gunBulletsRicochetAudio = ((Component)((Component)revolverItem).gameObject.transform.GetChild(2)).GetComponent<AudioSource>();
				revolverItem.gunAnimator = ((Component)revolverItem).gameObject.GetComponent<Animator>();
				revolverItem.revolverRayPoint = ((Component)revolverItem).gameObject.transform.GetChild(3);
				revolverItem.gunShootParticle = ((Component)((Component)revolverItem).gameObject.transform.GetChild(3).GetChild(0)).GetComponent<ParticleSystem>();
				revolverItem.cylinderTransform = ((Component)revolverItem).gameObject.transform.GetChild(5).GetChild(0).GetChild(0);
				revolverItem.revolverAmmos.Add(((Component)((Component)revolverItem).gameObject.transform.GetChild(5).GetChild(0).GetChild(0)
					.GetChild(0)).GetComponent<MeshRenderer>());
				revolverItem.revolverAmmos.Add(((Component)((Component)revolverItem).gameObject.transform.GetChild(5).GetChild(0).GetChild(0)
					.GetChild(1)).GetComponent<MeshRenderer>());
				revolverItem.revolverAmmos.Add(((Component)((Component)revolverItem).gameObject.transform.GetChild(5).GetChild(0).GetChild(0)
					.GetChild(2)).GetComponent<MeshRenderer>());
				revolverItem.revolverAmmos.Add(((Component)((Component)revolverItem).gameObject.transform.GetChild(5).GetChild(0).GetChild(0)
					.GetChild(3)).GetComponent<MeshRenderer>());
				revolverItem.revolverAmmos.Add(((Component)((Component)revolverItem).gameObject.transform.GetChild(5).GetChild(0).GetChild(0)
					.GetChild(4)).GetComponent<MeshRenderer>());
				revolverItem.revolverAmmos.Add(((Component)((Component)revolverItem).gameObject.transform.GetChild(5).GetChild(0).GetChild(0)
					.GetChild(5)).GetComponent<MeshRenderer>());
				revolverItem.revolverAmmoInHandTransform = ((Component)revolverItem).gameObject.transform.GetChild(0);
				revolverItem.revolverAmmoInHand = ((Component)((Component)revolverItem).gameObject.transform.GetChild(0).GetChild(0)).GetComponent<MeshRenderer>();
				revolverItem.gunCompatibleAmmoID = 500;
				((GrabbableObject)revolverItem).itemProperties = Plugin.revolverItem;
				arItem.spawnPrefab = m4Prefab;
				M4Item m4Item = arItem.spawnPrefab.AddComponent<M4Item>();
				((GrabbableObject)m4Item).grabbable = true;
				((GrabbableObject)m4Item).isInFactory = true;
				((GrabbableObject)m4Item).itemProperties = arItem;
				((GrabbableObject)m4Item).grabbableToEnemies = true;
				m4Item.gunCompatibleAmmoID = 485;
				m4Item.gunAnimator = ((Component)m4Item).gameObject.GetComponent<Animator>();
				m4Item.gunAudio = ((Component)m4Item).gameObject.GetComponent<AudioSource>();
				m4Item.gunShootAudio = ((Component)((Component)m4Item).transform.GetChild(0)).GetComponent<AudioSource>();
				m4Item.gunBulletsRicochetAudio = ((Component)((Component)m4Item).transform.GetChild(1)).GetComponent<AudioSource>();
				m4Item.gunShootSFX = m4FireClip;
				m4Item.gunReloadSFX = m4ReloadClip;
				m4Item.gunInspectSFX = m4InspectClip;
				m4Item.noAmmoSFX = m4TriggerClip;
				m4Item.gunShootParticle = ((Component)((Component)m4Item).transform.GetChild(5).GetChild(0)).GetComponent<ParticleSystem>();
				m4Item.gunRayPoint = ((Component)m4Item).transform.GetChild(5);
				if (twoHandedRifle)
				{
					arItem.twoHanded = true;
				}
				gummyFlashlight.spawnPrefab = gummylightPrefab;
				GummylightItem gummylightItem = gummyFlashlight.spawnPrefab.AddComponent<GummylightItem>();
				((GrabbableObject)gummylightItem).useCooldown = 0.12f;
				((GrabbableObject)gummylightItem).itemProperties = gummyFlashlight;
				((GrabbableObject)gummylightItem).mainObjectRenderer = ((Component)((Component)gummylightItem).transform.GetChild(2)).GetComponent<MeshRenderer>();
				((GrabbableObject)gummylightItem).insertedBattery.charge = 1f;
				((GrabbableObject)gummylightItem).grabbableToEnemies = true;
				gummylightItem.flashlightBulb = ((Component)((Component)gummylightItem).transform.GetChild(0)).GetComponent<Light>();
				gummylightItem.flashlightBulbGlow = ((Component)((Component)gummylightItem).transform.GetChild(1)).GetComponent<Light>();
				gummylightItem.flashlightAudio = ((Component)gummylightItem).GetComponent<AudioSource>();
				gummylightItem.flashlightClips = (AudioClip[])(object)new AudioClip[1] { gummylightClick };
				gummylightItem.outOfBatteriesClip = gummylightOutage;
				gummylightItem.flashlightFlicker = flashFlicker;
				gummylightItem.bulbLight = flashlightBulb;
				gummylightItem.bulbDark = blackRubber;
				gummylightItem.flashlightMesh = ((Component)((Component)gummylightItem).transform.GetChild(2)).GetComponent<MeshRenderer>();
				gummylightItem.changeMaterial = true;
				((GrabbableObject)gummylightItem).isInFactory = true;
				((GrabbableObject)gummylightItem).grabbable = true;
				gummylightItem.flashlightTypeID = 10;
				Object.Destroy((Object)(object)gummyFlashlight.spawnPrefab.GetComponent<FlashlightItem>());
				Plugin.axeItem.spawnPrefab = axePrefab;
				AxeItem axeItem = Plugin.axeItem.spawnPrefab.AddComponent<AxeItem>();
				Shovel component = Plugin.axeItem.spawnPrefab.GetComponent<Shovel>();
				((GrabbableObject)axeItem).itemProperties = Plugin.axeItem;
				((GrabbableObject)axeItem).grabbable = true;
				((GrabbableObject)axeItem).isInFactory = true;
				((GrabbableObject)axeItem).grabbableToEnemies = true;
				axeItem.shovelHitForce = 1;
				axeItem.reelUp = component.reelUp;
				axeItem.swing = component.swing;
				axeItem.hitSFX = component.hitSFX;
				axeItem.shovelAudio = component.shovelAudio;
				Object.Destroy((Object)(object)component);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Successfully loaded assets!");
			}
			catch (Exception ex2)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Couldn't load assets: " + ex2.Message));
			}
		}

		private void Translate()
		{
			revolverItem.toolTips[0] = "격발 : [RMB]";
			revolverItem.toolTips[1] = "탄약 삽탄하기 : [E]";
			revolverItem.toolTips[2] = "실린더 열기 : [Q]";
			gummyFlashlight.toolTips[0] = "전등 전환하기 : [RMB]";
			gummyFlashlight.toolTips[1] = "손전등 흔들기 : [Q]";
			arItem.toolTips[0] = "격발 : [RMB]";
			arItem.toolTips[1] = "재장전 : [E]";
			arItem.toolTips[2] = "탄약 확인하기 : [Q]";
			axeItem.toolTips[0] = "도끼 휘두르기 : [RMB]";
			revolverItem.spawnPrefab.GetComponentInChildren<ScanNodeProperties>().headerText = "리볼버";
			revolverAmmoItem.spawnPrefab.GetComponentInChildren<ScanNodeProperties>().headerText = "총알";
			arItem.spawnPrefab.GetComponentInChildren<ScanNodeProperties>().headerText = "소총";
			arMagItem.spawnPrefab.GetComponentInChildren<ScanNodeProperties>().headerText = "탄창";
			bulbItem.spawnPrefab.GetComponentInChildren<ScanNodeProperties>().headerText = "전구";
			chemicalItem.spawnPrefab.GetComponentInChildren<ScanNodeProperties>().headerText = "화학 약품";
		}

		private void CreateShopItem()
		{
			if (translateKorean)
			{
				revolverAmmoItem.itemName = "총알";
				revolverItem.itemName = "리볼버";
				gummyFlashlight.itemName = "젤리";
				arMagItem.itemName = "탄창";
				arItem.itemName = "소총";
				axeItem.itemName = "도끼";
				chemicalItem.itemName = "화학 약품";
				bulbItem.itemName = "전구";
			}
			else
			{
				revolverAmmoItem.itemName = "Bullet";
				revolverItem.itemName = "Revolver";
				gummyFlashlight.itemName = "Gummy flashlight";
				arMagItem.itemName = "Magazine";
				arItem.itemName = "Rifle";
				axeItem.itemName = "Axe";
			}
			TerminalNode val = NewTerminalNode("리볼버를 주문하려고 합니다. 수량: [variableAmount]. \r\n아이템의 총 가격: [totalCost].\n\nCONFIRM 또는 DENY를 입력하세요.\n\n", "You have requested to order revolvers. Amount: [variableAmount]. \r\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\n\n");
			TerminalNode val2 = NewTerminalNode("[variableAmount]개의 리볼버를 주문했습니다. 당신의 현재 소지금은 [playerCredits]입니다.\n\n우리의 계약자는 작업 중에도 빠른 무료 배송 혜택을 누릴 수 있습니다! 구매한 모든 상품은 1시간마다 대략적인 위치에 도착합니다.\n\n", "Ordered [variableAmount] revolvers. Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\n\n");
			TerminalNode val3 = NewTerminalNode("\n더욱 강력한 자기 보호를 위해!\n실린더를 열고 리볼버 탄약을 삽탄하여 장전하세요.\n\n", "\nFor more powerful self-defense!\nOpen the cylinder and insert revolver ammo to load it.\n\n");
			TerminalNode val4 = NewTerminalNode("리볼버 탄약을 주문하려고 합니다. 수량: [variableAmount]. \r\n아이템의 총 가격: [totalCost].\n\nCONFIRM 또는 DENY를 입력하세요.\n\n", "You have requested to order revolver ammos. Amount: [variableAmount]. \r\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\n\n");
			TerminalNode val5 = NewTerminalNode("[variableAmount]개의 리볼버 탄약을 주문했습니다. 당신의 현재 소지금은 [playerCredits]입니다.\n\n우리의 계약자는 작업 중에도 빠른 무료 배송 혜택을 누릴 수 있습니다! 구매한 모든 상품은 1시간마다 대략적인 위치에 도착합니다.\n\n", "Ordered [variableAmount] revolver ammos. Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\n\n");
			TerminalNode val6 = NewTerminalNode("\n리볼버에 장전하고 <b>치명적인</b> 순간에 격발하세요!\n\n", "\nLoad to your revolver and fire at LETHAL moments!\n\n");
			TerminalNode val7 = NewTerminalNode("소총을 주문하려고 합니다. 수량: [variableAmount]. \r\n아이템의 총 가격: [totalCost].\n\nCONFIRM 또는 DENY를 입력하세요.\n\n", "You have requested to order rifles. Amount: [variableAmount]. \r\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\n\n");
			TerminalNode val8 = NewTerminalNode("[variableAmount]개의 소총을 주문했습니다. 당신의 현재 소지금은 [playerCredits]입니다.\n\n우리의 계약자는 작업 중에도 빠른 무료 배송 혜택을 누릴 수 있습니다! 구매한 모든 상품은 1시간마다 대략적인 위치에 도착합니다.\n\n", "Ordered [variableAmount] rifles. Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\n\n");
			TerminalNode val9 = NewTerminalNode("\n더욱 강력한 자기 보호를 위해!\n탄창을 장전하여 사용하세요.\n\n", "\nFor more powerful self-defense!\nload magazine to fire it.\n\n");
			TerminalNode val10 = NewTerminalNode("소총 탄창을 주문하려고 합니다. 수량: [variableAmount]. \r\n아이템의 총 가격: [totalCost].\n\nCONFIRM 또는 DENY를 입력하세요.\n\n", "You have requested to order rifle magazines. Amount: [variableAmount]. \r\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\n\n");
			TerminalNode val11 = NewTerminalNode("[variableAmount]개의 소총 탄창을 주문했습니다. 당신의 현재 소지금은 [playerCredits]입니다.\n\n우리의 계약자는 작업 중에도 빠른 무료 배송 혜택을 누릴 수 있습니다! 구매한 모든 상품은 1시간마다 대략적인 위치에 도착합니다.\n\n", "Ordered [variableAmount] rifle magazines. Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\n\n");
			TerminalNode val12 = NewTerminalNode("\n소총에 장전하고 <b>치명적인</b> 순간에 격발하세요!\n\n", "\nLoad to your rifle and fire at LETHAL moments!\n\n");
			TerminalNode val13 = NewTerminalNode("젤리 손전등을 주문하려고 합니다. 수량: [variableAmount]. \r\n아이템의 총 가격: [totalCost].\n\nCONFIRM 또는 DENY를 입력하세요.\n\n", "You have requested to order gummy flashlights. Amount: [variableAmount]. \r\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\n\n");
			TerminalNode val14 = NewTerminalNode("[variableAmount]개의 젤리 손전등을 주문했습니다. 당신의 현재 소지금은 [playerCredits]입니다.\n\n우리의 계약자는 작업 중에도 빠른 무료 배송 혜택을 누릴 수 있습니다! 구매한 모든 상품은 1시간마다 대략적인 위치에 도착합니다.\n\n", "Ordered [variableAmount] gummy flashlights. Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\n\n");
			TerminalNode val15 = NewTerminalNode("\n자가발전 손전등입니다.\n그저 평범한 장난감이지만, 배터리가 다 떨어졌을 때 여러분의 어두운 앞길을 비춰 줄 것입니다!\n\n", "\nA self-powered flashlight.\nIt's just a toy, but it'll light up your dark path when the batteries run out!\n\n");
			if (revolverPrice > -1)
			{
				Items.RegisterShopItem(revolverItem, val, val2, val3, revolverPrice);
			}
			if (revolverAmmoPrice > -1)
			{
				Items.RegisterShopItem(revolverAmmoItem, val4, val5, val6, revolverAmmoPrice);
			}
			if (riflePrice > -1)
			{
				Items.RegisterShopItem(arItem, val7, val8, val9, riflePrice);
			}
			if (rifleMagPrice > -1)
			{
				Items.RegisterShopItem(arMagItem, val10, val11, val12, rifleMagPrice);
			}
		}

		public TerminalNode NewTerminalNode(string korean, string english)
		{
			TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
			if (translateKorean)
			{
				val.displayText = korean;
			}
			else
			{
				val.displayText = english;
			}
			val.clearPreviousText = true;
			val.maxCharactersToType = 15;
			val.buyRerouteToMoon = -1;
			val.displayPlanetInfo = -1;
			val.shipUnlockableID = -1;
			val.creatureFileID = -1;
			val.storyLogFileID = -1;
			return val;
		}
	}
}
namespace PiggyVarietyMod.Patches
{
	public class CustomTouchInteractTrigger : MonoBehaviour
	{
		public bool isIdleTrigger;

		public bool isKillTrigger;

		public TeslaGate teslaGate;

		private void OnTriggerEnter(Collider collider)
		{
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB component = ((Component)collider).GetComponent<PlayerControllerB>();
			if ((Object)(object)component != (Object)null)
			{
				Plugin.mls.LogInfo((object)("Tesla gate detected player: " + component.playerUsername + ", Idle: " + isIdleTrigger + ", Kill: " + isKillTrigger));
				if (!component.isPlayerDead)
				{
					if (isIdleTrigger)
					{
						teslaGate.activatePlayerList.Add(component);
						teslaGate.activateList.Add(((Component)collider).gameObject);
					}
					else if (!isIdleTrigger && !isKillTrigger)
					{
						teslaGate.engagingPlayerList.Add(component);
						teslaGate.engagingList.Add(((Component)collider).gameObject);
					}
				}
			}
			EnemyAICollisionDetect component2 = ((Component)collider).GetComponent<EnemyAICollisionDetect>();
			IHittable val = default(IHittable);
			if ((Object)(object)component2 != (Object)null && ((Component)((Component)component2).transform).TryGetComponent<IHittable>(ref val))
			{
				Plugin.mls.LogInfo((object)("Tesla gate detected enemy: " + component2.mainScript.enemyType.enemyName + ", Idle: " + isIdleTrigger + ", Kill: " + isKillTrigger));
				if (isIdleTrigger)
				{
				}
				if (isKillTrigger && (Object)(object)component2 != (Object)null && (Object)(object)component2.mainScript != (Object)null && ((NetworkBehaviour)component2.mainScript).IsOwner && component2.mainScript.enemyType.canDie && !component2.mainScript.isEnemyDead)
				{
					val.Hit(5, Vector3.zero, (PlayerControllerB)null, true, -1);
				}
			}
		}

		private void OnTriggerStay(Collider collider)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: 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)
			if (!isKillTrigger)
			{
				return;
			}
			PlayerControllerB component = ((Component)collider).GetComponent<PlayerControllerB>();
			if ((Object)(object)component != (Object)null && (Object)(object)component == (Object)(object)GameNetworkManager.Instance.localPlayerController && !component.isPlayerDead)
			{
				GameNetworkManager.Instance.localPlayerController.KillPlayer(Vector3.down * 17f, true, (CauseOfDeath)11, 0, default(Vector3));
				return;
			}
			EnemyAICollisionDetect component2 = ((Component)collider).GetComponent<EnemyAICollisionDetect>();
			if ((Object)(object)component2 != (Object)null && (Object)(object)component2.mainScript != (Object)null && ((NetworkBehaviour)component2.mainScript).IsOwner && component2.mainScript.enemyType.canDie && !component2.mainScript.isEnemyDead)
			{
				component2.mainScript.KillEnemyOnOwnerClient(false);
			}
		}

		private void OnTriggerExit(Collider collider)
		{
			PlayerControllerB component = ((Component)collider).GetComponent<PlayerControllerB>();
			if ((Object)(object)component != (Object)null)
			{
				teslaGate.engagingPlayerList.Remove(component);
				teslaGate.engagingList.Remove(((Component)collider).gameObject);
				if (isIdleTrigger)
				{
					teslaGate.activatePlayerList.Remove(component);
					teslaGate.activateList.Remove(((Component)collider).gameObject);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Dungeon))]
	internal class DungeonPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("SpawnDoorPrefab")]
		private static void SpawnDoorPrefab_Prefix(Doorway a, Doorway b, RandomStream randomStream)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Expected O, but got Unknown
			for (int i = 0; i < a.ConnectorPrefabWeights.Count; i++)
			{
				GameObjectWeight val = a.ConnectorPrefabWeights[i];
				if (((Object)val.GameObject).name == "TeslaGateSpawn")
				{
					return;
				}
				if (((Object)val.GameObject).name == "BigDoorSpawn")
				{
					GameObjectWeight val2 = new GameObjectWeight();
					a.ConnectorPrefabWeights.Add(val2);
					val2.Weight = 0.05f * Plugin.teslaSpawnWeight;
					val2.GameObject = Plugin.teslaGateSpawn;
					Plugin.mls.LogInfo((object)("added tesla to " + ((Object)((Component)a).gameObject).name));
				}
			}
			for (int j = 0; j < b.ConnectorPrefabWeights.Count; j++)
			{
				GameObjectWeight val3 = b.ConnectorPrefabWeights[j];
				if (((Object)val3.GameObject).name == "TeslaGateSpawn")
				{
					break;
				}
				if (((Object)val3.GameObject).name == "BigDoorSpawn")
				{
					GameObjectWeight val4 = new GameObjectWeight();
					b.ConnectorPrefabWeights.Add(val4);
					val4.Weight = 0.07f * Plugin.teslaSpawnWeight;
					val4.GameObject = Plugin.teslaGateSpawn;
					Plugin.mls.LogInfo((object)("added tesla to " + ((Object)((Component)b).gameObject).name));
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		public static AnimationClip middleFinger;

		public static AnimationClip middleFinger_D;

		public static AnimationClip clap;

		public static AnimationClip clap_D;

		public static AnimationClip shy;

		public static AnimationClip griddy;

		public static AnimationClip twerk;

		public static AnimationClip salute;

		public static AnimationClip prisyadka;

		public static AnimationClip sign;

		public static AnimationClip sign_D;

		private static bool pv_isPlayerFirstFrame;

		private static void UpdateAnimator(PlayerControllerB __instance, Animator ___playerBodyAnimator)
		{
		}

		private static void UpdateMoreEmotesAnimator(PlayerControllerB __instance, Animator ___playerBodyAnimator)
		{
			//IL_02e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ee: Expected O, but got Unknown
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Expected O, but got Unknown
			if ((Object)(object)middleFinger == (Object)null || (Object)(object)middleFinger_D == (Object)null || (((Object)(object)clap == (Object)null) | ((Object)(object)clap_D == (Object)null)) || (((Object)(object)shy == (Object)null) | ((Object)(object)griddy == (Object)null)) || (Object)(object)twerk == (Object)null || (Object)(object)salute == (Object)null || (Object)(object)prisyadka == (Object)null || (Object)(object)sign == (Object)null || (Object)(object)sign_D == (Object)null)
			{
				GetMoreEmotes(___playerBodyAnimator.runtimeAnimatorController);
			}
			if (!((Object)(object)___playerBodyAnimator.runtimeAnimatorController != (Object)(object)Plugin.playerAnimator) || !((Object)(object)___playerBodyAnimator.runtimeAnimatorController != (Object)(object)Plugin.otherPlayerAnimator))
			{
				return;
			}
			if ((Object)(object)__instance == (Object)(object)StartOfRound.Instance.localPlayerController)
			{
				if ((Object)(object)middleFinger != (Object)null && (Object)(object)middleFinger_D != (Object)null && (Object)(object)clap != (Object)null && (Object)(object)clap_D != (Object)null && (Object)(object)shy != (Object)null && (Object)(object)griddy != (Object)null && (Object)(object)twerk != (Object)null && (Object)(object)salute != (Object)null && (Object)(object)prisyadka != (Object)null && (Object)(object)sign != (Object)null && (Object)(object)sign_D != (Object)null)
				{
					if (!(__instance.playerBodyAnimator.runtimeAnimatorController is AnimatorOverrideController))
					{
						__instance.playerBodyAnimator.runtimeAnimatorController = (RuntimeAnimatorController)new AnimatorOverrideController(__instance.playerBodyAnimator.runtimeAnimatorController);
					}
					__instance.SpawnPlayerAnimation();
					UpdateAnimatorVariable(Plugin.playerAnimator);
					EmotePatch.local = Plugin.playerAnimator;
					Plugin.mls.LogInfo((object)"Replace More Emotes Animator!");
				}
			}
			else if ((Object)(object)middleFinger != (Object)null && (Object)(object)middleFinger_D != (Object)null && (Object)(object)clap != (Object)null && (Object)(object)clap_D != (Object)null && (Object)(object)shy != (Object)null && (Object)(object)griddy != (Object)null && (Object)(object)twerk != (Object)null && (Object)(object)salute != (Object)null && (Object)(object)prisyadka != (Object)null && (Object)(object)sign != (Object)null && (Object)(object)sign_D != (Object)null)
			{
				UpdateAnimatorVariable(Plugin.otherPlayerAnimator);
				EmotePatch.others = Plugin.otherPlayerAnimator;
				Plugin.mls.LogInfo((object)"Replace More Emotes Other Animator!");
				if (!(__instance.playerBodyAnimator.runtimeAnimatorController is AnimatorOverrideController))
				{
					__instance.playerBodyAnimator.runtimeAnimatorController = (RuntimeAnimatorController)new AnimatorOverrideController(__instance.playerBodyAnimator.runtimeAnimatorController);
				}
			}
		}

		private static void OnFirstLocalPlayerFrameWithNewAnimator(PlayerControllerB __instance)
		{
			pv_isPlayerFirstFrame = false;
			__instance.SpawnPlayerAnimation();
		}

		private static void GetMoreEmotes(RuntimeAnimatorController animator)
		{
			AnimationClip[] animationClips = animator.animationClips;
			foreach (AnimationClip val in animationClips)
			{
				if ((Object)(object)middleFinger == (Object)null && ((Object)val).name == "Middle_Finger")
				{
					middleFinger = val;
				}
				if ((Object)(object)middleFinger_D == (Object)null && ((Object)val).name == "D_Middle_Finger")
				{
					middleFinger_D = val;
				}
				if ((Object)(object)clap == (Object)null && ((Object)val).name == "Clap")
				{
					clap = val;
				}
				if ((Object)(object)clap_D == (Object)null && ((Object)val).name == "D_Clap")
				{
					clap_D = val;
				}
				if ((Object)(object)shy == (Object)null && ((Object)val).name == "Shy")
				{
					shy = val;
				}
				if ((Object)(object)griddy == (Object)null && ((Object)val).name == "The_Griddy")
				{
					griddy = val;
				}
				if ((Object)(object)twerk == (Object)null && ((Object)val).name == "Twerk")
				{
					twerk = val;
				}
				if ((Object)(object)salute == (Object)null && ((Object)val).name == "Salute")
				{
					salute = val;
				}
				if ((Object)(object)prisyadka == (Object)null && ((Object)val).name == "Prisyadka")
				{
					prisyadka = val;
				}
				if ((Object)(object)sign == (Object)null && ((Object)val).name == "Sign")
				{
					sign = val;
				}
				if ((Object)(object)sign_D == (Object)null && ((Object)val).name == "D_Sign")
				{
					sign_D = val;
				}
			}
		}

		private static void UpdateAnimatorVariable(RuntimeAnimatorController animator)
		{
			AnimationClip[] animationClips = animator.animationClips;
			for (int i = 0; i < animationClips.Length; i++)
			{
				switch (((Object)animationClips[i]).name)
				{
				case "Middle_Finger":
					animationClips[i] = middleFinger;
					break;
				case "D_Middle_Finger":
					animationClips[i] = middleFinger_D;
					break;
				case "Clap":
					animationClips[i] = clap;
					break;
				case "D_Clap":
					animationClips[i] = clap_D;
					break;
				case "Shy":
					animationClips[i] = shy;
					break;
				case "The_Griddy":
					animationClips[i] = griddy;
					break;
				case "Twerk":
					animationClips[i] = twerk;
					break;
				case "Salute":
					animationClips[i] = salute;
					break;
				case "Prisyadka":
					animationClips[i] = prisyadka;
					break;
				case "Sign":
					animationClips[i] = sign;
					break;
				case "D_Sign":
					animationClips[i] = sign_D;
					break;
				}
			}
		}
	}
	public class GummylightItem : GrabbableObject
	{
		[Space(15f)]
		public bool usingPlayerHelmetLight;

		public int flashlightInterferenceLevel;

		public static int globalFlashlightInterferenceLevel;

		public Light flashlightBulb;

		public Light flashlightBulbGlow;

		public AudioSource flashlightAudio;

		public AudioClip[] flashlightClips;

		public AudioClip outOfBatteriesClip;

		public AudioClip flashlightFlicker;

		public Material bulbLight;

		public Material bulbDark;

		public MeshRenderer flashlightMesh;

		public int flashlightTypeID;

		public bool changeMaterial = true;

		private float initialIntensity;

		private PlayerControllerB previousPlayerHeldBy;

		public override void Start()
		{
			base.useCooldown = 0.12f;
			base.itemProperties = Plugin.gummyFlashlight;
			base.mainObjectRenderer = ((Component)((Component)this).transform.GetChild(2)).GetComponent<MeshRenderer>();
			base.insertedBattery.charge = 1f;
			base.grabbableToEnemies = true;
			flashlightBulb = ((Component)((Component)this).transform.GetChild(0)).GetComponent<Light>();
			flashlightBulbGlow = ((Component)((Component)this).transform.GetChild(1)).GetComponent<Light>();
			flashlightAudio = ((Component)this).GetComponent<AudioSource>();
			flashlightClips = (AudioClip[])(object)new AudioClip[1] { Plugin.gummylightClick };
			outOfBatteriesClip = Plugin.gummylightOutage;
			flashlightFlicker = Plugin.flashFlicker;
			bulbLight = Plugin.flashlightBulb;
			bulbDark = Plugin.blackRubber;
			flashlightMesh = ((Component)((Component)this).transform.GetChild(2)).GetComponent<MeshRenderer>();
			changeMaterial = true;
			base.isInFactory = true;
			base.grabbable = true;
			flashlightTypeID = 0;
			Object.Destroy((Object)(object)((Component)this).GetComponent<FlashlightItem>());
			((GrabbableObject)this).Start();
			initialIntensity = flashlightBulb.intensity;
		}

		public override void ItemActivate(bool used, bool buttonDown = true)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (flashlightInterferenceLevel < 2)
			{
				SwitchFlashlight(used);
			}
			flashlightAudio.PlayOneShot(flashlightClips[Random.Range(0, flashlightClips.Length)]);
			RoundManager.Instance.PlayAudibleNoise(((Component)this).transform.position, 7f, 0.4f, 0, base.isInElevator && StartOfRound.Instance.hangarDoorsClosed, 0);
		}

		public override void UseUpBatteries()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			((GrabbableObject)this).UseUpBatteries();
			SwitchFlashlight(on: false);
			flashlightAudio.PlayOneShot(outOfBatteriesClip, 1f);
			RoundManager.Instance.PlayAudibleNoise(((Component)this).transform.position, 13f, 0.65f, 0, base.isInElevator && StartOfRound.Instance.hangarDoorsClosed, 0);
		}

		public override void PocketItem()
		{
			previousPlayerHeldBy.equippedUsableItemQE = false;
			if (!((NetworkBehaviour)this).IsOwner)
			{
				((GrabbableObject)this).PocketItem();
				return;
			}
			if ((Object)(object)previousPlayerHeldBy != (Object)null)
			{
				((Behaviour)flashlightBulb).enabled = false;
				((Behaviour)flashlightBulbGlow).enabled = false;
				if (base.isBeingUsed && ((Object)(object)previousPlayerHeldBy.ItemSlots[previousPlayerHeldBy.currentItemSlot] == (Object)null || previousPlayerHeldBy.ItemSlots[previousPlayerHeldBy.currentItemSlot].itemProperties.itemId != 1 || previousPlayerHeldBy.ItemSlots[previousPlayerHeldBy.currentItemSlot].itemProperties.itemId != 6))
				{
					((Behaviour)previousPlayerHeldBy.helmetLight).enabled = true;
					previousPlayerHeldBy.pocketedFlashlight = (GrabbableObject)(object)this;
					usingPlayerHelmetLight = true;
					PocketFlashlightServerRpc(stillUsingFlashlight: true);
				}
				else
				{
					base.isBeingUsed = false;
					usingPlayerHelmetLight = false;
					((Behaviour)flashlightBulbGlow).enabled = false;
					SwitchFlashlight(on: false);
					PocketFlashlightServerRpc();
				}
			}
			else
			{
				Debug.Log((object)"Could not find what player was holding this flashlight item");
			}
			if (((NetworkBehaviour)this).IsOwner && (Object)(object)base.playerHeldBy != (Object)null)
			{
				base.playerHeldBy.equippedUsableItemQE = false;
			}
			((GrabbableObject)this).PocketItem();
		}

		[ServerRpc]
		public void PocketFlashlightServerRpc(bool stillUsingFlashlight = false)
		{
			PocketFlashlightClientRpc(stillUsingFlashlight);
		}

		[ClientRpc]
		public void PocketFlashlightClientRpc(bool stillUsingFlashlight)
		{
			if (((NetworkBehaviour)this).IsOwner)
			{
				return;
			}
			((Behaviour)flashlightBulb).enabled = false;
			((Behaviour)flashlightBulbGlow).enabled = false;
			if (stillUsingFlashlight)
			{
				if (!((Object)(object)previousPlayerHeldBy == (Object)null))
				{
					((Behaviour)previousPlayerHeldBy.helmetLight).enabled = true;
					previousPlayerHeldBy.pocketedFlashlight = (GrabbableObject)(object)this;
					usingPlayerHelmetLight = true;
				}
			}
			else
			{
				base.isBeingUsed = false;
				usingPlayerHelmetLight = false;
				((Behaviour)flashlightBulbGlow).enabled = false;
				SwitchFlashlight(on: false);
			}
		}

		public override void DiscardItem()
		{
			if ((Object)(object)base.playerHeldBy != (Object)null)
			{
				base.playerHeldBy.equippedUsableItemQE = false;
			}
			if ((Object)(object)previousPlayerHeldBy != (Object)null)
			{
				((Behaviour)previousPlayerHeldBy.helmetLight).enabled = false;
				((Behaviour)flashlightBulb).enabled = base.isBeingUsed;
				((Behaviour)flashlightBulbGlow).enabled = base.isBeingUsed;
			}
			((GrabbableObject)this).DiscardItem();
		}

		public override void EquipItem()
		{
			previousPlayerHeldBy = base.playerHeldBy;
			base.playerHeldBy.equippedUsableItemQE = true;
			base.playerHeldBy.ChangeHelmetLight(flashlightTypeID, true);
			((Behaviour)base.playerHeldBy.helmetLight).enabled = false;
			usingPlayerHelmetLight = false;
			if (base.isBeingUsed)
			{
				SwitchFlashlight(on: true);
			}
			((GrabbableObject)this).EquipItem();
		}

		public void SwitchFlashlight(bool on)
		{
			base.isBeingUsed = on;
			if (!((NetworkBehaviour)this).IsOwner)
			{
				Debug.Log((object)$"Flashlight click. playerheldby null?: {(Object)(object)base.playerHeldBy != (Object)null}");
				Debug.Log((object)$"Flashlight being disabled or enabled: {on}");
				if ((Object)(object)base.playerHeldBy != (Object)null)
				{
					base.playerHeldBy.ChangeHelmetLight(flashlightTypeID, on);
				}
				((Behaviour)flashlightBulb).enabled = false;
				((Behaviour)flashlightBulbGlow).enabled = false;
			}
			else
			{
				((Behaviour)flashlightBulb).enabled = on;
				((Behaviour)flashlightBulbGlow).enabled = on;
			}
			if (usingPlayerHelmetLight && (Object)(object)base.playerHeldBy != (Object)null)
			{
				((Behaviour)base.playerHeldBy.helmetLight).enabled = on;
			}
			if (changeMaterial)
			{
				Material[] sharedMaterials = ((Renderer)flashlightMesh).sharedMaterials;
				if (on)
				{
					sharedMaterials[1] = bulbLight;
				}
				else
				{
					sharedMaterials[1] = bulbDark;
				}
				((Renderer)flashlightMesh).sharedMaterials = sharedMaterials;
			}
		}

		public override void Update()
		{
			((GrabbableObject)this).Update();
			int num = ((flashlightInterferenceLevel <= globalFlashlightInterferenceLevel) ? globalFlashlightInterferenceLevel : flashlightInterferenceLevel);
			if (num >= 2)
			{
				flashlightBulb.intensity = 0f;
			}
			else if (num == 1)
			{
				flashlightBulb.intensity = Random.Range(0f, 200f);
			}
			else
			{
				flashlightBulb.intensity = initialIntensity;
			}
		}

		public override void ItemInteractLeftRight(bool right)
		{
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			Debug.Log((object)$"r/l activate: {right}");
			((GrabbableObject)this).ItemInteractLeftRight(right);
			if (!right && (Object)(object)base.playerHeldBy != (Object)null)
			{
				flashlightAudio.PlayOneShot(Plugin.flashlightShake);
				WalkieTalkie.TransmitOneShotAudio(flashlightAudio, Plugin.flashlightShake, 1f);
				base.playerHeldBy.playerBodyAnimator.SetTrigger("shakeItem");
				float num = base.insertedBattery.charge * 100f + 8f;
				if (num <= 100f)
				{
					base.insertedBattery = new Battery(false, num * 0.01f);
					((GrabbableObject)this).SyncBatteryServerRpc((int)num);
				}
				else
				{
					base.insertedBattery = new Battery(false, num * 0.01f);
					((GrabbableObject)this).SyncBatteryServerRpc(100);
				}
				if (((NetworkBehaviour)this).IsOwner)
				{
					RoundManager.Instance.PlayAudibleNoise(((Component)this).transform.position, 5f, 0.2f, 0, base.isInElevator && StartOfRound.Instance.hangarDoorsClosed, 941);
				}
			}
		}
	}
	public class M4Item : GrabbableObject
	{
		public static Dictionary<ulong, RuntimeAnimatorController> playerAnimatorDictionary = new Dictionary<ulong, RuntimeAnimatorController>();

		private bool isCrouching;

		private bool isJumping;

		private bool isWalking;

		private bool isSprinting;

		private AnimatorStateInfo currentStateInfo;

		private float currentAnimationTime;

		public int gunCompatibleAmmoID = 1410;

		public bool isReloading;

		public bool isInspecting;

		public bool cantFire;

		public bool isFiring;

		public int ammosLoaded;

		public Animator gunAnimator;

		public AudioSource gunAudio;

		public AudioSource gunShootAudio;

		public AudioSource gunBulletsRicochetAudio;

		private Coroutine gunCoroutine;

		public AudioClip gunShootSFX;

		public AudioClip gunReloadSFX;

		public AudioClip gunInspectSFX;

		public AudioClip noAmmoSFX;

		private bool hasHitGroundWithSafetyOff = true;

		private int ammoSlotToUse = -1;

		private bool localClientSendingShootGunRPC;

		private PlayerControllerB previousPlayerHeldBy;

		public ParticleSystem gunShootParticle;

		public Transform gunRayPoint;

		private RaycastHit[] enemyColliders;

		private RaycastHit[] playerColliders;

		private EnemyAI heldByEnemy;

		public override void Start()
		{
			((GrabbableObject)this).Start();
		}

		public override int GetItemDataToSave()
		{
			((GrabbableObject)this).GetItemDataToSave();
			return ammosLoaded;
		}

		public override void LoadItemSaveData(int saveData)
		{
			((GrabbableObject)this).LoadItemSaveData(saveData);
			ammosLoaded = saveData;
		}

		public override void Update()
		{
			((GrabbableObject)this).Update();
			if (!isInspecting && isFiring && !isReloading && !cantFire && !base.playerHeldBy.playerBodyAnimator.GetBool("ReloadM4") && ammosLoaded > 0)
			{
				ShootGunAndSync(heldByPlayer: true);
			}
		}

		public override void EquipItem()
		{
			((GrabbableObject)this).EquipItem();
			previousPlayerHeldBy = base.playerHeldBy;
			previousPlayerHeldBy.equippedUsableItemQE = true;
			hasHitGroundWithSafetyOff = false;
			if ((Object)(object)base.playerHeldBy != (Object)null)
			{
				UpdateAnimator(base.playerHeldBy, base.playerHeldBy.playerBodyAnimator, restore: false);
			}
			if (Plugin.translateKorean)
			{
				KR_SetAmmoControlTip(isChecking: false);
			}
			else
			{
				SetAmmoControlTip(isChecking: false);
			}
		}

		public override void GrabItem()
		{
			if ((Object)(object)base.playerHeldBy != (Object)null)
			{
				UpdateAnimator(base.playerHeldBy, base.playerHeldBy.playerBodyAnimator, restore: false);
			}
			((GrabbableObject)this).GrabItem();
		}

		public override void GrabItemFromEnemy(EnemyAI enemy)
		{
			((GrabbableObject)this).GrabItemFromEnemy(enemy);
			heldByEnemy = enemy;
			hasHitGroundWithSafetyOff = false;
		}

		public override void DiscardItemFromEnemy()
		{
			((GrabbableObject)this).DiscardItemFromEnemy();
			heldByEnemy = null;
		}

		public override void ItemActivate(bool used, bool buttonDown = false)
		{
			Debug.Log((object)buttonDown);
			((GrabbableObject)this).ItemActivate(used, buttonDown);
			isFiring = buttonDown;
			if (!isInspecting && !isReloading && !cantFire && !base.playerHeldBy.playerBodyAnimator.GetBool("ReloadM4") && ammosLoaded <= 0)
			{
				gunAudio.PlayOneShot(noAmmoSFX);
			}
		}

		public void ShootGunAndSync(bool heldByPlayer)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			Vector3 gunPosition;
			Vector3 forward;
			if (!heldByPlayer)
			{
				gunPosition = gunRayPoint.position;
				forward = gunRayPoint.forward;
			}
			else
			{
				gunPosition = ((Component)GameNetworkManager.Instance.localPlayerController.gameplayCamera).transform.position - ((Component)GameNetworkManager.Instance.localPlayerController.gameplayCamera).transform.up * 0.45f;
				forward = ((Component)GameNetworkManager.Instance.localPlayerController.gameplayCamera).transform.forward;
			}
			ShootGun(gunPosition, forward);
		}

		[ServerRpc(RequireOwnership = false)]
		public void ShootGunServerRpc(Vector3 gunPosition, Vector3 gunForward)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			ShootGunClientRpc(gunPosition, gunForward);
		}

		[ClientRpc]
		public void ShootGunClientRpc(Vector3 gunPosition, Vector3 gunForward)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			Debug.Log((object)"Shoot gun client rpc received");
			if (localClientSendingShootGunRPC)
			{
				localClientSendingShootGunRPC = false;
				Debug.Log((object)"localClientSendingShootGunRPC was true");
			}
			else
			{
				ShootGun(gunPosition, gunForward);
			}
		}

		public IEnumerator FireDelay()
		{
			cantFire = true;
			yield return (object)new WaitForSeconds(0.07f);
			cantFire = false;
		}

		public void ShootGun(Vector3 gunPosition, Vector3 gunForward)
		{
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			//IL_0605: Unknown result type (might be due to invalid IL or missing references)
			//IL_0690: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_042c: Unknown result type (might be due to invalid IL or missing references)
			//IL_043e: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_07b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0759: Unknown result type (might be due to invalid IL or missing references)
			//IL_0763: Unknown result type (might be due to invalid IL or missing references)
			//IL_0461: Unknown result type (might be due to invalid IL or missing references)
			//IL_0466: Unknown result type (might be due to invalid IL or missing references)
			//IL_046b: Unknown result type (might be due to invalid IL or missing references)
			//IL_048b: Unknown result type (might be due to invalid IL or missing references)
			//IL_049d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0526: Unknown result type (might be due to invalid IL or missing references)
			//IL_052b: Unknown result type (might be due to invalid IL or missing references)
			//IL_053d: Unknown result type (might be due to invalid IL or missing references)
			//IL_054f: Unknown result type (might be due to invalid IL or missing references)
			//IL_058d: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.translateKorean)
			{
				KR_SetAmmoControlTip(isChecking: false);
			}
			else
			{
				SetAmmoControlTip(isChecking: false);
			}
			CentipedeAI[] array = Object.FindObjectsByType<CentipedeAI>((FindObjectsSortMode)0);
			FlowerSnakeEnemy[] array2 = Object.FindObjectsByType<FlowerSnakeEnemy>((FindObjectsSortMode)0);
			for (int i = 0; i < array.Length; i++)
			{
				if ((Object)(object)array[i].clingingToPlayer == (Object)(object)base.playerHeldBy)
				{
					((EnemyAI)array[i]).HitEnemy(2, base.playerHeldBy, true, -1);
				}
			}
			for (int j = 0; j < array2.Length; j++)
			{
				if ((Object)(object)array2[j].clingingToPlayer == (Object)(object)base.playerHeldBy)
				{
					((EnemyAI)array2[j]).HitEnemy(2, base.playerHeldBy, true, -1);
				}
			}
			((MonoBehaviour)this).StartCoroutine(FireDelay());
			bool flag = false;
			if (base.isHeld && (Object)(object)base.playerHeldBy != (Object)null && (Object)(object)base.playerHeldBy == (Object)(object)GameNetworkManager.Instance.localPlayerController)
			{
				base.playerHeldBy.playerBodyAnimator.SetTrigger("ShootM4");
				flag = true;
			}
			gunAnimator.SetTrigger("Fire");
			gunShootAudio.PlayOneShot(gunShootSFX);
			WalkieTalkie.TransmitOneShotAudio(gunShootAudio, gunShootSFX, 1f);
			gunShootParticle.Play(true);
			ammosLoaded = Mathf.Clamp(ammosLoaded - 1, 0, 30);
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if ((Object)(object)localPlayerController == (Object)null)
			{
				return;
			}
			float num = Vector3.Distance(((Component)localPlayerController).transform.position, ((Component)gunRayPoint).transform.position);
			bool flag2 = false;
			int num2 = 0;
			float num3 = 0f;
			Vector3 val = localPlayerController.playerCollider.ClosestPoint(gunPosition);
			if (!flag && !Physics.Linecast(gunPosition, val, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1) && Vector3.Angle(gunForward, val - gunPosition) < 30f)
			{
				flag2 = true;
			}
			if (num < 12f)
			{
				num3 = 0.25f;
				HUDManager.Instance.ShakeCamera((ScreenShakeType)0);
				num2 = 100;
			}
			Ray val2 = default(Ray);
			((Ray)(ref val2))..ctor(((Component)base.playerHeldBy.gameplayCamera).transform.position, ((Component)base.playerHeldBy.gameplayCamera).transform.forward);
			if (enemyColliders == null)
			{
				enemyColliders = (RaycastHit[])(object)new RaycastHit[35];
			}
			RaycastHit val3 = default(RaycastHit);
			if (Physics.Raycast(((Component)base.playerHeldBy.gameplayCamera).transform.position, ((Component)base.playerHeldBy.gameplayCamera).transform.forward, ref val3, float.PositiveInfinity, StartOfRound.Instance.collidersAndRoomMaskAndDefault))
			{
				((Component)gunBulletsRicochetAudio).transform.position = ((Ray)(ref val2)).GetPoint(((RaycastHit)(ref val3)).distance - 0.5f);
				gunBulletsRicochetAudio.Play();
			}
			if ((Object)(object)base.playerHeldBy == (Object)(object)StartOfRound.Instance.localPlayerController)
			{
				int num4 = Physics.SphereCastNonAlloc(val2, 0.25f, enemyColliders, float.PositiveInfinity, 524288, (QueryTriggerInteraction)2);
				IHittable val4 = default(IHittable);
				for (int k = 0; k < num4; k++)
				{
					Debug.Log((object)"Raycasting enemy");
					if (!Object.op_Implicit((Object)(object)((Component)((RaycastHit)(ref enemyColliders[k])).transform).GetComponent<EnemyAICollisionDetect>()))
					{
						continue;
					}
					EnemyAI mainScript = ((Component)((RaycastHit)(ref enemyColliders[k])).transform).GetComponent<EnemyAICollisionDetect>().mainScript;
					if ((Object)(object)heldByEnemy != (Object)null && (Object)(object)heldByEnemy == (Object)(object)mainScript)
					{
						Debug.Log((object)"Rifle is held by enemy, skipping enemy raycast");
						continue;
					}
					Debug.Log((object)("Hit enemy " + mainScript.enemyType.enemyName));
					if (((RaycastHit)(ref enemyColliders[k])).distance == 0f)
					{
						Debug.Log((object)"Spherecast started inside enemy collider");
					}
					else if (Physics.Linecast(((Component)base.playerHeldBy.gameplayCamera).transform.position, ((RaycastHit)(ref enemyColliders[k])).point, ref val3, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))
					{
						Debug.DrawRay(((RaycastHit)(ref val3)).point, Vector3.up, Color.red, 15f);
						Debug.DrawLine(((Component)base.playerHeldBy.gameplayCamera).transform.position, ((RaycastHit)(ref enemyColliders[k])).point, Color.cyan, 15f);
						Plugin.mls.LogInfo((object)("Raycast hit wall: " + ((Object)((Component)((RaycastHit)(ref val3)).collider).gameObject).name + ", distance: " + ((RaycastHit)(ref val3)).distance));
					}
					else if (((Component)((RaycastHit)(ref enemyColliders[k])).transform).TryGetComponent<IHittable>(ref val4))
					{
						Vector3 forward = ((Component)base.playerHeldBy.gameplayCamera).transform.forward;
						float num5 = Vector3.Distance(((Component)base.playerHeldBy.gameplayCamera).transform.position, ((RaycastHit)(ref enemyColliders[k])).point);
						Plugin.mls.LogInfo((object)("Damage to enemy, damage: " + Plugin.rifleMonsterDamage + ", distance:" + num5));
						val4.Hit(Plugin.rifleMonsterDamage, forward, base.playerHeldBy, true, -1);
					}
					else
					{
						Plugin.mls.LogInfo((object)("Could not get hittable script from collider, transform: " + ((Object)((RaycastHit)(ref enemyColliders[k])).transform).name));
					}
				}
			}
			if (playerColliders == null)
			{
				playerColliders = (RaycastHit[])(object)new RaycastHit[10];
			}
			int num6 = Physics.SphereCastNonAlloc(val2, 0.3f, playerColliders, float.PositiveInfinity, StartOfRound.Instance.collidersRoomMaskDefaultAndPlayers, (QueryTriggerInteraction)2);
			for (int l = 0; l < num6; l++)
			{
				if ((Object)(object)((Component)((RaycastHit)(ref playerColliders[l])).transform).GetComponent<PlayerControllerB>() != (Object)null && (Object)(object)((Component)((RaycastHit)(ref playerColliders[l])).transform).GetComponent<PlayerControllerB>() != (Object)(object)base.playerHeldBy)
				{
					float num7 = Vector3.Distance(((Component)base.playerHeldBy.gameplayCamera).transform.position, ((RaycastHit)(ref playerColliders[l])).point);
					if (num7 < 10f)
					{
						((Component)((RaycastHit)(ref playerColliders[l])).transform).GetComponent<PlayerControllerB>().DamagePlayer(Plugin.rifleMaxPlayerDamage, true, true, (CauseOfDeath)7, 0, false, ((Component)base.playerHeldBy.gameplayCamera).transform.forward * 30f);
					}
					else if (num7 < 25f)
					{
						((Component)((RaycastHit)(ref playerColliders[l])).transform).GetComponent<PlayerControllerB>().DamagePlayer(Mathf.RoundToInt((float)(Plugin.rifleMaxPlayerDamage - Plugin.rifleMaxPlayerDamage / 3)), true, true, (CauseOfDeath)7, 0, false, ((Component)base.playerHeldBy.gameplayCamera).transform.forward * 30f);
					}
					else
					{
						((Component)((RaycastHit)(ref playerColliders[l])).transform).GetComponent<PlayerControllerB>().DamagePlayer(Mathf.RoundToInt((float)(Plugin.rifleMaxPlayerDamage / 3)), true, true, (CauseOfDeath)7, 0, false, ((Component)base.playerHeldBy.gameplayCamera).transform.forward * 30f);
					}
					Debug.Log((object)"Rifle vs Player why COD");
				}
			}
		}

		private IEnumerator delayedEarsRinging(float effectSeverity)
		{
			yield return (object)new WaitForSeconds(0.25f);
			SoundManager.Instance.earsRingingTimer = effectSeverity;
		}

		public override void ItemInteractLeftRight(bool right)
		{
			((GrabbableObject)this).ItemInteractLeftRight(right);
			if (!((Object)(object)base.playerHeldBy == (Object)null))
			{
				Debug.Log((object)$"r/l activate: {right}");
				if (!right)
				{
					StartCheckMagazine();
				}
				else if (!isInspecting && !isReloading && ammosLoaded < 30)
				{
					StartReloadGun();
				}
			}
		}

		private void StartReloadGun()
		{
			if ((Plugin.customGunInfinityAmmo || ReloadedGun()) && !isReloading)
			{
				((MonoBehaviour)this).StartCoroutine(ReloadGunAnimation());
			}
			else
			{
				gunAudio.PlayOneShot(noAmmoSFX);
			}
		}

		private void StartCheckMagazine()
		{
			if (!isInspecting)
			{
				((MonoBehaviour)this).StartCoroutine(CheckAmmoGunAnimation());
			}
			else
			{
				gunAudio.PlayOneShot(noAmmoSFX);
			}
		}

		private IEnumerator CheckAmmoGunAnimation()
		{
			base.playerHeldBy.playerBodyAnimator.SetTrigger("InspectM4");
			isInspecting = true;
			gunAudio.PlayOneShot(gunInspectSFX);
			if ((Object)(object)base.playerHeldBy == (Object)(object)StartOfRound.Instance.localPlayerController)
			{
				WalkieTalkie.TransmitOneShotAudio(gunAudio, gunInspectSFX, 1f);
			}
			yield return (object)new WaitForSeconds(1f);
			if (Plugin.translateKorean)
			{
				KR_SetAmmoControlTip(isChecking: true);
			}
			else
			{
				SetAmmoControlTip(isChecking: true);
			}
			yield return (object)new WaitForSeconds(1f);
			isInspecting = false;
		}

		private void SetAmmoControlTip(bool isChecking)
		{
			string text = "Check ammo : [Q]";
			if (ammosLoaded == 30)
			{
				text = (isChecking ? "Check ammo : [Q] [Full]" : "Check ammo : [Q] [??]");
			}
			else if (ammosLoaded >= 20 && 30 > ammosLoaded)
			{
				text = (isChecking ? "Check ammo : [Q] [<30]" : "Check ammo : [Q] [??]");
			}
			else if (ammosLoaded >= 10 && 20 > ammosLoaded)
			{
				text = (isChecking ? "Check ammo : [Q] [<20]" : "Check ammo : [Q] [??]");
			}
			else if (ammosLoaded >= 1 && 10 > ammosLoaded)
			{
				text = (isChecking ? "Check ammo : [Q] [<10]" : "Check ammo : [Q] [??]");
			}
			else if (ammosLoaded <= 0)
			{
				text = (isChecking ? "Check ammo : [Q] [Empty]" : "Check ammo : [Q] [??]");
			}
			if (((NetworkBehaviour)this).IsOwner)
			{
				HUDManager.Instance.ChangeControlTip(3, text, false);
			}
		}

		private void KR_SetAmmoControlTip(bool isChecking)
		{
			string text = "탄약 확인하기 : [Q]";
			if (ammosLoaded == 30)
			{
				text = (isChecking ? "탄약 확인하기 : [Q] [가득 참]" : "탄약 확인하기 : [Q] [??]");
			}
			else if (ammosLoaded >= 20 && 30 > ammosLoaded)
			{
				text = (isChecking ? "탄약 확인하기 : [Q] [<30]" : "탄약 확인하기 : [Q] [??]");
			}
			else if (ammosLoaded >= 10 && 20 > ammosLoaded)
			{
				text = (isChecking ? "탄약 확인하기 : [Q] [<20]" : "탄약 확인하기 : [Q] [??]");
			}
			else if (ammosLoaded >= 1 && 10 > ammosLoaded)
			{
				text = (isChecking ? "탄약 확인하기 : [Q] [<10]" : "탄약 확인하기 : [Q] [??]");
			}
			else if (ammosLoaded <= 0)
			{
				text = (isChecking ? "탄약 확인하기 : [Q] [비어 있음]" : "탄약 확인하기 : [Q] [??]");
			}
			if (((NetworkBehaviour)this).IsOwner)
			{
				HUDManager.Instance.ChangeControlTip(3, text, false);
			}
		}

		private IEnumerator ReloadGunAnimation()
		{
			base.playerHeldBy.playerBodyAnimator.SetTrigger("ReloadM4");
			gunAnimator.SetTrigger("Reloading");
			isReloading = true;
			gunAudio.PlayOneShot(gunReloadSFX);
			if ((Object)(object)base.playerHeldBy == (Object)(object)StartOfRound.Instance.localPlayerController)
			{
				WalkieTalkie.TransmitOneShotAudio(gunAudio, gunReloadSFX, 1f);
			}
			yield return (object)new WaitForSeconds(2f);
			if (isReloading)
			{
				if ((Object)(object)base.playerHeldBy == (Object)(object)StartOfRound.Instance.localPlayerController && !Plugin.customGunInfinityAmmo)
				{
					base.playerHeldBy.DestroyItemInSlotAndSync(ammoSlotToUse);
				}
				ammoSlotToUse = -1;
				ammosLoaded = 30;
				if (Plugin.translateKorean)
				{
					KR_SetAmmoControlTip(isChecking: true);
				}
				else
				{
					SetAmmoControlTip(isChecking: true);
				}
			}
			yield return (object)new WaitForSeconds(0.55f);
			isReloading = false;
		}

		private bool ReloadedGun()
		{
			int num = FindAmmoInInventory();
			if (num == -1)
			{
				Debug.Log((object)"not reloading");
				return false;
			}
			Debug.Log((object)"reloading!");
			ammoSlotToUse = num;
			return true;
		}

		private int FindAmmoInInventory()
		{
			for (int i = 0; i < base.playerHeldBy.ItemSlots.Length; i++)
			{
				if (!((Object)(object)base.playerHeldBy.ItemSlots[i] == (Object)null))
				{
					GrabbableObject obj = base.playerHeldBy.ItemSlots[i];
					GunAmmo val = (GunAmmo)(object)((obj is GunAmmo) ? obj : null);
					Debug.Log((object)$"Ammo null in slot #{i}?: {(Object)(object)val == (Object)null}");
					if ((Object)(object)val != (Object)null)
					{
						Debug.Log((object)$"Ammo in slot #{i} id: {val.ammoType}");
					}
					if ((Object)(object)val != (Object)null && val.ammoType == gunCompatibleAmmoID)
					{
						return i;
					}
				}
			}
			return -1;
		}

		public override void PocketItem()
		{
			if ((Object)(object)base.playerHeldBy != (Object)null)
			{
				UpdateAnimator(base.playerHeldBy, base.playerHeldBy.playerBodyAnimator, restore: true);
			}
			((GrabbableObject)this).PocketItem();
			StopUsingGun();
		}

		public override void DiscardItem()
		{
			if ((Object)(object)base.playerHeldBy != (Object)null)
			{
				UpdateAnimator(base.playerHeldBy, base.playerHeldBy.playerBodyAnimator, restore: true);
			}
			((GrabbableObject)this).DiscardItem();
			StopUsingGun();
		}

		private void StopUsingGun()
		{
			previousPlayerHeldBy.equippedUsableItemQE = false;
			if (gunCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(gunCoroutine);
			}
			gunAudio.Stop();
			isReloading = false;
			previousPlayerHeldBy.playerBodyAnimator.SetTrigger("SwitchHoldAnimation");
			gunAnimator.SetTrigger("Reset");
			isInspecting = false;
		}

		private void UpdateAnimator(PlayerControllerB player, Animator playerBodyAnimator, bool restore)
		{
			if (!restore)
			{
				if ((Object)(object)playerBodyAnimator.runtimeAnimatorController != (Object)(object)Plugin.playerAnimator && (Object)(object)playerBodyAnimator.runtimeAnimatorController != (Object)(object)Plugin.otherPlayerAnimator)
				{
					if ((Object)(object)player == (Object)(object)StartOfRound.Instance.localPlayerController)
					{
						SaveAnimatorStates(playerBodyAnimator);
						playerBodyAnimator.runtimeAnimatorController = Plugin.playerAnimator;
						RestoreAnimatorStates(playerBodyAnimator);
						Plugin.mls.LogInfo((object)"Replace Player Animator!");
					}
					else
					{
						SaveAnimatorStates(playerBodyAnimator);
						playerBodyAnimator.runtimeAnimatorController = Plugin.otherPlayerAnimator;
						RestoreAnimatorStates(playerBodyAnimator);
						Plugin.mls.LogInfo((object)"Replace Other Player Animator!");
					}
				}
			}
			else if (playerAnimatorDictionary.ContainsKey(player.playerClientId))
			{
				playerBodyAnimator.runtimeAnimatorController = playerAnimatorDictionary[player.playerClientId];
				playerAnimatorDictionary.Remove(player.playerClientId);
				Plugin.mls.LogInfo((object)"Restored Player Animator!");
			}
		}

		private void SaveAnimatorStates(Animator animator)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			isCrouching = animator.GetBool("crouching");
			isJumping = animator.GetBool("Jumping");
			isWalking = animator.GetBool("Walking");
			isSprinting = animator.GetBool("Sprinting");
			currentStateInfo = animator.GetCurrentAnimatorStateInfo(0);
			currentAnimationTime = ((AnimatorStateInfo)(ref currentStateInfo)).normalizedTime;
		}

		public void RestoreAnimatorStates(Animator animator)
		{
			animator.Play(((AnimatorStateInfo)(ref currentStateInfo)).fullPathHash, 0, currentAnimationTime);
			animator.SetBool("crouching", isCrouching);
			animator.SetBool("Jumping", isJumping);
			animator.SetBool("Walking", isWalking);
			animator.SetBool("Sprinting", isSprinting);
		}
	}
	public class RevolverItem : GrabbableObject
	{
		public static Dictionary<ulong, RuntimeAnimatorController> playerAnimatorDictionary = new Dictionary<ulong, RuntimeAnimatorController>();

		private bool isCrouching;

		private bool isJumping;

		private bool isWalking;

		private bool isSprinting;

		private AnimatorStateInfo currentStateInfo;

		private float currentAnimationTime;

		public int gunCompatibleAmmoID = 1410;

		public bool isReloading;

		public bool cantFire;

		public Transform cylinderTransform;

		public bool isCylinderMoving;

		public int ammosLoaded;

		public Animator gunAnimator;

		public AudioSource gunAudio;

		public AudioSource gunShootAudio;

		public AudioSource gunBulletsRicochetAudio;

		private Coroutine gunCoroutine;

		public List<AudioClip> gunShootSFX = new List<AudioClip>();

		public AudioClip gunReloadSFX;

		public AudioClip cylinderOpenSFX;

		public AudioClip cylinderCloseSFX;

		public AudioClip gunReloadFinishSFX;

		public AudioClip noAmmoSFX;

		public AudioClip gunSafetySFX;

		public AudioClip switchSafetyOnSFX;

		public AudioClip switchSafetyOffSFX;

		private bool hasHitGroundWithSafetyOff = true;

		private int ammoSlotToUse = -1;

		private bool localClientSendingShootGunRPC;

		private PlayerControllerB previousPlayerHeldBy;

		public ParticleSystem gunShootParticle;

		public Transform revolverRayPoint;

		public List<MeshRenderer> revolverAmmos = new List<MeshRenderer>();

		public MeshRenderer revolverAmmoInHand;

		public Transform revolverAmmoInHandTransform;

		private RaycastHit[] enemyColliders;

		private RaycastHit[] playerColliders;

		private EnemyAI heldByEnemy;

		public override void Start()
		{
			((GrabbableObject)this).Start();
		}

		public override int GetItemDataToSave()
		{
			((GrabbableObject)this).GetItemDataToSave();
			return ammosLoaded;
		}

		public override void LoadItemSaveData(int saveData)
		{
			((GrabbableObject)this).LoadItemSaveData(saveData);
			ammosLoaded = saveData;
		}

		public override void Update()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			((GrabbableObject)this).Update();
			if (!isReloading)
			{
				switch (ammosLoaded)
				{
				case 0:
					cylinderTransform.localRotation = Quaternion.Lerp(cylinderTransform.localRotation, Quaternion.Euler(new Vector3(0f, 0f, 0f)), Time.deltaTime * 25f);
					break;
				case 1:
					cylinderTransform.localRotation = Quaternion.Lerp(cylinderTransform.localRotation, Quaternion.Euler(new Vector3(0f, 60f, 0f)), Time.deltaTime * 25f);
					break;
				case 2:
					cylinderTransform.localRotation = Quaternion.Lerp(cylinderTransform.localRotation, Quaternion.Euler(new Vector3(0f, 120f, 0f)), Time.deltaTime * 25f);
					break;
				case 3:
					cylinderTransform.localRotation = Quaternion.Lerp(cylinderTransform.localRotation, Quaternion.Euler(new Vector3(0f, 180f, 0f)), Time.deltaTime * 25f);
					break;
				case 4:
					cylinderTransform.localRotation = Quaternion.Lerp(cylinderTransform.localRotation, Quaternion.Euler(new Vector3(0f, 240f, 0f)), Time.deltaTime * 25f);
					break;
				case 5:
					cylinderTransform.localRotation = Quaternion.Lerp(cylinderTransform.localRotation, Quaternion.Euler(new Vector3(0f, 300f, 0f)), Time.deltaTime * 25f);
					break;
				case 6:
					cylinderTransform.localRotation = Quaternion.Euler(new Vector3(0f, 0f, 0f));
					break;
				}
			}
		}

		public override void EquipItem()
		{
			((GrabbableObject)this).EquipItem();
			SyncRevolverAmmoServerRpc(ammosLoaded);
			if ((Object)(object)base.playerHeldBy != (Object)null)
			{
				UpdateAnimator(base.playerHeldBy, base.playerHeldBy.playerBodyAnimator, restore: false);
			}
			base.playerHeldBy.playerBodyAnimator.SetBool("ReloadRevolver", false);
			gunAnimator.SetBool("Reloading", false);
			((Renderer)revolverAmmoInHand).enabled = false;
			previousPlayerHeldBy = base.playerHeldBy;
			previousPlayerHeldBy.equippedUsableItemQE = true;
			isCylinderMoving = false;
			hasHitGroundWithSafetyOff = false;
			foreach (MeshRenderer revolverAmmo in revolverAmmos)
			{
				((Renderer)revolverAmmo).enabled = false;
			}
			if (ammosLoaded > 0)
			{
				for (int i = 0; i <= ammosLoaded - 1; i++)
				{
					((Renderer)revolverAmmos[i]).enabled = true;
				}
			}
		}

		public override void GrabItem()
		{
			if ((Object)(object)base.playerHeldBy != (Object)null)
			{
				UpdateAnimator(base.playerHeldBy, base.playerHeldBy.playerBodyAnimator, restore: false);
			}
			((GrabbableObject)this).GrabItem();
		}

		public override void GrabItemFromEnemy(EnemyAI enemy)
		{
			((GrabbableObject)this).GrabItemFromEnemy(enemy);
			heldByEnemy = enemy;
			hasHitGroundWithSafetyOff = false;
		}

		public override void DiscardItemFromEnemy()
		{
			((GrabbableObject)this).DiscardItemFromEnemy();
			heldByEnemy = null;
		}

		public override void ItemActivate(bool used, bool buttonDown = true)
		{
			SyncRevolverAmmoServerRpc(ammosLoaded);
			((GrabbableObject)this).ItemActivate(used, buttonDown);
			if (!isReloading && !cantFire && !gunAnimator.GetBool("Reloading"))
			{
				if (ammosLoaded > 0)
				{
					gunAnimator.SetBool("Reloading", false);
					ShootGunAndSync(heldByPlayer: true);
				}
				else
				{
					((MonoBehaviour)this).StartCoroutine(FireDelay());
					gunAnimator.SetTrigger("Fire");
					gunAudio.PlayOneShot(noAmmoSFX);
				}
			}
		}

		public void ShootGunAndSync(bool heldByPlayer)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			Vector3 revolverPosition;
			Vector3 forward;
			if (!heldByPlayer)
			{
				revolverPosition = revolverRayPoint.position;
				forward = revolverRayPoint.forward;
			}
			else
			{
				revolverPosition = ((Component)base.playerHeldBy.gameplayCamera).transform.position - ((Component)base.playerHeldBy.gameplayCamera).transform.up * 0.45f;
				forward = ((Component)base.playerHeldBy.gameplayCamera).transform.forward;
			}
			ShootGun(revolverPosition, forward);
		}

		public IEnumerator FireDelay()
		{
			cantFire = true;
			yield return (object)new WaitForSeconds(0.2f);
			cantFire = false;
		}

		public void ShootGun(Vector3 revolverPosition, Vector3 revolverForward)
		{
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0435: Unknown result type (might be due to invalid IL or missing references)
			//IL_0782: Unknown result type (might be due to invalid IL or missing references)
			//IL_080d: Unknown result type (might be due to invalid IL or missing references)
			//IL_081f: Unknown result type (might be due to invalid IL or missing references)
			//IL_086c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0876: Unknown result type (might be due to invalid IL or missing references)
			//IL_0540: Unknown result type (might be due to invalid IL or missing references)
			//IL_0552: Unknown result type (might be due to invalid IL or missing references)
			//IL_0928: Unknown result type (might be due to invalid IL or missing references)
			//IL_0932: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_08e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0575: Unknown result type (might be due to invalid IL or missing references)
			//IL_057a: Unknown result type (might be due to invalid IL or missing references)
			//IL_057f: Unknown result type (might be due to invalid IL or missing references)
			//IL_059f: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_063a: Unknown result type (might be due to invalid IL or missing references)
			//IL_063f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0651: Unknown result type (might be due to invalid IL or missing references)
			//IL_0663: Unknown result type (might be due to invalid IL or missing references)
			//IL_070a: Unknown result type (might be due to invalid IL or missing references)
			CentipedeAI[] array = Object.FindObjectsByType<CentipedeAI>((FindObjectsSortMode)0);
			FlowerSnakeEnemy[] array2 = Object.FindObjectsByType<FlowerSnakeEnemy>((FindObjectsSortMode)0);
			for (int i = 0; i < array.Length; i++)
			{
				if ((Object)(object)array[i].clingingToPlayer == (Object)(object)base.playerHeldBy)
				{
					((EnemyAI)array[i]).HitEnemy(5, base.playerHeldBy, true, -1);
				}
			}
			for (int j = 0; j < array2.Length; j++)
			{
				if ((Object)(object)array2[j].clingingToPlayer == (Object)(object)base.playerHeldBy)
				{
					((EnemyAI)array2[j]).HitEnemy(5, base.playerHeldBy, true, -1);
				}
			}
			((MonoBehaviour)this).StartCoroutine(FireDelay());
			bool flag = false;
			if (base.isHeld && (Object)(object)base.playerHeldBy != (Object)null && (Object)(object)base.playerHeldBy == (Object)(object)GameNetworkManager.Instance.localPlayerController)
			{
				base.playerHeldBy.playerBodyAnimator.SetTrigger("ShootRevolver");
				flag = true;
			}
			gunAnimator.SetTrigger("Fire");
			RoundManager.PlayRandomClip(gunShootAudio, gunShootSFX.ToArray(), true, 1f, 1840, 1000);
			WalkieTalkie.TransmitOneShotAudio(gunShootAudio, gunShootSFX[0], 1f);
			gunShootParticle.Play(true);
			ammosLoaded = Mathf.Clamp(ammosLoaded - 1, 0, 6);
			foreach (MeshRenderer revolverAmmo in revolverAmmos)
			{
				((Renderer)revolverAmmo).enabled = false;
			}
			if (ammosLoaded > 0)
			{
				for (int k = 0; k <= ammosLoaded - 1; k++)
				{
		

BepInEx/plugins/americanompany/RemoveCameraFilter.dll

Decompiled 2 years ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using UnityEngine;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("RemoveCameraFilter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RemoveCameraFilter")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("8119b276-5c2c-446f-a321-72045794dc73")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace RemoveCameraFilter;

[BepInPlugin("kruumy.RemoveCameraFilter", "Remove Camera Filter", "1.0.0")]
public class Main : BaseUnityPlugin
{
	private void Awake()
	{
		SceneManager.activeSceneChanged += SceneManager_activeSceneChanged;
	}

	private void SceneManager_activeSceneChanged(Scene arg0, Scene arg1)
	{
		Object[] array = Object.FindObjectsOfTypeAll(typeof(CustomPassVolume));
		foreach (Object obj in array)
		{
			CustomPassVolume val = (CustomPassVolume)(object)((obj is CustomPassVolume) ? obj : null);
			if (val != null)
			{
				((Behaviour)val).enabled = false;
				val.isGlobal = false;
			}
		}
	}
}

BepInEx/plugins/americanompany/SilentLandmines.dll

Decompiled 2 years ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using SilentLandmines.Patches;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("SilentLandmines")]
[assembly: AssemblyDescription("Silences the occasional beeps of landmines, and suppresses the idle animation from playing.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SilentLandmines")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("FA3F219D-1CA1-475B-AF79-1933F0D7CD81")]
[assembly: AssemblyFileVersion("1.0.*")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.8768.38098")]
namespace SilentLandmines
{
	[BepInPlugin("Vee.SilentLandmines", "Vee's Silent Landmines", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		internal ManualLogSource Logger;

		private readonly Harmony _harmony = new Harmony("Vee.SilentLandmines");

		public static Plugin Instance { get; private set; }

		private void Awake()
		{
			if (!((Object)(object)Instance != (Object)null))
			{
				Instance = this;
				Logger = Logger.CreateLogSource("Vee.SilentLandmines");
				Logger.LogInfo((object)"Vee's Silent Landmines 1.0.0 has awakened.");
				_harmony.PatchAll(typeof(LandminePatch));
			}
		}
	}
	internal static class PluginData
	{
		internal const string ModGUID = "Vee.SilentLandmines";

		internal const string ModName = "Vee's Silent Landmines";

		internal const string ModVersion = "1.0.0";
	}
}
namespace SilentLandmines.Patches
{
	[HarmonyPatch(typeof(Landmine))]
	public class LandminePatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void SilenceLandmine(ref AudioSource ___mineAudio, ref AudioSource ___mineFarAudio, ref Animator ___mineAnimator)
		{
			((Behaviour)___mineAudio).enabled = false;
			((Behaviour)___mineFarAudio).enabled = false;
			___mineAnimator.speed = 0f;
			Plugin.Instance.Logger.LogDebug((object)"A landmine has been silenced.");
		}

		[HarmonyPatch("PressMineServerRpc")]
		[HarmonyPrefix]
		private static void RestoreLandmineAnimator(ref AudioSource ___mineAudio, ref AudioSource ___mineFarAudio, ref Animator ___mineAnimator)
		{
			___mineAnimator.speed = 1f;
			((Behaviour)___mineAudio).enabled = true;
			((Behaviour)___mineFarAudio).enabled = true;
		}
	}
}

BepInEx/plugins/americanompany/SnatchingBracken.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using GameNetcodeStuff;
using HarmonyLib;
using LethalConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using SnatchinBracken;
using SnatchinBracken.Patches;
using SnatchinBracken.Patches.data;
using SnatchingBracken;
using SnatchingBracken.NetcodePatcher;
using SnatchingBracken.Patches.dungeon;
using SnatchingBracken.Patches.network;
using SnatchingBracken.Patches.tasks;
using SnatchingBracken.Utils;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("SnatchingBracken")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SnatchingBracken")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("afcd9203-dbdd-4b28-85a1-fb12890f0d98")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace SnatchinBracken
{
	[BepInPlugin("Ovchinikov.SnatchinBracken.Main", "SnatchinBracken", "1.5.1")]
	public class SnatchinBrackenBase : BaseUnityPlugin
	{
		private const string modGUID = "Ovchinikov.SnatchinBracken.Main";

		private const string modName = "SnatchinBracken";

		private const string modVersion = "1.5.1";

		private static SnatchinBrackenBase _instance;

		private readonly Harmony harmony = new Harmony("Ovchinikov.SnatchinBracken.Main");

		private static SnatchinBrackenBase instance;

		internal ManualLogSource mls;

		public static SnatchinBrackenBase Instance => _instance;

		private void Awake()
		{
			if ((Object)(object)instance == (Object)null)
			{
				instance = this;
			}
			if ((Object)(object)_instance == (Object)null)
			{
				_instance = this;
			}
			else if ((Object)(object)_instance != (Object)(object)this)
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			mls = Logger.CreateLogSource("Ovchinikov.SnatchinBracken.Main");
			mls.LogInfo((object)"Enabling SnatchinBracken");
			InitializeConfigValues();
			harmony.PatchAll(typeof(SnatchinBrackenBase));
			harmony.PatchAll(typeof(BrackenAIPatch));
			harmony.PatchAll(typeof(EnemyAIPatch));
			harmony.PatchAll(typeof(TeleporterPatch));
			harmony.PatchAll(typeof(LandminePatch));
			harmony.PatchAll(typeof(TurretPatch));
			harmony.PatchAll(typeof(PlayerPatch));
			harmony.PatchAll(typeof(DungeonGenPatch));
			harmony.PatchAll(typeof(StartOfRound));
			mls.LogInfo((object)"Finished Enabling SnatchinBracken");
			patcher();
		}

		private void InitializeConfigValues()
		{
			mls.LogInfo((object)"Parsing SnatchinBracken config");
			try
			{
				if (AppDomain.CurrentDomain.GetAssemblies().Any((Assembly a) => a.GetName().Name == "LethalConfig"))
				{
					LethalConfigAPIHook.InitializeConfig();
				}
				else
				{
					loadConfig();
				}
			}
			catch
			{
				mls.LogInfo((object)"LethalConfigAPI not found, using built-in BepInEx config stuff.");
				loadConfig();
			}
			mls.LogInfo((object)"Config finished parsing");
		}

		private void patcher()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}

		private void loadConfig()
		{
			mls.LogInfo((object)"LethalConfigAPI not found, using built-in BepInEx config stuff.");
			ConfigEntry<bool> dropItemsOption = ((BaseUnityPlugin)this).Config.Bind<bool>("SnatchinBracken Settings", "Drop Items on Snatch", true, "Should players drop their items when a Bracken grabs them?");
			SharedData.Instance.DropItems = dropItemsOption.Value;
			dropItemsOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.DropItems = dropItemsOption.Value;
				}
			};
			ConfigEntry<bool> turretOption = ((BaseUnityPlugin)this).Config.Bind<bool>("SnatchinBracken Settings", "Ignore Turrets on Snatch", true, "Should players be ignored by turrets when dragged?");
			SharedData.Instance.IgnoreTurrets = turretOption.Value;
			turretOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.IgnoreTurrets = turretOption.Value;
				}
			};
			ConfigEntry<bool> allowDraggedTps = ((BaseUnityPlugin)this).Config.Bind<bool>("SnatchinBracken Settings", "Allow teleports to save dragged players", true, "Should players be able to be saved through teleportation?");
			SharedData.Instance.AllowTeleports = allowDraggedTps.Value;
			allowDraggedTps.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.AllowTeleports = allowDraggedTps.Value;
				}
			};
			ConfigEntry<bool> monstersIgnorePlayersOption = ((BaseUnityPlugin)this).Config.Bind<bool>("SnatchinBracken Settings", "Enemies Ignore Dragged Players", true, "Should players be ignored by other monsters while being dragged?");
			SharedData.Instance.MonstersIgnorePlayers = monstersIgnorePlayersOption.Value;
			monstersIgnorePlayersOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.MonstersIgnorePlayers = monstersIgnorePlayersOption.Value;
				}
			};
			ConfigEntry<bool> stuckForceKillOption = ((BaseUnityPlugin)this).Config.Bind<bool>("SnatchinBracken Settings", "Stuck Force Kill", false, "If enabled, Brackens will force kill when stuck at the same spot for at least 5 seconds.");
			SharedData.Instance.StuckForceKill = stuckForceKillOption.Value;
			stuckForceKillOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.StuckForceKill = stuckForceKillOption.Value;
				}
			};
			ConfigEntry<bool> brackenRoomOption = ((BaseUnityPlugin)this).Config.Bind<bool>("SnatchinBracken Settings", "Force Set Favorite Location To Bracken Room", true, "If enabled, Brackens' favorite locations will be set to the Bracken room. The room sometimes doesn't spawn, so please don't be alarmed if they don't take you there if this is enabled.");
			SharedData.Instance.BrackenRoom = brackenRoomOption.Value;
			brackenRoomOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.BrackenRoom = brackenRoomOption.Value;
				}
			};
			ConfigEntry<bool> mineOption = ((BaseUnityPlugin)this).Config.Bind<bool>("SnatchinBracken Settings", "Ignore Mines on Snatch", true, "Should players ignore Landmines while being dragged?");
			SharedData.Instance.IgnoreMines = mineOption.Value;
			mineOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.IgnoreMines = mineOption.Value;
				}
			};
			ConfigEntry<int> instaKillPercentEntry = ((BaseUnityPlugin)this).Config.Bind<int>("SnatchinBracken Settings", "Chance for Insta Kill", 0, "Percent chance for insta kill, 0 to disable.");
			SharedData.Instance.PercentChanceForInsta = instaKillPercentEntry.Value;
			instaKillPercentEntry.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.PercentChanceForInsta = instaKillPercentEntry.Value;
				}
			};
			ConfigEntry<bool> allowSecondsUntilAutoKill = ((BaseUnityPlugin)this).Config.Bind<bool>("SnatchinBracken Settings", "Allow Seconds Until Auto Kill", true, "If disabled, the Bracken won't kill based on time configured in \"Seconds Until Auto Kill\" (although may still kill if auto stuck is toggled off).");
			SharedData.Instance.KillBasedOffOfTime = allowSecondsUntilAutoKill.Value;
			allowSecondsUntilAutoKill.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.KillBasedOffOfTime = allowSecondsUntilAutoKill.Value;
				}
			};
			ConfigEntry<int> brackenKillTimeEntry = ((BaseUnityPlugin)this).Config.Bind<int>("SnatchinBracken Settings", "Seconds Until Auto Kill", 60, "Time in seconds until Bracken automatically kills when grabbed. Range: 1-60 seconds.");
			SharedData.Instance.KillAtTime = brackenKillTimeEntry.Value;
			brackenKillTimeEntry.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.KillAtTime = brackenKillTimeEntry.Value;
				}
			};
			ConfigEntry<int> brackenNextAttemptEntry = ((BaseUnityPlugin)this).Config.Bind<int>("SnatchinBracken Settings", "Seconds Until Next Attempt", 5, "Time in seconds until Bracken is allowed to take another victim.");
			SharedData.Instance.SecondsBeforeNextAttempt = brackenNextAttemptEntry.Value;
			brackenNextAttemptEntry.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.SecondsBeforeNextAttempt = brackenNextAttemptEntry.Value;
				}
			};
			ConfigEntry<bool> doDamageOnIntervalEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("SnatchinBracken Settings", "Do Gradual Damage", false, "Should players be hurt gradually while being dragged?");
			SharedData.Instance.DoDamageOnInterval = doDamageOnIntervalEntry.Value;
			doDamageOnIntervalEntry.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.DoDamageOnInterval = doDamageOnIntervalEntry.Value;
				}
			};
			ConfigEntry<int> damageDealtProgressively = ((BaseUnityPlugin)this).Config.Bind<int>("SnatchinBracken Settings", "Damage Dealt At Interval", 5, "This only applies if you have \"Do Gradual Damage\" enabled. While dragged, every second this configured amount of damage will be dealt to the player.");
			SharedData.Instance.DamageDealtAtInterval = damageDealtProgressively.Value;
			damageDealtProgressively.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.DamageDealtAtInterval = damageDealtProgressively.Value;
				}
			};
			ConfigEntry<bool> allowDistanceBasedKiller = ((BaseUnityPlugin)this).Config.Bind<bool>("SnatchinBracken Settings", "Allow Distance Until Auto Kill", true, "If disabled, the Bracken won't kill based on distance from favorite spot configured in \"Distance For Kill\" (although may still kill if auto stuck is toggled off).");
			SharedData.Instance.KillBasedOffOfDistance = allowDistanceBasedKiller.Value;
			allowDistanceBasedKiller.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.KillBasedOffOfDistance = allowDistanceBasedKiller.Value;
				}
			};
			ConfigEntry<int> distanceAutoKillerEntry = ((BaseUnityPlugin)this).Config.Bind<int>("SnatchinBracken Settings", "Distance For Kill", 1, "How far should the Bracken be from its favorite spot to initiate a kill?");
			SharedData.Instance.DistanceFromFavorite = distanceAutoKillerEntry.Value;
			distanceAutoKillerEntry.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.DistanceFromFavorite = distanceAutoKillerEntry.Value;
				}
			};
			ConfigEntry<bool> instaKillOption = ((BaseUnityPlugin)this).Config.Bind<bool>("SnatchinBracken Settings", "Instakill When Alone", false, "Should players be instantly killed if they're alone?");
			SharedData.Instance.InstantKillIfAlone = instaKillOption.Value;
			instaKillOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.InstantKillIfAlone = instaKillOption.Value;
				}
			};
		}
	}
}
namespace SnatchinBracken.Patches
{
	[HarmonyPatch(typeof(FlowermanAI))]
	internal class BrackenAIPatch
	{
		private const string modGUID = "Ovchinikov.SnatchinBracken.FlowermanAI";

		private static ManualLogSource mls;

		private static List<FlowermanAI> JustProcessed;

		static BrackenAIPatch()
		{
			JustProcessed = new List<FlowermanAI>();
			mls = Logger.CreateLogSource("Ovchinikov.SnatchinBracken.FlowermanAI");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAI), "ChooseFarthestNodeFromPosition")]
		private static void FarthestNodeAdjustment(EnemyAI __instance, ref Transform __result, Vector3 pos, bool avoidLineOfSight = false, int offset = 0, bool doAsync = false, int maxAsyncIterations = 50, bool capDistance = false)
		{
			//IL_0049: 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)
			FlowermanAI val = (FlowermanAI)(object)((__instance is FlowermanAI) ? __instance : null);
			if (val != null && Object.op_Implicit((Object)(object)SharedData.Instance.BrackenRoomPosition) && (Object)(object)__result != (Object)null && SharedData.Instance.BrackenRoom)
			{
				if (__instance.SetDestinationToPosition(SharedData.Instance.BrackenRoomPosition.position, true))
				{
					__result = SharedData.Instance.BrackenRoomPosition;
				}
				else if (!__instance.SetDestinationToPosition(__result.position, true))
				{
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void PostfixStart(FlowermanAI __instance)
		{
			if ((((NetworkBehaviour)__instance).IsHost || ((NetworkBehaviour)__instance).IsServer) && SharedData.Instance.StuckForceKill)
			{
				((Component)__instance).gameObject.AddComponent<FlowermanLocationTask>();
			}
			if ((Object)(object)SharedData.Instance.BrackenRoomPosition != (Object)null && SharedData.Instance.BrackenRoom)
			{
				((EnemyAI)__instance).favoriteSpot = SharedData.Instance.BrackenRoomPosition;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("KillPlayerAnimationServerRpc")]
		private static bool PrefixKillPlayerAnimationServerRpc(FlowermanAI __instance, int playerObjectId)
		{
			mls.LogInfo((object)"Running kill Player animation");
			if (!((NetworkBehaviour)__instance).IsHost && !((NetworkBehaviour)__instance).IsServer)
			{
				return true;
			}
			if ((Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if ((CountAlivePlayers() <= 1 && SharedData.Instance.InstantKillIfAlone) || RollForChance(SharedData.Instance.PercentChanceForInsta))
			{
				return true;
			}
			PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerObjectId];
			if ((Object)(object)val == (Object)null)
			{
				return true;
			}
			if (SharedData.Instance.BindedDrags.ContainsKey(__instance))
			{
				return false;
			}
			if (SharedData.Instance.BindedDrags.ContainsValue(val))
			{
				return false;
			}
			if (SharedData.Instance.LastGrabbedTimeStamp.ContainsKey(__instance) && Time.time - SharedData.Instance.LastGrabbedTimeStamp[__instance] <= SharedData.Instance.SecondsBeforeNextAttempt)
			{
				return false;
			}
			if (SharedData.Instance.DropItems)
			{
				val.DropAllHeldItemsAndSync();
			}
			else if (!SharedData.Instance.DropItems)
			{
				DropDoubleHandedItem(val);
			}
			FlowermanBinding component = ((Component)val).GetComponent<FlowermanBinding>();
			component.PrepForBindingServerRpc(playerObjectId, ((NetworkBehaviour)__instance).NetworkObjectId);
			component.BindPlayerServerRpc(playerObjectId, ((NetworkBehaviour)__instance).NetworkObjectId);
			component.UpdateFavoriteSpotServerRpc(playerObjectId, ((NetworkBehaviour)__instance).NetworkObjectId);
			component.MufflePlayerVoiceServerRpc(playerObjectId);
			component.MakeInsaneServerRpc(playerObjectId, 49.9f);
			FlowermanLocationTask component2 = ((Component)__instance).gameObject.GetComponent<FlowermanLocationTask>();
			if ((Object)(object)component2 != (Object)null && !SharedData.Instance.DoDamageOnInterval)
			{
				component2.StartCheckStuckCoroutine(__instance, val);
			}
			if (!SharedData.Instance.GradualDamageCoroutineStarted.ContainsKey(__instance) && SharedData.Instance.DoDamageOnInterval)
			{
				((MonoBehaviour)__instance).StartCoroutine(GeneralUtils.DoGradualDamage(__instance, val, 1f, SharedData.Instance.DamageDealtAtInterval));
				SharedData.Instance.GradualDamageCoroutineStarted[__instance] = true;
			}
			((EnemyAI)__instance).SwitchToBehaviourStateOnLocalClient(1);
			if (((NetworkBehaviour)__instance).IsServer)
			{
				((EnemyAI)__instance).SwitchToBehaviourState(1);
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(EnemyAI), "SetEnemyStunned")]
		private static void SetEnemyStunnedPrefix(EnemyAI __instance, bool setToStunned, float setToStunTime = 1f, PlayerControllerB setStunnedByPlayer = null)
		{
			FlowermanAI val = (FlowermanAI)(object)((__instance is FlowermanAI) ? __instance : null);
			if (val == null)
			{
				return;
			}
			if (SharedData.Instance.BindedDrags.ContainsKey(val))
			{
				PlayerControllerB valueSafe = GeneralExtensions.GetValueSafe<FlowermanAI, PlayerControllerB>(SharedData.Instance.BindedDrags, val);
				GeneralUtils.StopGradualDamageCoroutine(val, valueSafe);
			}
			if ((((NetworkBehaviour)val).IsHost || ((NetworkBehaviour)val).IsServer) && SharedData.Instance.BindedDrags.ContainsKey(val))
			{
				PlayerControllerB valueSafe2 = GeneralExtensions.GetValueSafe<FlowermanAI, PlayerControllerB>(SharedData.Instance.BindedDrags, val);
				int valueSafe3 = GeneralExtensions.GetValueSafe<PlayerControllerB, int>(SharedData.Instance.PlayerIDs, valueSafe2);
				SharedData.UpdateTimestampNow(val, valueSafe2);
				FlowermanLocationTask component = ((Component)val).gameObject.GetComponent<FlowermanLocationTask>();
				if ((Object)(object)component != (Object)null)
				{
					component.StopCheckStuckCoroutine();
				}
				GeneralUtils.ManuallyUnbindPlayer(val, valueSafe2);
				GeneralUtils.ManuallyDropPlayerOnHit(val, valueSafe2);
				FlowermanBinding component2 = ((Component)valueSafe2).GetComponent<FlowermanBinding>();
				if ((Object)(object)component2 != (Object)null)
				{
					component2.UnbindPlayerServerRpc(valueSafe3, ((NetworkBehaviour)__instance).NetworkObjectId);
					component2.ResetEntityStatesServerRpc(valueSafe3, ((NetworkBehaviour)__instance).NetworkObjectId);
					component2.UnmufflePlayerVoiceServerRpc(valueSafe3);
					component2.GiveChillPillServerRpc(valueSafe3);
				}
				JustProcessed.Add(val);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("HitEnemy")]
		private static void HitEnemyPostPatch(FlowermanAI __instance, int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
		{
			if (!((NetworkBehaviour)__instance).IsHost && !((NetworkBehaviour)__instance).IsServer && JustProcessed.Contains(__instance))
			{
				__instance.angerMeter = 0f;
				__instance.isInAngerMode = false;
				__instance.angerCheckInterval = 0f;
				JustProcessed.Remove(__instance);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("HitEnemy")]
		private static bool HitEnemyPrePatch(FlowermanAI __instance, int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
		{
			if (SharedData.Instance.BindedDrags.ContainsKey(__instance))
			{
				PlayerControllerB valueSafe = GeneralExtensions.GetValueSafe<FlowermanAI, PlayerControllerB>(SharedData.Instance.BindedDrags, __instance);
				GeneralUtils.StopGradualDamageCoroutine(__instance, valueSafe);
			}
			if (!((NetworkBehaviour)__instance).IsHost && !((NetworkBehaviour)__instance).IsServer)
			{
				return true;
			}
			if (SharedData.Instance.BindedDrags.ContainsKey(__instance))
			{
				mls.LogInfo((object)"Hit bracken, dropping");
				PlayerControllerB valueSafe2 = GeneralExtensions.GetValueSafe<FlowermanAI, PlayerControllerB>(SharedData.Instance.BindedDrags, __instance);
				int valueSafe3 = GeneralExtensions.GetValueSafe<PlayerControllerB, int>(SharedData.Instance.PlayerIDs, valueSafe2);
				SharedData.UpdateTimestampNow(__instance, valueSafe2);
				FlowermanLocationTask component = ((Component)__instance).gameObject.GetComponent<FlowermanLocationTask>();
				if ((Object)(object)component != (Object)null)
				{
					component.StopCheckStuckCoroutine();
				}
				GeneralUtils.ManuallyUnbindPlayer(__instance, valueSafe2);
				GeneralUtils.ManuallyDropPlayerOnHit(__instance, valueSafe2);
				FlowermanBinding component2 = ((Component)valueSafe2).gameObject.GetComponent<FlowermanBinding>();
				if ((Object)(object)component2 != (Object)null)
				{
					component2.UnbindPlayerServerRpc(valueSafe3, ((NetworkBehaviour)__instance).NetworkObjectId);
					component2.ResetEntityStatesServerRpc(valueSafe3, ((NetworkBehaviour)__instance).NetworkObjectId);
					component2.UnmufflePlayerVoiceServerRpc(valueSafe3);
					component2.GiveChillPillServerRpc(valueSafe3);
				}
				JustProcessed.Add(__instance);
			}
			return true;
		}

		private static int CountAlivePlayers()
		{
			return StartOfRound.Instance.livingPlayers;
		}

		[HarmonyPrefix]
		[HarmonyPatch("DropPlayerBody")]
		private static bool DropBodyPatch(FlowermanAI __instance)
		{
			if (!__instance.carryingPlayerBody || (Object)(object)__instance.bodyBeingCarried == (Object)null)
			{
				return false;
			}
			if (!SharedData.Instance.BindedDrags.ContainsKey(__instance))
			{
				return true;
			}
			PlayerControllerB val = SharedData.Instance.BindedDrags[__instance];
			if ((!((NetworkBehaviour)__instance).IsHost && !((NetworkBehaviour)__instance).IsServer) || (Object)(object)val == (Object)null)
			{
				return true;
			}
			if (!GeneralUtils.PrerequisiteKilling(__instance))
			{
				return false;
			}
			int valueSafe = GeneralExtensions.GetValueSafe<PlayerControllerB, int>(SharedData.Instance.PlayerIDs, val);
			if ((Object)(object)val == (Object)null)
			{
				SharedData.Instance.BindedDrags.Remove(__instance);
				return true;
			}
			if (!SharedData.Instance.DoDamageOnInterval)
			{
				val.inSpecialInteractAnimation = false;
				((Component)val).GetComponent<FlowermanBinding>().UnbindPlayerServerRpc(valueSafe, ((NetworkBehaviour)__instance).NetworkObjectId);
				FlowermanLocationTask component = ((Component)__instance).gameObject.GetComponent<FlowermanLocationTask>();
				if ((Object)(object)component != (Object)null)
				{
					component.StopCheckStuckCoroutine();
				}
				__instance.carryingPlayerBody = false;
				__instance.bodyBeingCarried = null;
				((EnemyAI)__instance).creatureAnimator.SetBool("carryingBody", false);
				GeneralUtils.FinishKillAnimationNormally(__instance, val, valueSafe);
			}
			return false;
		}

		private static bool RollForChance(int percentChance)
		{
			if (percentChance == 0)
			{
				return false;
			}
			if (percentChance < 0 || percentChance > 100)
			{
				throw new ArgumentOutOfRangeException("percentChance", "Percent chance must be between 0 and 100.");
			}
			int num = SharedData.RandomInstance.Next(1, 101);
			return num <= percentChance;
		}

		private static void DropDoubleHandedItem(PlayerControllerB player, bool itemsFall = true, bool disconnecting = false)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (player.twoHanded)
			{
				player.DiscardHeldObject(false, (NetworkObject)null, default(Vector3), true);
			}
		}
	}
	[HarmonyPatch(typeof(EnemyAI))]
	internal class EnemyAIPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void FlowermanStart(EnemyAI __instance)
		{
			FlowermanAI val = (FlowermanAI)(object)((__instance is FlowermanAI) ? __instance : null);
			if (val != null)
			{
				SharedData.Instance.FlowermanIDs[((NetworkBehaviour)__instance).NetworkObjectId] = val;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("Update")]
		private static void UpdatePatcher(EnemyAI __instance)
		{
			//IL_00b4: 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)
			FlowermanAI val = (FlowermanAI)(object)((__instance is FlowermanAI) ? __instance : null);
			if (val == null || !SharedData.Instance.BindedDrags.ContainsKey(val))
			{
				return;
			}
			PlayerControllerB valueSafe = GeneralExtensions.GetValueSafe<FlowermanAI, PlayerControllerB>(SharedData.Instance.BindedDrags, val);
			if ((Object)(object)valueSafe == (Object)null)
			{
				return;
			}
			if (valueSafe.isPlayerDead)
			{
				GeneralUtils.UnbindPlayerAndBracken(valueSafe, val);
				return;
			}
			UpdatePosition(val, valueSafe);
			if (!((NetworkBehaviour)__instance).IsHost && !((NetworkBehaviour)__instance).IsServer)
			{
				return;
			}
			int valueSafe2 = GeneralExtensions.GetValueSafe<PlayerControllerB, int>(SharedData.Instance.PlayerIDs, valueSafe);
			float num = SharedData.Instance.LastGrabbedTimeStamp[val];
			float num2 = Vector3.Distance(((Component)__instance).transform.position, __instance.favoriteSpot.position);
			if (((Time.time - num >= SharedData.Instance.KillAtTime && SharedData.Instance.KillBasedOffOfTime) || (num2 <= SharedData.Instance.DistanceFromFavorite && SharedData.Instance.KillBasedOffOfDistance)) && !SharedData.Instance.DoDamageOnInterval)
			{
				SharedData.UpdateTimestampNow(val, valueSafe);
				GeneralUtils.UnbindPlayerAndBracken(valueSafe, val);
				((Component)valueSafe).GetComponent<FlowermanBinding>().GiveChillPillServerRpc(valueSafe2);
				FlowermanLocationTask component = ((Component)__instance).gameObject.GetComponent<FlowermanLocationTask>();
				if ((Object)(object)component != (Object)null)
				{
					component.StopCheckStuckCoroutine();
				}
				GeneralUtils.FinishKillAnimationNormally(val, valueSafe, valueSafe2);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("MeetsStandardPlayerCollisionConditions")]
		private static bool OverrideCollisionCheck(EnemyAI __instance, Collider other, bool inKillAnimation = false, bool overrideIsInsideFactoryCheck = false)
		{
			if (!((NetworkBehaviour)__instance).IsHost)
			{
				return true;
			}
			FlowermanAI val = (FlowermanAI)(object)((__instance is FlowermanAI) ? __instance : null);
			if (val == null)
			{
				return true;
			}
			if (SharedData.Instance.LastGrabbedTimeStamp.ContainsKey(val))
			{
				if (Time.time - SharedData.Instance.LastGrabbedTimeStamp[val] <= SharedData.Instance.SecondsBeforeNextAttempt)
				{
					return false;
				}
				if (__instance.isEnemyDead)
				{
					return true;
				}
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component != (Object)null && !SharedData.Instance.BindedDrags.ContainsKey(val))
				{
					val.KillPlayerAnimationServerRpc((int)component.playerClientId);
				}
			}
			return true;
		}

		[HarmonyPrefix]
		[HarmonyPatch("TargetClosestPlayer")]
		private static bool ClosestPlayerPatch(FlowermanAI __instance)
		{
			if (!((NetworkBehaviour)__instance).IsHost && !((NetworkBehaviour)__instance).IsServer)
			{
				return true;
			}
			return !SharedData.Instance.BindedDrags.ContainsKey(__instance);
		}

		[HarmonyPrefix]
		[HarmonyPatch("PlayerIsTargetable")]
		private static bool PlayerIsTargetablePatch(EnemyAI __instance, PlayerControllerB playerScript, bool cannotBeInShip = false)
		{
			if (SharedData.Instance.MonstersIgnorePlayers)
			{
				FlowermanAI val = (FlowermanAI)(object)((__instance is FlowermanAI) ? __instance : null);
				if (val != null)
				{
					if (SharedData.Instance.LastGrabbedTimeStamp.ContainsKey(val) && Time.time - SharedData.Instance.LastGrabbedTimeStamp[val] <= SharedData.Instance.SecondsBeforeNextAttempt)
					{
						return false;
					}
					return !SharedData.Instance.BindedDrags.ContainsKey(val);
				}
				return !SharedData.Instance.BindedDrags.ContainsValue(playerScript);
			}
			return true;
		}

		private static void UpdatePosition(FlowermanAI __instance, PlayerControllerB player)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			float num = -0.8f;
			Vector3 position = ((Component)__instance).transform.position + ((Component)__instance).transform.forward * num;
			((Component)player).transform.position = position;
		}
	}
	[HarmonyPatch(typeof(Landmine))]
	internal class LandminePatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("OnTriggerEnter")]
		private static bool PrefixTriggerEntry(Landmine __instance, Collider other)
		{
			if (!((NetworkBehaviour)__instance).IsHost && !((NetworkBehaviour)__instance).IsServer)
			{
				return true;
			}
			if (!SharedData.Instance.IgnoreMines)
			{
				return true;
			}
			FlowermanAI componentInParent = ((Component)other).gameObject.GetComponentInParent<FlowermanAI>();
			if ((Object)(object)componentInParent != (Object)null && SharedData.Instance.BindedDrags.ContainsKey(componentInParent))
			{
				return false;
			}
			PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
			if ((Object)(object)component != (Object)null && SharedData.Instance.BindedDrags.ContainsValue(component) && !component.isPlayerDead)
			{
				return false;
			}
			return true;
		}

		[HarmonyPrefix]
		[HarmonyPatch("OnTriggerExit")]
		private static bool PostfixTriggerExit(Landmine __instance, Collider other)
		{
			if (!SharedData.Instance.IgnoreMines)
			{
				return true;
			}
			FlowermanAI componentInParent = ((Component)other).gameObject.GetComponentInParent<FlowermanAI>();
			if ((Object)(object)componentInParent != (Object)null && SharedData.Instance.BindedDrags.ContainsKey(componentInParent))
			{
				return false;
			}
			PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
			if ((Object)(object)component != (Object)null && SharedData.Instance.BindedDrags.ContainsValue(component) && !component.isPlayerDead)
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class TeleporterPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("TeleportPlayer")]
		private static bool PrefixTeleportPlayer(PlayerControllerB __instance, Vector3 pos, bool withRotation = false, float rot = 0f, bool allowInteractTrigger = false, bool enableController = true)
		{
			if (!((NetworkBehaviour)__instance).IsHost && !((NetworkBehaviour)__instance).IsServer)
			{
				return true;
			}
			if ((Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if (SharedData.Instance.BindedDrags.ContainsValue(__instance))
			{
				FlowermanAI val = GeneralUtils.SearchForCorrelatedFlowerman(__instance);
				if ((Object)(object)val != (Object)null)
				{
					if (!SharedData.Instance.AllowTeleports)
					{
						return false;
					}
					int playerId = SharedData.Instance.PlayerIDs[__instance];
					SharedData.UpdateTimestampNow(val, __instance);
					GeneralUtils.ManuallyUnbindPlayer(val, __instance);
					FlowermanBinding component = ((Component)__instance).gameObject.GetComponent<FlowermanBinding>();
					if ((Object)(object)component != (Object)null)
					{
						((Component)__instance).gameObject.GetComponent<FlowermanBinding>().ResetEntityStatesServerRpc(playerId, ((NetworkBehaviour)val).NetworkObjectId);
						((Component)__instance).gameObject.GetComponent<FlowermanBinding>().UnbindPlayerServerRpc(playerId, ((NetworkBehaviour)val).NetworkObjectId);
						((Component)__instance).gameObject.GetComponent<FlowermanBinding>().UnmufflePlayerVoiceServerRpc(playerId);
						((Component)__instance).gameObject.GetComponent<FlowermanBinding>().GiveChillPillServerRpc(playerId);
					}
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Turret))]
	internal class TurretPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("CheckForPlayersInLineOfSight")]
		private static void PostfixCheckForPlayersInLineOfSight(Turret __instance, ref PlayerControllerB __result, float radius, bool angleRangeCheck)
		{
			if (SharedData.Instance.IgnoreTurrets && (Object)(object)__result != (Object)null && SharedData.Instance.BindedDrags.ContainsValue(__result))
			{
				__result = null;
			}
		}
	}
}
namespace SnatchinBracken.Patches.data
{
	internal class SharedData
	{
		private static SharedData _instance;

		private static Random _random = new Random();

		public Dictionary<FlowermanAI, bool> GradualDamageCoroutineStarted = new Dictionary<FlowermanAI, bool>();

		public Dictionary<FlowermanAI, bool> InsanityCoroutineStarted = new Dictionary<FlowermanAI, bool>();

		public Dictionary<PlayerControllerB, float> DroppedTimestamp = new Dictionary<PlayerControllerB, float>();

		public static SharedData Instance => _instance ?? (_instance = new SharedData());

		public static Random RandomInstance => _random;

		public Dictionary<FlowermanAI, PlayerControllerB> BindedDrags { get; } = new Dictionary<FlowermanAI, PlayerControllerB>();


		public Dictionary<ulong, FlowermanAI> FlowermanIDs { get; } = new Dictionary<ulong, FlowermanAI>();


		public Dictionary<PlayerControllerB, int> PlayerIDs { get; } = new Dictionary<PlayerControllerB, int>();


		public Dictionary<int, PlayerControllerB> IDsToPlayerController { get; } = new Dictionary<int, PlayerControllerB>();


		public Dictionary<FlowermanAI, float> LastGrabbedTimeStamp { get; } = new Dictionary<FlowermanAI, float>();


		public bool DropItems { get; set; }

		public bool IgnoreTurrets { get; set; }

		public bool InstantKillIfAlone { get; set; }

		public bool IgnoreMines { get; set; }

		public bool AllowTeleports { get; set; }

		public bool DoDamageOnInterval { get; set; }

		public bool StuckForceKill { get; set; }

		public bool MonstersIgnorePlayers { get; set; }

		public bool BrackenRoom { get; set; }

		public bool KillBasedOffOfTime { get; set; }

		public float KillAtTime { get; set; }

		public float SecondsBeforeNextAttempt { get; set; }

		public int DamageDealtAtInterval { get; set; }

		public int PercentChanceForInsta { get; set; }

		public bool KillBasedOffOfDistance { get; set; }

		public float DistanceFromFavorite { get; set; }

		public Transform BrackenRoomPosition { get; set; }

		public static void UpdateTimestampNow(FlowermanAI flowermanAI, PlayerControllerB player)
		{
			Instance.LastGrabbedTimeStamp[flowermanAI] = Time.time;
			Instance.DroppedTimestamp[player] = Time.time;
		}

		public static void FlushDictionaries()
		{
			Instance.BindedDrags.Clear();
			Instance.FlowermanIDs.Clear();
			Instance.LastGrabbedTimeStamp.Clear();
			Instance.GradualDamageCoroutineStarted.Clear();
			Instance.DroppedTimestamp.Clear();
		}

		public static void GiveChillPillToAll()
		{
			foreach (KeyValuePair<FlowermanAI, PlayerControllerB> bindedDrag in Instance.BindedDrags)
			{
				int playerId = Instance.PlayerIDs[bindedDrag.Value];
				((Component)bindedDrag.Value).gameObject.GetComponent<FlowermanBinding>().GiveChillPillServerRpc(playerId);
			}
		}
	}
}
namespace SnatchingBracken
{
	internal class LethalConfigAPIHook
	{
		public static void InitializeConfig()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Expected O, but got Unknown
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Expected O, but got Unknown
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Expected O, but got Unknown
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Expected O, but got Unknown
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Expected O, but got Unknown
			//IL_0309: Unknown result type (might be due to invalid IL or missing references)
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0316: Unknown result type (might be due to invalid IL or missing references)
			//IL_031d: Expected O, but got Unknown
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0326: Expected O, but got Unknown
			//IL_0329: Expected O, but got Unknown
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_0338: Expected O, but got Unknown
			//IL_0399: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a0: Expected O, but got Unknown
			//IL_03fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0401: Unknown result type (might be due to invalid IL or missing references)
			//IL_0409: Unknown result type (might be due to invalid IL or missing references)
			//IL_0410: Expected O, but got Unknown
			//IL_0411: Unknown result type (might be due to invalid IL or missing references)
			//IL_0419: Expected O, but got Unknown
			//IL_041c: Expected O, but got Unknown
			//IL_0424: Unknown result type (might be due to invalid IL or missing references)
			//IL_042b: Expected O, but got Unknown
			//IL_0487: Unknown result type (might be due to invalid IL or missing references)
			//IL_048c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0494: Unknown result type (might be due to invalid IL or missing references)
			//IL_049b: Expected O, but got Unknown
			//IL_049c: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a4: Expected O, but got Unknown
			//IL_04a7: Expected O, but got Unknown
			//IL_04af: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b6: Expected O, but got Unknown
			//IL_0518: Unknown result type (might be due to invalid IL or missing references)
			//IL_051f: Expected O, but got Unknown
			//IL_057a: Unknown result type (might be due to invalid IL or missing references)
			//IL_057f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0587: Unknown result type (might be due to invalid IL or missing references)
			//IL_058e: Expected O, but got Unknown
			//IL_058f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0597: Expected O, but got Unknown
			//IL_059a: Expected O, but got Unknown
			//IL_05a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a9: Expected O, but got Unknown
			//IL_060a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0611: Expected O, but got Unknown
			//IL_066c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0671: Unknown result type (might be due to invalid IL or missing references)
			//IL_0679: Unknown result type (might be due to invalid IL or missing references)
			//IL_0680: Expected O, but got Unknown
			//IL_0681: Unknown result type (might be due to invalid IL or missing references)
			//IL_0689: Expected O, but got Unknown
			//IL_068c: Expected O, but got Unknown
			//IL_0694: Unknown result type (might be due to invalid IL or missing references)
			//IL_069b: Expected O, but got Unknown
			//IL_06fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0704: Expected O, but got Unknown
			LethalConfigManager.SetModDescription("A mod that alters the behavior of the Bracken. The Bracken pulls players into a new spot before performing a kill. DON'T CHANGE SETTINGS WHILE THE BRACKEN IS ACTIVELY GRABBING!");
			ConfigEntry<bool> dropItemsOption = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<bool>("SnatchinBracken Settings", "Drop Items on Snatch", true, "Should players drop their items when a Bracken grabs them?");
			BoolCheckBoxConfigItem val = new BoolCheckBoxConfigItem(dropItemsOption);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val);
			SharedData.Instance.DropItems = dropItemsOption.Value;
			dropItemsOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.DropItems = dropItemsOption.Value;
				}
			};
			ConfigEntry<bool> turretOption = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<bool>("SnatchinBracken Settings", "Ignore Turrets on Snatch", true, "Should players be ignored by turrets when dragged?");
			BoolCheckBoxConfigItem val2 = new BoolCheckBoxConfigItem(turretOption);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val2);
			SharedData.Instance.IgnoreTurrets = turretOption.Value;
			turretOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.IgnoreTurrets = turretOption.Value;
				}
			};
			ConfigEntry<bool> stuckForceKillOption = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<bool>("SnatchinBracken Settings", "Stuck Force Kill", false, "If enabled, Brackens will force kill when stuck at the same spot for at least 5 seconds.");
			BoolCheckBoxConfigItem val3 = new BoolCheckBoxConfigItem(stuckForceKillOption);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val3);
			SharedData.Instance.StuckForceKill = stuckForceKillOption.Value;
			stuckForceKillOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.StuckForceKill = stuckForceKillOption.Value;
				}
			};
			ConfigEntry<bool> brackenRoomOption = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<bool>("SnatchinBracken Settings", "Force Set Favorite Location To Bracken Room", true, "If enabled, Brackens' favorite locations will be set to the Bracken room. The room sometimes doesn't spawn, so please don't be alarmed if they don't take you there if this is enabled.");
			BoolCheckBoxConfigItem val4 = new BoolCheckBoxConfigItem(brackenRoomOption);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val4);
			SharedData.Instance.BrackenRoom = brackenRoomOption.Value;
			brackenRoomOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.BrackenRoom = brackenRoomOption.Value;
				}
			};
			ConfigEntry<bool> allowDraggedTps = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<bool>("SnatchinBracken Settings", "Allow teleports to save dragged players", true, "Should players be able to be saved through teleportation?");
			BoolCheckBoxConfigItem val5 = new BoolCheckBoxConfigItem(allowDraggedTps);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val5);
			SharedData.Instance.AllowTeleports = allowDraggedTps.Value;
			allowDraggedTps.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.AllowTeleports = allowDraggedTps.Value;
				}
			};
			ConfigEntry<bool> mineOption = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<bool>("SnatchinBracken Settings", "Ignore Mines on Snatch", true, "Should players ignore Landmines while being dragged?");
			BoolCheckBoxConfigItem val6 = new BoolCheckBoxConfigItem(mineOption);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val6);
			SharedData.Instance.IgnoreMines = mineOption.Value;
			mineOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.IgnoreMines = mineOption.Value;
				}
			};
			ConfigEntry<bool> monstersIgnorePlayersOption = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<bool>("SnatchinBracken Settings", "Enemies Ignore Dragged Players", true, "Should players be ignored by other monsters while being dragged?");
			BoolCheckBoxConfigItem val7 = new BoolCheckBoxConfigItem(monstersIgnorePlayersOption);
			SharedData.Instance.MonstersIgnorePlayers = monstersIgnorePlayersOption.Value;
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val7);
			monstersIgnorePlayersOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.MonstersIgnorePlayers = monstersIgnorePlayersOption.Value;
				}
			};
			ConfigEntry<int> instaKillPercentEntry = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<int>("SnatchinBracken Settings", "Chance for Insta Kill", 0, "Percent chance for insta kill, 0 to disable.");
			IntSliderOptions val8 = new IntSliderOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<int>)val8).Min = 0;
			((BaseRangeOptions<int>)val8).Max = 100;
			IntSliderOptions val9 = val8;
			IntSliderConfigItem val10 = new IntSliderConfigItem(instaKillPercentEntry, val9);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val10);
			SharedData.Instance.PercentChanceForInsta = instaKillPercentEntry.Value;
			instaKillPercentEntry.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.PercentChanceForInsta = instaKillPercentEntry.Value;
				}
			};
			ConfigEntry<bool> allowSecondsUntilAutoKill = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<bool>("SnatchinBracken Settings", "Allow Seconds Until Auto Kill", true, "If disabled, the Bracken won't kill based on time configured in \"Seconds Until Auto Kill\" (although may still kill if auto stuck is toggled off).");
			BoolCheckBoxConfigItem val11 = new BoolCheckBoxConfigItem(allowSecondsUntilAutoKill);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val11);
			SharedData.Instance.KillBasedOffOfTime = allowSecondsUntilAutoKill.Value;
			allowSecondsUntilAutoKill.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.KillBasedOffOfTime = allowSecondsUntilAutoKill.Value;
				}
			};
			ConfigEntry<int> brackenKillTimeEntry = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<int>("SnatchinBracken Settings", "Seconds Until Auto Kill", 15, "Time in seconds until Bracken automatically kills when grabbed. Range: 1-60 seconds.");
			IntSliderOptions val12 = new IntSliderOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<int>)val12).Min = 1;
			((BaseRangeOptions<int>)val12).Max = 60;
			IntSliderOptions val13 = val12;
			IntSliderConfigItem val14 = new IntSliderConfigItem(brackenKillTimeEntry, val13);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val14);
			SharedData.Instance.KillAtTime = brackenKillTimeEntry.Value;
			brackenKillTimeEntry.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.KillAtTime = brackenKillTimeEntry.Value;
				}
			};
			ConfigEntry<int> brackenNextAttemptEntry = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<int>("SnatchinBracken Settings", "Seconds Until Next Attempt", 5, "Time in seconds until Bracken is allowed to take another victim.");
			IntSliderOptions val15 = new IntSliderOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<int>)val15).Min = 1;
			((BaseRangeOptions<int>)val15).Max = 60;
			IntSliderOptions val16 = val15;
			IntSliderConfigItem val17 = new IntSliderConfigItem(brackenNextAttemptEntry, val16);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val17);
			SharedData.Instance.SecondsBeforeNextAttempt = brackenNextAttemptEntry.Value;
			brackenNextAttemptEntry.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.SecondsBeforeNextAttempt = brackenNextAttemptEntry.Value;
				}
			};
			ConfigEntry<bool> doDamageOnIntervalEntry = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<bool>("SnatchinBracken Settings", "Do Gradual Damage", false, "Should players be hurt gradually while being dragged?");
			BoolCheckBoxConfigItem val18 = new BoolCheckBoxConfigItem(doDamageOnIntervalEntry);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val18);
			SharedData.Instance.DoDamageOnInterval = doDamageOnIntervalEntry.Value;
			doDamageOnIntervalEntry.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.DoDamageOnInterval = doDamageOnIntervalEntry.Value;
				}
			};
			ConfigEntry<int> damageDealtProgressively = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<int>("SnatchinBracken Settings", "Damage Dealt At Interval", 5, "This only applies if you have \"Do Gradual Damage\" enabled. While dragged, every second this configured amount of damage will be dealt to the player. Keep in mind, players still regenerate in critical condition.");
			IntSliderOptions val19 = new IntSliderOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<int>)val19).Min = 1;
			((BaseRangeOptions<int>)val19).Max = 100;
			IntSliderOptions val20 = val19;
			IntSliderConfigItem val21 = new IntSliderConfigItem(damageDealtProgressively, val20);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val21);
			SharedData.Instance.DamageDealtAtInterval = damageDealtProgressively.Value;
			damageDealtProgressively.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.DamageDealtAtInterval = damageDealtProgressively.Value;
				}
			};
			ConfigEntry<bool> allowDistanceBasedKiller = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<bool>("SnatchinBracken Settings", "Allow Distance Until Auto Kill", true, "If disabled, the Bracken won't kill based on distance from favorite spot configured in \"Distance For Kill\" (although may still kill if auto stuck is toggled off).");
			BoolCheckBoxConfigItem val22 = new BoolCheckBoxConfigItem(allowDistanceBasedKiller);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val22);
			SharedData.Instance.KillBasedOffOfDistance = allowDistanceBasedKiller.Value;
			allowDistanceBasedKiller.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.KillBasedOffOfDistance = allowDistanceBasedKiller.Value;
				}
			};
			ConfigEntry<int> distanceAutoKillerEntry = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<int>("SnatchinBracken Settings", "Distance For Kill", 1, "How far should the Bracken be from its favorite spot to initiate a kill?");
			IntSliderOptions val23 = new IntSliderOptions
			{
				RequiresRestart = false
			};
			((BaseRangeOptions<int>)val23).Min = 1;
			((BaseRangeOptions<int>)val23).Max = 60;
			IntSliderOptions val24 = val23;
			IntSliderConfigItem val25 = new IntSliderConfigItem(distanceAutoKillerEntry, val24);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val25);
			SharedData.Instance.DistanceFromFavorite = distanceAutoKillerEntry.Value;
			distanceAutoKillerEntry.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.DistanceFromFavorite = distanceAutoKillerEntry.Value;
				}
			};
			ConfigEntry<bool> instaKillOption = ((BaseUnityPlugin)SnatchinBrackenBase.Instance).Config.Bind<bool>("SnatchinBracken Settings", "Instakill When Alone", false, "Should players be instantly killed if they're alone?");
			BoolCheckBoxConfigItem val26 = new BoolCheckBoxConfigItem(instaKillOption);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)val26);
			SharedData.Instance.InstantKillIfAlone = instaKillOption.Value;
			instaKillOption.SettingChanged += delegate
			{
				if (((NetworkBehaviour)HUDManager.Instance).IsHost || ((NetworkBehaviour)HUDManager.Instance).IsServer)
				{
					SharedData.Instance.InstantKillIfAlone = instaKillOption.Value;
				}
			};
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("IHittable.Hit")]
		private static bool HitOverride(PlayerControllerB __instance, int force, Vector3 hitDirection, PlayerControllerB playerWhoHit, bool playHitSFX = false)
		{
			if (SharedData.Instance.BindedDrags.ContainsValue(__instance) || (SharedData.Instance.DroppedTimestamp.ContainsKey(__instance) && SharedData.Instance.DroppedTimestamp[__instance] + 1f >= Time.time))
			{
				return false;
			}
			return true;
		}

		[HarmonyPrefix]
		[HarmonyPatch("Awake")]
		private static void onAwake(PlayerControllerB __instance)
		{
			if ((Object)(object)((Component)__instance).gameObject.GetComponent<FlowermanBinding>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<FlowermanBinding>();
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("Start")]
		private static void onStart(PlayerControllerB __instance)
		{
			if ((Object)(object)((Component)__instance).gameObject.GetComponent<FlowermanBinding>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<FlowermanBinding>();
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("KillPlayer")]
		private static void KillPlayerPatch(PlayerControllerB __instance, Vector3 bodyVelocity, bool spawnBody = true, CauseOfDeath causeOfDeath = 0, int deathAnimation = 0)
		{
			if (!SharedData.Instance.BindedDrags.ContainsValue(__instance))
			{
				return;
			}
			FlowermanAI val = GeneralUtils.SearchForCorrelatedFlowerman(__instance);
			if ((Object)(object)val != (Object)null)
			{
				int playerId = SharedData.Instance.PlayerIDs[__instance];
				FlowermanBinding component = ((Component)__instance).gameObject.GetComponent<FlowermanBinding>();
				if ((Object)(object)component != (Object)null)
				{
					component.ResetEntityStatesServerRpc(playerId, ((NetworkBehaviour)val).NetworkObjectId);
					component.GiveChillPillServerRpc(playerId);
					component.UnbindPlayerServerRpc(playerId, ((NetworkBehaviour)val).NetworkObjectId);
				}
				GeneralUtils.StopGradualDamageCoroutine(val, __instance);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("SetPlayerSanityLevel")]
		private static bool SetSanityLevel(PlayerControllerB __instance)
		{
			if (SharedData.Instance.BindedDrags.ContainsValue(__instance))
			{
				return false;
			}
			return true;
		}
	}
}
namespace SnatchingBracken.Utils
{
	internal class GeneralUtils
	{
		private static GeneralUtils instance;

		public static GeneralUtils Instance
		{
			get
			{
				if (instance == null)
				{
					instance = new GeneralUtils();
				}
				return instance;
			}
		}

		public static FlowermanAI SearchForCorrelatedFlowerman(PlayerControllerB player)
		{
			foreach (KeyValuePair<FlowermanAI, PlayerControllerB> bindedDrag in SharedData.Instance.BindedDrags)
			{
				if (bindedDrag.Value.actualClientId == player.actualClientId)
				{
					return bindedDrag.Key;
				}
			}
			return null;
		}

		public static void ManuallyUnbindPlayer(FlowermanAI flowerman, PlayerControllerB player)
		{
			int valueSafe = GeneralExtensions.GetValueSafe<PlayerControllerB, int>(SharedData.Instance.PlayerIDs, player);
			player.inSpecialInteractAnimation = false;
			flowerman.carryingPlayerBody = false;
			((EnemyAI)flowerman).creatureAnimator.SetBool("killing", false);
			((EnemyAI)flowerman).creatureAnimator.SetBool("carryingBody", false);
			flowerman.FinishKillAnimation(false);
			((EnemyAI)flowerman).stunnedByPlayer = null;
			((EnemyAI)flowerman).stunNormalizedTimer = 0f;
			((EnemyAI)flowerman).favoriteSpot = null;
		}

		public static void ManuallyDropPlayerOnHit(FlowermanAI __instance, PlayerControllerB player)
		{
			player.inSpecialInteractAnimation = false;
			player.inAnimationWithEnemy = null;
			__instance.carryingPlayerBody = false;
			((EnemyAI)__instance).creatureAnimator.SetBool("killing", false);
			((EnemyAI)__instance).creatureAnimator.SetBool("carryingBody", false);
			__instance.angerMeter = 0f;
			__instance.isInAngerMode = false;
			((EnemyAI)__instance).stunnedByPlayer = null;
			((EnemyAI)__instance).stunNormalizedTimer = 0f;
			__instance.evadeStealthTimer = 0.1f;
			__instance.timesThreatened = 0;
			__instance.FinishKillAnimation(false);
		}

		public static void RemoveDictionaryReferences(FlowermanAI __instance, PlayerControllerB player, int playerId)
		{
			SharedData.Instance.GradualDamageCoroutineStarted.Remove(__instance);
			FlowermanBinding component = ((Component)player).gameObject.GetComponent<FlowermanBinding>();
			component.ResetEntityStatesServerRpc(playerId, ((NetworkBehaviour)__instance).NetworkObjectId);
			component.GiveChillPillServerRpc(playerId);
			component.UnbindPlayerServerRpc(playerId, ((NetworkBehaviour)__instance).NetworkObjectId);
		}

		public static void StopGradualDamageCoroutine(FlowermanAI flowermanAI, PlayerControllerB player)
		{
			if (SharedData.Instance.GradualDamageCoroutineStarted.ContainsKey(flowermanAI))
			{
				((MonoBehaviour)flowermanAI).StopCoroutine(DoGradualDamage(flowermanAI, player, 1f, SharedData.Instance.DamageDealtAtInterval));
				SharedData.Instance.GradualDamageCoroutineStarted.Remove(flowermanAI);
			}
		}

		public static IEnumerator DoGradualDamage(FlowermanAI flowermanAI, PlayerControllerB player, float damageInterval, int damageAmount)
		{
			while (!player.isPlayerDead && (Object)(object)flowermanAI != (Object)null && SharedData.Instance.BindedDrags.ContainsKey(flowermanAI))
			{
				yield return (object)new WaitForSeconds(damageInterval);
				if (!player.isPlayerDead && (Object)(object)flowermanAI != (Object)null && SharedData.Instance.BindedDrags.ContainsKey(flowermanAI))
				{
					if (player.health - damageAmount <= 0)
					{
						StopGradualDamageCoroutine(flowermanAI, player);
						player.inSpecialInteractAnimation = false;
						int id2 = SharedData.Instance.PlayerIDs[player];
						FlowermanBinding flowermanBinding = ((Component)player).gameObject.GetComponent<FlowermanBinding>();
						if ((Object)(object)flowermanBinding != (Object)null)
						{
							flowermanBinding.UnbindPlayerServerRpc(id2, ((NetworkBehaviour)flowermanAI).NetworkObjectId);
							flowermanBinding.ResetEntityStatesServerRpc(id2, ((NetworkBehaviour)flowermanAI).NetworkObjectId);
							flowermanBinding.UnmufflePlayerVoiceServerRpc(id2);
							flowermanBinding.GiveChillPillServerRpc(id2);
						}
						FlowermanLocationTask task = ((Component)flowermanAI).gameObject.GetComponent<FlowermanLocationTask>();
						if ((Object)(object)task != (Object)null)
						{
							task.StopCheckStuckCoroutine();
						}
						flowermanAI.carryingPlayerBody = false;
						flowermanAI.bodyBeingCarried = null;
						((EnemyAI)flowermanAI).creatureAnimator.SetBool("carryingBody", false);
						FinishKillAnimationNormally(flowermanAI, player, id2);
					}
					else
					{
						int id = SharedData.Instance.PlayerIDs[player];
						((Component)player).GetComponent<FlowermanBinding>().DamagePlayerServerRpc(id, damageAmount);
					}
				}
				else
				{
					StopGradualDamageCoroutine(flowermanAI, player);
				}
			}
		}

		public static void UnbindPlayerAndBracken(PlayerControllerB player, FlowermanAI __instance)
		{
			if (SharedData.Instance.PlayerIDs.ContainsKey(player))
			{
				int valueSafe = GeneralExtensions.GetValueSafe<PlayerControllerB, int>(SharedData.Instance.PlayerIDs, player);
				player.inSpecialInteractAnimation = false;
				player.inAnimationWithEnemy = null;
				__instance.carryingPlayerBody = true;
				((EnemyAI)__instance).creatureAnimator.SetBool("killing", false);
				((EnemyAI)__instance).creatureAnimator.SetBool("carryingBody", false);
				((EnemyAI)__instance).stunnedByPlayer = null;
				((EnemyAI)__instance).stunNormalizedTimer = 0f;
				__instance.angerMeter = 0f;
				__instance.isInAngerMode = false;
				__instance.timesThreatened = 0;
				__instance.FinishKillAnimation(false);
				RemoveDictionaryReferences(__instance, player, valueSafe);
			}
		}

		public static bool PrerequisiteKilling(FlowermanAI flowerman)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			if (SharedData.Instance.LastGrabbedTimeStamp.ContainsKey(flowerman))
			{
				float num = SharedData.Instance.LastGrabbedTimeStamp[flowerman];
				float num2 = Vector3.Distance(((Component)flowerman).transform.position, ((EnemyAI)flowerman).favoriteSpot.position);
				if (Time.time - num >= SharedData.Instance.KillAtTime || num2 <= SharedData.Instance.DistanceFromFavorite)
				{
					return true;
				}
			}
			return false;
		}

		public static void FinishKillAnimationNormally(FlowermanAI __instance, PlayerControllerB playerControllerB, int playerId)
		{
			((EnemyAI)__instance).inSpecialAnimationWithPlayer = playerControllerB;
			playerControllerB.inSpecialInteractAnimation = true;
			__instance.KillPlayerAnimationClientRpc(playerId);
		}
	}
}
namespace SnatchingBracken.Patches.tasks
{
	public class FlowermanLocationTask : MonoBehaviour
	{
		private Coroutine checkStuckCoroutine;

		public void StartCheckStuckCoroutine(FlowermanAI flowermanAI, PlayerControllerB player)
		{
			checkStuckCoroutine = ((MonoBehaviour)this).StartCoroutine(CheckIfStuck(flowermanAI, player));
		}

		public void StopCheckStuckCoroutine()
		{
			if (checkStuckCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(checkStuckCoroutine);
				checkStuckCoroutine = null;
			}
		}

		private IEnumerator CheckIfStuck(FlowermanAI flowermanAI, PlayerControllerB player)
		{
			Vector3 lastPosition = ((Component)flowermanAI).transform.position;
			while ((Object)(object)flowermanAI != (Object)null)
			{
				yield return (object)new WaitForSeconds(5f);
				Vector3 currentPosition = ((Component)flowermanAI).transform.position;
				if (Vector3.Distance(lastPosition, currentPosition) <= 1f)
				{
					HandleStuckFlowerman(flowermanAI, player);
				}
				lastPosition = currentPosition;
			}
		}

		private void HandleStuckFlowerman(FlowermanAI flowermanAI, PlayerControllerB player)
		{
			StopCheckStuckCoroutine();
			int playerId = SharedData.Instance.PlayerIDs[player];
			SharedData.UpdateTimestampNow(flowermanAI, player);
			GeneralUtils.UnbindPlayerAndBracken(player, flowermanAI);
			((Component)player).GetComponent<FlowermanBinding>().GiveChillPillServerRpc(playerId);
			GeneralUtils.FinishKillAnimationNormally(flowermanAI, player, playerId);
		}
	}
}
namespace SnatchingBracken.Patches.ship
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("ShipLeave")]
		private static void PrefixShipLeave(StartOfRoundPatch __instance)
		{
			SharedData.Instance.BrackenRoomPosition = null;
			SharedData.FlushDictionaries();
			SharedData.GiveChillPillToAll();
		}

		[HarmonyPrefix]
		[HarmonyPatch("openingDoorsSequence")]
		private static void ClearPlayerSanityOnLand(StartOfRound __instance)
		{
			SharedData.GiveChillPillToAll();
		}
	}
}
namespace SnatchingBracken.Patches.network
{
	public class FlowermanBinding : NetworkBehaviour
	{
		[ServerRpc(RequireOwnership = false)]
		public void BindPlayerServerRpc(int playerId, ulong flowermanId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2841149136u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, flowermanId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2841149136u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					AddBindingsClientRpc(playerId, flowermanId);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void UnbindPlayerServerRpc(int playerId, ulong flowermanId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1240084643u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, flowermanId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1240084643u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					RemoveBindingsClientRpc(playerId, flowermanId);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void ResetEntityStatesServerRpc(int playerId, ulong flowermanId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3697084031u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, flowermanId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3697084031u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					ResetEntityStatesClientRpc(playerId, flowermanId);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void PrepForBindingServerRpc(int playerId, ulong flowermanId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3576432139u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, flowermanId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3576432139u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					PrepForBindingClientRpc(playerId, flowermanId);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void DamagePlayerServerRpc(int playerId, int damage)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1928701905u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, damage);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1928701905u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					DamagePlayerClientRpc(playerId, damage);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void UpdateFavoriteSpotServerRpc(int playerId, ulong flowermanId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3595148175u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, flowermanId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3595148175u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					UpdateFavoriteSpotClientRpc(playerId, flowermanId);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void MufflePlayerVoiceServerRpc(int playerId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2582248323u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2582248323u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					MufflePlayerVoiceClientRpc(playerId);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void UnmufflePlayerVoiceServerRpc(int playerId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3509983500u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3509983500u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					UnmufflePlayerVoiceClientRpc(playerId);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void MakeInsaneServerRpc(int playerId, float targetInsanity)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2823097549u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref targetInsanity, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2823097549u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					MakeInsaneClientRpc(playerId, targetInsanity);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void GiveChillPillServerRpc(int playerId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3204958366u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3204958366u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					GiveChillPillClientRpc(playerId);
				}
			}
		}

		[ClientRpc]
		public void UpdateFavoriteSpotClientRpc(int playerId, ulong flowermanId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1506678615u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, flowermanId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1506678615u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					PlayerControllerB val3 = StartOfRound.Instance.allPlayerScripts[playerId];
					FlowermanAI val4 = SharedData.Instance.FlowermanIDs[flowermanId];
					Transform favoriteSpot = ((!SharedData.Instance.BrackenRoom || !((Object)(object)SharedData.Instance.BrackenRoomPosition != (Object)null)) ? ((EnemyAI)val4).ChooseFarthestNodeFromPosition(((Component)val3).transform.position, false, 0, false, 50, false) : SharedData.Instance.BrackenRoomPosition);
					((EnemyAI)val4).favoriteSpot = favoriteSpot;
				}
			}
		}

		[ClientRpc]
		public void GiveChillPillClientRpc(int playerId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3079751162u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, playerId);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3079751162u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				PlayerControllerB val3 = StartOfRound.Instance.allPlayerScripts[playerId];
				if ((Object)(object)val3 == (Object)(object)StartOfRound.Instance.localPlayerController)
				{
					val3.insanityLevel = 0f;
					StartOfRound.Instance.fearLevelIncreasing = false;
					StartOfRound.Instance.fearLevel = 0f;
				}
			}
		}

		[ClientRpc]
		public void MakeInsaneClientRpc(int playerId, float targetInsanity)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(182933403u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, playerId);
				((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref targetInsanity, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 182933403u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				PlayerControllerB val3 = StartOfRound.Instance.allPlayerScripts[playerId];
				if ((Object)(object)val3 == (Object)(object)StartOfRound.Instance.localPlayerController)
				{
					val3.JumpToFearLevel(targetInsanity, true);
				}
			}
		}

		[ClientRpc]
		public void MufflePlayerVoiceClientRpc(int playerId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1450070789u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, playerId);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1450070789u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				PlayerControllerB val3 = StartOfRound.Instance.allPlayerScripts[playerId];
				if ((Object)(object)val3.currentVoiceChatAudioSource == (Object)null)
				{
					StartOfRound.Instance.RefreshPlayerVoicePlaybackObjects();
				}
				if ((Object)(object)val3.currentVoiceChatAudioSource != (Object)null)
				{
					((Component)val3.currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>().lowpassResonanceQ = 5f;
					OccludeAudio component = ((Component)val3.currentVoiceChatAudioSource).GetComponent<OccludeAudio>();
					component.overridingLowPass = true;
					component.lowPassOverride = 500f;
					val3.voiceMuffledByEnemy = true;
				}
			}
		}

		[ClientRpc]
		public void UnmufflePlayerVoiceClientRpc(int playerId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2434358873u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, playerId);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2434358873u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				PlayerControllerB val3 = StartOfRound.Instance.allPlayerScripts[playerId];
				if ((Object)(object)val3.currentVoiceChatAudioSource == (Object)null)
				{
					StartOfRound.Instance.RefreshPlayerVoicePlaybackObjects();
				}
				if ((Object)(object)val3.currentVoiceChatAudioSource != (Object)null)
				{
					((Component)val3.currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>().lowpassResonanceQ = 1f;
					OccludeAudio component = ((Component)val3.currentVoiceChatAudioSource).GetComponent<OccludeAudio>();
					component.overridingLowPass = false;
					component.lowPassOverride = 20000f;
					val3.voiceMuffledByEnemy = false;
				}
			}
		}

		[ClientRpc]
		public void DamagePlayerClientRpc(int playerId, int damage)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1193047885u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, damage);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1193047885u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					PlayerControllerB val3 = StartOfRound.Instance.allPlayerScripts[playerId];
					val3.DamagePlayer(damage, true, true, (CauseOfDeath)5, 0, false, default(Vector3));
				}
			}
		}

		[ClientRpc]
		public void ResetEntityStatesClientRpc(int playerId, ulong flowermanId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2270563105u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, flowermanId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2270563105u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					PlayerControllerB val3 = StartOfRound.Instance.allPlayerScripts[playerId];
					FlowermanAI val4 = SharedData.Instance.FlowermanIDs[flowermanId];
					val3.inSpecialInteractAnimation = false;
					val3.inAnimationWithEnemy = null;
					val4.carryingPlayerBody = false;
					((EnemyAI)val4).creatureAnimator.SetBool("killing", false);
					((EnemyAI)val4).creatureAnimator.SetBool("carryingBody", false);
					((EnemyAI)val4).stunnedByPlayer = null;
					((EnemyAI)val4).stunNormalizedTimer = 0f;
					val4.angerMeter = 0f;
					val4.isInAngerMode = false;
					val4.timesThreatened = 0;
					val4.inKillAnimation = false;
					val4.evadeStealthTimer = 0.1f;
					((EnemyAI)val4).inSpecialAnimationWithPlayer = null;
					((EnemyAI)val4).inSpecialAnimation = false;
					((EnemyAI)val4).SetClientCalculatingAI(false);
					((Behaviour)((EnemyAI)val4).agent).enabled = true;
					((EnemyAI)val4).favoriteSpot = null;
					val4.FinishKillAnimation(false);
				}
			}
		}

		[ClientRpc]
		public void PrepForBindingClientRpc(int playerId, ulong flowermanId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1304423344u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, flowermanId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1304423344u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					PlayerControllerB val3 = StartOfRound.Instance.allPlayerScripts[playerId];
					FlowermanAI val4 = SharedData.Instance.FlowermanIDs[flowermanId];
					((EnemyAI)val4).creatureAnimator.SetBool("killing", false);
					((EnemyAI)val4).creatureAnimator.SetBool("carryingBody", true);
					val4.carryingPlayerBody = true;
					val3.inSpecialInteractAnimation = true;
					val4.inKillAnimation = false;
					((EnemyAI)val4).targetPlayer = null;
				}
			}
		}

		[ClientRpc]
		public void AddBindingsClientRpc(int playerId, ulong flowermanId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1647441961u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, flowermanId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1647441961u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					PlayerControllerB val3 = StartOfRound.Instance.allPlayerScripts[playerId];
					FlowermanAI key = SharedData.Instance.FlowermanIDs[flowermanId];
					SharedData.Instance.BindedDrags[key] = val3;
					SharedData.Instance.PlayerIDs[val3] = playerId;
					SharedData.Instance.IDsToPlayerController[playerId] = val3;
					SharedData.Instance.LastGrabbedTimeStamp[key] = Time.time;
				}
			}
		}

		[ClientRpc]
		public void RemoveBindingsClientRpc(int playerId, ulong flowermanID)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2727274551u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, flowermanID);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2727274551u, val, (RpcDelivery)0);
	

BepInEx/plugins/americanompany/TheFiend.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using GameNetcodeStuff;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using TheFiend;
using TheFiend.NetcodePatcher;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Audio;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("TheFiend")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Your mod description.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("TheFiend")]
[assembly: AssemblyTitle("TheFiend")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
		NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>();
		NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>();
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public class TheFiendAI : EnemyAI
{
	public NetworkVariable<int> StateOfMind;

	public NetworkVariable<int> Funky = new NetworkVariable<int>(1, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	private Animator animator;

	public GameObject Main;

	public GameObject Neck;

	public GameObject Spine;

	public GameObject LeftHand;

	public GameObject RightHand;

	public MeshRenderer MapDot;

	public SkinnedMeshRenderer skinnedMesh;

	private float OldYScale;

	public Random enemyRandom;

	public AudioClip[] audioClips;

	public AudioClip StepClip;

	private AudioSource AS;

	private AudioSource AS2;

	private Vector3 FavSpot;

	private bool ResetNode;

	private bool EatingPlayer;

	public NetworkVariable<bool> Seeking;

	public NetworkVariable<bool> Invis;

	public NetworkVariable<bool> RageMode;

	public NetworkVariable<bool> GlobalCD;

	public NetworkVariable<bool> StandingMode;

	public NetworkVariable<bool> IsDying = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> LungApparatusWillRage = new NetworkVariable<bool>(global::TheFiend.TheFiend.WillRageAfterApparatus.Value, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public Quaternion OldR;

	public bool Step;

	private Vector3 LastPos;

	private Vector3 Node;

	private int LightTriggerTimes;

	private NavMeshPath path;

	private GameObject Head;

	private GameObject breakerBox;

	private RoundManager roundManager;

	public TimeOfDay timeOfDay;

	private GameObject LungApparatus;

	private Vector3 LungApparatusPosition;

	public GameObject TargetLook;

	public void Awake()
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Expected O, but got Unknown
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		path = new NavMeshPath();
		FavSpot = ((Component)this).transform.position;
		Head = ((Component)Neck.transform.Find("mixamorig:Head")).gameObject;
		OldR = Neck.transform.localRotation;
		animator = ((Component)this).GetComponent<Animator>();
		animator.Play("Idle");
		AS = ((Component)this).GetComponent<AudioSource>();
		AS2 = Spine.GetComponent<AudioSource>();
		try
		{
			breakerBox = ((Component)Object.FindObjectOfType<BreakerBox>()).gameObject;
		}
		catch
		{
			breakerBox = null;
		}
		roundManager = Object.FindObjectOfType<RoundManager>();
		timeOfDay = Object.FindObjectOfType<TimeOfDay>();
		((Renderer)MapDot).material.color = Color.red;
		AudioMixerGroup outputAudioMixerGroup = SoundManager.Instance.diageticMixer.FindMatchingGroups("SFX")[0];
		AS.outputAudioMixerGroup = outputAudioMixerGroup;
	}

	public override void Start()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//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)
		((EnemyAI)this).Start();
		OldYScale = Main.transform.position.y;
		enemyRandom = new Random(StartOfRound.Instance.randomMapSeed + base.thisEnemyIndex);
		AS.clip = audioClips[0];
		AS.loop = true;
		AS.Play();
		LungApparatus = GameObject.Find("LungApparatus(Clone)");
		if (Object.op_Implicit((Object)(object)LungApparatus))
		{
			LungApparatusPosition = LungApparatus.transform.position;
		}
	}

	public void FixedUpdate()
	{
		if (Step && !Invis.Value)
		{
			AS2.pitch = Random.Range(0.6f, 1f);
			AS2.PlayOneShot(StepClip);
		}
	}

	public void LateUpdate()
	{
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)TargetLook != (Object)null)
		{
			Neck.transform.LookAt(TargetLook.transform, Vector3.up);
		}
		else
		{
			Neck.transform.localRotation = OldR;
		}
	}

	public override void DoAIInterval()
	{
		//IL_024e: Unknown result type (might be due to invalid IL or missing references)
		//IL_025a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0283: Unknown result type (might be due to invalid IL or missing references)
		//IL_028f: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0412: Unknown result type (might be due to invalid IL or missing references)
		//IL_041e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0318: Unknown result type (might be due to invalid IL or missing references)
		//IL_0324: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_04cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0860: Unknown result type (might be due to invalid IL or missing references)
		//IL_0865: Unknown result type (might be due to invalid IL or missing references)
		//IL_09a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0877: Unknown result type (might be due to invalid IL or missing references)
		//IL_059b: Unknown result type (might be due to invalid IL or missing references)
		//IL_09f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_09f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_079a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0a28: Unknown result type (might be due to invalid IL or missing references)
		//IL_07e8: Unknown result type (might be due to invalid IL or missing references)
		((EnemyAI)this).DoAIInterval();
		if ((Object)(object)base.stunnedByPlayer != (Object)null)
		{
			AS.clip = audioClips[2];
			AS.loop = false;
			AS.Play();
			IsDying.Value = true;
			Object.Destroy((Object)(object)((Component)this).gameObject, 4f);
			base.stunnedByPlayer = null;
			((Renderer)skinnedMesh).enabled = false;
		}
		if (!IsDying.Value)
		{
			if (timeOfDay.hour >= 15)
			{
				Funky.Value = 2;
			}
			if (Seeking.Value)
			{
				AS.volume = 0f;
			}
			else if (StateOfMind.Value != 3)
			{
				AS.volume = global::TheFiend.TheFiend.Volume.Value;
			}
			if (Invis.Value)
			{
				((Renderer)skinnedMesh).enabled = false;
			}
			else
			{
				((Renderer)skinnedMesh).enabled = true;
			}
			if (Random.Range(1, 10000) == 1)
			{
				TeleportServerRpc();
			}
			if (Random.Range(1, 10000 / Funky.Value) == 1 && StateOfMind.Value == 3)
			{
				HideOnCellingServerRpc();
			}
			if (Random.Range(1, 10000 / Funky.Value) == 1 && !Seeking.Value)
			{
				ToggleSeekingServerRpc();
			}
			if (!GlobalCD.Value)
			{
				if (StateOfMind.Value < 3)
				{
					StateOfMind.Value = 0;
				}
				if (Object.op_Implicit((Object)(object)breakerBox) && !Seeking.Value)
				{
					GameObject gameObject = ((Component)breakerBox.transform.Find("Mesh")).gameObject;
					if (Vector3.Distance(Main.transform.position, gameObject.transform.position) <= 5f)
					{
						RaycastHit val = default(RaycastHit);
						if (Physics.Raycast(Neck.transform.position, gameObject.transform.position - Neck.transform.position, ref val, float.PositiveInfinity, ~LayerMask.GetMask(new string[1] { "Enmies" })) && Vector3.Distance(((RaycastHit)(ref val)).point, gameObject.transform.position) < 2f)
						{
							StateOfMind.Value = 4;
							TargetLook = gameObject;
							if (Vector3.Distance(Main.transform.position, gameObject.transform.position) <= 2f)
							{
								BreakerBoxBreakServerRpc();
							}
						}
						else
						{
							StateOfMind.Value = 0;
						}
					}
				}
				if (((EnemyAI)this).TargetClosestPlayer(100f, false, 70f))
				{
					TargetLook = ((Component)base.targetPlayer).gameObject;
					if (Object.op_Implicit((Object)(object)base.targetPlayer.currentlyHeldObject) && ((Object)((Component)base.targetPlayer.currentlyHeldObject).gameObject).name.Contains("FlashlightItem"))
					{
						GameObject gameObject2 = ((Component)((Component)base.targetPlayer.currentlyHeldObject).gameObject.transform.Find("Light")).gameObject;
						Light component = gameObject2.GetComponent<Light>();
						if (((Behaviour)component).enabled && Vector3.Distance(Head.transform.position, gameObject2.transform.position) <= 2.5f)
						{
							FearedServerRpc(TempRage: false, uselight: true);
							LightTriggerTimes++;
						}
					}
				}
				if (StateOfMind.Value == 3 && !GlobalCD.Value && !Seeking.Value && ((EnemyAI)this).TargetClosestPlayer(100f, false, 70f))
				{
					TargetLook = ((Component)base.targetPlayer).gameObject;
					if (Vector3.Distance(((Component)this).transform.position, ((Component)base.targetPlayer).gameObject.transform.position) <= 4f)
					{
						HideOnCellingServerRpc();
					}
				}
				if (!EatingPlayer && StateOfMind.Value <= 2 && !GlobalCD.Value && !StandingMode.Value)
				{
					if (((EnemyAI)this).TargetClosestPlayer(100f, false, 70f))
					{
						TargetLook = ((Component)base.targetPlayer).gameObject;
						ResetNode = true;
						if (base.agent.remainingDistance > 10f && !RageMode.Value)
						{
							OldYScale = Main.transform.position.y;
							if (!Seeking.Value)
							{
								StateOfMind.Value = 1;
								base.agent.speed = 3 + (Funky.Value - 1);
								animator.Play("Walk");
								if (CheckDoor())
								{
									if (Random.Range(1, 100) == 1 && StateOfMind.Value != 3)
									{
										HideOnCellingServerRpc();
									}
								}
								else if (Random.Range(1, 1000) == 1 && StateOfMind.Value != 3)
								{
									HideOnCellingServerRpc();
								}
							}
							else
							{
								base.agent.speed = 1f;
								animator.Play("Seeking");
								BreakDoorServerRpc();
							}
							if (Random.Range(1, global::TheFiend.TheFiend.FlickerRngChance.Value) == 1)
							{
								roundManager.FlickerLights(true, true);
							}
						}
						else if (!Seeking.Value)
						{
							StateOfMind.Value = 2;
							if ((Object)(object)((EnemyAI)this).CheckLineOfSightForPlayer(45f, 60, -1) != (Object)null)
							{
								base.targetPlayer.JumpToFearLevel(0.9f, true);
							}
							if (!RageMode.Value)
							{
								base.agent.speed = 9 * Funky.Value;
							}
							else
							{
								base.agent.speed = 20 * Funky.Value;
							}
							animator.Play("Run");
							BreakDoorServerRpc();
						}
						((EnemyAI)this).SetDestinationToPosition(((Component)base.targetPlayer).transform.position, false);
						if (Seeking.Value)
						{
							PlayerControllerB[] array = Object.FindObjectsOfType(typeof(PlayerControllerB)) as PlayerControllerB[];
							foreach (PlayerControllerB val2 in array)
							{
								if (val2.HasLineOfSightToPosition(Neck.transform.position, 45f, 60, -1f))
								{
									ToggleSeekingServerRpc();
									FearedServerRpc(TempRage: true);
									break;
								}
							}
						}
					}
					else
					{
						base.agent.speed = 3f;
						if (ResetNode)
						{
							WonderVectorServerRpc(60f);
							ResetNode = false;
						}
						if (Node != Vector3.zero)
						{
							((EnemyAI)this).SetDestinationToPosition(Node, false);
						}
						else
						{
							ResetNode = true;
						}
						if (base.agent.remainingDistance == 0f)
						{
							ResetNode = true;
						}
						if (Random.Range(1, 100) == 1)
						{
							ResetNode = true;
						}
						TargetLook = null;
					}
					if (!GlobalCD.Value)
					{
						if (base.agent.remainingDistance == 0f && StateOfMind.Value == 0 && !RageMode.Value)
						{
							animator.Play("Idle");
						}
						else if (!Seeking.Value && StateOfMind.Value == 1)
						{
							animator.Play("Walk");
						}
					}
				}
				if (StateOfMind.Value == 4 && Object.op_Implicit((Object)(object)TargetLook))
				{
					animator.Play("Walk");
					((EnemyAI)this).SetDestinationToPosition(TargetLook.transform.position, false);
				}
				if ((Object)(object)LungApparatus != (Object)null && LungApparatusWillRage.Value && !Invis.Value && LungApparatus.transform.position != LungApparatusPosition)
				{
					((Component)LungApparatus.transform.Find("Point Light")).gameObject.GetComponent<Light>().color = Color.red;
					((GrabbableObject)LungApparatus.GetComponent<LungProp>()).scrapValue = 300;
					LungApparatus = null;
					((MonoBehaviour)this).StartCoroutine(Rage());
				}
			}
		}
		((EnemyAI)this).SyncPositionToClients();
	}

	[ServerRpc]
	public void ToggleSeekingServerRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Invalid comparison between Unknown and I4
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Invalid comparison between Unknown and I4
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
		{
			if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
				return;
			}
			ServerRpcParams val = default(ServerRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2185458962u, val, (RpcDelivery)0);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2185458962u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			Seeking.Value = !Seeking.Value;
		}
	}

	private void OnTriggerStay(Collider collision)
	{
		//IL_0065: 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_0097: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)((Component)collision).gameObject.GetComponent<PlayerControllerB>()) && StateOfMind.Value != 3 && !GlobalCD.Value && !Invis.Value && !IsDying.Value && !EatingPlayer && Vector3.Distance(((Component)this).transform.position, ((Component)collision).gameObject.transform.position) < 4f)
		{
			GrabServerRpc(NetworkBehaviourReference.op_Implicit((NetworkBehaviour)(object)((Component)collision).gameObject.GetComponent<PlayerControllerB>()));
		}
	}

	[ServerRpc(RequireOwnership = false)]
	public void SceamServerRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2166844155u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2166844155u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				AS.Stop();
				AS.clip = audioClips[Random.Range(1, 2)];
				AS.loop = false;
				AS.Play();
				SceamClientRpc();
			}
		}
	}

	[ClientRpc]
	public void SceamClientRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3334696286u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3334696286u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				AS.Stop();
				AS.clip = audioClips[Random.Range(1, 2)];
				AS.loop = false;
				AS.Play();
			}
		}
	}

	[ServerRpc(RequireOwnership = false)]
	public void IdleSoundServerRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(579005519u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 579005519u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				AS.Stop();
				AS.clip = audioClips[0];
				AS.loop = true;
				AS.Play();
				IdleSoundClientRpc();
			}
		}
	}

	[ClientRpc]
	public void IdleSoundClientRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(469331619u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 469331619u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				AS.Stop();
				AS.clip = audioClips[0];
				AS.loop = true;
				AS.Play();
			}
		}
	}

	[ServerRpc(RequireOwnership = false)]
	public void GrabServerRpc(NetworkBehaviourReference PlayerControllerBRef)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2819942690u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref PlayerControllerBRef, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2819942690u, val, (RpcDelivery)0);
			}
			PlayerControllerB val3 = default(PlayerControllerB);
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && ((NetworkBehaviourReference)(ref PlayerControllerBRef)).TryGet<PlayerControllerB>(ref val3, (NetworkManager)null))
			{
				GrabClientRpc(NetworkObjectReference.op_Implicit(((Component)val3).gameObject));
			}
		}
	}

	[ClientRpc]
	public void GrabClientRpc(NetworkObjectReference networkObject)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2797167683u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(ref networkObject, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2797167683u, val, (RpcDelivery)0);
			}
			NetworkObject val3 = default(NetworkObject);
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && ((NetworkObjectReference)(ref networkObject)).TryGet(ref val3, (NetworkManager)null))
			{
				((MonoBehaviour)this).StartCoroutine(Grabbing(((Component)val3).gameObject));
			}
		}
	}

	public IEnumerator Grabbing(GameObject Player)
	{
		if (EatingPlayer || !Object.op_Implicit((Object)(object)Player))
		{
			yield break;
		}
		PlayerControllerB PCB = Player.GetComponent<PlayerControllerB>();
		if (PCB.health <= 50)
		{
			EatingPlayer = true;
			TargetLook = null;
			base.agent.speed = 0f;
			((EnemyAI)this).SetDestinationToPosition(((Component)base.agent).transform.position, false);
			float oldspeed = PCB.movementSpeed;
			PCB.movementSpeed = 0f;
			animator.Play("Grab");
			((Component)this).transform.LookAt(Player.transform.position, Vector3.up);
			((MonoBehaviour)this).StartCoroutine(RotatePlayerToMe(PCB));
			SceamServerRpc();
			yield return (object)new WaitForSeconds(1.7f);
			PCB.KillPlayer(Main.transform.forward * 30f, true, (CauseOfDeath)6, 1, default(Vector3));
			if (((NetworkBehaviour)PCB).IsOwner)
			{
				PCB.movementSpeed = oldspeed;
			}
			yield return (object)new WaitForSeconds(1f);
			IdleSoundServerRpc();
			animator.Play("Idle");
			yield return (object)new WaitForSeconds(3f);
			yield return (object)new WaitForSeconds(2f);
			RageMode.Value = false;
			if (Random.Range(1, 30) == 1)
			{
				HideOnCellingServerRpc();
			}
			EatingPlayer = false;
		}
		else
		{
			PCB.DamagePlayer(50, true, true, (CauseOfDeath)0, 0, false, default(Vector3));
			PCB.externalForceAutoFade += Main.transform.forward * 30f;
			animator.Play("Craw");
			GlobalCD.Value = true;
			PCB.movementAudio.PlayOneShot(audioClips[6], 1f);
			StartCooldown(1f);
		}
	}

	private IEnumerator RotatePlayerToMe(PlayerControllerB PCB)
	{
		if (Object.op_Implicit((Object)(object)PCB))
		{
			Vector3 Position = ((Component)this).transform.position - ((Component)PCB).gameObject.transform.position;
			while (PCB.health != 0)
			{
				PlayerSmoothLookAt(Position, PCB);
				yield return null;
			}
		}
	}

	private void PlayerSmoothLookAt(Vector3 newDirection, PlayerControllerB PCB)
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		((Component)PCB).gameObject.transform.rotation = Quaternion.Lerp(((Component)PCB).gameObject.transform.rotation, Quaternion.LookRotation(newDirection), Time.deltaTime * 5f);
	}

	[ServerRpc(RequireOwnership = false)]
	public void HideOnCellingServerRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: 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_011d: 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_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_019e: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
		{
			ServerRpcParams val = default(ServerRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(862535042u, val, (RpcDelivery)0);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 862535042u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
		{
			return;
		}
		if (StateOfMind.Value != 3)
		{
			if (StateOfMind.Value <= 3)
			{
				StateOfMind.Value = 3;
				LastPos = Main.transform.position;
				OldYScale = Main.transform.position.y;
				RaycastHit val3 = default(RaycastHit);
				Physics.Raycast(Main.transform.position, ((Component)this).transform.TransformDirection(Vector3.up), ref val3, float.PositiveInfinity, ~LayerMask.GetMask(new string[1] { "Enmies" }));
				animator.Play("Hide");
				AS.Stop();
				base.agent.speed = 0f;
				SetYLevelClientRpc(((RaycastHit)(ref val3)).point.y);
				((Renderer)MapDot).enabled = false;
			}
		}
		else if (!StandingMode.Value)
		{
			((MonoBehaviour)this).StartCoroutine(Stand());
		}
	}

	[ClientRpc]
	public void SetYLevelClientRpc(float y)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3597756483u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref y, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3597756483u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				Main.transform.position = new Vector3(Main.transform.position.x, y, Main.transform.position.z);
			}
		}
	}

	public IEnumerator Stand()
	{
		StandingMode.Value = true;
		((Renderer)MapDot).enabled = true;
		Rigidbody rig = Main.AddComponent<Rigidbody>();
		rig.detectCollisions = false;
		while (Vector3.Distance(Main.transform.position, LastPos) > 1.5f)
		{
			yield return null;
		}
		Object.Destroy((Object)(object)rig);
		animator.Play("UnHide");
		yield return (object)new WaitForSeconds(0.2f);
		SetYLevelClientRpc(OldYScale);
		animator.Play("Idle");
		SceamServerRpc();
		yield return (object)new WaitForSeconds(2f);
		IdleSoundServerRpc();
		BreakDoorServerRpc();
		StateOfMind.Value = 1;
		StandingMode.Value = false;
	}

	[ServerRpc]
	public void BreakDoorServerRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Invalid comparison between Unknown and I4
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Invalid comparison between Unknown and I4
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_018d: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
		{
			if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
				return;
			}
			ServerRpcParams val = default(ServerRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2228961150u, val, (RpcDelivery)0);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2228961150u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
		{
			return;
		}
		try
		{
			DoorLock[] array = Object.FindObjectsOfType(typeof(DoorLock)) as DoorLock[];
			foreach (DoorLock val3 in array)
			{
				GameObject gameObject = ((Component)((Component)((Component)((Component)val3).transform.parent).transform.parent).transform.parent).gameObject;
				if (!Object.op_Implicit((Object)(object)gameObject.GetComponent<Rigidbody>()) && Vector3.Distance(((Component)this).transform.position, gameObject.transform.position) <= 4f)
				{
					NetworkObjectReference netObjRef = NetworkObjectReference.op_Implicit(gameObject);
					Vector3 val4 = ((Component)base.targetPlayer).transform.position - ((Component)this).transform.position;
					BashDoorClientRpc(netObjRef, ((Vector3)(ref val4)).normalized * 20f);
				}
			}
		}
		catch
		{
		}
	}

	[ClientRpc]
	public void BashDoorClientRpc(NetworkObjectReference netObjRef, Vector3 Position)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2581177773u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(ref netObjRef, default(ForNetworkSerializable));
				((FastBufferWriter)(ref val2)).WriteValueSafe(ref Position);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2581177773u, val, (RpcDelivery)0);
			}
			NetworkObject val3 = default(NetworkObject);
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && ((NetworkObjectReference)(ref netObjRef)).TryGet(ref val3, (NetworkManager)null))
			{
				GameObject gameObject = ((Component)val3).gameObject;
				Rigidbody val4 = gameObject.AddComponent<Rigidbody>();
				AudioSource val5 = gameObject.AddComponent<AudioSource>();
				val5.spatialBlend = 1f;
				val5.maxDistance = 60f;
				val5.rolloffMode = (AudioRolloffMode)1;
				val5.volume = 3f;
				((MonoBehaviour)this).StartCoroutine(TurnOffC(val4, 0.12f));
				val4.AddForce(Position, (ForceMode)1);
				val5.PlayOneShot(audioClips[3]);
			}
		}
	}

	public bool CheckDoor()
	{
		//IL_0041: 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)
		DoorLock[] array = Object.FindObjectsOfType(typeof(DoorLock)) as DoorLock[];
		foreach (DoorLock val in array)
		{
			GameObject gameObject = ((Component)((Component)((Component)val).transform.parent).transform.parent).gameObject;
			if (Vector3.Distance(((Component)this).transform.position, gameObject.transform.position) <= 4f)
			{
				return true;
			}
		}
		return false;
	}

	private IEnumerator TurnOffC(Rigidbody rigidbody, float time)
	{
		rigidbody.detectCollisions = false;
		yield return (object)new WaitForSeconds(time);
		rigidbody.detectCollisions = true;
		Object.Destroy((Object)(object)((Component)rigidbody).gameObject, 5f);
	}

	[ServerRpc(RequireOwnership = false)]
	public void FearedServerRpc(bool TempRage, bool uselight = false)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
		{
			ServerRpcParams val = default(ServerRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3886079065u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref TempRage, default(ForPrimitives));
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref uselight, default(ForPrimitives));
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3886079065u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && !EatingPlayer && !StandingMode.Value)
		{
			GlobalCD.Value = true;
			FearedClientRpc();
			((MonoBehaviour)this).StartCoroutine(CD(5f));
			float tempRage = 3f;
			if (uselight)
			{
				tempRage = LightTriggerTimes * 2;
			}
			if (TempRage)
			{
				((MonoBehaviour)this).StartCoroutine(SetTempRage(tempRage));
			}
		}
	}

	public IEnumerator Rage()
	{
		GlobalCD.Value = true;
		yield return (object)new WaitForSeconds(0.2f);
		animator.Play("Rage");
		PlayerControllerB[] array = Object.FindObjectsOfType(typeof(PlayerControllerB)) as PlayerControllerB[];
		foreach (PlayerControllerB player in array)
		{
			player.JumpToFearLevel(0.9f, true);
		}
		AS.maxDistance = 500f;
		AS.Stop();
		AS.clip = audioClips[5];
		AS.loop = false;
		AS.Play();
		yield return (object)new WaitForSeconds(9f);
		ToggleRageServerRpc(TheRageValue: true);
		AS.maxDistance = 30f;
		GlobalCD.Value = false;
		yield return (object)new WaitForSeconds(20f);
		ToggleRageServerRpc(TheRageValue: false);
	}

	[ServerRpc(RequireOwnership = false)]
	public void ToggleRageServerRpc(bool TheRageValue)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1019923705u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref TheRageValue, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1019923705u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				RageMode.Value = TheRageValue;
			}
		}
	}

	[ServerRpc(RequireOwnership = false)]
	public void TeleportServerRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_015a: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
		{
			ServerRpcParams val = default(ServerRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1623300671u, val, (RpcDelivery)0);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1623300671u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost) || Invis.Value)
		{
			return;
		}
		Invis.Value = true;
		List<PlayerControllerB> list = new List<PlayerControllerB>();
		PlayerControllerB[] array = Object.FindObjectsOfType(typeof(PlayerControllerB)) as PlayerControllerB[];
		foreach (PlayerControllerB val3 in array)
		{
			if (val3.isInsideFactory)
			{
				list.Add(val3);
			}
		}
		if (list.Count > 0)
		{
			((Component)this).transform.position = ((Component)list[Random.Range(1, list.Count)]).gameObject.transform.position;
		}
		GlobalCD.Value = true;
		((MonoBehaviour)this).StartCoroutine(CD(25f, UnInvis: true));
	}

	[ClientRpc]
	public void FearedClientRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3221369379u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3221369379u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				animator.Play("CoverFace");
				base.agent.speed = 0f;
				AS.Stop();
				AS.clip = audioClips[4];
				AS.loop = false;
				AS.Play();
			}
		}
	}

	public void StartCooldown(float time, bool UnInvis = false)
	{
		((MonoBehaviour)this).StartCoroutine(CD(time, UnInvis));
	}

	private IEnumerator CD(float time, bool UnInvis = false)
	{
		base.agent.speed = 0f;
		yield return (object)new WaitForSeconds(time);
		GlobalCD.Value = false;
		if (UnInvis)
		{
			Invis.Value = false;
		}
	}

	private IEnumerator StateMindCD(float time, int typenow)
	{
		yield return (object)new WaitForSeconds(time);
		StateOfMind.Value = typenow;
	}

	private IEnumerator SetTempRage(float time)
	{
		ToggleRageServerRpc(TheRageValue: true);
		yield return (object)new WaitForSeconds(time);
		ToggleRageServerRpc(TheRageValue: false);
	}

	[ServerRpc(RequireOwnership = false)]
	public void WonderVectorServerRpc(float Range)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
		{
			ServerRpcParams val = default(ServerRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2540260648u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref Range, default(ForPrimitives));
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2540260648u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			Vector3 val3 = ((Component)this).transform.position + new Vector3(Random.Range(0f - Range, Range), 0f, Random.Range(0f - Range, Range));
			if (base.agent.CalculatePath(val3, path))
			{
				Node = val3;
			}
			else
			{
				Node = Vector3.zero;
			}
		}
	}

	[ServerRpc]
	public void BreakerBoxBreakServerRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Invalid comparison between Unknown and I4
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Invalid comparison between Unknown and I4
		//IL_0121: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
		{
			if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
				return;
			}
			ServerRpcParams val = default(ServerRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(180009697u, val, (RpcDelivery)0);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 180009697u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && !Object.op_Implicit((Object)(object)breakerBox.GetComponent<Rigidbody>()))
		{
			BreakerBoxBreakClientRpc(NetworkObjectReference.op_Implicit(breakerBox));
		}
	}

	[ClientRpc]
	public void BreakerBoxBreakClientRpc(NetworkObjectReference networkObjectReference)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Invalid comparison between Unknown and I4
		//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_014b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: 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_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_0163: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(4033774285u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(ref networkObjectReference, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4033774285u, val, (RpcDelivery)0);
			}
			NetworkObject val3 = default(NetworkObject);
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && ((NetworkObjectReference)(ref networkObjectReference)).TryGet(ref val3, (NetworkManager)null))
			{
				GameObject gameObject = ((Component)val3).gameObject;
				((Component)((Component)gameObject.transform.Find("Mesh")).transform.Find("PowerBoxDoor")).gameObject.AddComponent<Rigidbody>();
				Rigidbody val4 = gameObject.AddComponent<Rigidbody>();
				((MonoBehaviour)this).StartCoroutine(TurnOffC(val4, 0.1f));
				Vector3 val5 = Neck.transform.position - ((Component)this).transform.position;
				val4.AddForce(((Vector3)(ref val5)).normalized * 15f, (ForceMode)1);
				gameObject.GetComponent<AudioSource>().PlayOneShot(audioClips[3]);
				Object.Destroy((Object)(object)gameObject, 5f);
				gameObject = null;
				roundManager.PowerSwitchOffClientRpc();
				((MonoBehaviour)this).StartCoroutine(StateMindCD(1f, 0));
				animator.Play("Grab");
			}
		}
	}

	protected override void __initializeVariables()
	{
		if (StateOfMind == null)
		{
			throw new Exception("TheFiendAI.StateOfMind cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)StateOfMind).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)StateOfMind, "StateOfMind");
		((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)StateOfMind);
		if (Funky == null)
		{
			throw new Exception("TheFiendAI.Funky cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)Funky).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)Funky, "Funky");
		((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)Funky);
		if (Seeking == null)
		{
			throw new Exception("TheFiendAI.Seeking cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)Seeking).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)Seeking, "Seeking");
		((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)Seeking);
		if (Invis == null)
		{
			throw new Exception("TheFiendAI.Invis cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)Invis).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)Invis, "Invis");
		((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)Invis);
		if (RageMode == null)
		{
			throw new Exception("TheFiendAI.RageMode cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)RageMode).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)RageMode, "RageMode");
		((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)RageMode);
		if (GlobalCD == null)
		{
			throw new Exception("TheFiendAI.GlobalCD cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)GlobalCD).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)GlobalCD, "GlobalCD");
		((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)GlobalCD);
		if (StandingMode == null)
		{
			throw new Exception("TheFiendAI.StandingMode cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)StandingMode).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)StandingMode, "StandingMode");
		((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)StandingMode);
		if (IsDying == null)
		{
			throw new Exception("TheFiendAI.IsDying cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)IsDying).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)IsDying, "IsDying");
		((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)IsDying);
		if (LungApparatusWillRage == null)
		{
			throw new Exception("TheFiendAI.LungApparatusWillRage cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)LungApparatusWillRage).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)LungApparatusWillRage, "LungApparatusWillRage");
		((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)LungApparatusWillRage);
		((EnemyAI)this).__initializeVariables();
	}

	[RuntimeInitializeOnLoadMethod]
	internal static void InitializeRPCS_TheFiendAI()
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Expected O, but got Unknown
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Expected O, but got Unknown
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Expected O, but got Unknown
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Expected O, but got Unknown
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: Expected O, but got Unknown
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Expected O, but got Unknown
		//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: Expected O, but got Unknown
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_010e: Expected O, but got Unknown
		//IL_011f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0129: Expected O, but got Unknown
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Expected O, but got Unknown
		//IL_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Expected O, but got Unknown
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_017a: Expected O, but got Unknown
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0195: Expected O, but got Unknown
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b0: Expected O, but got Unknown
		//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cb: Expected O, but got Unknown
		//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e6: Expected O, but got Unknown
		NetworkManager.__rpc_func_table.Add(2185458962u, new RpcReceiveHandler(__rpc_handler_2185458962));
		NetworkManager.__rpc_func_table.Add(2166844155u, new RpcReceiveHandler(__rpc_handler_2166844155));
		NetworkManager.__rpc_func_table.Add(3334696286u, new RpcReceiveHandler(__rpc_handler_3334696286));
		NetworkManager.__rpc_func_table.Add(579005519u, new RpcReceiveHandler(__rpc_handler_579005519));
		NetworkManager.__rpc_func_table.Add(469331619u, new RpcReceiveHandler(__rpc_handler_469331619));
		NetworkManager.__rpc_func_table.Add(2819942690u, new RpcReceiveHandler(__rpc_handler_2819942690));
		NetworkManager.__rpc_func_table.Add(2797167683u, new RpcReceiveHandler(__rpc_handler_2797167683));
		NetworkManager.__rpc_func_table.Add(862535042u, new RpcReceiveHandler(__rpc_handler_862535042));
		NetworkManager.__rpc_func_table.Add(3597756483u, new RpcReceiveHandler(__rpc_handler_3597756483));
		NetworkManager.__rpc_func_table.Add(2228961150u, new RpcReceiveHandler(__rpc_handler_2228961150));
		NetworkManager.__rpc_func_table.Add(2581177773u, new RpcReceiveHandler(__rpc_handler_2581177773));
		NetworkManager.__rpc_func_table.Add(3886079065u, new RpcReceiveHandler(__rpc_handler_3886079065));
		NetworkManager.__rpc_func_table.Add(1019923705u, new RpcReceiveHandler(__rpc_handler_1019923705));
		NetworkManager.__rpc_func_table.Add(1623300671u, new RpcReceiveHandler(__rpc_handler_1623300671));
		NetworkManager.__rpc_func_table.Add(3221369379u, new RpcReceiveHandler(__rpc_handler_3221369379));
		NetworkManager.__rpc_func_table.Add(2540260648u, new RpcReceiveHandler(__rpc_handler_2540260648));
		NetworkManager.__rpc_func_table.Add(180009697u, new RpcReceiveHandler(__rpc_handler_180009697));
		NetworkManager.__rpc_func_table.Add(4033774285u, new RpcReceiveHandler(__rpc_handler_4033774285));
	}

	private static void __rpc_handler_2185458962(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: 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_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Invalid comparison between Unknown and I4
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
		{
			if ((int)networkManager.LogLevel <= 1)
			{
				Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
			}
		}
		else
		{
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((TheFiendAI)(object)target).ToggleSeekingServerRpc();
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_2166844155(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((TheFiendAI)(object)target).SceamServerRpc();
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_3334696286(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			target.__rpc_exec_stage = (__RpcExecStage)2;
			((TheFiendAI)(object)target).SceamClientRpc();
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_579005519(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((TheFiendAI)(object)target).IdleSoundServerRpc();
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_469331619(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			target.__rpc_exec_stage = (__RpcExecStage)2;
			((TheFiendAI)(object)target).IdleSoundClientRpc();
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_2819942690(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			NetworkBehaviourReference playerControllerBRef = default(NetworkBehaviourReference);
			((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref playerControllerBRef, default(ForNetworkSerializable));
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((TheFiendAI)(object)target).GrabServerRpc(playerControllerBRef);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_2797167683(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			NetworkObjectReference networkObject = default(NetworkObjectReference);
			((FastBufferReader)(ref reader)).ReadValueSafe<NetworkObjectReference>(ref networkObject, default(ForNetworkSerializable));
			target.__rpc_exec_stage = (__RpcExecStage)2;
			((TheFiendAI)(object)target).GrabClientRpc(networkObject);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_862535042(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((TheFiendAI)(object)target).HideOnCellingServerRpc();
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_3597756483(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			float yLevelClientRpc = default(float);
			((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref yLevelClientRpc, default(ForPrimitives));
			target.__rpc_exec_stage = (__RpcExecStage)2;
			((TheFiendAI)(object)target).SetYLevelClientRpc(yLevelClientRpc);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_2228961150(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: 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_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Invalid comparison between Unknown and I4
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
		{
			if ((int)networkManager.LogLevel <= 1)
			{
				Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
			}
		}
		else
		{
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((TheFiendAI)(object)target).BreakDoorServerRpc();
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_2581177773(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: 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_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			NetworkObjectReference netObjRef = default(NetworkObjectReference);
			((FastBufferReader)(ref reader)).ReadValueSafe<NetworkObjectReference>(ref netObjRef, default(ForNetworkSerializable));
			Vector3 position = default(Vector3);
			((FastBufferReader)(ref reader)).ReadValueSafe(ref position);
			target.__rpc_exec_stage = (__RpcExecStage)2;
			((TheFiendAI)(object)target).BashDoorClientRpc(netObjRef, position);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_3886079065(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			bool tempRage = default(bool);
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref tempRage, default(ForPrimitives));
			bool uselight = default(bool);
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref uselight, default(ForPrimitives));
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((TheFiendAI)(object)target).FearedServerRpc(tempRage, uselight);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_1019923705(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			bool theRageValue = default(bool);
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref theRageValue, default(ForPrimitives));
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((TheFiendAI)(object)target).ToggleRageServerRpc(theRageValue);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_1623300671(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((TheFiendAI)(object)target).TeleportServerRpc();
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_3221369379(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			target.__rpc_exec_stage = (__RpcExecStage)2;
			((TheFiendAI)(object)target).FearedClientRpc();
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_2540260648(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			float range = default(float);
			((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref range, default(ForPrimitives));
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((TheFiendAI)(object)target).WonderVectorServerRpc(range);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_180009697(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: 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_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Invalid comparison between Unknown and I4
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
		{
			if ((int)networkManager.LogLevel <= 1)
			{
				Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
			}
		}
		else
		{
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((TheFiendAI)(object)target).BreakerBoxBreakServerRpc();
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_4033774285(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			NetworkObjectReference networkObjectReference = default(NetworkObjectReference);
			((FastBufferReader)(ref reader)).ReadValueSafe<NetworkObjectReference>(ref networkObjectReference, default(ForNetworkSerializable));
			target.__rpc_exec_stage = (__RpcExecStage)2;
			((TheFiendAI)(object)target).BreakerBoxBreakClientRpc(networkObjectReference);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	protected internal override string __getTypeName()
	{
		return "TheFiendAI";
	}
}
namespace TheFiend
{
	[BepInPlugin("com.TheFiend", "The Fiend", "0.0.0")]
	public class TheFiend : BaseUnityPlugin
	{
		public static TheFiend instance;

		public static string RoleCompanyFolder = "Assets/TheFiend/";

		public static AssetBundle bundle;

		public static ConfigEntry<int> SpawnChance;

		public static ConfigEntry<LevelTypes> Moon;

		public static ConfigEntry<int> FlickerRngChance;

		public static ConfigEntry<bool> WillRageAfterApparatus;

		public static ConfigEntry<float> Volume;

		private void Awake()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			ConfigFile val = new ConfigFile(Path.Combine(Paths.ConfigPath, "Fiend.cfg"), true);
			SpawnChance = val.Bind<int>("Fiend", "Spawn Weight", 30, new ConfigDescription("The Chance to spawn the fiend inside of the building", (AcceptableValueBase)null, Array.Empty<object>()));
			Moon = val.Bind<LevelTypes>("Fiend", "Moon", (LevelTypes)(-1), new ConfigDescription("What is the only moon it can spawn on. Only one VALUE at a time.", (AcceptableValueBase)null, Array.Empty<object>()));
			FlickerRngChance = val.Bind<int>("Fiend", "Flicker Chance", 1000, new ConfigDescription("This is a Random chance out of 1/1000 happening to a random player", (AcceptableValueBase)null, Array.Empty<object>()));
			WillRageAfterApparatus = val.Bind<bool>("Fiend", "Rage After Apparatus", true, new ConfigDescription("Trigger his rage mode if you remove the Apparatus.", (AcceptableValueBase)null, Array.Empty<object>()));
			Volume = val.Bind<float>("Fiend", "Volume", 1f, new ConfigDescription("Sounds as scream and idle sound, not step sounds", (AcceptableValueBase)null, Array.Empty<object>()));
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			instance = this;
			bundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "thefiend"));
			EnemyType val2 = bundle.LoadAsset<EnemyType>(RoleCompanyFolder + "TheFiend.asset");
			Enemies.RegisterEnemy(val2, SpawnChance.Value, Moon.Value, bundle.LoadAsset<TerminalNode>(RoleCompanyFolder + "TheFiendNode.asset"), bundle.LoadAsset<TerminalKeyword>(RoleCompanyFolder + "TheFiendKey.asset"));
			NetworkPrefabs.RegisterNetworkPrefab(val2.enemyPrefab);
			Utilities.FixMixerGroups(val2.enemyPrefab);
		}

		public void AddScrap(string Name, int Rare, LevelTypes level)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			Item val = bundle.LoadAsset<Item>(RoleCompanyFolder + Name + ".asset");
			NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
			Utilities.FixMixerGroups(val.spawnPrefab);
			Items.RegisterScrap(val, Rare, level);
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "TheFiend";

		public const string PLUGIN_NAME = "TheFiend";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace TheFiend.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}

BepInEx/plugins/americanompany/WeatherRegistry.dll

Decompiled 2 years ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ConsoleTables;
using HarmonyLib;
using LethalLib.Modules;
using LobbyCompatibility.Enums;
using LobbyCompatibility.Features;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using MrovLib;
using MrovLib.Events;
using Newtonsoft.Json;
using On;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.ProBuilder;
using WeatherRegistry.Events;
using WeatherRegistry.NetcodePatcher;
using WeatherRegistry.Patches;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: AssemblyCompany("WeatherRegistry")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A Weather API for Lethal Company.")]
[assembly: AssemblyFileVersion("0.1.25.0")]
[assembly: AssemblyInformationalVersion("0.1.25+120b2935fd3331a650c769e345630eaf934722d8")]
[assembly: AssemblyProduct("WeatherRegistry")]
[assembly: AssemblyTitle("WeatherRegistry")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/AndreyMrovol/LethalWeatherRegistry/")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
		NetworkVariableSerializationTypes.InitializeSerializer_FixedString<FixedString4096Bytes>();
		NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<FixedString4096Bytes>();
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace WeatherRegistry
{
	public class Rarity
	{
		private int _weight;

		public int Weight
		{
			get
			{
				return _weight;
			}
			set
			{
				_weight = Math.Clamp(value, 0, 10000);
			}
		}
	}
	public class NameRarity : Rarity
	{
		public string Name { get; set; }
	}
	public class LevelRarity : Rarity
	{
		public SelectableLevel Level { get; set; }
	}
	public class WeatherRarity : Rarity
	{
		public Weather Weather { get; set; }
	}
	internal abstract class ConfigHandler<T, CT> : ConfigHandler<T, CT>
	{
		public ConfigHandler(CT defaultValue, Weather weather, string configTitle, ConfigDescription configDescription = null)
		{
			((ConfigHandler<T, CT>)this).DefaultValue = defaultValue;
			((ConfigHandler<T, CT>)this).ConfigEntry = ConfigManager.configFile.Bind<CT>("Weather: " + ((Object)weather).name + ((weather.Origin != 0) ? $" ({weather.Origin})" : ""), configTitle, ((ConfigHandler<T, CT>)this).DefaultValue, configDescription);
		}
	}
	internal class LevelListConfigHandler : ConfigHandler<SelectableLevel[], string>
	{
		public override SelectableLevel[] Value => ConfigHelper.ConvertStringToLevels(((ConfigHandler<SelectableLevel[], string>)this).ConfigEntry.Value);

		public LevelListConfigHandler(string defaultValue, Weather weather, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, weather, configTitle, configDescription)
		{
		}
	}
	internal class LevelWeightsConfigHandler : ConfigHandler<LevelRarity[], string>
	{
		public override LevelRarity[] Value => ConfigHelper.ConvertStringToLevelRarities(((ConfigHandler<LevelRarity[], string>)this).ConfigEntry.Value);

		public LevelWeightsConfigHandler(string defaultValue, Weather weather, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, weather, configTitle, configDescription)
		{
		}
	}
	internal class WeatherWeightsConfigHandler : ConfigHandler<WeatherRarity[], string>
	{
		public override WeatherRarity[] Value => ConfigHelper.ConvertStringToWeatherWeights(((ConfigHandler<WeatherRarity[], string>)this).ConfigEntry.Value);

		public WeatherWeightsConfigHandler(string defaultValue, Weather weather, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, weather, configTitle, configDescription)
		{
		}
	}
	internal class IntegerConfigHandler : ConfigHandler<int, int>
	{
		public override int Value => ((ConfigHandler<int, int>)this).ConfigEntry.Value;

		public IntegerConfigHandler(int defaultValue, Weather weather, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, weather, configTitle, configDescription)
		{
		}
	}
	internal class FloatConfigHandler : ConfigHandler<float, float>
	{
		public override float Value => ((ConfigHandler<float, float>)this).ConfigEntry.Value;

		public FloatConfigHandler(float defaultValue, Weather weather, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, weather, configTitle, configDescription)
		{
		}
	}
	internal class StringConfigHandler : ConfigHandler<string, string>
	{
		public override string Value => ((ConfigHandler<string, string>)this).ConfigEntry.Value;

		public StringConfigHandler(string defaultValue, Weather weather, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, weather, configTitle, configDescription)
		{
		}
	}
	internal class ConfigHelper
	{
		private static Logger logger = new Logger("WeatherRegistry", ConfigManager.LogWeightResolving);

		private static Dictionary<string, Weather> _weathersDictionary = null;

		public static Dictionary<string, Weather> StringToWeather
		{
			get
			{
				if (_weathersDictionary != null)
				{
					return _weathersDictionary;
				}
				Dictionary<string, Weather> Weathers = new Dictionary<string, Weather>();
				WeatherManager.Weathers.ToList().ForEach(delegate(Weather weather)
				{
					Weathers.TryAdd(((Object)weather).name.ToLowerInvariant(), weather);
					Weathers.TryAdd(weather.Name.ToLowerInvariant(), weather);
					Weathers.TryAdd(GetAlphanumericName(weather).ToLowerInvariant(), weather);
				});
				_weathersDictionary = Weathers;
				return Weathers;
			}
			set
			{
				_weathersDictionary = value;
			}
		}

		public static Weather ResolveStringToWeather(string str)
		{
			return StringToWeather.GetValueOrDefault(str.ToLowerInvariant());
		}

		public static string GetNumberlessName(SelectableLevel level)
		{
			return StringResolver.GetNumberlessName(level);
		}

		public static string GetAlphanumericName(Weather weather)
		{
			Regex regex = new Regex("^[0-9]+|[-_/\\\\\\ ]");
			return new string(regex.Replace(weather.Name, ""));
		}

		public static string[] ConvertStringToArray(string str)
		{
			return (from s in str.Split(';')
				where !string.IsNullOrWhiteSpace(s)
				select s.Trim()).ToArray();
		}

		public static SelectableLevel[] ConvertStringToLevels(string str)
		{
			return StringResolver.ResolveStringToLevels(str);
		}

		public static NameRarity[] ConvertStringToRarities(string str)
		{
			string[] array = ConvertStringToArray(str);
			List<NameRarity> list = new List<NameRarity>();
			string[] array2 = array;
			foreach (string text in array2)
			{
				string[] array3 = text.Split(':');
				if (array3.Length == 2 && int.TryParse(array3[1], out var result))
				{
					list.Add(new NameRarity
					{
						Name = array3[0],
						Weight = result
					});
				}
			}
			return list.ToArray();
		}

		public static LevelRarity[] ConvertStringToLevelRarities(string str)
		{
			string[] array = ConvertStringToArray(str);
			List<LevelRarity> list = new List<LevelRarity>();
			string[] array2 = array;
			foreach (string text in array2)
			{
				string[] array3 = text.Split('@');
				if (array3.Length != 2 || !int.TryParse(array3[1], out var result))
				{
					continue;
				}
				SelectableLevel[] array4 = StringResolver.ResolveStringToLevels(array3[0]);
				SelectableLevel[] array5 = array4;
				foreach (SelectableLevel val in array5)
				{
					if (!((Object)(object)val == (Object)null))
					{
						list.Add(new LevelRarity
						{
							Level = val,
							Weight = result
						});
					}
				}
			}
			return list.ToArray();
		}

		public static WeatherRarity[] ConvertStringToWeatherWeights(string str)
		{
			string[] array = ConvertStringToArray(str);
			List<WeatherRarity> list = new List<WeatherRarity>();
			string[] array2 = array;
			foreach (string text in array2)
			{
				string[] array3 = text.Split('@');
				if (array3.Length == 2 && int.TryParse(array3[1], out var result))
				{
					Weather weather = ResolveStringToWeather(array3[0]);
					if (!((Object)(object)weather == (Object)null))
					{
						list.Add(new WeatherRarity
						{
							Weather = weather,
							Weight = result
						});
					}
				}
			}
			return list.ToArray();
		}
	}
	public class ConfigManager
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static Event <0>__StartupActions;

			public static EventHandler <1>__OnConfigChange;
		}

		internal static ConfigFile configFile;

		public static ConfigManager Instance { get; private set; }

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

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

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

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

		private static ConfigEntry<string> SunAnimatorBlacklist { get; set; }

		public static SelectableLevel[] SunAnimatorBlacklistLevels { get; internal set; }

		public static void Init(ConfigFile config)
		{
			Instance = new ConfigManager(config);
		}

		private ConfigManager(ConfigFile config)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			configFile = config;
			WeatherRegistryEvent setupFinished = EventManager.SetupFinished;
			object obj = <>O.<0>__StartupActions;
			if (obj == null)
			{
				Event val = StartupActions;
				<>O.<0>__StartupActions = val;
				obj = (object)val;
			}
			((CustomEvent)setupFinished).AddListener((Event)obj);
			LogWeatherChanges = configFile.Bind<bool>("|Debugging", "Log Weather Changes", true, "Log weather changes to console");
			LogStartup = configFile.Bind<bool>("|Debugging", "Log Startup", true, "Log startup information to console");
			LogWeightResolving = configFile.Bind<bool>("|Debugging", "Log Weight Resolving", true, "Log weight resolving to console");
			ColoredWeathers = configFile.Bind<bool>("|General", "Colored Weathers", true, "Enable colored weathers in map screen");
			SunAnimatorBlacklist = configFile.Bind<string>("|SunAnimator", "Blacklist", "Asteroid-13;", "Semicolon-separated list of level names to blacklist from being patched by sun animator");
		}

		private static void OnConfigChange(object sender, EventArgs eventArgs)
		{
			SunAnimatorBlacklistLevels = ConfigHelper.ConvertStringToLevels(SunAnimatorBlacklist.Value);
		}

		internal static void StartupActions()
		{
			SunAnimatorBlacklistLevels = ConfigHelper.ConvertStringToLevels(SunAnimatorBlacklist.Value);
			SunAnimatorBlacklist.SettingChanged += OnConfigChange;
		}
	}
	internal class Defaults
	{
		internal static List<LevelWeatherType> VanillaWeathers = Defaults.VanillaWeathers;

		internal static Dictionary<LevelWeatherType, Color> VanillaWeatherColors = new Dictionary<LevelWeatherType, Color>
		{
			{
				(LevelWeatherType)(-1),
				new Color(0.41f, 1f, 0.42f, 1f)
			},
			{
				(LevelWeatherType)0,
				new Color(0.41f, 1f, 0.42f, 1f)
			},
			{
				(LevelWeatherType)3,
				new Color(1f, 0.86f, 0f, 1f)
			},
			{
				(LevelWeatherType)1,
				new Color(1f, 0.86f, 0f, 1f)
			},
			{
				(LevelWeatherType)2,
				new Color(1f, 0.57f, 0f, 1f)
			},
			{
				(LevelWeatherType)4,
				new Color(1f, 0.57f, 0f, 1f)
			},
			{
				(LevelWeatherType)5,
				new Color(1f, 0f, 0f, 1f)
			}
		};

		internal static Dictionary<LevelWeatherType, string> VanillaWeatherToWeatherWeights = new Dictionary<LevelWeatherType, string>
		{
			{
				(LevelWeatherType)(-1),
				"None@160; Rainy@100; Stormy@70; Flooded@20; Foggy@40; Eclipsed@10"
			},
			{
				(LevelWeatherType)1,
				"None@100; Rainy@60; Stormy@40; Flooded@30; Foggy@50; Eclipsed@20"
			},
			{
				(LevelWeatherType)2,
				"None@160; Rainy@110; Stormy@10; Flooded@120; Foggy@20; Eclipsed@80"
			},
			{
				(LevelWeatherType)4,
				"None@160; Rainy@60; Stormy@50; Flooded@10; Foggy@60; Eclipsed@40"
			},
			{
				(LevelWeatherType)3,
				"None@200; Rainy@60; Stormy@50; Flooded@10; Foggy@30; Eclipsed@20"
			},
			{
				(LevelWeatherType)5,
				"None@300; Rainy@40; Stormy@16; Flooded@20; Foggy@60; Eclipsed@10"
			}
		};

		internal static Color LethalLibColor = new Color(0f, 0.44f, 0.76f, 1f);
	}
	public class WeatherConfig
	{
		[JsonIgnore]
		internal IntegerConfigHandler DefaultWeight;

		[JsonIgnore]
		internal FloatConfigHandler ScrapAmountMultiplier;

		[JsonIgnore]
		internal FloatConfigHandler ScrapValueMultiplier;

		[JsonIgnore]
		internal LevelListConfigHandler LevelFilters;

		[JsonIgnore]
		internal LevelWeightsConfigHandler LevelWeights;

		[JsonIgnore]
		internal WeatherWeightsConfigHandler WeatherToWeatherWeights;

		[JsonIgnore]
		internal ConfigEntry<bool> _filteringOptionConfig { get; private set; }

		internal void Init(Weather weather)
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Expected O, but got Unknown
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Expected O, but got Unknown
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Expected O, but got Unknown
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Expected O, but got Unknown
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Expected O, but got Unknown
			string text = "Weather: " + ((Object)weather).name + ((weather.Origin != 0) ? $" ({weather.Origin})" : "");
			DefaultWeight = new IntegerConfigHandler(weather._defaultWeight, weather, "Default weight", new ConfigDescription("The default weight of this weather", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10000), Array.Empty<object>()));
			ScrapAmountMultiplier = new FloatConfigHandler(weather._scrapAmountMultiplier, weather, "Scrap amount multiplier", new ConfigDescription("Multiplier for the amount of scrap spawned", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			ScrapValueMultiplier = new FloatConfigHandler(weather._scrapValueMultiplier, weather, "Scrap value multiplier", new ConfigDescription("Multiplier for the value of scrap spawned", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			_filteringOptionConfig = ConfigManager.configFile.Bind<bool>(text, "Filtering option", weather.LevelFilteringOption == FilteringOption.Include, new ConfigDescription("Whether to make the filter a whitelist (false is blacklist, true is whitelist)", (AcceptableValueBase)null, Array.Empty<object>()));
			LevelFilters = new LevelListConfigHandler(string.Join(";", weather.DefaultLevelFilters) + ";", weather, "Level filter", new ConfigDescription("Semicolon-separated list of level names to filter", (AcceptableValueBase)null, Array.Empty<object>()));
			LevelWeights = new LevelWeightsConfigHandler(string.Join(';', weather.DefaultLevelWeights) + ";", weather, "Level weights", new ConfigDescription("Semicolon-separated list of level weights", (AcceptableValueBase)null, Array.Empty<object>()));
			WeatherToWeatherWeights = new WeatherWeightsConfigHandler((Defaults.VanillaWeatherToWeatherWeights.TryGetValue(weather.VanillaWeatherType, out var value) ? value : (string.Join(';', weather.DefaultWeatherToWeatherWeights) + ";")) ?? "", weather, "Weather weights", new ConfigDescription("Semicolon-separated list of weather weights", (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[CreateAssetMenu(fileName = "WeatherEffect", menuName = "WeatherRegistry/WeatherEffect", order = 10)]
	public class ImprovedWeatherEffect : ScriptableObject
	{
		[JsonIgnore]
		public GameObject EffectObject;

		[JsonIgnore]
		public GameObject WorldObject;

		private bool _effectEnabled;

		[field: SerializeField]
		public string SunAnimatorBool { get; set; }

		[field: SerializeField]
		public int DefaultVariable1 { get; set; }

		[field: SerializeField]
		public int DefaultVariable2 { get; set; }

		public bool EffectEnabled
		{
			get
			{
				return _effectEnabled;
			}
			set
			{
				Plugin.logger.LogWarning((object)$"Setting effect {((Object)this).name} to {value}");
				GameObject effectObject = EffectObject;
				if (effectObject != null)
				{
					effectObject.SetActive(value);
				}
				GameObject worldObject = WorldObject;
				if (worldObject != null)
				{
					worldObject.SetActive(value);
				}
				_effectEnabled = value;
			}
		}

		public void DisableEffect(bool permament = false)
		{
			if (permament)
			{
				EffectEnabled = false;
				return;
			}
			GameObject effectObject = EffectObject;
			if (effectObject != null)
			{
				effectObject.SetActive(false);
			}
		}

		public ImprovedWeatherEffect(GameObject effectObject, GameObject worldObject)
		{
			EffectObject = effectObject;
			WorldObject = worldObject;
		}
	}
	public enum WeatherType
	{
		Clear,
		Vanilla,
		Modded
	}
	public enum WeatherOrigin
	{
		Vanilla,
		WeatherRegistry,
		LethalLib,
		LethalLevelLoader
	}
	public enum FilteringOption
	{
		Include,
		Exclude
	}
	[JsonObject(/*Could not decode attribute arguments.*/)]
	[CreateAssetMenu(fileName = "Weather", menuName = "WeatherRegistry/WeatherDefinition", order = 5)]
	public class Weather : ScriptableObject
	{
		[JsonProperty]
		public string Name;

		[JsonIgnore]
		public ImprovedWeatherEffect Effect;

		[JsonIgnore]
		public Dictionary<SelectableLevel, LevelWeatherVariables> WeatherVariables = new Dictionary<SelectableLevel, LevelWeatherVariables>();

		[JsonIgnore]
		public AnimationClip AnimationClip;

		[JsonIgnore]
		internal WeatherConfig Config = new WeatherConfig();

		internal int _defaultWeight = 100;

		internal float _scrapAmountMultiplier = 1f;

		internal float _scrapValueMultiplier = 1f;

		[JsonProperty]
		public LevelWeatherType VanillaWeatherType { get; internal set; } = (LevelWeatherType)(-1);


		[JsonIgnore]
		internal WeatherOrigin Origin { get; set; } = WeatherOrigin.WeatherRegistry;


		[JsonProperty]
		public WeatherType Type { get; internal set; } = WeatherType.Modded;


		[field: SerializeField]
		public Color Color { get; set; } = Color.cyan;


		[SerializeField]
		public int DefaultWeight
		{
			get
			{
				return ((ConfigHandler<int, int>)Config.DefaultWeight).Value;
			}
			set
			{
				_defaultWeight = value;
			}
		}

		[JsonIgnore]
		[field: SerializeField]
		public string[] DefaultLevelFilters { get; set; } = new string[1] { "Gordion" };


		public string[] DefaultLevelWeights { get; set; } = new string[1] { "MoonName@50" };


		public string[] DefaultWeatherToWeatherWeights { get; set; } = new string[1] { "WeatherName@50" };


		[SerializeField]
		public float ScrapAmountMultiplier
		{
			get
			{
				return ((ConfigHandler<float, float>)Config.ScrapAmountMultiplier).Value;
			}
			set
			{
				_scrapAmountMultiplier = value;
			}
		}

		[SerializeField]
		public float ScrapValueMultiplier
		{
			get
			{
				return ((ConfigHandler<float, float>)Config.ScrapValueMultiplier).Value;
			}
			set
			{
				_scrapValueMultiplier = value;
			}
		}

		[JsonIgnore]
		[field: SerializeField]
		public FilteringOption LevelFilteringOption { get; set; } = FilteringOption.Exclude;


		[JsonIgnore]
		public List<SelectableLevel> LevelFilters => ((ConfigHandler<SelectableLevel[], string>)Config.LevelFilters).Value.ToList();

		[JsonIgnore]
		public Dictionary<LevelWeatherType, int> WeatherWeights => ((ConfigHandler<WeatherRarity[], string>)Config.WeatherToWeatherWeights).Value.ToDictionary((WeatherRarity rarity) => rarity.Weather.VanillaWeatherType, (WeatherRarity rarity) => rarity.Weight);

		[JsonIgnore]
		public Dictionary<SelectableLevel, int> LevelWeights => ((ConfigHandler<LevelRarity[], string>)Config.LevelWeights).Value.ToDictionary((LevelRarity rarity) => rarity.Level, (LevelRarity rarity) => rarity.Weight);

		public Weather(string name = "None", ImprovedWeatherEffect effect = null)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogDebug((object)("Called Weather constructor for weather " + name));
			Regex regex = new Regex("<.*?>");
			Name = regex.Replace(name, "");
			((Object)this).name = regex.Replace(name, "");
			Effect = effect;
			if ((Object)(object)effect != (Object)null)
			{
				((Object)Effect).name = name;
			}
		}

		internal virtual void Init()
		{
			string text = "Weather: " + ((Object)this).name + ((Origin != 0) ? $" ({Origin})" : "");
			Config.Init(this);
			LevelFilteringOption = ((!Config._filteringOptionConfig.Value) ? FilteringOption.Exclude : FilteringOption.Include);
			((Object)this).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)this);
			Object.Instantiate<Weather>(this);
		}

		private void Reset()
		{
			Type = WeatherType.Modded;
			ScrapAmountMultiplier = 1f;
			ScrapValueMultiplier = 1f;
			DefaultWeight = 50;
		}

		public void RemoveFromMoon(string moonNames)
		{
			ConfigHelper.ConvertStringToLevels(moonNames).ToList().ForEach(delegate(SelectableLevel level)
			{
				LevelFilters.Remove(level);
			});
		}

		public void RemoveFromMoon(SelectableLevel moon)
		{
			LevelFilters.Remove(moon);
		}

		public int GetWeight(SelectableLevel level)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			Logger logger = WeatherCalculation.Logger;
			int num = DefaultWeight;
			int value2;
			if (LevelWeights.TryGetValue(level, out var value))
			{
				logger.LogDebug((object)$"{Name} has level weight {value}");
				num = value;
			}
			else if (WeatherWeights.TryGetValue(level.currentWeather, out value2) && StartOfRound.Instance.gameStats.daysSpent != 0)
			{
				logger.LogDebug((object)$"{Name} has weather>weather weight {value2}");
				num = value2;
			}
			else
			{
				logger.LogDebug((object)$"{Name} has default weight {num}");
			}
			return num;
		}
	}
	public class LevelWeatherVariables
	{
		public SelectableLevel Level;

		public int WeatherVariable1;

		public int WeatherVariable2;
	}
	public class LevelWeather : LevelWeatherVariables
	{
		public Weather Weather;

		public LevelWeatherVariables Variables;
	}
	public class EventManager
	{
		public static WeatherRegistryEvent DisableAllWeathers = new WeatherRegistryEvent();

		public static WeatherRegistryEvent SetupFinished = new WeatherRegistryEvent();

		public static WeatherRegistryEvent<int> DayChanged = new WeatherRegistryEvent<int>();

		public static WeatherRegistryEvent<(SelectableLevel level, Weather weather, string screenText)> MapScreenUpdated = new WeatherRegistryEvent<(SelectableLevel, Weather, string)>();

		public static WeatherRegistryEvent<(SelectableLevel level, Weather weather)> WeatherChanged = new WeatherRegistryEvent<(SelectableLevel, Weather)>();

		public static WeatherRegistryEvent<(SelectableLevel level, Weather weather)> ShipLanding = new WeatherRegistryEvent<(SelectableLevel, Weather)>();
	}
	internal class LobbyCompatibilityCompatibility
	{
		public static void Init()
		{
			Plugin.logger.LogWarning((object)"LobbyCompatibility detected, registering plugin with LobbyCompatibility.");
			Version version = Version.Parse("0.1.25");
			PluginHelper.RegisterPlugin("mrov.WeatherRegistry", version, (CompatibilityLevel)2, (VersionStrictness)0);
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class OpeningDoorsSequencePatch
	{
		[HarmonyILManipulator]
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		internal static void StartOfRound_openingDoorsSequence(ILContext il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(il);
			if (!val.TryGotoNext((MoveType)2, new Func<Instruction, bool>[1]
			{
				(Instruction instr) => ILPatternMatchingExt.MatchStfld<StartOfRound>(instr, "shipDoorsEnabled")
			}))
			{
				Plugin.logger.LogError((object)"Failed IL weather hook for StartOfRound.openingDoorsSequence");
				return;
			}
			Plugin.logger.LogInfo((object)"IL weather hook for StartOfRound.openingDoorsSequence");
			val.EmitDelegate<Action>((Action)RunWeatherPatches);
			val.EmitDelegate<Action>((Action)SetWeatherEffects);
			if (!val.TryGotoNext((MoveType)2, new Func<Instruction, bool>[1]
			{
				(Instruction instr) => ILPatternMatchingExt.MatchLdfld<SelectableLevel>(instr, "LevelDescription")
			}))
			{
				Plugin.logger.LogError((object)"Failed IL hook for StartOfRound.openingDoorsSequence");
				return;
			}
			val.Emit(OpCodes.Ldloc_1);
			val.EmitDelegate<Func<string, StartOfRound, string>>((Func<string, StartOfRound, string>)delegate(string desc, StartOfRound self)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Invalid comparison between Unknown and I4
				string text = (((int)self.currentLevel.currentWeather != -1) ? WeatherManager.GetCurrentWeatherName(self.currentLevel) : "Clear");
				string text2 = "WEATHER: " + text;
				return text2 + "\n" + desc;
			});
		}

		internal static void RunWeatherPatches()
		{
			TimeOfDay.Instance.nextTimeSync = 0f;
		}

		internal static void SetWeatherEffects()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			SelectableLevel currentLevel = StartOfRound.Instance.currentLevel;
			Weather currentWeather = WeatherManager.GetCurrentWeather(currentLevel);
			Plugin.logger.LogDebug((object)("Landing at " + ConfigHelper.GetNumberlessName(currentLevel) + " with weather " + JsonConvert.SerializeObject((object)currentWeather, (Formatting)0, new JsonSerializerSettings
			{
				ReferenceLoopHandling = (ReferenceLoopHandling)1
			})));
			SunAnimator.OverrideSunAnimator(currentWeather.VanillaWeatherType);
			((CustomEvent<(SelectableLevel, Weather)>)(object)EventManager.ShipLanding).Invoke((currentLevel, currentWeather));
		}
	}
	[BepInPlugin("mrov.WeatherRegistry", "WeatherRegistry", "0.1.25")]
	[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 GUID = "mrov.WeatherRegistry";

		internal static ManualLogSource logger;

		internal static Harmony harmony = new Harmony("mrov.WeatherRegistry");

		internal static bool IsLethalLibLoaded = false;

		internal static Hook WeatherTypeEnumHook;

		private void Awake()
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			logger = ((BaseUnityPlugin)this).Logger;
			harmony.PatchAll();
			ConfigManager.Init(((BaseUnityPlugin)this).Config);
			SunAnimator.Init();
			if (Chainloader.PluginInfos.ContainsKey("evaisa.lethallib"))
			{
				IsLethalLibLoaded = true;
				LethalLibPatch.Init();
			}
			else
			{
				logger.LogInfo((object)"LethalLib not detected!");
			}
			WeatherTypeEnumHook = new Hook((MethodBase)typeof(Enum).GetMethod("ToString", Array.Empty<Type>()), typeof(WeatherManager).GetMethod("LevelWeatherTypeEnumHook"));
			if (Chainloader.PluginInfos.ContainsKey("BMX.LobbyCompatibility"))
			{
				LobbyCompatibilityCompatibility.Init();
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin mrov.WeatherRegistry is loaded!");
		}
	}
	public class Settings
	{
		public static Dictionary<string, Color> ScreenMapColors = new Dictionary<string, Color>();

		public static bool SelectWeathers = true;
	}
	public class WeatherCalculation
	{
		internal static Dictionary<string, LevelWeatherType> previousDayWeather = new Dictionary<string, LevelWeatherType>();

		public static Logger Logger = new Logger("WeatherRegistry", ConfigManager.LogWeatherChanges);

		internal static Dictionary<string, LevelWeatherType> NewWeathers(StartOfRound startOfRound)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			if (!((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				Logger.LogInfo((object)"Not a host, cannot generate weathers!");
				return null;
			}
			previousDayWeather.Clear();
			Dictionary<string, LevelWeatherType> dictionary = new Dictionary<string, LevelWeatherType>();
			int seed = startOfRound.randomMapSeed + 31;
			Random random = new Random(seed);
			List<SelectableLevel> list = startOfRound.levels.ToList();
			int daysSpent = startOfRound.gameStats.daysSpent;
			int timesFulfilledQuota = TimeOfDay.Instance.timesFulfilledQuota;
			int num = daysSpent % 3;
			foreach (SelectableLevel item in list)
			{
				previousDayWeather[item.PlanetName] = item.currentWeather;
				Logger.LogMessage((object)"-------------");
				Logger.LogMessage((object)(item.PlanetName ?? ""));
				Logger.LogDebug((object)$"previousDayWeather: {previousDayWeather[item.PlanetName]}");
				if (item.overrideWeather)
				{
					Logger.LogMessage((object)$"Override weather present, changing weather to {item.overrideWeatherType}");
					Weather weather = WeatherManager.GetWeather(item.overrideWeatherType);
					dictionary[item.PlanetName] = weather.VanillaWeatherType;
					WeatherManager.CurrentWeathers[item] = weather;
					((CustomEvent<(SelectableLevel, Weather)>)(object)EventManager.WeatherChanged).Invoke((item, weather));
					continue;
				}
				dictionary[item.PlanetName] = (LevelWeatherType)(-1);
				WeightHandler<Weather> planetWeightedList = WeatherManager.GetPlanetWeightedList(item);
				Weather weather2 = planetWeightedList.Random();
				dictionary[item.PlanetName] = weather2.VanillaWeatherType;
				WeatherManager.CurrentWeathers[item] = weather2;
				((CustomEvent<(SelectableLevel, Weather)>)(object)EventManager.WeatherChanged).Invoke((item, weather2));
				Logger.LogMessage((object)("Selected weather: " + weather2.Name));
				try
				{
					Logger.LogMessage((object)$"Chance for that was {planetWeightedList.Get(weather2)} / {planetWeightedList.Sum} ({(float)planetWeightedList.Get(weather2) / (float)planetWeightedList.Sum * 100f}%)");
				}
				catch
				{
				}
			}
			Logger.LogMessage((object)"-------------");
			return dictionary;
		}
	}
	public static class WeatherController
	{
		public static void ChangeCurrentWeather(Weather weather)
		{
			SelectableLevel currentLevel = StartOfRound.Instance.currentLevel;
			ChangeWeather(currentLevel, weather);
		}

		public static void ChangeCurrentWeather(LevelWeatherType weatherType)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			SelectableLevel currentLevel = StartOfRound.Instance.currentLevel;
			ChangeWeather(currentLevel, weatherType);
		}

		public static void ChangeWeather(SelectableLevel level, LevelWeatherType weatherType)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			Weather weather = WeatherManager.GetWeather(weatherType);
			ChangeWeather(level, weather);
		}

		public static void ChangeWeather(SelectableLevel level, Weather weather)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			if (Settings.SelectWeathers)
			{
				WeatherManager.CurrentWeathers[level] = weather;
				level.currentWeather = weather.VanillaWeatherType;
				Plugin.logger.LogWarning((object)$"Changed weather for {ConfigHelper.GetNumberlessName(level)} to {weather.VanillaWeatherType}");
				((CustomEvent<(SelectableLevel, Weather)>)(object)EventManager.WeatherChanged).Invoke((level, weather));
				StartOfRound.Instance.SetMapScreenInfoToCurrentLevel();
			}
		}
	}
	public static class WeatherManager
	{
		internal static bool IsSetupFinished = false;

		public static Dictionary<int, Weather> ModdedWeatherEnumExtension = new Dictionary<int, Weather>();

		public static Dictionary<SelectableLevel, Weather> CurrentWeathers = new Dictionary<SelectableLevel, Weather>();

		public static List<Weather> RegisteredWeathers { get; internal set; } = new List<Weather>();


		public static List<LevelWeather> LevelWeathers { get; internal set; } = new List<LevelWeather>();


		public static List<Weather> Weathers { get; internal set; } = new List<Weather>();


		public static Weather NoneWeather { get; internal set; }

		public static void RegisterWeather(Weather weather)
		{
			RegisteredWeathers.Add(weather);
		}

		public static Weather GetWeather(LevelWeatherType levelWeatherType)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return Weathers.Find((Weather weather) => weather.VanillaWeatherType == levelWeatherType);
		}

		public static void Reset()
		{
			IsSetupFinished = false;
			Weathers.ForEach(delegate(Weather weather)
			{
				if (weather.Origin != WeatherOrigin.WeatherRegistry)
				{
					Object.Destroy((Object)(object)weather.Effect);
					Object.Destroy((Object)(object)weather);
				}
			});
			LevelWeathers.Clear();
			Weathers.Clear();
			ModdedWeatherEnumExtension.Clear();
			CurrentWeathers.Clear();
			Settings.ScreenMapColors.Clear();
			ConfigHelper.StringToWeather = null;
			RegisteredWeathers.RemoveAll((Weather weather) => weather.Origin != WeatherOrigin.WeatherRegistry);
		}

		public static string LevelWeatherTypeEnumHook(Func<Enum, string> orig, Enum self)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected I4, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected I4, but got Unknown
			if (self.GetType() == typeof(LevelWeatherType) && ModdedWeatherEnumExtension.ContainsKey((int)(LevelWeatherType)(object)self))
			{
				return ((Object)ModdedWeatherEnumExtension[(int)(LevelWeatherType)(object)self]).name;
			}
			return orig(self);
		}

		internal static List<LevelWeatherType> GetPlanetPossibleWeathers(SelectableLevel level)
		{
			List<LevelWeatherType> list = (from randomWeather in level.randomWeathers
				where (int)randomWeather.weatherType != -1
				select randomWeather into x
				select x.weatherType).Distinct().ToList();
			list.Insert(0, (LevelWeatherType)(-1));
			Plugin.logger.LogDebug((object)("Possible weathers: " + string.Join("; ", list.Select((LevelWeatherType x) => ((object)(LevelWeatherType)(ref x)).ToString()))));
			if (list == null || list.Count() == 0)
			{
				Plugin.logger.LogError((object)"Level's random weathers are null");
				return new List<LevelWeatherType>();
			}
			return list;
		}

		internal static WeightHandler<Weather> GetPlanetWeightedList(SelectableLevel level)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			WeightHandler<Weather> val = new WeightHandler<Weather>();
			Logger logger = WeatherCalculation.Logger;
			List<LevelWeatherType> planetPossibleWeathers = GetPlanetPossibleWeathers(level);
			if (planetPossibleWeathers == null || planetPossibleWeathers.Count() == 0)
			{
				Plugin.logger.LogError((object)"Level's random weathers are null");
				return val;
			}
			foreach (LevelWeatherType item in planetPossibleWeathers)
			{
				Weather weather = GetWeather(item);
				int weight = weather.GetWeight(level);
				val.Add(weather, weight);
			}
			return val;
		}

		internal static Weather GetCurrentWeather(SelectableLevel level)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if (CurrentWeathers.ContainsKey(level))
			{
				return CurrentWeathers[level];
			}
			return GetWeather(level.currentWeather);
		}

		internal static string GetCurrentWeatherName(SelectableLevel level)
		{
			return GetCurrentWeather(level).Name;
		}

		internal static AnimationClip GetWeatherAnimationClip(LevelWeatherType weatherType)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return GetWeather(weatherType).AnimationClip;
		}
	}
	internal class WeatherSync : NetworkBehaviour
	{
		public static GameObject WeatherSyncPrefab;

		private static WeatherSync _instance;

		public static NetworkManager networkManager;

		private static List<GameObject> queuedNetworkPrefabs = new List<GameObject>();

		public static bool networkHasStarted = false;

		private string LatestWeathersReceived = "";

		private static string DefaultValue = "{}";

		public NetworkVariable<FixedString4096Bytes> WeathersSynced = new NetworkVariable<FixedString4096Bytes>(FixedString4096Bytes.op_Implicit(DefaultValue), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static WeatherSync Instance
		{
			get
			{
				if ((Object)(object)_instance == (Object)null)
				{
					_instance = Object.FindObjectOfType<WeatherSync>();
				}
				if ((Object)(object)_instance == (Object)null)
				{
					Plugin.logger.LogError((object)"WeatherSync instance is null");
				}
				return _instance;
			}
			set
			{
				_instance = value;
			}
		}

		public string Weather
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				FixedString4096Bytes value = WeathersSynced.Value;
				return ((object)(FixedString4096Bytes)(ref value)).ToString();
			}
			set
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				WeathersSynced.Value = new FixedString4096Bytes(value);
			}
		}

		public override void OnNetworkSpawn()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			((NetworkBehaviour)this).OnNetworkSpawn();
			((Object)((Component)this).gameObject).name = "WeatherSync";
			Instance = this;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Plugin.logger.LogWarning((object)$"WeathersSynced: {WeathersSynced.Value}");
			NetworkVariable<FixedString4096Bytes> weathersSynced = WeathersSynced;
			weathersSynced.OnValueChanged = (OnValueChangedDelegate<FixedString4096Bytes>)(object)Delegate.Combine((Delegate?)(object)weathersSynced.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<FixedString4096Bytes>(WeathersReceived));
		}

		public void SetNew(string weathers)
		{
			Plugin.logger.LogInfo((object)("Setting new weathers: " + weathers));
			Plugin.logger.LogInfo((object)string.Format("Current weathers: {0} (is null? {1}) (is empty? {2}", Weather, Weather == null, Weather == ""));
			Weather = weathers;
		}

		public void WeathersReceived(FixedString4096Bytes oldWeathers, FixedString4096Bytes weathers)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogInfo((object)$"Weathers received: {weathers}");
			if (WeatherManager.IsSetupFinished)
			{
				ApplyWeathers(((object)(FixedString4096Bytes)(ref weathers)).ToString());
			}
		}

		public void ApplyWeathers(string weathers)
		{
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogInfo((object)("Weathers to apply: " + weathers));
			if (LatestWeathersReceived == weathers)
			{
				Plugin.logger.LogInfo((object)"Weathers are the same as last ones, skipping");
				return;
			}
			if (weathers == DefaultValue)
			{
				Plugin.logger.LogInfo((object)"Weathers are not set, skipping");
				return;
			}
			Dictionary<string, LevelWeatherType> dictionary = JsonConvert.DeserializeObject<Dictionary<string, LevelWeatherType>>(weathers);
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				val.currentWeather = dictionary[val.PlanetName];
			}
			LatestWeathersReceived = weathers;
			StartOfRound.Instance.SetMapScreenInfoToCurrentLevel();
		}

		public static void RegisterNetworkPrefab(GameObject prefab)
		{
			if (!networkHasStarted)
			{
				Plugin.logger.LogWarning((object)("Registering NetworkPrefab: " + (object)prefab));
				queuedNetworkPrefabs.Add(prefab);
			}
			else
			{
				Plugin.logger.LogWarning((object)("Attempted To Register NetworkPrefab: " + ((object)prefab)?.ToString() + " After GameNetworkManager Has Started!"));
			}
		}

		internal static void RegisterPrefabs(NetworkManager networkManager)
		{
			Plugin.logger.LogWarning((object)"Registering NetworkPrefabs in NetworkManager");
			List<GameObject> list = new List<GameObject>();
			foreach (NetworkPrefab prefab in networkManager.NetworkConfig.Prefabs.m_Prefabs)
			{
				list.Add(prefab.Prefab);
			}
			int num = 0;
			foreach (GameObject queuedNetworkPrefab in queuedNetworkPrefabs)
			{
				Plugin.logger.LogDebug((object)("Trying To Register Prefab: " + (object)queuedNetworkPrefab));
				if (!list.Contains(queuedNetworkPrefab))
				{
					networkManager.AddNetworkPrefab(queuedNetworkPrefab);
					list.Add(queuedNetworkPrefab);
				}
				else
				{
					num++;
				}
			}
			Plugin.logger.LogDebug((object)("Skipped Registering " + num + " NetworkObjects As They Were Already Registered."));
			networkHasStarted = true;
		}

		protected override void __initializeVariables()
		{
			if (WeathersSynced == null)
			{
				throw new Exception("WeatherSync.WeathersSynced cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)WeathersSynced).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)WeathersSynced, "WeathersSynced");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)WeathersSynced);
			((NetworkBehaviour)this).__initializeVariables();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		protected internal override string __getTypeName()
		{
			return "WeatherSync";
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "WeatherRegistry";

		public const string PLUGIN_NAME = "WeatherRegistry";

		public const string PLUGIN_VERSION = "0.1.25";
	}
}
namespace WeatherRegistry.Patches
{
	[HarmonyPatch(typeof(TimeOfDay))]
	public static class TimeOfDayPatch
	{
		internal static ManualLogSource logger = Logger.CreateLogSource("WeatherTweaks TimeOfDay");

		[HarmonyPostfix]
		[HarmonyPatch(typeof(TimeOfDay), "DisableAllWeather")]
		private static void DisableAllWeatherPatch(TimeOfDay __instance, bool deactivateObjects)
		{
			logger.LogDebug((object)"Disabling all weather");
			if (!deactivateObjects)
			{
				return;
			}
			logger.LogDebug((object)"DecativateObjects is true");
			foreach (ImprovedWeatherEffect item in WeatherManager.Weathers.Select((Weather weather) => weather.Effect))
			{
				item.DisableEffect(deactivateObjects);
			}
			((CustomEvent)EventManager.DisableAllWeathers).Invoke();
			SunAnimator.Clear();
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "Start")]
	internal class GameNetworkManagerStartPatch
	{
		[HarmonyPrefix]
		public static void GameMethodPatch(GameNetworkManager __instance)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			WeatherSync.networkManager = ((Component)__instance).GetComponent<NetworkManager>();
			GameObject val = new GameObject("WeatherRegistrySyncInit");
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<NetworkObject>();
			byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("weatherregistryweathersync"));
			val.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0);
			val.AddComponent<WeatherSync>();
			val.GetComponent<NetworkObject>().DontDestroyWithOwner = true;
			val.GetComponent<NetworkObject>().SceneMigrationSynchronization = true;
			val.GetComponent<NetworkObject>().DestroyWithScene = false;
			Object.DontDestroyOnLoad((Object)(object)val);
			WeatherSync.WeatherSyncPrefab = val;
			WeatherSync.RegisterNetworkPrefab(val);
			WeatherSync.RegisterPrefabs(((Component)__instance).GetComponent<NetworkManager>());
			Plugin.logger.LogWarning((object)"WeatherSync initialized in GameNetworkManager.Start");
		}
	}
	public class LethalLibPatch
	{
		public static Dictionary<int, CustomWeather> GetLethalLibWeathers()
		{
			return Weathers.customWeathers;
		}

		public static List<Weather> ConvertLLWeathers()
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<int, CustomWeather> lethalLibWeathers = GetLethalLibWeathers();
			List<Weather> list = new List<Weather>();
			foreach (KeyValuePair<int, CustomWeather> item in lethalLibWeathers)
			{
				CustomWeather value = item.Value;
				ImprovedWeatherEffect improvedWeatherEffect = new ImprovedWeatherEffect(value.weatherEffect.effectObject, value.weatherEffect.effectPermanentObject);
				((Object)improvedWeatherEffect).name = value.name;
				improvedWeatherEffect.SunAnimatorBool = value.weatherEffect.sunAnimatorBool;
				improvedWeatherEffect.DefaultVariable1 = value.weatherVariable1;
				improvedWeatherEffect.DefaultVariable2 = value.weatherVariable2;
				ImprovedWeatherEffect effect = improvedWeatherEffect;
				Weather weather = new Weather(value.name, effect)
				{
					VanillaWeatherType = (LevelWeatherType)item.Key,
					Origin = WeatherOrigin.LethalLib,
					Color = Defaults.LethalLibColor,
					DefaultWeight = 50
				};
				list.Add(weather);
				WeatherManager.ModdedWeatherEnumExtension.Add(item.Key, weather);
			}
			return list;
		}

		public static void Init()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			Plugin.logger.LogWarning((object)"Disabling LethalLib injections");
			FieldInfo field = typeof(Weathers).GetField("weatherEnumHook", BindingFlags.Static | BindingFlags.NonPublic);
			Hook val = (Hook)field.GetValue(null);
			val.Undo();
			Plugin.harmony.Patch((MethodBase)AccessTools.Method(typeof(Weathers), "RegisterLevelWeathers_StartOfRound_Awake", (Type[])null, (Type[])null), new HarmonyMethod(typeof(LethalLibPatch), "StartOfRoundAwakePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.harmony.Patch((MethodBase)AccessTools.Method(typeof(Weathers), "TimeOfDay_Awake", (Type[])null, (Type[])null), new HarmonyMethod(typeof(LethalLibPatch), "TimeOfDayAwakePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static bool StartOfRoundAwakePrefix(orig_Awake orig, StartOfRound self)
		{
			Plugin.logger.LogWarning((object)"Skipping LethalLib StartOfRound method");
			orig.Invoke(self);
			return false;
		}

		internal static bool TimeOfDayAwakePrefix(orig_Awake orig, TimeOfDay self)
		{
			Plugin.logger.LogWarning((object)"Skipping LethalLib TimeOfDay method");
			orig.Invoke(self);
			return false;
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	public static class SetMapScreenInfoToCurrentLevelPatch
	{
		[HarmonyPatch("SetMapScreenInfoToCurrentLevel")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		internal static void GameMethodPatch(ref TextMeshProUGUI ___screenLevelDescription, ref SelectableLevel ___currentLevel)
		{
			if (!WeatherManager.IsSetupFinished)
			{
				Plugin.logger.LogWarning((object)"WeatherManager is not set up yet.");
				return;
			}
			Regex regex = new Regex("\\n{2,}");
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("ORBITING: " + ___currentLevel.PlanetName + "\n");
			stringBuilder.Append("WEATHER: " + GetColoredString(___currentLevel) + "\n");
			stringBuilder.Append(regex.Replace(___currentLevel.LevelDescription, "\n") ?? "");
			((TMP_Text)___screenLevelDescription).fontWeight = (FontWeight)700;
			((TMP_Text)___screenLevelDescription).text = stringBuilder.ToString();
			((CustomEvent<(SelectableLevel, Weather, string)>)(object)EventManager.MapScreenUpdated).Invoke((___currentLevel, WeatherManager.GetCurrentWeather(___currentLevel), stringBuilder.ToString()));
		}

		private static string GetDisplayWeatherString(SelectableLevel level, Weather weather)
		{
			return weather.Name;
		}

		private static string GetColoredString(SelectableLevel level)
		{
			Weather currentWeather = WeatherManager.GetCurrentWeather(level);
			string displayWeatherString = GetDisplayWeatherString(level, currentWeather);
			if (!ConfigManager.ColoredWeathers.Value)
			{
				return displayWeatherString;
			}
			string outputString = "";
			Regex regex = new Regex("(\\/)|(\\?)|(>)|(\\+)");
			regex.Split(displayWeatherString).ToList().ForEach(delegate(string word)
			{
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				string text = word.Trim();
				Color value;
				string text2 = ColorUtility.ToHtmlStringRGB(Settings.ScreenMapColors.TryGetValue(text, out value) ? value : Color.black);
				outputString += ((text2 != "000000") ? ("<color=#" + text2 + ">" + word + "</color>") : (text ?? ""));
			});
			return outputString;
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class SetPlanetsWeatherPatch
	{
		[HarmonyPatch("SetPlanetsWeather")]
		[HarmonyPrefix]
		public static bool GameMethodPatch(int connectedPlayersOnServer, StartOfRound __instance)
		{
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogInfo((object)"SetPlanetsWeather called.");
			if (!WeatherManager.IsSetupFinished)
			{
				Plugin.logger.LogWarning((object)"WeatherManager is not set up yet.");
				return false;
			}
			if (!Settings.SelectWeathers)
			{
				Plugin.logger.LogWarning((object)"Weather selection is disabled.");
				return true;
			}
			if ((Object)(object)__instance == (Object)null)
			{
				Plugin.logger.LogWarning((object)"Instance is null");
				return true;
			}
			if (((NetworkBehaviour)__instance).IsHost)
			{
				WeatherManager.CurrentWeathers = new Dictionary<SelectableLevel, Weather>();
				Dictionary<string, LevelWeatherType> dictionary = WeatherCalculation.NewWeathers(__instance);
				Plugin.logger.LogDebug((object)$"Instance: {WeatherSync.Instance}");
				Plugin.logger.LogDebug((object)$"Weathers: {dictionary}");
				Plugin.logger.LogDebug((object)$"WeatherSync: {WeatherSync.Instance.WeathersSynced}");
				Plugin.logger.LogDebug((object)$"WeathersSynced: {WeatherSync.Instance.WeathersSynced.Value}");
				WeatherSync.Instance.SetNew(JsonConvert.SerializeObject((object)dictionary));
			}
			((CustomEvent<int>)EventManager.DayChanged).Invoke(__instance.gameStats.daysSpent);
			return false;
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	public class SpawnScrapInLevelPatches
	{
		[HarmonyPatch("SpawnScrapInLevel")]
		[HarmonyAfter(new string[] { "com.github.fredolx.meteomultiplier", "DarthLilo.WeatherBonuses" })]
		[HarmonyPriority(0)]
		[HarmonyPrefix]
		private static void ChangeMultipliers(RoundManager __instance)
		{
			Weather currentWeather = WeatherManager.GetCurrentWeather(__instance.currentLevel);
			__instance.scrapValueMultiplier = currentWeather.ScrapValueMultiplier * 0.4f;
			__instance.scrapAmountMultiplier = currentWeather.ScrapAmountMultiplier;
		}

		[HarmonyPatch("SpawnScrapInLevel")]
		[HarmonyPostfix]
		[HarmonyPriority(800)]
		private static void LogMultipliers(RoundManager __instance)
		{
			Plugin.logger.LogInfo((object)$"Spawned scrap in level with multipliers: {__instance.scrapValueMultiplier}, {__instance.scrapAmountMultiplier}");
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("OnDisable")]
		[HarmonyPrefix]
		public static void DisableWeathersPatch()
		{
			foreach (Weather weather in WeatherManager.Weathers)
			{
				weather.Effect.DisableEffect(permament: true);
			}
			((CustomEvent)EventManager.DisableAllWeathers).Invoke();
		}
	}
	internal class SunAnimator
	{
		public class AnimationClipOverrides : List<KeyValuePair<AnimationClip, AnimationClip>>
		{
			public AnimationClip this[string name]
			{
				get
				{
					return Find((KeyValuePair<AnimationClip, AnimationClip> x) => ((Object)x.Key).name.Equals(name)).Value;
				}
				set
				{
					int num = FindIndex((KeyValuePair<AnimationClip, AnimationClip> x) => ((Object)x.Key).name.Equals(name));
					if (num != -1)
					{
						base[num] = new KeyValuePair<AnimationClip, AnimationClip>(base[num].Key, value);
					}
				}
			}

			public AnimationClipOverrides(int capacity)
				: base(capacity)
			{
			}
		}

		internal static ManualLogSource logger = Logger.CreateLogSource("WeatherRegistry SunAnimator");

		internal static Dictionary<string, LevelWeatherType> vanillaBools = new Dictionary<string, LevelWeatherType>
		{
			{
				"",
				(LevelWeatherType)(-1)
			},
			{
				"overcast",
				(LevelWeatherType)2
			},
			{
				"eclipse",
				(LevelWeatherType)5
			}
		};

		internal static Dictionary<LevelWeatherType, string> clipNames = new Dictionary<LevelWeatherType, string>
		{
			{
				(LevelWeatherType)(-1),
				""
			},
			{
				(LevelWeatherType)2,
				"Stormy"
			},
			{
				(LevelWeatherType)5,
				"Eclipse"
			}
		};

		internal static List<string> animatorControllerBlacklist = new List<string>(1) { "SunAnimContainerCompanyLevel" };

		internal static AnimatorOverrideController animatorOverrideController;

		public static void Init()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			Harmony val = new Harmony("WeatherRegistry.SunAnimator");
			val.Patch((MethodBase)AccessTools.Method(typeof(Animator), "SetBool", new Type[2]
			{
				typeof(string),
				typeof(bool)
			}, (Type[])null), new HarmonyMethod(typeof(SunAnimator), "SetBoolStringPatch", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			logger.LogWarning((object)"Patching Animator.SetBool(string, bool)");
		}

		public static bool SetBoolPatch(Animator __instance, object nameOrId, bool value)
		{
			string text = nameOrId as string;
			if ((Object)(object)TimeOfDay.Instance == (Object)null)
			{
				return true;
			}
			if (text == "overcast" || text == "eclipse")
			{
				ConfigManager.SunAnimatorBlacklistLevels.Contains(StartOfRound.Instance.currentLevel);
				return true;
			}
			return true;
		}

		public static bool SetBoolStringPatch(Animator __instance, string name, bool value)
		{
			return SetBoolPatch(__instance, name, value);
		}

		public static void OverrideSunAnimator(LevelWeatherType weatherType)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Expected O, but got Unknown
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_039b: Unknown result type (might be due to invalid IL or missing references)
			//IL_049b: Unknown result type (might be due to invalid IL or missing references)
			//IL_047f: Unknown result type (might be due to invalid IL or missing references)
			//IL_053c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0542: Invalid comparison between Unknown and I4
			//IL_04c4: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogDebug((object)"OverrideSunAnimator called");
			if (ConfigManager.SunAnimatorBlacklistLevels.Contains(StartOfRound.Instance.currentLevel))
			{
				logger.LogWarning((object)$"Current level {StartOfRound.Instance.currentLevel} is blacklisted");
				return;
			}
			if ((Object)(object)TimeOfDay.Instance.sunAnimator == (Object)null)
			{
				logger.LogWarning((object)"sunAnimator is null, skipping");
				return;
			}
			AnimatorClipInfo[] currentAnimatorClipInfo = TimeOfDay.Instance.sunAnimator.GetCurrentAnimatorClipInfo(0);
			if (currentAnimatorClipInfo.Length == 0)
			{
				logger.LogWarning((object)"There are no SunAnimator clips, skipping");
				return;
			}
			logger.LogInfo((object)("Current clip: " + ((Object)((AnimatorClipInfo)(ref currentAnimatorClipInfo[0])).clip).name));
			string name = ((Object)TimeOfDay.Instance.sunAnimator.runtimeAnimatorController).name;
			logger.LogInfo((object)$"animatorControllerName: {name}, weatherType: {weatherType}");
			if (animatorControllerBlacklist.Contains(name))
			{
				logger.LogWarning((object)("TimeOfDay.Instance.sunAnimator controller " + name + " is blacklisted"));
				return;
			}
			if ((Object)(object)animatorOverrideController == (Object)null)
			{
				animatorOverrideController = new AnimatorOverrideController(TimeOfDay.Instance.sunAnimator.runtimeAnimatorController)
				{
					name = name + "override"
				};
			}
			AnimationClipOverrides clipOverrides = new AnimationClipOverrides(animatorOverrideController.overridesCount);
			logger.LogDebug((object)$"Overrides: {animatorOverrideController.overridesCount}");
			animatorOverrideController.GetOverrides((List<KeyValuePair<AnimationClip, AnimationClip>>)clipOverrides);
			List<AnimationClip> list = animatorOverrideController.runtimeAnimatorController.animationClips.ToList();
			Dictionary<LevelWeatherType, AnimationClip> clips = new Dictionary<LevelWeatherType, AnimationClip>();
			Weather weather = WeatherManager.GetWeather(weatherType);
			try
			{
				AnimationClip val = list.Find((AnimationClip clip) => ((Object)clip).name.Contains(clipNames[(LevelWeatherType)5]));
				AnimationClip val2 = list.Find((AnimationClip clip) => ((Object)clip).name.Contains(clipNames[(LevelWeatherType)2]));
				AnimationClip val3 = list.Find((AnimationClip clip) => !((Object)clip).name.Contains(clipNames[(LevelWeatherType)2]) && !((Object)clip).name.Contains(clipNames[(LevelWeatherType)5]));
				clips = new Dictionary<LevelWeatherType, AnimationClip>
				{
					{
						(LevelWeatherType)5,
						val
					},
					{
						(LevelWeatherType)2,
						val2
					},
					{
						(LevelWeatherType)4,
						val2
					},
					{
						(LevelWeatherType)3,
						val2
					},
					{
						(LevelWeatherType)1,
						val2
					},
					{
						(LevelWeatherType)(-1),
						val3
					}
				};
				if ((Object)(object)WeatherManager.GetWeatherAnimationClip(weatherType) != (Object)null)
				{
					AnimationClip weatherAnimationClip = WeatherManager.GetWeatherAnimationClip(weatherType);
					ArrayUtility.Add<AnimationClip>(TimeOfDay.Instance.sunAnimator.runtimeAnimatorController.animationClips, weatherAnimationClip);
					list.Add(weatherAnimationClip);
					clips[weatherType] = weatherAnimationClip;
					logger.LogInfo((object)$"Added animation clip for weather type {weatherType}");
					TimeOfDay.Instance.sunAnimator.runtimeAnimatorController.animationClips.ToList().ForEach(delegate(AnimationClip clip)
					{
						logger.LogInfo((object)("clip: " + ((Object)clip).name));
					});
				}
				else if (weather.Type != WeatherType.Vanilla)
				{
					logger.LogWarning((object)$"No custom animation clip found for weather type {weatherType}");
					logger.LogDebug((object)"Trying to apply vanilla animator bool");
					if (!vanillaBools.TryGetValue(weather.Effect.SunAnimatorBool, out var _))
					{
						logger.LogInfo((object)$"No vanilla bool found for weather type {weatherType}");
						return;
					}
					clips[weatherType] = clips[vanillaBools[weather.Effect.SunAnimatorBool]];
				}
				if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null)
				{
					return;
				}
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Detected a null clip: " + ex.Message));
				return;
			}
			logger.LogWarning((object)$"Clips: {clips.Count}");
			if (clips.Keys.Select((LevelWeatherType key) => key == weatherType).Count() == 0)
			{
				logger.LogWarning((object)$"No animation clip found for weather type {weatherType}");
				return;
			}
			AnimationClip value2;
			string text = (clips.TryGetValue(weatherType, out value2) ? ((Object)value2).name : null);
			if (text == null)
			{
				logger.LogWarning((object)$"No animation clip found for weather type {weatherType}");
				return;
			}
			clips.ToList().ForEach(delegate(KeyValuePair<LevelWeatherType, AnimationClip> clipPair)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				if (clipPair.Key != weatherType)
				{
					clipOverrides[((Object)clipPair.Value).name] = clips[weatherType];
					logger.LogDebug((object)("Setting override from " + ((Object)clipPair.Value).name + " to " + ((Object)clips[weatherType]).name));
				}
				else
				{
					clipOverrides[((Object)clipPair.Value).name] = null;
					logger.LogDebug((object)("Setting override from " + ((Object)clipPair.Value).name + " to null"));
				}
			});
			logger.LogDebug((object)string.Format("Current bools: {0} {1}", TimeOfDay.Instance.sunAnimator.GetBool("overcast"), TimeOfDay.Instance.sunAnimator.GetBool("eclipsed")));
			if ((int)weatherType != -1)
			{
				animatorOverrideController.ApplyOverrides((IList<KeyValuePair<AnimationClip, AnimationClip>>)clipOverrides);
				TimeOfDay.Instance.sunAnimator.runtimeAnimatorController = (RuntimeAnimatorController)(object)animatorOverrideController;
			}
			else
			{
				TimeOfDay.Instance.sunAnimator.runtimeAnimatorController = animatorOverrideController.runtimeAnimatorController;
			}
			logger.LogInfo((object)("Current clip: " + ((Object)((AnimatorClipInfo)(ref TimeOfDay.Instance.sunAnimator.GetCurrentAnimatorClipInfo(0)[0])).clip).name));
		}

		internal static void LogOverrides(AnimationClipOverrides clipOverrides)
		{
			logger.LogDebug((object)$"Overrides: {clipOverrides.Count}");
			clipOverrides.ToList().ForEach(delegate(KeyValuePair<AnimationClip, AnimationClip> clip)
			{
				logger.LogInfo((object)("overrideclip " + (Object.op_Implicit((Object)(object)clip.Key) ? ((Object)clip.Key).name : "null") + " : " + (Object.op_Implicit((Object)(object)clip.Value) ? ((Object)clip.Value).name : "null")));
			});
		}

		internal static void Clear()
		{
			animatorOverrideController = null;
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	public static class TerminalStartPatch
	{
		internal static Logger Logger = new Logger("WeatherRegistry", ConfigManager.LogStartup);

		internal static WeatherEffect[] vanillaEffectsArray { get; private set; } = null;


		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		internal static void StartOfRoundAwakePrefix(RoundManager __instance)
		{
			Logger.LogInfo((object)"StartOfRoundAwakePrefix Patch");
			if (((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().IsHost)
			{
				Logger.LogDebug((object)"Host detected, spawning WeatherSync");
				WeatherSync component = Object.Instantiate<GameObject>(WeatherSync.WeatherSyncPrefab).GetComponent<WeatherSync>();
				((Component)component).GetComponent<NetworkObject>().Spawn(false);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("Awake")]
		[HarmonyPriority(800)]
		public static bool TerminalPrefix(Terminal __instance)
		{
			if (WeatherManager.IsSetupFinished)
			{
				WeatherManager.IsSetupFinished = false;
			}
			return true;
		}

		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		[HarmonyPriority(800)]
		public static void Postfix(Terminal __instance)
		{
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0406: Unknown result type (might be due to invalid IL or missing references)
			//IL_040b: Unknown result type (might be due to invalid IL or missing references)
			//IL_041d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0434: Unknown result type (might be due to invalid IL or missing references)
			//IL_044b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0462: Unknown result type (might be due to invalid IL or missing references)
			//IL_0469: Unknown result type (might be due to invalid IL or missing references)
			//IL_0470: Unknown result type (might be due to invalid IL or missing references)
			//IL_047c: Expected O, but got Unknown
			//IL_05dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f3: Expected O, but got Unknown
			Logger.LogInfo((object)"Terminal Start Patch");
			WeatherManager.Reset();
			WeatherEffect[] effects = TimeOfDay.Instance.effects;
			List<WeatherEffect> list = effects.ToList();
			if (effects == null || effects.Count() == 0)
			{
				Logger.LogInfo((object)"Effects are null");
			}
			else
			{
				Logger.LogInfo((object)$"Effects: {effects.Count()}");
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				List<RandomWeatherWithVariables> list2 = val.randomWeathers.ToList();
				RandomWeatherWithVariables[] randomWeathers = val.randomWeathers;
				foreach (RandomWeatherWithVariables val2 in randomWeathers)
				{
					if (!Enum.IsDefined(typeof(LevelWeatherType), val2.weatherType))
					{
						list2.Remove(val2);
						Plugin.logger.LogDebug((object)$"Removing weather {val2.weatherType} from level {((Object)val).name}");
					}
				}
				if (list2.Count != val.randomWeathers.Count())
				{
					val.randomWeathers = list2.ToArray();
				}
			}
			Logger.LogInfo((object)"Creating NoneWeather type");
			Weather weather3 = new Weather("None", new ImprovedWeatherEffect(null, null))
			{
				Type = WeatherType.Clear,
				Color = Defaults.VanillaWeatherColors[(LevelWeatherType)(-1)],
				VanillaWeatherType = (LevelWeatherType)(-1),
				Origin = WeatherOrigin.Vanilla
			};
			WeatherManager.Weathers.Add(weather3);
			WeatherManager.NoneWeather = weather3;
			for (int k = 0; k < effects.Count(); k++)
			{
				WeatherEffect val3 = effects[k];
				Logger.LogInfo((object)("Effect: " + val3.name));
				LevelWeatherType val4 = (LevelWeatherType)k;
				bool flag = Defaults.VanillaWeathers.Contains(val4);
				WeatherType type = (flag ? WeatherType.Vanilla : WeatherType.Modded);
				Color color = (flag ? Defaults.VanillaWeatherColors[val4] : Color.blue);
				ImprovedWeatherEffect effect = new ImprovedWeatherEffect(val3.effectObject, val3.effectPermanentObject)
				{
					SunAnimatorBool = val3.sunAnimatorBool
				};
				Weather item = new Weather(((object)(LevelWeatherType)(ref val4)).ToString(), effect)
				{
					Type = type,
					Color = color,
					VanillaWeatherType = val4,
					Origin = WeatherOrigin.Vanilla
				};
				WeatherManager.Weathers.Add(item);
			}
			if (Plugin.IsLethalLibLoaded)
			{
				Logger.LogWarning((object)"Getting LethalLib Weathers");
				List<Weather> list3 = LethalLibPatch.ConvertLLWeathers();
				foreach (Weather item3 in list3)
				{
					Logger.LogWarning((object)("LethalLib Weather: " + item3.Name));
					WeatherManager.RegisteredWeathers.Add(item3);
				}
			}
			int biggestKeyInModdedWeathersDictionary = Enum.GetValues(typeof(LevelWeatherType)).Length - 1;
			if (WeatherManager.ModdedWeatherEnumExtension.Count > 0)
			{
				biggestKeyInModdedWeathersDictionary = WeatherManager.ModdedWeatherEnumExtension.Keys.Max() + 1;
			}
			Logger.LogDebug((object)(WeatherManager.ModdedWeatherEnumExtension.Count > 0));
			Logger.LogDebug((object)("Biggest key in modded weathers dictionary: " + biggestKeyInModdedWeathersDictionary));
			WeatherManager.RegisteredWeathers.Where((Weather weather) => weather.Origin == WeatherOrigin.WeatherRegistry).ToList().ForEach(delegate(Weather weather)
			{
				int num2 = biggestKeyInModdedWeathersDictionary;
				weather.VanillaWeatherType = (LevelWeatherType)num2;
				Logger.LogInfo((object)$"Registering weather {weather.Name} under ID {num2}");
				WeatherManager.ModdedWeatherEnumExtension.Add(num2, weather);
				biggestKeyInModdedWeathersDictionary++;
			});
			int num = 0;
			foreach (KeyValuePair<int, Weather> item4 in WeatherManager.ModdedWeatherEnumExtension)
			{
				if (item4.Key > num)
				{
					num = item4.Key;
				}
			}
			while (list.Count <= num)
			{
				list.Add(null);
			}
			foreach (KeyValuePair<int, Weather> item5 in WeatherManager.ModdedWeatherEnumExtension)
			{
				list[item5.Key] = new WeatherEffect
				{
					name = item5.Value.Name,
					effectObject = item5.Value.Effect.EffectObject,
					effectPermanentObject = item5.Value.Effect.WorldObject,
					sunAnimatorBool = item5.Value.Effect.SunAnimatorBool,
					effectEnabled = false,
					lerpPosition = false,
					transitioning = false
				};
				GameObject effectObject = list[item5.Key].effectObject;
				if (effectObject != null)
				{
					effectObject.SetActive(false);
				}
				GameObject effectPermanentObject = list[item5.Key].effectPermanentObject;
				if (effectPermanentObject != null)
				{
					effectPermanentObject.SetActive(false);
				}
			}
			TimeOfDay.Instance.effects = list.ToArray();
			List<Weather> list4 = WeatherManager.RegisteredWeathers.Distinct().ToList();
			list4.Sort(delegate(Weather a, Weather b)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				LevelWeatherType vanillaWeatherType = a.VanillaWeatherType;
				return ((Enum)(LevelWeatherType)(ref vanillaWeatherType)).CompareTo((object?)b.VanillaWeatherType);
			});
			for (int l = 0; l < list4.Count; l++)
			{
				Logger.LogInfo((object)("Registered Weather: " + list4[l].Name));
				Weather item2 = list4[l];
				WeatherManager.Weathers.Add(item2);
			}
			Logger.LogWarning((object)$"Weathers: {WeatherManager.Weathers.Count}");
			List<SelectableLevel> list5 = StartOfRound.Instance.levels.ToList();
			foreach (Weather weather2 in WeatherManager.Weathers)
			{
				Settings.ScreenMapColors.Add(weather2.Name, weather2.Color);
				weather2.Init();
				List<SelectableLevel> list6 = new List<SelectableLevel>();
				if (weather2.LevelFilteringOption == FilteringOption.Include)
				{
					list6 = weather2.LevelFilters;
				}
				else if (weather2.LevelFilteringOption == FilteringOption.Exclude)
				{
					list6 = StartOfRound.Instance.levels.ToList();
					list6.RemoveAll((SelectableLevel level) => weather2.LevelFilters.Contains(level));
				}
				Logger.LogInfo((object)("Weather " + ((Object)weather2).name + " has " + weather2.LevelFilteringOption.ToString() + " filtering option set up"));
				AddWeatherToLevels(weather2, list5, list6);
			}
			ConsoleTable possibleWeathersTable = new ConsoleTable(new string[2] { "Planet", "Random weathers" });
			list5.Sort((SelectableLevel a, SelectableLevel b) => ConfigHelper.GetNumberlessName(a).CompareTo(ConfigHelper.GetNumberlessName(b)));
			list5.ForEach(delegate(SelectableLevel level)
			{
				List<LevelWeatherType> list7 = level.randomWeathers.Select((RandomWeatherWithVariables x) => x.weatherType).ToList();
				list7.Sort();
				string text = JsonConvert.SerializeObject((object)list7.Select((LevelWeatherType x) => ((object)(LevelWeatherType)(ref x)).ToString()).ToList());
				possibleWeathersTable.AddRow(new object[2]
				{
					ConfigHelper.GetNumberlessName(level),
					text
				});
			});
			Logger.LogInfo((object)("Possible weathers:\n" + possibleWeathersTable.ToMinimalString()));
			WeatherManager.IsSetupFinished = true;
			StartOfRound.Instance.SetPlanetsWeather(0);
			StartOfRound.Instance.SetMapScreenInfoToCurrentLevel();
			if (!((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				WeatherSync.Instance.ApplyWeathers(WeatherSync.Instance.Weather);
			}
			((CustomEvent)EventManager.SetupFinished).Invoke();
		}

		private static void AddWeatherToLevels(Weather weather, List<SelectableLevel> levels, List<SelectableLevel> LevelsToApply)
		{
			List<LevelWeatherVariables> list = new List<LevelWeatherVariables>();
			weather.WeatherVariables.Clear();
			foreach (SelectableLevel level in levels)
			{
				Logger.LogDebug((object)("Level: " + ConfigHelper.GetNumberlessName(level) + ", weather: " + weather.Name));
				List<RandomWeatherWithVariables> randomWeathers2 = level.randomWeathers.ToList();
				LevelWeather levelWeather = new LevelWeather
				{
					Weather = weather,
					Level = level,
					Variables = new LevelWeatherVariables()
				};
				RandomWeatherWithVariables val = null;
				val = ((IEnumerable<RandomWeatherWithVariables>)level.randomWeathers).FirstOrDefault((Func<RandomWeatherWithVariables, bool>)((RandomWeatherWithVariables randomWeather) => randomWeather.weatherType == weather.VanillaWeatherType));
				if (!InitializeRandomWeather(ref val, weather, level, ref randomWeathers2, LevelsToApply))
				{
					Logger.LogDebug((object)"randomWeather is null, skipping");
					continue;
				}
				levelWeather.Variables.Level = level;
				levelWeather.Variables.WeatherVariable1 = val?.weatherVariable ?? 1;
				levelWeather.Variables.WeatherVariable2 = val?.weatherVariable2 ?? 1;
				WeatherManager.LevelWeathers.Add(levelWeather);
				list.Add(levelWeather.Variables);
				weather.WeatherVariables.Add(level, levelWeather.Variables);
			}
			static bool InitializeRandomWeather(ref RandomWeatherWithVariables randomWeather, Weather weather, SelectableLevel level, ref List<RandomWeatherWithVariables> randomWeathers, List<SelectableLevel> LevelsToApply)
			{
				//IL_0253: Unknown result type (might be due to invalid IL or missing references)
				//IL_0258: Unknown result type (might be due to invalid IL or missing references)
				//IL_025f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0264: Unknown result type (might be due to invalid IL or missing references)
				//IL_0269: Unknown result type (might be due to invalid IL or missing references)
				//IL_027f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0296: Expected O, but got Unknown
				if (randomWeather == null && weather.Type == WeatherType.Vanilla)
				{
					return false;
				}
				if (weather.Type == WeatherType.Clear)
				{
					randomWeathers.RemoveAll((RandomWeatherWithVariables randomWeather) => randomWeather.weatherType == weather.VanillaWeatherType);
					level.randomWeathers = randomWeathers.ToArray();
					return false;
				}
				if (level.PlanetName == "71 Gordion" && !LevelsToApply.Contains(level))
				{
					Logger.LogDebug((object)("Removing weather " + weather.Name + " from the company moon"));
					randomWeathers.RemoveAll((RandomWeatherWithVariables randomWeather) => randomWeather.weatherType == weather.VanillaWeatherType);
					level.randomWeathers = randomWeathers.ToArray();
					return false;
				}
				switch (weather.Type)
				{
				case WeatherType.Vanilla:
					if (!LevelsToApply.Contains(level))
					{
						Logger.LogDebug((object)("Level " + ((Object)level).name + " is not in the list of levels to apply weather to"));
						if (randomWeather != null)
						{
							Logger.LogDebug((object)("Removing weather " + weather.Name + " from level " + ((Object)level).name));
							randomWeathers.RemoveAll((RandomWeatherWithVariables randomWeather) => randomWeather.weatherType == weather.VanillaWeatherType);
							level.randomWeathers = randomWeathers.ToArray();
						}
						return false;
					}
					return true;
				case WeatherType.Modded:
				{
					if (randomWeather != null)
					{
						Logger.LogDebug((object)("Removing weather " + weather.Name + " from level " + ((Object)level).name + " (added before lobby reload)"));
						randomWeathers.RemoveAll((RandomWeatherWithVariables randomWeather) => randomWeather.weatherType == weather.VanillaWeatherType);
					}
					Logger.LogDebug((object)("Adding modded weather " + weather.Name));
					if (!LevelsToApply.Contains(level))
					{
						Logger.LogDebug((object)("Level " + ((Object)level).name + " is not in the list of levels to apply weather to"));
						return false;
					}
					Logger.LogDebug((object)$"Injecting modded weather {weather.Name} for level {((Object)level).name} (variables {weather.Effect.DefaultVariable1}/{weather.Effect.DefaultVariable2})");
					RandomWeatherWithVariables item = (randomWeather = new RandomWeatherWithVariables
					{
						weatherType = weather.VanillaWeatherType,
						weatherVariable = weather.Effect.DefaultVariable1,
						weatherVariable2 = weather.Effect.DefaultVariable2
					});
					randomWeathers.Add(item);
					level.randomWeathers = randomWeathers.ToArray();
					break;
				}
				}
				return true;
			}
		}
	}
}
namespace WeatherRegistry.Events
{
	public class WeatherRegistryEvent<T> : CustomEvent<T>
	{
	}
	public class WeatherRegistryEvent : CustomEvent
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace WeatherRegistry.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}

BepInEx/plugins/americanompany/WeatherTweaks.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ConsoleTables;
using HarmonyLib;
using LethalLevelLoader;
using LethalNetworkAPI;
using LobbyCompatibility.Enums;
using LobbyCompatibility.Features;
using Microsoft.CodeAnalysis;
using MrovLib;
using MrovLib.Compatibility;
using MrovLib.Events;
using Newtonsoft.Json;
using Steamworks.Data;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using WeatherRegistry;
using WeatherRegistry.Events;
using WeatherRegistry.Patches;
using WeatherTweaks.Definitions;
using WeatherTweaks.Modules;
using WeatherTweaks.Patches;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: IgnoresAccessChecksTo("WeatherRegistry")]
[assembly: AssemblyCompany("WeatherTweaks")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("A template for Lethal Company")]
[assembly: AssemblyFileVersion("0.0.1.0")]
[assembly: AssemblyInformationalVersion("0.0.1+027a6166645265a284ffecce5c07f10b344aacb0")]
[assembly: AssemblyProduct("WeatherTweaks")]
[assembly: AssemblyTitle("WeatherTweaks")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace WeatherTweaks
{
	[HarmonyPatch(typeof(TimeOfDay))]
	public static class ChangeMidDay
	{
		internal static float lastCheckedEntry = 0f;

		internal static Random random;

		internal static WeatherTweaks.Definitions.Types.ProgressingWeatherEntry currentEntry;

		internal static WeatherTweaks.Definitions.Types.ProgressingWeatherEntry nextEntry;

		internal static ManualLogSource logger = Logger.CreateLogSource("WeatherTweaks ChangeMidDay");

		[HarmonyPostfix]
		[HarmonyPatch("MoveTimeOfDay")]
		internal static void MoveTimeOfDayPatch(TimeOfDay __instance)
		{
			if (Variables.CurrentLevelWeather.Type == CustomWeatherType.Progressing && ((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				float normalizedTimeOfDay = __instance.normalizedTimeOfDay;
				float num = ((nextEntry != null) ? nextEntry.DayTime : 0f);
				if (normalizedTimeOfDay >= num)
				{
					RunProgressingEntryActions(normalizedTimeOfDay);
				}
			}
		}

		internal static void RunProgressingEntryActions(float normalizedTimeOfDay)
		{
			//IL_0065: 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)
			WeatherType currentWeather = Variables.CurrentLevelWeather;
			if (random == null)
			{
				random = new Random(StartOfRound.Instance.randomMapSeed);
			}
			if (currentEntry == null)
			{
				currentEntry = new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0f,
					Chance = 1f,
					Weather = currentWeather.weatherType
				};
			}
			WeatherTweaks.Definitions.Types.ProgressingWeatherType progressingWeatherType = Variables.ProgressingWeatherTypes.First((WeatherTweaks.Definitions.Types.ProgressingWeatherType weather) => weather.Name == currentWeather.Name);
			List<WeatherTweaks.Definitions.Types.ProgressingWeatherEntry> weatherEntries = progressingWeatherType.WeatherEntries;
			weatherEntries.RemoveAll((WeatherTweaks.Definitions.Types.ProgressingWeatherEntry entry) => entry.DayTime < lastCheckedEntry);
			nextEntry = weatherEntries.FirstOrDefault((WeatherTweaks.Definitions.Types.ProgressingWeatherEntry entry) => entry.DayTime > lastCheckedEntry);
			foreach (WeatherTweaks.Definitions.Types.ProgressingWeatherEntry item in weatherEntries)
			{
				if (normalizedTimeOfDay > item.DayTime && item.DayTime > lastCheckedEntry)
				{
					logger.LogInfo((object)$"Changing weather to {item.GetWeatherType().Name} at {item.DayTime}");
					float num = (float)random.NextDouble();
					if (num > item.Chance)
					{
						logger.LogWarning((object)$"Random roll failed - got {num}, needed {item.Chance} or lower");
						lastCheckedEntry = item.DayTime;
						break;
					}
					NetworkedConfig.SetProgressingWeatherEntry(item);
					NetworkedConfig.SetWeatherEffects(new List<Weather>(1) { item.GetWeatherType().Weather });
					((MonoBehaviour)TimeOfDay.Instance).StartCoroutine(DoMidDayChange(item));
					lastCheckedEntry = item.DayTime;
					currentEntry = item;
					break;
				}
			}
		}

		internal static IEnumerator DoMidDayChange(WeatherTweaks.Definitions.Types.ProgressingWeatherEntry entry)
		{
			if (entry == null)
			{
				logger.LogError((object)"ProgressingWeatherEntry is null");
				yield return null;
			}
			logger.LogWarning((object)$"Changing weather to {entry.GetWeatherType().Name} at {entry.DayTime}, chance {entry.Chance} - is player inside? {EntranceTeleportPatch.isPlayerInside}");
			HUDManager.Instance.ReadDialogue(entry.GetDialogueSegment().ToArray());
			yield return (object)new WaitForSeconds(3f);
			WeatherType fullWeatherType = Variables.GetFullWeatherType(entry.GetWeatherType());
			logger.LogWarning((object)$"{fullWeatherType.Name} {fullWeatherType.Type} {fullWeatherType.weatherType}");
			StartOfRound.Instance.currentLevel.currentWeather = fullWeatherType.weatherType;
			TimeOfDay.Instance.currentLevelWeather = fullWeatherType.weatherType;
			GameNetworkManager.Instance.localPlayerController.currentAudioTrigger.weatherEffect = (int)fullWeatherType.weatherType;
			currentEntry = entry;
			GameInteraction.SetWeatherEffects(TimeOfDay.Instance, new List<ImprovedWeatherEffect>(1) { fullWeatherType.Weather.Effect });
		}
	}
	public abstract class ConfigHandler<T, CT> : ConfigHandler<T, CT>
	{
		public ConfigHandler(CT defaultValue, string configTitle, ConfigDescription configDescription = null)
		{
			((ConfigHandler<T, CT>)this).DefaultValue = defaultValue;
			((ConfigHandler<T, CT>)this).ConfigEntry = ConfigManager.configFile.Bind<CT>("5> Foggy patch", configTitle, ((ConfigHandler<T, CT>)this).DefaultValue, configDescription);
		}
	}
	public class LevelListConfigHandler : ConfigHandler<SelectableLevel[], string>
	{
		public override SelectableLevel[] Value => ConfigHelper.ConvertStringToLevels(((ConfigHandler<SelectableLevel[], string>)this).ConfigEntry.Value);

		public LevelListConfigHandler(string defaultValue, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, configTitle, configDescription)
		{
		}

		public void SetNewLevelsToIgnore(SelectableLevel[] levels)
		{
			string value = (((ConfigHandler<SelectableLevel[], string>)this).DefaultValue = string.Join(";", levels.Select((SelectableLevel level) => StringResolver.GetNumberlessName(level))) + ";");
			((ConfigHandler<SelectableLevel[], string>)this).ConfigEntry.Value = value;
		}
	}
	public class ConfigManager
	{
		internal static ConfigFile configFile;

		public static LevelListConfigHandler FoggyIgnoreLevels;

		public static ConfigManager Instance { get; private set; }

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

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

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

		public static ConfigEntry<int> FirstDaySeed { get; private set; }

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

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

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

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

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

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

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

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

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

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

		public static void Init(ConfigFile config)
		{
			Instance = new ConfigManager(config);
		}

		private ConfigManager(ConfigFile config)
		{
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Expected O, but got Unknown
			configFile = config;
			LogWeatherSelection = configFile.Bind<bool>("0> Debug", "LogWeatherSelection", true, "Log weather selection");
			LogWeatherVariables = configFile.Bind<bool>("0> Debug", "LogWeatherVariables", true, "Log resolving weather variables");
			LogLogs = configFile.Bind<bool>("0> Debug", "Logs", true, "Log logging logs");
			UncertainWeatherEnabled = configFile.Bind<bool>("1> Uncertain weather", "UncertainWeatherEnabled", true, "Enable uncertain weather mechanic");
			MaxMultiplier = configFile.Bind<float>("2> Multipliers", "MaxMultiplier", 0.8f, "Maximum difficulty multiplier (between 0 and 1)");
			ScaleDownClearWeather = configFile.Bind<bool>("2> Multipliers", "ScaleDownClearWeather", true, "Scale down clear weather's weight based on planet's available random weathers to match % chance ");
			GameLengthMultiplier = configFile.Bind<float>("2a> Difficulty multipliers", "GameLengthMultiplier", 0.05f, "Difficulty multiplier - game length (quotas done)");
			GamePlayersMultiplier = configFile.Bind<float>("2a> Difficulty multipliers", "GamePlayersMultiplier", 0.01f, "Difficulty multiplier - players amount");
			FirstDaySeed = configFile.Bind<int>("3> First day", "FirstDaySeed", 0, "Seed for the first day's weather");
			FirstDaySpecial = configFile.Bind<bool>("3> First day", "FirstDaySpecial", true, "Enable special weather picking algorithm for the first day");
			FirstDayRandomSeed = configFile.Bind<bool>("3> First day", "FirstDayRandomSeed", true, "Use random seed for the first day's weather");
			AlwaysUncertain = configFile.Bind<bool>("4> Special modes", "AlwaysUncertain", false, "Always make weather uncertain");
			AlwaysUnknown = configFile.Bind<bool>("4> Special modes", "AlwaysUnknown", false, "Always make weather unknown");
			AlwaysClear = configFile.Bind<bool>("4> Special modes", "AlwaysClear", false, "Always make weather clear - good for testing");
			FoggyIgnoreLevels = new LevelListConfigHandler("", "FoggyIgnoreLevels", new ConfigDescription("Levels to ignore applying foggy weather patch on", (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	public static class DisplayTable
	{
		public static void DisplayWeathersTable()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			if (!Variables.IsSetupFinished)
			{
				return;
			}
			ConsoleTable val = new ConsoleTable(new string[3] { "Planet", "Level weather", "Uncertain weather" });
			Plugin.logger.LogWarning((object)$"Displaying weathers table, instance: {StartOfRound.Instance}");
			if ((Object)(object)StartOfRound.Instance == (Object)null)
			{
				return;
			}
			List<SelectableLevel> gameLevels = Variables.GetGameLevels();
			foreach (SelectableLevel item in gameLevels)
			{
				bool flag = UncertainWeather.uncertainWeathers.ContainsKey(item.PlanetName);
				val.AddRow(new object[3]
				{
					item.PlanetName,
					Variables.GetPlanetCurrentWeather(item, uncertain: false),
					flag ? UncertainWeather.uncertainWeathers[item.PlanetName] : ""
				});
			}
			Plugin.logger.LogInfo((object)("Currently set weathers: \n" + val.ToMinimalString()));
		}
	}
	internal class GameInteraction
	{
		internal static Logger logger = new Logger("WeatherTweaks GameInteraction", ConfigManager.LogLogs);

		internal static void SetWeather(Dictionary<string, WeatherType> weatherData)
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogMessage((object)"Setting weather");
			List<SelectableLevel> gameLevels = Variables.GetGameLevels();
			foreach (SelectableLevel item in gameLevels)
			{
				string planetName = item.PlanetName;
				logger.LogDebug((object)("Setting weather for " + planetName));
				if (weatherData.ContainsKey(planetName))
				{
					WeatherType fullWeatherType = Variables.GetFullWeatherType(weatherData[planetName]);
					item.currentWeather = fullWeatherType.weatherType;
					Variables.CurrentWeathers[item] = fullWeatherType;
					logger.LogDebug((object)("Setting weather for " + planetName + " to " + fullWeatherType.Name));
				}
				else
				{
					Plugin.logger.LogWarning((object)("Weather data for " + planetName + " somehow not found, skipping"));
				}
			}
			StartOfRound.Instance.SetMapScreenInfoToCurrentLevel();
		}

		internal static void SetWeather(WeatherType weatherType)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			SelectableLevel currentLevel = StartOfRound.Instance.currentLevel;
			currentLevel.currentWeather = weatherType.weatherType;
			Variables.CurrentWeathers[currentLevel] = weatherType;
			logger.LogDebug((object)("Setting weather for " + currentLevel.PlanetName + " to " + weatherType.Name));
		}

		internal static void SetWeatherEffects(TimeOfDay timeOfDay, List<ImprovedWeatherEffect> weatherEffects)
		{
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			if (!Variables.IsSetupFinished)
			{
				logger.LogDebug((object)"Setup not finished, skipping setting weather effects");
				return;
			}
			logger.LogDebug((object)$"Setting weather effects for {timeOfDay.currentLevel.PlanetName}: {weatherEffects.Count} effects");
			if (weatherEffects == null)
			{
				logger.LogDebug((object)"No weather effects to set");
				return;
			}
			Variables.CurrentEffects = weatherEffects;
			List<LevelWeatherType> list = new List<LevelWeatherType>();
			foreach (Weather weather in WeatherManager.Weathers)
			{
				if ((Object)(object)weather.Effect == (Object)null)
				{
					continue;
				}
				ImprovedWeatherEffect effect = weather.Effect;
				if (weatherEffects.Contains(effect))
				{
					logger.LogDebug((object)("Enabling effect from weather: " + weather.Name));
					if (!EntranceTeleportPatch.isPlayerInside)
					{
						weather.Effect.EffectEnabled = true;
					}
					else
					{
						logger.LogWarning((object)"Player is inside, skipping effect object activation");
						weather.Effect.DisableEffect(true);
					}
					if (effect.SunAnimatorBool != "" && effect.SunAnimatorBool != null)
					{
						list.Add(weather.VanillaWeatherType);
					}
				}
				else
				{
					logger.LogDebug((object)("Disabling effect: " + weather.Name));
					weather.Effect.DisableEffect(true);
				}
			}
			if (list.Count == 0)
			{
				SunAnimator.OverrideSunAnimator((LevelWeatherType)(-1));
				return;
			}
			list.Distinct().ToList().ForEach(delegate(LevelWeatherType loopWeatherType)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				SunAnimator.OverrideSunAnimator(loopWeatherType);
			});
		}
	}
	internal class NetworkedConfig
	{
		public static LethalNetworkVariable<string> currentWeatherDictionarySynced = new LethalNetworkVariable<string>("previousWeather");

		public static LethalNetworkVariable<string> currentWeatherStringsSynced = new LethalNetworkVariable<string>("previousWeatherStrings");

		public static LethalNetworkVariable<string> weatherEffectsSynced = new LethalNetworkVariable<string>("weatherEffects");

		public static LethalNetworkVariable<string> weatherTypeSynced = new LethalNetworkVariable<string>("weatherType");

		public static LethalNetworkVariable<string> currentProgressingWeatherEntry = new LethalNetworkVariable<string>("currentProgressingWeatherEntry");

		public static void Init()
		{
			currentWeatherDictionarySynced.OnValueChanged += WeatherDataReceived;
			currentWeatherStringsSynced.OnValueChanged += WeatherDisplayDataReceived;
			weatherEffectsSynced.OnValueChanged += WeatherEffectsReceived;
			weatherTypeSynced.OnValueChanged += WeatherTypeReceived;
			currentProgressingWeatherEntry.OnValueChanged += ProgressingWeatherEntryReceived;
		}

		public static void WeatherDataReceived(string weatherData)
		{
			Dictionary<string, WeatherType> currentWeather = JsonConvert.DeserializeObject<Dictionary<string, WeatherType>>(weatherData);
			Plugin.logger.LogWarning((object)weatherData.Count());
			if (weatherData == null || ((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				return;
			}
			Plugin.logger.LogInfo((object)("Received weather data " + weatherData + " from server, applying"));
			GameInteraction.SetWeather(currentWeather);
			DisplayTable.DisplayWeathersTable();
			StartOfRound.Instance.SetMapScreenInfoToCurrentLevel();
			Dictionary<SelectableLevel, WeatherType> dictionary = new Dictionary<SelectableLevel, WeatherType>();
			List<SelectableLevel> gameLevels = Variables.GetGameLevels(includeCompanyMoon: true);
			Variables.CurrentWeathers = new Dictionary<SelectableLevel, WeatherType>();
			gameLevels.ToList().ForEach(delegate(SelectableLevel level)
			{
				KeyValuePair<string, WeatherType> keyValuePair = currentWeather.FirstOrDefault((KeyValuePair<string, WeatherType> x) => x.Key == level.PlanetName);
				if (keyValuePair.Key != null)
				{
					Variables.CurrentWeathers.Add(level, keyValuePair.Value);
				}
			});
		}

		public static void WeatherDisplayDataReceived(string weatherData)
		{
			Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(weatherData);
			if (dictionary != null && !((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				Plugin.logger.LogInfo((object)("Received weather display data " + weatherData + " from server, applying"));
				UncertainWeather.uncertainWeathers = dictionary;
				StartOfRound.Instance.SetMapScreenInfoToCurrentLevel();
			}
		}

		public static void WeatherEffectsReceived(string weatherEffects)
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogDebug((object)("Received weather effects: " + weatherEffects));
			List<Weather> source = JsonConvert.DeserializeObject<List<Weather>>(weatherEffects);
			List<ImprovedWeatherEffect> list = new List<ImprovedWeatherEffect>();
			if (list == null)
			{
				return;
			}
			foreach (Weather weather in WeatherManager.Weathers)
			{
				if (source.Select((Weather deserialized) => deserialized.VanillaWeatherType).Contains(weather.VanillaWeatherType))
				{
					list.Add(weather.Effect);
				}
			}
			Plugin.logger.LogInfo((object)("Received weather effects data " + weatherEffects + " from server, applying"));
			list.ForEach(delegate(ImprovedWeatherEffect effect)
			{
				Plugin.logger.LogDebug((object)$"Effect: {effect}");
			});
			GameInteraction.SetWeatherEffects(TimeOfDay.Instance, list);
		}

		public static void WeatherTypeReceived(string weatherType)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			WeatherType weatherType2 = JsonConvert.DeserializeObject<WeatherType>(weatherType);
			if (weatherType2 != null && !((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				Plugin.logger.LogWarning((object)("Received weather type data " + weatherType + " from server, applying"));
				Variables.CurrentLevelWeather = Variables.GetFullWeatherType(weatherType2);
				StartOfRound.Instance.currentLevel.currentWeather = Variables.CurrentLevelWeather.weatherType;
			}
		}

		public static void ProgressingWeatherEntryReceived(string progressingWeatherEntry)
		{
			WeatherTweaks.Definitions.Types.ProgressingWeatherEntry progressingWeatherEntry2 = JsonConvert.DeserializeObject<WeatherTweaks.Definitions.Types.ProgressingWeatherEntry>(progressingWeatherEntry);
			if (progressingWeatherEntry2 != null && !((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				Plugin.logger.LogWarning((object)("Received progressing weather entry data " + progressingWeatherEntry + " from server, applying"));
				((MonoBehaviour)TimeOfDay.Instance).StartCoroutine(ChangeMidDay.DoMidDayChange(progressingWeatherEntry2));
			}
		}

		public static void SetWeather(Dictionary<string, WeatherType> currentWeathers)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			string text = JsonConvert.SerializeObject((object)currentWeathers, (Formatting)0, new JsonSerializerSettings
			{
				ReferenceLoopHandling = (ReferenceLoopHandling)1
			});
			currentWeatherDictionarySynced.Value = text;
			Plugin.logger.LogInfo((object)("Set weather data on server: " + text));
		}

		public static void SetDisplayWeather(Dictionary<string, string> uncertainWeathers)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			string text = JsonConvert.SerializeObject((object)uncertainWeathers, (Formatting)0, new JsonSerializerSettings
			{
				ReferenceLoopHandling = (ReferenceLoopHandling)1
			});
			currentWeatherStringsSynced.Value = text;
			Plugin.logger.LogInfo((object)("Set weather display data on server: " + text));
		}

		public static void SetWeatherEffects(List<Weather> weathers)
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			Plugin.logger.LogDebug((object)$"Setting weather effects: {weathers}");
			if (weathers != null)
			{
				weathers.ForEach(delegate(Weather weather)
				{
					Plugin.logger.LogDebug((object)$"Weather: {weather}");
				});
				weathers.Select((Weather weather) => (int)weather.VanillaWeatherType != -1);
				Variables.CurrentEffects.RemoveAll((ImprovedWeatherEffect effect) => (Object)(object)effect == (Object)null);
				string text = JsonConvert.SerializeObject((object)weathers, (Formatting)0, new JsonSerializerSettings
				{
					ReferenceLoopHandling = (ReferenceLoopHandling)1
				});
				if (!(text == weatherEffectsSynced.Value))
				{
					weatherEffectsSynced.Value = text;
					Plugin.logger.LogInfo((object)("Set weather effects on server: " + text));
				}
			}
		}

		public static void SetWeatherType(WeatherType weatherType)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			string text = JsonConvert.SerializeObject((object)weatherType, (Formatting)0, new JsonSerializerSettings
			{
				ReferenceLoopHandling = (ReferenceLoopHandling)1
			});
			Plugin.logger.LogInfo((object)("Set weather type on server: " + text));
			weatherTypeSynced.Value = text;
		}

		public static void SetProgressingWeatherEntry(WeatherTweaks.Definitions.Types.ProgressingWeatherEntry entry)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			string text = JsonConvert.SerializeObject((object)entry, (Formatting)0, new JsonSerializerSettings
			{
				ReferenceLoopHandling = (ReferenceLoopHandling)1
			});
			Plugin.logger.LogInfo((object)("Set progressing weather entry on server: " + text));
			currentProgressingWeatherEntry.Value = text;
		}
	}
	[HarmonyPatch(typeof(EclipseWeather))]
	[HarmonyPatch(typeof(FloodWeather))]
	[HarmonyPatch(typeof(StormyWeather))]
	[HarmonyPatch(typeof(RoundManager))]
	internal class BasegameWeatherPatch
	{
		internal static Logger logger = new Logger("WeatherTweaks BaseGameWeatherPatches", ConfigManager.LogLogs);

		internal static Harmony harmony = new Harmony("WeatherTweaks.BaseGame");

		private static FieldInfo metalObjects = AccessTools.Field(typeof(StormyWeather), "metalObjects");

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(EclipseWeather), "OnEnable")]
		private static IEnumerable<CodeInstruction> EclipseOnEnablePatch(IEnumerable<CodeInstruction> instructions)
		{
			return CurrentWeatherVariablePatch(instructions, (LevelWeatherType)5, "EclipseWeather.OnEnable");
		}

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(FloodWeather), "OnEnable")]
		private static IEnumerable<CodeInstruction> FloodedOnEnablePatch(IEnumerable<CodeInstruction> instructions)
		{
			return CurrentWeatherVariablePatch(instructions, (LevelWeatherType)4, "FloodWeather.OnEnable");
		}

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(FloodWeather), "OnGlobalTimeSync")]
		private static IEnumerable<CodeInstruction> FloodedOnGlobalTimeSyncPatch(IEnumerable<CodeInstruction> instructions)
		{
			return CurrentWeatherVariable2Patch(instructions, (LevelWeatherType)4, "FloodWeather.OnGlobalTimeSync");
		}

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(FloodWeather), "Update")]
		private static IEnumerable<CodeInstruction> FloodedUpdatePatch(IEnumerable<CodeInstruction> instructions)
		{
			return CurrentWeatherVariablePatch(instructions, (LevelWeatherType)4, "FloodWeather.Update");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FloodWeather), "OnEnable")]
		private static void FloodedOnEnablePostfix(FloodWeather __instance)
		{
			__instance.floodLevelOffset = Mathf.Clamp(TimeOfDay.Instance.globalTime / 1080f, 0f, 100f) * Variables.GetLevelWeatherVariable((LevelWeatherType)4, variable2: true);
			logger.LogWarning((object)$"Enabling FloodWeather with level offset {__instance.floodLevelOffset}");
		}

		internal static IEnumerable<CodeInstruction> VariablePatch(IEnumerable<CodeInstruction> instructions, LevelWeatherType weatherType, string wherefrom, bool variable1 = true)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Expected O, but got Unknown
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			logger.LogInfo((object)$"Patching {wherefrom} for {weatherType}");
			CodeMatcher codeMatcher = new CodeMatcher(instructions, (ILGenerator)null);
			CodeMatch val = new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(TimeOfDay), "currentWeatherVariable"), (string)null);
			CodeMatch val2 = new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(TimeOfDay), "currentWeatherVariable2"), (string)null);
			codeMatcher = codeMatcher.MatchForward(false, (CodeMatch[])(object)new CodeMatch[2]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(TimeOfDay), "Instance", (Type[])null, (Type[])null), (string)null),
				variable1 ? val : val2
			});
			logger.LogDebug((object)$"Matched Ldfld for {wherefrom} for {weatherType}");
			codeMatcher.Repeat((Action<CodeMatcher>)delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Unknown result type (might be due to invalid IL or missing references)
				//IL_005d: Expected I4, but got Unknown
				//IL_005d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Expected O, but got Unknown
				//IL_008d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0093: Expected O, but got Unknown
				//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c8: Expected O, but got Unknown
				logger.LogInfo((object)$"Matched Ldfld for {wherefrom} for {weatherType}");
				codeMatcher.RemoveInstruction();
				codeMatcher.RemoveInstruction();
				codeMatcher.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldc_I4, (object)(int)weatherType)
				});
				codeMatcher.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldc_I4, (object)((!variable1) ? 1 : 0))
				});
				codeMatcher.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Variables), "GetLevelWeatherVariable", (Type[])null, (Type[])null))
				});
			}, (Action<string>)null);
			logger.LogDebug((object)$"Patched {wherefrom} for {weatherType}");
			return codeMatcher.InstructionEnumeration();
		}

		internal static IEnumerable<CodeInstruction> CurrentWeatherVariablePatch(IEnumerable<CodeInstruction> instructions, LevelWeatherType weatherType, string wherefrom)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return VariablePatch(instructions, weatherType, wherefrom);
		}

		internal static IEnumerable<CodeInstruction> CurrentWeatherVariable2Patch(IEnumerable<CodeInstruction> instructions, LevelWeatherType weatherType, string wherefrom)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return VariablePatch(instructions, weatherType, wherefrom, variable1: false);
		}

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(StormyWeather), "DetermineNextStrikeInterval")]
		private static IEnumerable<CodeInstruction> StormyDetermineNextStrikePatch(IEnumerable<CodeInstruction> instructions)
		{
			return CurrentWeatherVariablePatch(instructions, (LevelWeatherType)2, "StormyWeather.DetermineNextStrikeInterval");
		}

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(StormyWeather), "LightningStrikeRandom")]
		private static IEnumerable<CodeInstruction> StormyLightningStrikeRandomPatch(IEnumerable<CodeInstruction> instructions)
		{
			return CurrentWeatherVariablePatch(instructions, (LevelWeatherType)2, "StormyWeather.StormyLightningStrikeRandomPatch");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StormyWeather), "OnEnable")]
		private static void StormyOnEnablePostfix(StormyWeather __instance)
		{
			__instance.timeAtLastStrike = TimeOfDay.Instance.globalTime + 25f;
			logger.LogWarning((object)$"StormyWeather.Enable: {__instance.randomThunderTime} {__instance.timeAtLastStrike}");
		}

		[HarmonyPatch(typeof(StormyWeather), "OnDisable")]
		[HarmonyPostfix]
		public static void Fix_StormyNullRef(ref StormyWeather __instance)
		{
			((List<GrabbableObject>)metalObjects.GetValue(__instance)).Clear();
		}

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(RoundManager), "SpawnOutsideHazards")]
		private static IEnumerable<CodeInstruction> SpawnOutsideHazardsPatch(IEnumerable<CodeInstruction> instructions)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			CodeMatcher codeMatcher = new CodeMatcher(instructions, (ILGenerator)null);
			codeMatcher = codeMatcher.MatchForward(false, (CodeMatch[])(object)new CodeMatch[2]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(TimeOfDay), "Instance", (Type[])null, (Type[])null), (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(TimeOfDay), "currentLevelWeather"), (string)null)
			});
			logger.LogDebug((object)"Matched Ldfld for RoundManager.SpawnOutsideHazards");
			codeMatcher.Repeat((Action<CodeMatcher>)delegate
			{
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Expected O, but got Unknown
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Expected O, but got Unknown
				codeMatcher.RemoveInstruction();
				codeMatcher.RemoveInstruction();
				codeMatcher.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldc_I4, (object)1)
				});
				codeMatcher.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Variables), "LevelHasWeather", (Type[])null, (Type[])null))
				});
			}, (Action<string>)null);
			return codeMatcher.InstructionEnumeration();
		}
	}
	public static class DisableAllWeathers
	{
		internal static Logger logger = new Logger("WeatherTweaks TimeOfDay", ConfigManager.LogLogs);

		internal static void DisableAllWeather()
		{
			ChangeMidDay.lastCheckedEntry = 0f;
			ChangeMidDay.currentEntry = null;
			ChangeMidDay.nextEntry = null;
			if (((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				NetworkedConfig.SetWeatherEffects(new List<Weather>());
				NetworkedConfig.SetWeatherType(null);
				NetworkedConfig.SetProgressingWeatherEntry(null);
				ChangeMidDay.random = null;
			}
		}
	}
	[HarmonyPatch(typeof(EntranceTeleport))]
	internal class EntranceTeleportPatch
	{
		internal static Logger logger = new Logger("WeatherTweaks EntranceTeleport", ConfigManager.LogLogs);

		internal static bool isPlayerInside = false;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EntranceTeleport), "TeleportPlayer")]
		private static void TeleportPlayerPatch(EntranceTeleport __instance)
		{
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Invalid comparison between Unknown and I4
			logger.LogDebug((object)("TeleportPlayerPatch called with " + ((Object)__instance).name));
			isPlayerInside = __instance.isEntranceToBuilding;
			if (isPlayerInside)
			{
				logger.LogDebug((object)"Player is inside");
				return;
			}
			logger.LogDebug((object)"Player is outside");
			List<ImprovedWeatherEffect> list = new List<ImprovedWeatherEffect>();
			WeatherType currentWeather = Variables.GetCurrentWeather();
			if (currentWeather.Type == CustomWeatherType.Combined)
			{
				WeatherTweaks.Definitions.Types.CombinedWeatherType combinedWeatherType = (WeatherTweaks.Definitions.Types.CombinedWeatherType)currentWeather;
				list = combinedWeatherType.Weathers.Select((Weather weather) => weather.Effect).ToList();
			}
			else
			{
				list = new List<ImprovedWeatherEffect>(1) { currentWeather.Weather.Effect };
			}
			foreach (Weather weather in WeatherManager.Weathers)
			{
				logger.LogDebug((object)("Weather: " + weather.Name));
				if ((int)weather.Type != 0)
				{
					if (list.Contains(weather.Effect))
					{
						weather.Effect.EffectEnabled = true;
					}
					else
					{
						weather.Effect.DisableEffect(false);
					}
				}
			}
		}
	}
	internal class LobbyCompatibilityCompatibility
	{
		public static void Init()
		{
			Plugin.logger.LogWarning((object)"LobbyCompatibility detected, registering plugin with LobbyCompatibility.");
			Version version = Version.Parse("0.0.1");
			PluginHelper.RegisterPlugin("WeatherTweaks", version, (CompatibilityLevel)2, (VersionStrictness)0);
		}
	}
	internal class OpeningDoorsSequencePatch
	{
		internal static void SetWeatherEffects(SelectableLevel level, Weather weather)
		{
			//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_00a9: Expected O, but got Unknown
			WeatherType fullWeatherType = Variables.GetFullWeatherType(Variables.CurrentWeathers[level]);
			if (((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				if (fullWeatherType.Type == CustomWeatherType.Combined)
				{
					Plugin.logger.LogWarning((object)"WeatherType is CombinedWeatherType");
					WeatherTweaks.Definitions.Types.CombinedWeatherType combinedWeatherType = (WeatherTweaks.Definitions.Types.CombinedWeatherType)fullWeatherType;
					NetworkedConfig.SetWeatherEffects(combinedWeatherType.Weathers);
				}
				else
				{
					NetworkedConfig.SetWeatherEffects(new List<Weather>(1) { fullWeatherType.Weather });
				}
			}
			Variables.CurrentLevelWeather = fullWeatherType;
			Plugin.logger.LogWarning((object)("Landing at " + SharedMethods.GetNumberlessPlanetName(TimeOfDay.Instance.currentLevel) + " with weather " + JsonConvert.SerializeObject((object)fullWeatherType, (Formatting)0, new JsonSerializerSettings
			{
				ReferenceLoopHandling = (ReferenceLoopHandling)1
			})));
		}

		[HarmonyPatch("RunWeatherPatches")]
		[HarmonyPostfix]
		internal static void RunWeatherPatches()
		{
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	public static class SetPlanetsWeatherPatch
	{
		[HarmonyPatch("SetPlanetsWeather")]
		[HarmonyPrefix]
		[HarmonyAfter(new string[] { "mrov.WeatherRegistry", "imabatby.lethallevelloader" })]
		private static bool GameMethodPatch(int connectedPlayersOnServer, StartOfRound __instance)
		{
			//IL_0160: 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_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogMessage((object)"SetPlanetsWeather called.");
			if (!Variables.IsSetupFinished)
			{
				Plugin.logger.LogWarning((object)"Setup not finished");
				return true;
			}
			if ((Object)(object)__instance == (Object)null)
			{
				Plugin.logger.LogWarning((object)"Instance is null");
				return true;
			}
			List<SelectableLevel> gameLevels = Variables.GetGameLevels();
			if (gameLevels == null)
			{
				Plugin.logger.LogWarning((object)"Levels are null");
				return true;
			}
			ChangeMidDay.lastCheckedEntry = 0f;
			EntranceTeleportPatch.isPlayerInside = false;
			bool hasValue = GameNetworkManager.Instance.currentLobby.HasValue;
			Lobby valueOrDefault;
			if (((NetworkBehaviour)__instance).IsHost)
			{
				Variables.CurrentWeathers = new Dictionary<SelectableLevel, WeatherType>();
				Dictionary<string, WeatherType> weather = WeatherCalculation.NewWeathers(__instance);
				GameInteraction.SetWeather(weather);
				NetworkedConfig.SetWeather(weather);
				Dictionary<string, string> displayWeather = UncertainWeather.GenerateUncertainty();
				NetworkedConfig.SetDisplayWeather(displayWeather);
				__instance.SetMapScreenInfoToCurrentLevel();
				if (hasValue)
				{
					Lobby? currentLobby = GameNetworkManager.Instance.currentLobby;
					if (currentLobby.HasValue)
					{
						valueOrDefault = currentLobby.GetValueOrDefault();
						((Lobby)(ref valueOrDefault)).SetData("WeatherTweaks", "true");
					}
				}
			}
			else
			{
				Plugin.logger.LogMessage((object)"Not a host");
				if (hasValue)
				{
					Lobby? currentLobby = GameNetworkManager.Instance.currentLobby;
					object obj;
					if (!currentLobby.HasValue)
					{
						obj = null;
					}
					else
					{
						valueOrDefault = currentLobby.GetValueOrDefault();
						obj = ((Lobby)(ref valueOrDefault)).GetData("WeatherTweaks");
					}
					if (obj == null)
					{
						Plugin.logger.LogMessage((object)"Mod not detected on host, falling back to vanilla");
						return true;
					}
					Plugin.logger.LogMessage((object)"Detected mod on host, waiting for weather data");
				}
				Plugin.logger.LogDebug((object)("Current data: " + NetworkedConfig.currentWeatherDictionarySynced.Value));
			}
			return false;
		}

		[HarmonyPatch("SetPlanetsWeather")]
		[HarmonyPostfix]
		private static void DisplayCurrentWeathers()
		{
			DisplayTable.DisplayWeathersTable();
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	public static class TextPostProcessPatch
	{
		internal static Logger logger = new Logger("WeatherTweaks Terminal", ConfigManager.LogLogs);

		[HarmonyPatch("TextPostProcess")]
		[HarmonyPrefix]
		[HarmonyPriority(700)]
		private static bool PatchGameMethod(ref string modifiedDisplayText, TerminalNode node)
		{
			if (node.buyRerouteToMoon == -2)
			{
				logger.LogDebug((object)"buyRerouteToMoon == -2");
				Regex regex = new Regex("\\ It is (\\n)*currently.+\\[currentPlanetTime].+");
				if (regex.IsMatch(modifiedDisplayText))
				{
					modifiedDisplayText = regex.Replace(modifiedDisplayText, "");
				}
			}
			if (((Object)node).name == "MoonsCatalogue")
			{
				Regex regex2 = new Regex("\\[planetTime\\]");
				modifiedDisplayText = regex2.Replace(modifiedDisplayText, "");
			}
			return true;
		}
	}
	[BepInPlugin("WeatherTweaks", "WeatherTweaks", "0.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.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Event <>9__4_0;

			public static ParameterEvent<(SelectableLevel level, Weather weather)> <>9__4_1;

			public static Event <>9__4_2;

			public static Event <>9__4_3;

			public static ParameterEvent<Terminal> <>9__4_4;

			public static ParameterEvent<StartOfRound> <>9__4_5;

			internal void <Awake>b__4_0()
			{
				DisableAllWeathers.DisableAllWeather();
			}

			internal void <Awake>b__4_1((SelectableLevel level, Weather weather) data)
			{
				OpeningDoorsSequencePatch.SetWeatherEffects(data.level, data.weather);
			}

			internal void <Awake>b__4_2()
			{
				TerminalStartPatch.Start();
			}

			internal void <Awake>b__4_3()
			{
				Variables.PopulateWeathers();
			}

			internal void <Awake>b__4_4(Terminal terminal)
			{
				TerminalPatch.Postfix();
			}

			internal void <Awake>b__4_5(StartOfRound startofround)
			{
				Reset.ResetThings();
			}
		}

		internal static ManualLogSource logger;

		internal static Logger DebugLogger = new Logger("WeatherTweaks", (ConfigEntry<bool>)null);

		internal static bool IsLLLPresent = false;

		internal static GeneralImprovementsWeather GeneralImprovements;

		private void Awake()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Expected O, but got Unknown
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Expected O, but got Unknown
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Expected O, but got Unknown
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Expected O, but got Unknown
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			logger = ((BaseUnityPlugin)this).Logger;
			ConfigManager.Init(((BaseUnityPlugin)this).Config);
			Harmony val = new Harmony("WeatherTweaks");
			val.PatchAll();
			NetworkedConfig.Init();
			UncertainWeather.Init();
			new CombinedEclipsedFlooded();
			new CombinedFoggyRainy();
			new CombinedStormyFlooded();
			new CombinedStormyRainy();
			new CombinedEclipsedRainy();
			new CombinedMadness();
			new CombinedFoggyFlooded();
			new CombinedFoggyEclipsed();
			new CombinedStormyRainyEclipsed();
			new CombinedStormyRainyFlooded();
			new ProgressingNoneFoggy();
			new ProgressingNoneStormy();
			new ProgressingEclipsedFoggy();
			new ProgressingFoggyNone();
			new ProgressingHiddenEclipsed();
			new ProgressingStormyRainy();
			new ProgressingRainyEclipsed();
			new ProgressingMadness();
			Settings.SelectWeathers = false;
			WeatherRegistryEvent disableAllWeathers = EventManager.DisableAllWeathers;
			object obj = <>c.<>9__4_0;
			if (obj == null)
			{
				Event val2 = delegate
				{
					DisableAllWeathers.DisableAllWeather();
				};
				<>c.<>9__4_0 = val2;
				obj = (object)val2;
			}
			((CustomEvent)disableAllWeathers).AddListener((Event)obj);
			((CustomEvent<(SelectableLevel, Weather)>)(object)EventManager.ShipLanding).AddListener((ParameterEvent<(SelectableLevel, Weather)>)delegate((SelectableLevel level, Weather weather) data)
			{
				OpeningDoorsSequencePatch.SetWeatherEffects(data.level, data.weather);
			});
			WeatherRegistryEvent setupFinished = EventManager.SetupFinished;
			object obj2 = <>c.<>9__4_2;
			if (obj2 == null)
			{
				Event val3 = delegate
				{
					TerminalStartPatch.Start();
				};
				<>c.<>9__4_2 = val3;
				obj2 = (object)val3;
			}
			((CustomEvent)setupFinished).AddListener((Event)obj2);
			WeatherRegistryEvent setupFinished2 = EventManager.SetupFinished;
			object obj3 = <>c.<>9__4_3;
			if (obj3 == null)
			{
				Event val4 = delegate
				{
					Variables.PopulateWeathers();
				};
				<>c.<>9__4_3 = val4;
				obj3 = (object)val4;
			}
			((CustomEvent)setupFinished2).AddListener((Event)obj3);
			EventManager.TerminalStart.AddListener((ParameterEvent<Terminal>)delegate
			{
				TerminalPatch.Postfix();
			});
			EventManager.LobbyDisabled.AddListener((ParameterEvent<StartOfRound>)delegate
			{
				Reset.ResetThings();
			});
			if (Chainloader.PluginInfos.ContainsKey("imabatby.lethallevelloader"))
			{
				LLL.Init();
			}
			MethodInfo method = typeof(StartOfRound).GetMethod("SetPlanetsWeather");
			val.Unpatch((MethodBase)method, (HarmonyPatchType)2, "imabatby.lethallevelloader");
			GeneralImprovements = new GeneralImprovementsWeather("ShaosilGaming.GeneralImprovements");
			if (Chainloader.PluginInfos.ContainsKey("xxxstoner420bongmasterxxx.open_monitors"))
			{
				OpenMonitorsPatch.Init();
			}
			if (Chainloader.PluginInfos.ContainsKey("com.zealsprince.malfunctions"))
			{
				Malfunctions.Init();
			}
			if (Chainloader.PluginInfos.ContainsKey("BMX.LobbyCompatibility"))
			{
				LobbyCompatibilityCompatibility.Init();
			}
			Weather val5 = new Weather("Cloudy", new ImprovedWeatherEffect((GameObject)null, (GameObject)null)
			{
				SunAnimatorBool = "overcast"
			});
			val5.Color = new Color(0f, 0.62f, 0.55f, 1f);
			val5.ScrapAmountMultiplier = 1.6f;
			val5.ScrapValueMultiplier = 0.8f;
			val5.DefaultWeatherToWeatherWeights = new string[2] { "Eclipsed@200", "Stormy@80" };
			val5.DefaultWeight = 10;
			Weather val6 = val5;
			WeatherManager.RegisterWeather(val6);
			logger.LogInfo((object)"\r\n                  .::.                  \r\n                  :==:                  \r\n         :-.      :==:      .-:         \r\n        .-==-.    .::.    .-===.        \r\n          .-=-  .:----:.  -==.          \r\n              -==========-              \r\n             ==============             \r\n               .-==========- :-----     \r\n         :-==-:. .=========- :-----     \r\n       .========:   .-=====             \r\n       ============-. :==-              \r\n       -=============. .  -==.          \r\n        :-==========:     .-==-.        \r\n            ......          .-:         ");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin WeatherTweaks is loaded!");
		}
	}
	public static class TerminalPatch
	{
		public static void Postfix()
		{
			if (((CompatibilityBase)Plugin.GeneralImprovements).IsModPresent)
			{
				Plugin.logger.LogInfo((object)"GeneralImprovements is present");
				GeneralImprovementsWeather.Init();
			}
		}
	}
	internal class CombinedEclipsedFlooded : WeatherTweaks.Definitions.Types.CombinedWeatherType
	{
		public CombinedEclipsedFlooded()
			: base("Eclipsed + Flooded", new List<LevelWeatherType>(2)
			{
				(LevelWeatherType)5,
				(LevelWeatherType)4
			})
		{
		}
	}
	internal class CombinedFoggyRainy : WeatherTweaks.Definitions.Types.CombinedWeatherType
	{
		public CombinedFoggyRainy()
			: base("Foggy + Rainy", new List<LevelWeatherType>(2)
			{
				(LevelWeatherType)3,
				(LevelWeatherType)1
			})
		{
		}
	}
	internal class CombinedEclipsedRainy : WeatherTweaks.Definitions.Types.CombinedWeatherType
	{
		public CombinedEclipsedRainy()
			: base("Eclipsed + Rainy", new List<LevelWeatherType>(2)
			{
				(LevelWeatherType)5,
				(LevelWeatherType)1
			})
		{
		}
	}
	internal class CombinedStormyRainy : WeatherTweaks.Definitions.Types.CombinedWeatherType
	{
		public CombinedStormyRainy()
			: base("Stormy + Rainy", new List<LevelWeatherType>(2)
			{
				(LevelWeatherType)2,
				(LevelWeatherType)1
			})
		{
		}
	}
	internal class CombinedStormyFlooded : WeatherTweaks.Definitions.Types.CombinedWeatherType
	{
		public CombinedStormyFlooded()
			: base("Stormy + Flooded", new List<LevelWeatherType>(2)
			{
				(LevelWeatherType)2,
				(LevelWeatherType)4
			})
		{
		}
	}
	internal class CombinedFoggyFlooded : WeatherTweaks.Definitions.Types.CombinedWeatherType
	{
		public CombinedFoggyFlooded()
			: base("Foggy + Flooded", new List<LevelWeatherType>(2)
			{
				(LevelWeatherType)3,
				(LevelWeatherType)4
			})
		{
		}
	}
	internal class CombinedFoggyEclipsed : WeatherTweaks.Definitions.Types.CombinedWeatherType
	{
		public CombinedFoggyEclipsed()
			: base("Foggy + Eclipsed", new List<LevelWeatherType>(2)
			{
				(LevelWeatherType)3,
				(LevelWeatherType)5
			})
		{
		}
	}
	internal class CombinedStormyRainyEclipsed : WeatherTweaks.Definitions.Types.CombinedWeatherType
	{
		public CombinedStormyRainyEclipsed()
			: base("Stormy + Rainy + Eclipsed", new List<LevelWeatherType>(3)
			{
				(LevelWeatherType)2,
				(LevelWeatherType)1,
				(LevelWeatherType)5
			})
		{
		}
	}
	internal class CombinedStormyRainyFlooded : WeatherTweaks.Definitions.Types.CombinedWeatherType
	{
		public CombinedStormyRainyFlooded()
			: base("Stormy + Rainy + Flooded", new List<LevelWeatherType>(3)
			{
				(LevelWeatherType)2,
				(LevelWeatherType)1,
				(LevelWeatherType)4
			})
		{
		}
	}
	internal class CombinedMadness : WeatherTweaks.Definitions.Types.CombinedWeatherType
	{
		public CombinedMadness()
			: base("Madness", new List<LevelWeatherType>(5)
			{
				(LevelWeatherType)3,
				(LevelWeatherType)5,
				(LevelWeatherType)1,
				(LevelWeatherType)2,
				(LevelWeatherType)4
			}, 0.02f)
		{
		}
	}
	internal class ProgressingNoneFoggy : WeatherTweaks.Definitions.Types.ProgressingWeatherType
	{
		public ProgressingNoneFoggy()
			: base("None > Foggy", (LevelWeatherType)(-1), new List<WeatherTweaks.Definitions.Types.ProgressingWeatherEntry>(2)
			{
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.25f,
					Chance = 0.8f,
					Weather = (LevelWeatherType)3
				},
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.75f,
					Chance = 1f,
					Weather = (LevelWeatherType)3
				}
			})
		{
		}//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)

	}
	internal class ProgressingNoneStormy : WeatherTweaks.Definitions.Types.ProgressingWeatherType
	{
		public ProgressingNoneStormy()
			: base("None > Stormy", (LevelWeatherType)(-1), new List<WeatherTweaks.Definitions.Types.ProgressingWeatherEntry>(2)
			{
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.35f,
					Chance = 0.35f,
					Weather = (LevelWeatherType)2
				},
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.75f,
					Chance = 1f,
					Weather = (LevelWeatherType)2
				}
			})
		{
		}//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)

	}
	internal class ProgressingEclipsedFoggy : WeatherTweaks.Definitions.Types.ProgressingWeatherType
	{
		public ProgressingEclipsedFoggy()
			: base("Eclipsed > Foggy", (LevelWeatherType)5, new List<WeatherTweaks.Definitions.Types.ProgressingWeatherEntry>(2)
			{
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.4f,
					Chance = 0.5f,
					Weather = (LevelWeatherType)3
				},
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.85f,
					Chance = 1f,
					Weather = (LevelWeatherType)3
				}
			})
		{
		}//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)

	}
	internal class ProgressingFoggyNone : WeatherTweaks.Definitions.Types.ProgressingWeatherType
	{
		public ProgressingFoggyNone()
			: base("Foggy > None", (LevelWeatherType)3, new List<WeatherTweaks.Definitions.Types.ProgressingWeatherEntry>(1)
			{
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.45f,
					Chance = 1f,
					Weather = (LevelWeatherType)(-1)
				}
			})
		{
		}//IL_002b: Unknown result type (might be due to invalid IL or missing references)

	}
	internal class ProgressingHiddenEclipsed : WeatherTweaks.Definitions.Types.ProgressingWeatherType
	{
		public ProgressingHiddenEclipsed()
			: base("Eclipsed > None", (LevelWeatherType)5, new List<WeatherTweaks.Definitions.Types.ProgressingWeatherEntry>(1)
			{
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.66f,
					Chance = 1f,
					Weather = (LevelWeatherType)(-1)
				}
			})
		{
		}//IL_002b: Unknown result type (might be due to invalid IL or missing references)

	}
	internal class ProgressingStormyRainy : WeatherTweaks.Definitions.Types.ProgressingWeatherType
	{
		public ProgressingStormyRainy()
			: base("Stormy > Rainy", (LevelWeatherType)2, new List<WeatherTweaks.Definitions.Types.ProgressingWeatherEntry>(1)
			{
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.55f,
					Chance = 1f,
					Weather = (LevelWeatherType)1
				}
			})
		{
		}//IL_002b: Unknown result type (might be due to invalid IL or missing references)

	}
	internal class ProgressingRainyEclipsed : WeatherTweaks.Definitions.Types.ProgressingWeatherType
	{
		public ProgressingRainyEclipsed()
			: base("Rainy > Eclipsed", (LevelWeatherType)1, new List<WeatherTweaks.Definitions.Types.ProgressingWeatherEntry>(1)
			{
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.66f,
					Chance = 1f,
					Weather = (LevelWeatherType)5
				}
			})
		{
		}//IL_002b: Unknown result type (might be due to invalid IL or missing references)

	}
	internal class ProgressingMadness : WeatherTweaks.Definitions.Types.ProgressingWeatherType
	{
		public ProgressingMadness()
			: base(">Madness>", (LevelWeatherType)5, new List<WeatherTweaks.Definitions.Types.ProgressingWeatherEntry>(3)
			{
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.1f,
					Chance = 0.5f,
					Weather = (LevelWeatherType)4
				},
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.4f,
					Chance = 0.5f,
					Weather = (LevelWeatherType)3
				},
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.65f,
					Chance = 1f,
					Weather = (LevelWeatherType)2
				}
			}, 0.1f)
		{
		}//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)

	}
	internal class ProgressingTesting : WeatherTweaks.Definitions.Types.ProgressingWeatherType
	{
		public ProgressingTesting()
			: base("> Testing >", (LevelWeatherType)5, new List<WeatherTweaks.Definitions.Types.ProgressingWeatherEntry>(1)
			{
				new WeatherTweaks.Definitions.Types.ProgressingWeatherEntry
				{
					DayTime = 0.2f,
					Chance = 1f,
					Weather = (LevelWeatherType)(-1)
				}
			}, 500f)
		{
		}//IL_002b: Unknown result type (might be due to invalid IL or missing references)

	}
	internal class UncertainTypes
	{
		public class Uncertain : WeatherTweaks.Modules.Types.UncertainWeatherType
		{
			public Uncertain()
				: base("Uncertain")
			{
			}

			public override string CreateUncertaintyString(SelectableLevel level, Random random)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0098: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Unknown result type (might be due to invalid IL or missing references)
				LevelWeatherType weather = level.currentWeather;
				List<RandomWeatherWithVariables> list = level.randomWeathers.Where((RandomWeatherWithVariables w) => w.weatherType != weather).ToList();
				if (list.Count == 0)
				{
					return ((object)(LevelWeatherType)(ref weather)).ToString();
				}
				RandomWeatherWithVariables val = list[random.Next(list.Count)];
				if (random.Next(0, 3) == 0)
				{
					return $"{val.weatherType}?";
				}
				return $"{weather}?";
			}
		}

		public class Uncertain5050 : WeatherTweaks.Modules.Types.UncertainWeatherType
		{
			public Uncertain5050()
				: base("Uncertain5050")
			{
			}

			public override string CreateUncertaintyString(SelectableLevel level, Random random)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				LevelWeatherType weather = level.currentWeather;
				List<RandomWeatherWithVariables> list = level.randomWeathers.Where((RandomWeatherWithVariables w) => w.weatherType != weather).ToList();
				if (list.Count == 0)
				{
					return ((object)(LevelWeatherType)(ref weather)).ToString();
				}
				RandomWeatherWithVariables val = list[random.Next(list.Count)];
				if (random.Next(0, 1) == 0)
				{
					return $"{weather}/{val.weatherType}";
				}
				return $"{val.weatherType}/{weather}";
			}
		}

		public class Unknown : WeatherTweaks.Modules.Types.UncertainWeatherType
		{
			public Unknown()
				: base("Unknown")
			{
			}

			public override string CreateUncertaintyString(SelectableLevel level, Random random)
			{
				return "[UNKNOWN]";
			}
		}
	}
	internal class UncertainWeather
	{
		public static Dictionary<string, string> uncertainWeathers = new Dictionary<string, string>();

		public static List<WeatherTweaks.Modules.Types.UncertainWeatherType> uncertainWeatherTypes = new List<WeatherTweaks.Modules.Types.UncertainWeatherType>();

		public static void Init()
		{
			Plugin.logger.LogInfo((object)"UncertainWeather initialized.");
			uncertainWeatherTypes = new List<WeatherTweaks.Modules.Types.UncertainWeatherType>(3)
			{
				new UncertainTypes.Uncertain(),
				new UncertainTypes.Uncertain5050(),
				new UncertainTypes.Unknown()
			};
		}

		public static Dictionary<string, string> GenerateUncertainty()
		{
			uncertainWeathers.Clear();
			if (!ConfigManager.UncertainWeatherEnabled.Value)
			{
				Plugin.logger.LogInfo((object)"Uncertain weathers are disabled.");
				return uncertainWeathers;
			}
			if (StartOfRound.Instance.gameStats.daysSpent == 0 && !ConfigManager.AlwaysUncertain.Value && !ConfigManager.AlwaysUnknown.Value)
			{
				Plugin.logger.LogInfo((object)"It's the first day, no uncertainty will be generated.");
				return uncertainWeathers;
			}
			Plugin.logger.LogInfo((object)"GenerateUncertainty called.");
			StartOfRound instance = StartOfRound.Instance;
			Random random = new Random(instance.randomMapSeed + 31);
			int num = Mathf.Clamp((int)((double)Mathf.Clamp(instance.planetsWeatherRandomCurve.Evaluate((float)random.NextDouble()) * 0.4f, 0f, 1f) * (double)Variables.GameLevels.Count), 1, Variables.GameLevels.Count - 2);
			if (ConfigManager.AlwaysUncertain.Value || ConfigManager.AlwaysUnknown.Value)
			{
				num = Variables.GameLevels.Count;
			}
			Plugin.logger.LogDebug((object)$"howManyPlanetsUncertain: {num}");
			List<SelectableLevel> list = new List<SelectableLevel>();
			for (int i = 0; i < num; i++)
			{
				SelectableLevel item = Variables.GameLevels[random.Next(Variables.GameLevels.Count)];
				if (!list.Contains(item))
				{
					list.Add(item);
				}
				else
				{
					i--;
				}
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			List<WeatherTweaks.Modules.Types.UncertainWeatherType> list2 = new List<WeatherTweaks.Modules.Types.UncertainWeatherType>();
			foreach (WeatherTweaks.Modules.Types.UncertainWeatherType uncertainWeatherType in uncertainWeatherTypes)
			{
				if (uncertainWeatherType.Enabled.Value)
				{
					list2.Add(uncertainWeatherType);
				}
			}
			if (ConfigManager.AlwaysUnknown.Value)
			{
				Plugin.logger.LogDebug((object)"Setting possible types to only unknown.");
				list2 = new List<WeatherTweaks.Modules.Types.UncertainWeatherType>(1)
				{
					new UncertainTypes.Unknown()
				};
			}
			Plugin.logger.LogDebug((object)$"uncertainTypes: {list2.Count}");
			if (list2.Count == 0)
			{
				Plugin.logger.LogInfo((object)"No uncertain types are enabled, skipping uncertainty generation.");
				return uncertainWeathers;
			}
			foreach (SelectableLevel item2 in list)
			{
				int index = random.Next(list2.Count);
				string text = list2[index].CreateUncertaintyString(item2, random);
				Plugin.logger.LogDebug((object)("Rolled type: " + list2[index].Name + ", setting its uncertainty to " + text + "."));
				dictionary.Add(item2.PlanetName, text);
			}
			uncertainWeathers = dictionary;
			return dictionary;
		}
	}
	internal class Variables
	{
		internal static List<SelectableLevel> GameLevels = new List<SelectableLevel>();

		internal static bool IsSetupFinished = false;

		internal static WeatherType NoneWeather;

		public static List<WeatherType> WeatherTypes = new List<WeatherType>();

		public static List<WeatherTweaks.Definitions.Types.CombinedWeatherType> CombinedWeatherTypes = new List<WeatherTweaks.Definitions.Types.CombinedWeatherType>();

		public static List<WeatherTweaks.Definitions.Types.ProgressingWeatherType> ProgressingWeatherTypes = new List<WeatherTweaks.Definitions.Types.ProgressingWeatherType>();

		public static Dictionary<SelectableLevel, WeatherType> CurrentWeathers = new Dictionary<SelectableLevel, WeatherType>();

		public static List<ImprovedWeatherEffect> CurrentEffects = new List<ImprovedWeatherEffect>();

		public static WeatherType CurrentLevelWeather;

		public static WeatherType GetCurrentWeather()
		{
			if (CurrentLevelWeather.Type == CustomWeatherType.Progressing)
			{
				if (ChangeMidDay.currentEntry == null)
				{
					Plugin.logger.LogWarning((object)"Current entry is null");
					return CurrentLevelWeather;
				}
				return ChangeMidDay.currentEntry.GetWeatherType();
			}
			return CurrentLevelWeather;
		}

		internal static Dictionary<int, LevelWeatherType> GetWeatherData(string weatherData)
		{
			return JsonConvert.DeserializeObject<Dictionary<int, LevelWeatherType>>(weatherData);
		}

		internal static List<SelectableLevel> GetGameLevels(bool includeCompanyMoon = false)
		{
			Plugin.logger.LogDebug((object)$"Getting game levels, {includeCompanyMoon}");
			List<SelectableLevel> list = SharedMethods.GetGameLevels();
			if (!includeCompanyMoon)
			{
				list = list.Where((SelectableLevel level) => level.PlanetName != "71 Gordion").ToList();
			}
			GameLevels = list;
			return list;
		}

		internal static List<WeatherType> GetPlanetWeatherTypes(SelectableLevel level)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			List<LevelWeatherType> planetPossibleWeathers = WeatherManager.GetPlanetPossibleWeathers(level);
			if (planetPossibleWeathers.Count() == 0)
			{
				Plugin.logger.LogError((object)"Random weathers are empty");
				return new List<WeatherType>();
			}
			List<WeatherType> list = new List<WeatherType>();
			foreach (WeatherType weather in WeatherTypes)
			{
				if (planetPossibleWeathers.Contains(weather.weatherType) && weather.Type == CustomWeatherType.Normal)
				{
					list.Add(weather);
				}
				switch (weather.Type)
				{
				case CustomWeatherType.Combined:
				{
					WeatherTweaks.Definitions.Types.CombinedWeatherType combinedWeatherType = CombinedWeatherTypes.Find((WeatherTweaks.Definitions.Types.CombinedWeatherType x) => x.Name == weather.Name);
					if (combinedWeatherType.CanWeatherBeApplied(level))
					{
						list.Add(weather);
					}
					break;
				}
				case CustomWeatherType.Progressing:
				{
					WeatherTweaks.Definitions.Types.ProgressingWeatherType progressingWeatherType = ProgressingWeatherTypes.Find((WeatherTweaks.Definitions.Types.ProgressingWeatherType x) => x.Name == weather.Name);
					if (progressingWeatherType.CanWeatherBeApplied(level))
					{
						list.Add(weather);
					}
					break;
				}
				}
			}
			return list.Distinct().ToList();
		}

		internal static Dictionary<string, WeatherType> GetAllPlanetWeathersDictionary()
		{
			Dictionary<string, WeatherType> weathers = new Dictionary<string, WeatherType>();
			CurrentWeathers.ToList().ForEach(delegate(KeyValuePair<SelectableLevel, WeatherType> weather)
			{
				weathers.Add(weather.Key.PlanetName, weather.Value);
			});
			return weathers;
		}

		internal static void PopulateWeathers()
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogDebug((object)"Populating weathers");
			if ((Object)(object)TimeOfDay.Instance == (Object)null)
			{
				Plugin.logger.LogError((object)"TimeOfDay is null");
				return;
			}
			WeatherEffect[] effects = TimeOfDay.Instance.effects;
			WeatherTypes.Clear();
			if (effects == null || effects.Count() == 0)
			{
				Plugin.logger.LogWarning((object)"Effects are null");
			}
			NoneWeather = new WeatherType("None", CustomWeatherType.Normal)
			{
				Weather = WeatherManager.NoneWeather,
				weatherType = (LevelWeatherType)(-1)
			};
			WeatherTypes.Add(NoneWeather);
			foreach (Weather weather in WeatherManager.Weathers)
			{
				WeatherType item = new WeatherType(((Object)weather).name, CustomWeatherType.Normal)
				{
					Weather = weather,
					weatherType = weather.VanillaWeatherType
				};
				WeatherTypes.Add(item);
			}
			CombinedWeatherTypes.ForEach(delegate(WeatherTweaks.Definitions.Types.CombinedWeatherType combinedWeather)
			{
				if (!combinedWeather.Enabled.Value)
				{
					Plugin.logger.LogDebug((object)("Combined weather: " + combinedWeather.Name + " is disabled"));
				}
				else
				{
					Plugin.logger.LogDebug((object)("Adding combined weather: " + combinedWeather.Name));
					WeatherTypes.Add(combinedWeather);
				}
			});
			ProgressingWeatherTypes.ForEach(delegate(WeatherTweaks.Definitions.Types.ProgressingWeatherType progressingWeather)
			{
				if (!progressingWeather.Enabled.Value)
				{
					Plugin.logger.LogDebug((object)("Progressing weather: " + progressingWeather.Name + " is disabled"));
				}
				else
				{
					Plugin.logger.LogDebug((object)("Adding progressing weather: " + progressingWeather.Name));
					WeatherTypes.Add(progressingWeather);
				}
			});
		}

		public static string GetPlanetCurrentWeather(SelectableLevel level, bool uncertain = true)
		{
			bool flag = UncertainWeather.uncertainWeathers.ContainsKey(level.PlanetName);
			if (flag && uncertain)
			{
				return UncertainWeather.uncertainWeathers[level.PlanetName];
			}
			if (!CurrentWeathers.ContainsKey(level))
			{
				return ((object)(LevelWeatherType)(ref level.currentWeather)).ToString();
			}
			return CurrentWeathers[level].Name;
		}

		public static WeatherType GetPlanetCurrentWeatherType(SelectableLevel level)
		{
			WeatherType value;
			return GetFullWeatherType(CurrentWeathers.TryGetValue(level, out value) ? value : NoneWeather);
		}

		public static float GetLevelWeatherVariable(LevelWeatherType weatherType, bool variable2 = false)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			Logger val = new Logger("WeatherTweaks Variables", ConfigManager.LogWeatherVariables);
			if ((Object)(object)StartOfRound.Instance == (Object)null)
			{
				Plugin.logger.LogError((object)"StartOfRound is null");
				return 0f;
			}
			SelectableLevel currentLevel = StartOfRound.Instance.currentLevel;
			RandomWeatherWithVariables val2 = currentLevel.randomWeathers.First((RandomWeatherWithVariables x) => x.weatherType == weatherType);
			if (val2 == null || (Object)(object)StartOfRound.Instance == (Object)null || (Object)(object)currentLevel == (Object)null)
			{
				val.LogError((object)$"Failed to get weather variables for {currentLevel.PlanetName}:{weatherType}");
				return 0f;
			}
			val.LogDebug((object)$"Got weather variables for {currentLevel.PlanetName}:{weatherType} with variables {val2.weatherVariable} {val2.weatherVariable2}");
			if (variable2)
			{
				return val2.weatherVariable2;
			}
			return val2.weatherVariable;
		}

		public static LevelWeatherType LevelHasWeather(LevelWeatherType weatherType)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: 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_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			SelectableLevel currentLevel = StartOfRound.Instance.currentLevel;
			if ((Object)(object)StartOfRound.Instance == (Object)null || (Object)(object)currentLevel == (Object)null)
			{
				Plugin.logger.LogError((object)$"Failed to get weather variables for {currentLevel.PlanetName}:{weatherType}");
				return (LevelWeatherType)(-1);
			}
			WeatherType value;
			WeatherType fullWeatherType = GetFullWeatherType(CurrentWeathers.TryGetValue(currentLevel, out value) ? value : NoneWeather);
			Plugin.logger.LogDebug((object)fullWeatherType.Type);
			switch (fullWeatherType.Type)
			{
			case CustomWeatherType.Combined:
			{
				WeatherTweaks.Definitions.Types.CombinedWeatherType combinedWeatherType = (WeatherTweaks.Definitions.Types.CombinedWeatherType)fullWeatherType;
				if (combinedWeatherType.LevelWeatherTypes.Any((LevelWeatherType x) => x == weatherType))
				{
					Plugin.logger.LogWarning((object)$"Level {currentLevel.PlanetName} has weather {weatherType}");
					return weatherType;
				}
				break;
			}
			case CustomWeatherType.Progressing:
			{
				WeatherTweaks.Definitions.Types.ProgressingWeatherType progressingWeatherType = (WeatherTweaks.Definitions.Types.ProgressingWeatherType)fullWeatherType;
				if (progressingWeatherType.DoesHaveWeatherHappening(weatherType))
				{
					Plugin.logger.LogWarning((object)$"Level {currentLevel.PlanetName} has weather {weatherType}");
					return weatherType;
				}
				break;
			}
			default:
				if (fullWeatherType.Weather.VanillaWeatherType == weatherType)
				{
					Plugin.logger.LogWarning((object)$"Level {currentLevel.PlanetName} has weather {weatherType}");
					return weatherType;
				}
				break;
			}
			return (LevelWeatherType)(-1);
		}

		internal static WeatherType GetVanillaWeatherType(LevelWeatherType weatherType)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return WeatherTypes.Find((WeatherType x) => x.weatherType == weatherType && x.Type == CustomWeatherType.Normal);
		}

		internal static WeatherType GetFullWeatherType(WeatherType weatherType)
		{
			Plugin.logger.LogDebug((object)("Getting full weather type for " + weatherType.Name));
			return WeatherTypes.Find((WeatherType x) => x.Name == weatherType.Name);
		}

		internal static int GetWeatherLevelWeight(SelectableLevel level, LevelWeatherType weatherType)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return WeatherManager.GetWeather(weatherType).GetWeight(level);
		}

		internal static WeightHandler<WeatherType> GetPlanetWeightedList(SelectableLevel level, float difficulty = 0f)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Invalid comparison between Unknown and I4
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Unknown result type (might be due to invalid IL or missing references)
			//IL_0338: Invalid comparison between Unknown and I4
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			Logger val = new Logger("WeatherTweaks WeatherSelection", ConfigManager.LogWeatherSelection);
			WeightHandler<WeatherType> val2 = new WeightHandler<WeatherType>();
			WeightHandler<LevelWeatherType> weatherTypeWeights = new WeightHandler<LevelWeatherType>();
			difficulty = Math.Clamp(difficulty, 0f, ConfigManager.MaxMultiplier.Value);
			int possibleWeathersWeightSum = 0;
			List<WeatherType> weatherTypes = GetPlanetWeatherTypes(level);
			WeatherTypes.Where((WeatherType weatherType) => weatherType.Type == CustomWeatherType.Normal).ToList().ForEach(delegate(WeatherType weatherType)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				int weatherLevelWeight = GetWeatherLevelWeight(level, weatherType.weatherType);
				weatherTypeWeights.Add(weatherType.weatherType, weatherLevelWeight);
				if (weatherTypes.Contains(weatherType))
				{
					possibleWeathersWeightSum += weatherLevelWeight;
				}
			});
			weatherTypeWeights.Add((LevelWeatherType)(-1), GetWeatherLevelWeight(level, (LevelWeatherType)(-1)));
			foreach (WeatherType weatherType2 in weatherTypes)
			{
				int num = weatherTypeWeights.Get(weatherType2.weatherType);
				if (ConfigManager.ScaleDownClearWeather.Value && (int)weatherType2.weatherType == -1)
				{
					int weight = NoneWeather.Weather.GetWeight(level);
					int sum = weatherTypeWeights.Sum;
					double value = weight * Math.Max(possibleWeathersWeightSum, 1) / Math.Max(sum, 1);
					num = Convert.ToInt32(value);
					val.LogDebug((object)$"Scaling down clear weather weight from {weight} to {num} : ({weight} * {possibleWeathersWeightSum} / {sum}) == {num}");
				}
				if (weatherType2.Type == CustomWeatherType.Combined)
				{
					WeatherTweaks.Definitions.Types.CombinedWeatherType combinedWeatherType = CombinedWeatherTypes.Find((WeatherTweaks.Definitions.Types.CombinedWeatherType x) => x.Name == weatherType2.Name);
					if (!combinedWeatherType.CanWeatherBeApplied(level))
					{
						val.LogDebug((object)("Combined weather: " + combinedWeatherType.Name + " can't be applied"));
						continue;
					}
					num = Mathf.RoundToInt((float)weatherTypeWeights.Get(combinedWeatherType.weatherType) * combinedWeatherType.WeightModify);
					val.LogDebug((object)$"Weight of combined weather: {combinedWeatherType.Name} is {num}");
				}
				else if (weatherType2.Type == CustomWeatherType.Progressing)
				{
					WeatherTweaks.Definitions.Types.ProgressingWeatherType progressingWeatherType = ProgressingWeatherTypes.Find((WeatherTweaks.Definitions.Types.ProgressingWeatherType x) => x.Name == weatherType2.Name);
					if (!progressingWeatherType.CanWeatherBeApplied(level))
					{
						val.LogDebug((object)("Progressing weather: " + progressingWeatherType.Name + " can't be applied"));
						continue;
					}
					num = Mathf.RoundToInt((float)weatherTypeWeights.Get(weatherType2.weatherType) * progressingWeatherType.WeightModify);
					val.LogDebug((object)$"Weight of progressing weather: {progressingWeatherType.Name} is {num}");
				}
				if (difficulty != 0f && (int)weatherType2.weatherType == -1)
				{
					num = (int)((float)num * (1f - difficulty));
				}
				val.LogDebug((object)$"{weatherType2.Name} has weight {num}");
				val2.Add(weatherType2, num);
			}
			return val2;
		}
	}
	internal class WeatherCalculation
	{
		internal static Dictionary<string, LevelWeatherType> previousDayWeather = new Dictionary<string, LevelWeatherType>();

		internal static SelectableLevel CompanyMoon;

		internal static Dictionary<string, WeatherType> NewWeathers(StartOfRound startOfRound)
		{
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0319: Unknown result type (might be due to invalid IL or missing references)
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0382: Unknown result type (might be due to invalid IL or missing references)
			//IL_0411: Unknown result type (might be due to invalid IL or missing references)
			//IL_0437: Unknown result type (might be due to invalid IL or missing references)
			//IL_043d: Invalid comparison between Unknown and I4
			Plugin.logger.LogMessage((object)"SetWeathers called.");
			if (!((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				Plugin.logger.LogMessage((object)"Not a host, cannot generate weather!");
				return null;
			}
			previousDayWeather.Clear();
			int seed = startOfRound.randomMapSeed + 31;
			Random random = new Random(seed);
			Dictionary<string, LevelWeatherType> dictionary = VanillaWeathers(0, startOfRound);
			Dictionary<string, WeatherType> dictionary2 = new Dictionary<string, WeatherType>();
			List<LevelWeatherType> list = new List<LevelWeatherType>(7)
			{
				(LevelWeatherType)(-1),
				(LevelWeatherType)0,
				(LevelWeatherType)1,
				(LevelWeatherType)2,
				(LevelWeatherType)3,
				(LevelWeatherType)4,
				(LevelWeatherType)5
			};
			CompanyMoon = StartOfRound.Instance.levels.ToList().Find((SelectableLevel level) => level.PlanetName == "71 Gordion");
			List<SelectableLevel> gameLevels = Variables.GetGameLevels();
			int daysSpent = startOfRound.gameStats.daysSpent;
			int timesFulfilledQuota = TimeOfDay.Instance.timesFulfilledQuota;
			int num = daysSpent % 3;
			if (daysSpent == 0 && ConfigManager.FirstDaySpecial.Value)
			{
				seed = ConfigManager.FirstDaySeed.Value;
				if (ConfigManager.FirstDayRandomSeed.Value)
				{
					seed = random.Next(0, 10000000);
				}
				random = new Random(seed);
				List<string> noWeatherOnStartPlanets = new List<string>(2) { "41 Experimentation", "56 Vow" };
				List<SelectableLevel> list2 = gameLevels.Where((SelectableLevel level) => !noWeatherOnStartPlanets.Contains(level.PlanetName)).ToList();
				if (gameLevels.Count > 9)
				{
					int num2 = (int)((double)gameLevels.Count * 0.5);
					Plugin.logger.LogDebug((object)$"Planets without weather: {num2 + 2}");
					for (int i = 0; i < num2; i++)
					{
						string planetName = list2[random.Next(0, list2.Count)].PlanetName;
						noWeatherOnStartPlanets.Add(planetName);
						list2.RemoveAll((SelectableLevel level) => level.PlanetName == planetName);
					}
				}
				return FirstDayWeathers(gameLevels, noWeatherOnStartPlanets, random);
			}
			float num3 = (float)timesFulfilledQuota * ConfigManager.GameLengthMultiplier.Value;
			float num4 = (float)StartOfRound.Instance.livingPlayers * ConfigManager.GamePlayersMultiplier.Value;
			float num5 = num3 + num4;
			Plugin.logger.LogDebug((object)$"Difficulty multiplier: {num5}");
			foreach (SelectableLevel level2 in gameLevels)
			{
				previousDayWeather[level2.PlanetName] = level2.currentWeather;
				LevelWeatherType val = (LevelWeatherType)((!dictionary.ContainsKey(level2.PlanetName)) ? (-1) : ((int)dictionary[level2.PlanetName]));
				if (ConfigManager.AlwaysClear.Value)
				{
					Plugin.logger.LogDebug((object)"AlwaysClear is true, setting weather to None");
					dictionary2[level2.PlanetName] = Variables.NoneWeather;
					continue;
				}
				if (level2.overrideWeather)
				{
					Plugin.logger.LogDebug((object)$"Override weather present, changing weather to {level2.overrideWeatherType}");
					dictionary2[level2.PlanetName] = Variables.WeatherTypes.Find((WeatherType x) => x.weatherType == level2.overrideWeatherType && x.Type == CustomWeatherType.Normal);
					continue;
				}
				Plugin.logger.LogDebug((object)"-------------");
				Plugin.logger.LogDebug((object)(level2.PlanetName ?? ""));
				Plugin.logger.LogDebug((object)$"previousDayWeather: {previousDayWeather[level2.PlanetName]}");
				if ((int)previousDayWeather[level2.PlanetName] == 0)
				{
					previousDayWeather[level2.PlanetName] = (LevelWeatherType)(-1);
				}
				dictionary2[level2.PlanetName] = Variables.NoneWeather;
				WeightHandler<WeatherType> planetWeightedList = Variables.GetPlanetWeightedList(level2);
				WeatherType weatherType = planetWeightedList.Random();
				dictionary2[level2.PlanetName] = weatherType;
				Variables.CurrentWeathers[level2] = weatherType;
				Plugin.logger.LogDebug((object)("Selected weather: " + weatherType.Name));
				try
				{
					Plugin.logger.LogDebug((object)$"Chance for that was {planetWeightedList.Get(weatherType)} / {planetWeightedList.Sum} ({(float)planetWeightedList.Get(weatherType) / (float)planetWeightedList.Sum * 100f}%)");
				}
				catch
				{
				}
			}
			if ((Object)(object)CompanyMoon != (Object)null)
			{
				Variables.CurrentWeathers[CompanyMoon] = Variables.NoneWeather;
				dictionary2[CompanyMoon.PlanetName] = Variables.NoneWeather;
			}
			Plugin.logger.LogDebug((object)"-------------");
			return dictionary2;
		}

		private static Dictionary<string, WeatherType> FirstDayWeathers(List<SelectableLevel> levels, List<string> planetsWithoutWeather, Random random)
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogInfo((object)"First day, setting predefined weather conditions");
			Dictionary<string, WeatherType> dictionary = new Dictionary<string, WeatherType>();
			foreach (SelectableLevel level in levels)
			{
				string planetName = level.PlanetName;
				Plugin.logger.LogDebug((object)("planet: " + planetName));
				if (ConfigManager.AlwaysClear.Value)
				{
					Plugin.logger.LogDebug((object)"AlwaysClear is true, setting weather to None");
					dictionary[level.PlanetName] = Variables.NoneWeather;
					continue;
				}
				if (level.overrideWeather)
				{
					Plugin.logger.LogDebug((object)$"Override weather present, changing weather to {level.overrideWeatherType}");
					dictionary[level.PlanetName] = Variables.WeatherTypes.Find((WeatherType x) => x.weatherType == level.overrideWeatherType && x.Type == CustomWeatherType.Normal);
					continue;
				}
				List<WeatherType> list = (from randomWeather in Variables.GetPlanetWeatherTypes(level)
					where (int)randomWeather.weatherType != -1 && (int)randomWeather.weatherType != 0 && randomWeather.Type == CustomWeatherType.Normal
					select randomWeather).ToList();
				string text = JsonConvert.SerializeObject((object)list.Select((WeatherType x) => ((object)(LevelWeatherType)(ref x.weatherType)).ToString()).ToList());
				list.RemoveAll((WeatherType x) => (int)x.weatherType == 5);
				if (list.Count == 0 || list == null)
				{
					dictionary[planetName] = Variables.NoneWeather;
					Plugin.logger.LogDebug((object)("No random weathers for " + planetName + ", skipping"));
					continue;
				}
				if (planetsWithoutWeather.Contains(planetName))
				{
					dictionary[planetName] = Variables.NoneWeather;
					Plugin.logger.LogDebug((object)("Skipping " + planetName + " (predefined)"));
					continue;
				}
				bool flag = random.Next(0, 100) < 5;
				WeatherType selectedRandom = list[random.Next(0, list.Count)];
				if (flag)
				{
					Plugin.logger.LogDebug((object)("Setting eclipsed for " + planetName));
					if (!list.Any((WeatherType x) => (int)x.weatherType == 5))
					{
						Plugin.logger.LogDebug((object)("Eclipsed not possible for " + planetName + ", setting random weather"));
					}
					else
					{
						selectedRandom = list.First((WeatherType x) => (int)x.weatherType == 5);
					}
				}
				WeatherType weatherType2 = (dictionary[planetName] = Variables.WeatherTypes.Find((WeatherType x) => x.weatherType == selectedRandom.weatherType && x.Type == CustomWeatherType.Normal));
				Variables.CurrentWeathers[level] = weatherType2;
				Plugin.logger.LogDebug((object)("Set weather for " + planetName + ": " + weatherType2.Name));
			}
			if ((Object)(object)CompanyMoon != (Object)null)
			{
				Variables.CurrentWeathers[CompanyMoon] = Variables.NoneWeather;
				dictionary[CompanyMoon.PlanetName] = Variables.NoneWeather;
			}
			return dictionary;
		}

		private static Dictionary<string, LevelWeatherType> VanillaWeathers(int connectedPlayersOnServer, StartOfRound startOfRound)
		{
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, LevelWeatherType> dictionary = new Dictionary<string, LevelWeatherType>();
			Random random = new Random(startOfRound.randomMapSeed + 31);
			List<SelectableLevel> list = startOfRound.levels.ToList();
			float num = 1f;
			if (connectedPlayersOnServer + 1 > 1 && startOfRound.daysPlayersSurvivedInARow > 2 && startOfRound.daysPlayersSurvivedInARow % 3 == 0)
			{
				num = (float)random.Next(15, 25) / 10f;
			}
			int num2 = Mathf.Clamp((int)((double)Mathf.Clamp(startOfRound.planetsWeatherRandomCurve.Evaluate((float)random.NextDouble()) * num, 0f, 1f) * (double)startOfRound.levels.Length), 0, startOfRound.levels.Length);
			for (int i = 0; i < num2; i++)
			{
				SelectableLevel val = list[random.Next(0, list.Count)];
				if (val.randomWeathers != null && val.randomWeathers.Length != 0)
				{
					dictionary[val.PlanetName] = val.randomWeathers[random.Next(0, val.randomWeathers.Length)].weatherType;
				}
				list.Remove(val);
			}
			return dictionary;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "WeatherTweaks";

		public const string PLUGIN_NAME = "WeatherTweaks";

		public const string PLUGIN_VERSION = "0.0.1";
	}
}
namespace WeatherTweaks.Patches
{
	internal class Malfunctions
	{
		private static Type StartOfRoundPatches;

		private static Assembly assembly;

		private static Harmony harmony;

		internal static void Init()
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			assembly = ((object)Chainloader.PluginInfos["com.zealsprince.malfunctions"].Instance).GetType().Assembly;
			StartOfRoundPatches = AccessTools.TypeByName("Malfunctions.Patches.StartOfRoundPatches");
			if (StartOfRoundPatches == null)
			{
				Plugin.logger.LogError((object)"Could not find StartOfRoundPatches class in Malfunctions assembly");
			}
			else
			{
				Plugin.logger.LogDebug((object)"Found StartOfRoundPatches class in Malfunctions assembly");
			}
			harmony = new Harmony("WeatherTweaks.Malfunctions");
			HarmonyMethod val = new HarmonyMethod(typeof(Malfunctions).GetMethod("EclipseOnEnablePatch"));
			harmony.Patch((MethodBase)AccessTools.Method(StartOfRoundPatches, "OverwriteMapScreenInfo", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		public static IEnumerable<CodeInstruction> EclipseOnEnablePatch(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			ManualLogSource logger = Plugin.logger;
			CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null);
			val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[3]
			{
				new CodeMatch((OpCode?)OpCodes.Ldsfld, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldfld, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Brtrue, (object)null, (string)null)
			});
			val.Repeat((Action<CodeMatcher>)delegate(CodeMatcher match)
			{
				match.RemoveInstructions(3);
			}, (Action<string>)null);
			return val.InstructionEnumeration();
		}
	}
	public class GeneralImprovementsWeather : CompatibilityBase
	{
		private static Type type;

		private static FieldInfo weatherMonitorsField;

		private static FieldInfo fancyMonitorsField;

		private static int frame = 0;

		internal static Logger logger = new Logger("WeatherTweaks GI", ConfigManager.LogLogs);

		public GeneralImprovementsWeather(string guid, string version = null)
			: base(guid, version)
		{
		}

		public static void Init()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Expected O, but got Unknown
			string key = "ShaosilGaming.GeneralImprovements";
			Dictionary<string, PluginInfo> pluginInfos = Chainloader.PluginInfos;
			if (pluginInfos.ContainsKey(key))
			{
				string text = "GeneralImprovements.Utilities";
				string text2 = "MonitorsHelper";
				Assembly getModAssembly = ((CompatibilityBase)Plugin.GeneralImprovements).GetModAssembly;
				type = getModAssembly.GetType(text + "." + text2);
				if (type != null)
				{
					Plugin.logger.LogWarning((object)"GeneralImprovements found, patching weather displays");
					MethodInfo method = type.GetMethod("UpdateGenericTextList", BindingFlags.Static | BindingFlags.NonPublic);
					weatherMonitorsField = type.GetField("_weatherMonitorTexts", BindingFlags.Static | BindingFlags.NonPublic);
					fancyMonitorsField = type.GetField("_fancyWeatherMonitorTexts", BindingFlags.Static | BindingFlags.NonPublic);
					Harmony val = new Harmony("WeatherTweaks.GeneralImprovements");
					HarmonyMethod val2 = new HarmonyMethod(typeof(GeneralImprovementsWeather).GetMethod("TextPatch", BindingFlags.Static | BindingFlags.Public));
					val.Patch((MethodBase)method, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
		}

		public static void TextPatch(List<TextMeshProUGUI> textList, ref string text)
		{
			bool isWeatherMonitor = false;
			List<TextMeshProUGUI> weathermonitors = weatherMonitorsField.GetValue(null) as List<TextMeshProUGUI>;
			List<TextMeshProUGUI> fancymonitors = fancyMonitorsField.GetValue(null) as List<TextMeshProUGUI>;
			CollectionExtensions.Do<TextMeshProUGUI>((IEnumerable<TextMeshProUGUI>)textList, (Action<TextMeshProUGUI>)delegate(TextMeshProUGUI monitor)
			{
				if (!((Object)(object)monitor == (Object)null) && (weathermonitors.Contains(monitor) || fancymonitors.Contains(monitor)))
				{
					isWeatherMonitor = true;
				}
			});
			if (!isWeatherMonitor)
			{
				return;
			}
			string planetCurrentWeather = Variables.GetPlanetCurrentWeather(StartOfRound.Instance.currentLevel);
			bool flag = ((object)(LevelWeatherType)(ref StartOfRound.Instance.currentLevel.currentWeather)).ToString() != planetCurrentWeather;
			if (text.Contains("WEATHER:\n"))
			{
				string text2 = "WEATHER:\n" + planetCurrentWeather;
				logger.LogDebug((object)("Changing " + text.Replace("\n", " ") + " to " + text2.Replace("\n", " ")));
				text = text2;
			}
			else if (flag)
			{
				text = "???????????????????????????????????";
				text = Regex.Replace(text, "[?]", (Match m) => (frame++ % 20 == 0) ? " " : m.Value);
				text = Regex.Replace(text, ".{8}", "$0\n");
				text = Regex.Replace(text, "(?<=\\n.*\\n.*\\n.*\\n).+", "");
				frame++;
				if (frame == 20)
				{
					frame = 0;
				}
			}
		}
	}
	public static class LLL
	{
		internal static Logger logger = new Logger("WeatherTweaks LLL", ConfigManager.LogLogs);

		internal static void Init()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			Harmony val = new Harmony("WeatherTweaks.LLL");
			if (((CompatibilityBase)Plugin.LLL).IsModPresent)
			{
				logger.LogWarning((object)"Patching LethalLevelLoader");
				val.Patch((MethodBase)AccessTools.Method(typeof(TerminalManager), "GetWeatherConditions", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(LLL), "PatchNewLLL", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			else
			{
				logger.LogWarning((object)"Patching Old LethalLevelLoader");
				val.Patch((MethodBase)AccessTools.Method(typeof(TerminalManager), "GetWeatherConditions", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(LLL), "PatchOldLLL", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			Plugin.IsLLLPresent = true;
		}

		private static void PatchNewLLL(ExtendedLevel extendedLevel, ref string __result)
		{
			__result = PatchLLL(extendedLevel.SelectableLevel);
		}

		private static void PatchOldLLL(SelectableLevel selectableLevel, ref string __result)
		{
			__result = PatchLLL(selectableLevel);
		}

		private static string PatchLLL(SelectableLevel selectableLevel)
		{
			string text = Variables.GetPlanetCurrentWeather(selectableLevel);
			logger.LogDebug((object)("GetMoonConditions " + selectableLevel.PlanetName + "::" + text));
			if (text == "None")
			{
				text = "";
			}
			else if (!text.Contains("[") && !text.Contains("]"))
			{
				text = "(" + text + ")";
			}
			return text;
		}
	}
	[Ha