Decompiled source of PecesitosModpack v2.0.1

BepInEx/plugins/2018-LC_API/LC_API.dll

Decompiled 10 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
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;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.BundleAPI;
using LC_API.ClientAPI;
using LC_API.Comp;
using LC_API.Data;
using LC_API.Exceptions;
using LC_API.Extensions;
using LC_API.GameInterfaceAPI;
using LC_API.GameInterfaceAPI.Events;
using LC_API.GameInterfaceAPI.Events.Cache;
using LC_API.GameInterfaceAPI.Events.EventArgs.Player;
using LC_API.GameInterfaceAPI.Events.Handlers;
using LC_API.GameInterfaceAPI.Features;
using LC_API.ManualPatches;
using LC_API.Networking;
using LC_API.ServerAPI;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;

[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("2018")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Utilities for plugin devs")]
[assembly: AssemblyFileVersion("3.2.3.0")]
[assembly: AssemblyInformationalVersion("3.2.3+5b8fba91ac002f8974f3ef61cd5e339a2c49c652")]
[assembly: AssemblyProduct("Lethal Company API")]
[assembly: AssemblyTitle("LC_API")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("3.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
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 LC_API
{
	internal static class CheatDatabase
	{
		private const string SIG_REQ_GUID = "LC_API_ReqGUID";

		private const string SIG_SEND_MODS = "LC_APISendMods";

		private static Dictionary<string, PluginInfo> PluginsLoaded = new Dictionary<string, PluginInfo>();

		public static void RunLocalCheatDetector()
		{
			PluginsLoaded = Chainloader.PluginInfos;
			using Dictionary<string, PluginInfo>.ValueCollection.Enumerator enumerator = PluginsLoaded.Values.GetEnumerator();
			while (enumerator.MoveNext())
			{
				switch (enumerator.Current.Metadata.GUID)
				{
				case "mikes.lethalcompany.mikestweaks":
				case "mom.llama.enhancer":
				case "Posiedon.GameMaster":
				case "LethalCompanyScalingMaster":
				case "verity.amberalert":
					ModdedServer.SetServerModdedOnly();
					break;
				}
			}
		}

		public static void OtherPlayerCheatDetector()
		{
			Plugin.Log.LogWarning((object)"Asking all other players for their mod list..");
			GameTips.ShowTip("Mod List:", "Asking all other players for installed mods..");
			GameTips.ShowTip("Mod List:", "Check the logs for more detailed results.\n<size=13>(Note that if someone doesnt show up on the list, they may not have LC_API installed)</size>");
			Network.Broadcast("LC_API_ReqGUID");
		}

		[NetworkMessage("LC_APISendMods", false)]
		internal static void ReceivedModListHandler(ulong senderId, List<string> mods)
		{
			string text = LC_API.GameInterfaceAPI.Features.Player.Get(senderId).Username + " responded with these mods:\n" + string.Join("\n", mods);
			GameTips.ShowTip("Mod List:", text);
			Plugin.Log.LogWarning((object)text);
		}

		[NetworkMessage("LC_API_ReqGUID", false)]
		internal static void ReceivedModListHandler(ulong senderId)
		{
			List<string> list = new List<string>();
			foreach (PluginInfo value in PluginsLoaded.Values)
			{
				list.Add(value.Metadata.GUID);
			}
			Network.Broadcast("LC_APISendMods", list);
		}
	}
	[BepInPlugin("LC_API", "Lethal Company API", "3.2.3")]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		private ConfigEntry<bool> configOverrideModServer;

		private ConfigEntry<bool> configLegacyAssetLoading;

		private ConfigEntry<bool> configDisableBundleLoader;

		internal static Harmony Harmony;

		internal static Plugin Instance { get; private set; }

		public static bool Initialized { get; private set; }

		private void Awake()
		{
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Expected O, but got Unknown
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Expected O, but got Unknown
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Expected O, but got Unknown
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Expected O, but got Unknown
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Expected O, but got Unknown
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Expected O, but got Unknown
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Expected O, but got Unknown
			Instance = this;
			configOverrideModServer = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Force modded server browser", false, "Should the API force you into the modded server browser?");
			configLegacyAssetLoading = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Legacy asset bundle loading", false, "Should the BundleLoader use legacy asset loading? Turning this on may help with loading assets from older plugins.");
			configDisableBundleLoader = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Disable BundleLoader", false, "Should the BundleLoader be turned off? Enable this if you are having problems with mods that load assets using a different method from LC_API's BundleLoader.");
			CommandHandler.commandPrefix = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Prefix", "/", "Command prefix");
			Log = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogWarning((object)"\n.____    _________           _____  __________ .___  \r\n|    |   \\_   ___ \\         /  _  \\ \\______   \\|   | \r\n|    |   /    \\  \\/        /  /_\\  \\ |     ___/|   | \r\n|    |___\\     \\____      /    |    \\|    |    |   | \r\n|_______ \\\\______  /______\\____|__  /|____|    |___| \r\n        \\/       \\//_____/        \\/                 \r\n                                                     ");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Starting up..");
			if (configOverrideModServer.Value)
			{
				ModdedServer.SetServerModdedOnly();
			}
			Harmony = new Harmony("ModAPI");
			MethodInfo methodInfo = AccessTools.Method(typeof(GameNetworkManager), "SteamMatchmaking_OnLobbyCreated", (Type[])null, (Type[])null);
			AccessTools.Method(typeof(GameNetworkManager), "LobbyDataIsJoinable", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(ServerPatch), "OnLobbyCreate", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(MenuManager), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(ServerPatch), "CacheMenuManager", (Type[])null, (Type[])null);
			AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(typeof(HUDManager), "SubmitChat_performed", (Type[])null, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.Method(typeof(CommandHandler.SubmitChatPatch), "Transpiler", (Type[])null, (Type[])null);
			MethodInfo methodInfo7 = AccessTools.Method(typeof(GameNetworkManager), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo8 = AccessTools.Method(typeof(ServerPatch), "GameNetworkManagerAwake", (Type[])null, (Type[])null);
			MethodInfo methodInfo9 = AccessTools.Method(typeof(NetworkManager), "StartClient", (Type[])null, (Type[])null);
			MethodInfo methodInfo10 = AccessTools.Method(typeof(NetworkManager), "StartHost", (Type[])null, (Type[])null);
			MethodInfo methodInfo11 = AccessTools.Method(typeof(NetworkManager), "Shutdown", (Type[])null, (Type[])null);
			MethodInfo methodInfo12 = AccessTools.Method(typeof(RegisterPatch), "Postfix", (Type[])null, (Type[])null);
			MethodInfo methodInfo13 = AccessTools.Method(typeof(UnregisterPatch), "Postfix", (Type[])null, (Type[])null);
			Harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo7, new HarmonyMethod(methodInfo8), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo9, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo10, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo11, (HarmonyMethod)null, new HarmonyMethod(methodInfo13), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Network.Init();
			Events.Patch(Harmony);
		}

		internal void Start()
		{
			Initialize();
		}

		internal void OnDestroy()
		{
			Initialize();
		}

		internal void Initialize()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			if (!Initialized)
			{
				Initialized = true;
				if (!configDisableBundleLoader.Value)
				{
					BundleLoader.Load(configLegacyAssetLoading.Value);
				}
				GameObject val = new GameObject("API");
				Object.DontDestroyOnLoad((Object)val);
				val.AddComponent<LC_APIManager>();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Started!");
				CheatDatabase.RunLocalCheatDetector();
			}
		}

		internal static void PatchMethodManual(MethodInfo method, MethodInfo patch, Harmony harmony)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			harmony.Patch((MethodBase)method, new HarmonyMethod(patch), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
	}
	public static class Utils
	{
		public static string ReplaceWithCase(this string input, string toReplace, string replacement)
		{
			Dictionary<string, string> map = new Dictionary<string, string> { { toReplace, replacement } };
			return input.ReplaceWithCase(map);
		}

		public static string ReplaceWithCase(this string input, Dictionary<string, string> map)
		{
			string text = input;
			foreach (KeyValuePair<string, string> item in map)
			{
				string key = item.Key;
				string value = item.Value;
				text = Regex.Replace(text, key, delegate(Match match)
				{
					string value2 = match.Value;
					char[] array = value2.ToCharArray();
					string[] source = value2.Split(' ');
					bool flag = char.IsUpper(array[0]);
					bool flag2 = source.All((string w) => char.IsUpper(w[0]) || !char.IsLetter(w[0]));
					if (array.All((char c) => char.IsUpper(c) || !char.IsLetter(c)))
					{
						return value.ToUpper();
					}
					if (flag2)
					{
						return Regex.Replace(value, "\\b\\w", (Match charMatch) => charMatch.Value.ToUpper());
					}
					char[] array2 = value.ToCharArray();
					array2[0] = (flag ? char.ToUpper(array2[0]) : char.ToLower(array2[0]));
					return new string(array2);
				}, RegexOptions.IgnoreCase);
			}
			return text;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "LC_API";

		public const string PLUGIN_NAME = "Lethal Company API";

		public const string PLUGIN_VERSION = "3.2.3";
	}
}
namespace LC_API.ServerAPI
{
	public static class ModdedServer
	{
		private static bool moddedOnly;

		[Obsolete("Use SetServerModdedOnly() instead. This will be removed/private in a future update.")]
		public static bool setModdedOnly;

		public static int GameVersion { get; internal set; }

		public static bool ModdedOnly => moddedOnly;

		public static void SetServerModdedOnly()
		{
			moddedOnly = true;
			Plugin.Log.LogMessage((object)"A plugin has set your game to only allow you to play with other people who have mods!");
		}

		public static void OnSceneLoaded()
		{
			if (Object.op_Implicit((Object)(object)GameNetworkManager.Instance) && ModdedOnly)
			{
				GameNetworkManager instance = GameNetworkManager.Instance;
				instance.gameVersionNum += 16440;
				setModdedOnly = true;
			}
		}
	}
	[Obsolete("ServerAPI.Networking is obsolete and will be removed in future versions. Use LC_API.Networking.")]
	public static class Networking
	{
		public static Action<string, string> GetString = delegate
		{
		};

		public static Action<List<string>, string> GetListString = delegate
		{
		};

		public static Action<int, string> GetInt = delegate
		{
		};

		public static Action<float, string> GetFloat = delegate
		{
		};

		public static Action<Vector3, string> GetVector3 = delegate
		{
		};

		private static Dictionary<string, string> syncStringVars = new Dictionary<string, string>();

		public static void Broadcast(string data, string signature)
		{
			if (data.Contains("/"))
			{
				Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )");
				return;
			}
			HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data + "/" + signature + "/" + NetworkBroadcastDataType.BDstring.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1);
		}

		public static void Broadcast(List<string> data, string signature)
		{
			string text = "";
			foreach (string datum in data)
			{
				if (datum.Contains("/"))
				{
					Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )");
					return;
				}
				if (datum.Contains("\n"))
				{
					Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( NewLine )");
					return;
				}
				text = text + datum + "\n";
			}
			HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data?.ToString() + "/" + signature + "/" + NetworkBroadcastDataType.BDlistString.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1);
		}

		public static void Broadcast(int data, string signature)
		{
			HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data + "/" + signature + "/" + NetworkBroadcastDataType.BDint.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1);
		}

		public static void Broadcast(float data, string signature)
		{
			HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data + "/" + signature + "/" + NetworkBroadcastDataType.BDfloat.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1);
		}

		public static void Broadcast(Vector3 data, string signature)
		{
			//IL_0016: 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)
			HUDManager instance = HUDManager.Instance;
			string[] obj = new string[9] { "<size=0>NWE/", null, null, null, null, null, null, null, null };
			Vector3 val = data;
			obj[1] = ((object)(Vector3)(ref val)).ToString();
			obj[2] = "/";
			obj[3] = signature;
			obj[4] = "/";
			obj[5] = NetworkBroadcastDataType.BDvector3.ToString();
			obj[6] = "/";
			obj[7] = GameNetworkManager.Instance.localPlayerController.playerClientId.ToString();
			obj[8] = "/</size>";
			instance.AddTextToChatOnServer(string.Concat(obj), -1);
		}

		public static void RegisterSyncVariable(string name)
		{
			if (!syncStringVars.ContainsKey(name))
			{
				syncStringVars.Add(name, "");
			}
			else
			{
				Plugin.Log.LogError((object)("Cannot register Sync Variable! A Sync Variable has already been registered with name " + name));
			}
		}

		public static void SetSyncVariable(string name, string value)
		{
			if (syncStringVars.ContainsKey(name))
			{
				syncStringVars[name] = value;
				Broadcast(new List<string> { name, value }, "LCAPI_NET_SYNCVAR_SET");
			}
			else
			{
				Plugin.Log.LogError((object)("Cannot set the value of Sync Variable " + name + " as it is not registered!"));
			}
		}

		private static void SetSyncVariableB(string name, string value)
		{
			if (syncStringVars.ContainsKey(name))
			{
				syncStringVars[name] = value;
			}
			else
			{
				Plugin.Log.LogError((object)("Cannot set the value of Sync Variable " + name + " as it is not registered!"));
			}
		}

		internal static void LCAPI_NET_SYNCVAR_SET(List<string> list, string arg2)
		{
			if (arg2 == "LCAPI_NET_SYNCVAR_SET")
			{
				SetSyncVariableB(list[0], list[1]);
			}
		}

		public static string GetSyncVariable(string name)
		{
			if (syncStringVars.ContainsKey(name))
			{
				return syncStringVars[name];
			}
			Plugin.Log.LogError((object)("Cannot get the value of Sync Variable " + name + " as it is not registered!"));
			return "";
		}

		private static void GotString(string data, string signature)
		{
		}

		private static void GotInt(int data, string signature)
		{
		}

		private static void GotFloat(float data, string signature)
		{
		}

		private static void GotVector3(Vector3 data, string signature)
		{
		}

		internal static void SetupNetworking()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			for (int i = 0; i < types.Length; i++)
			{
				MethodInfo[] methods = types[i].GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}
	}
}
namespace LC_API.Networking
{
	public static class Network
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static HandleNamedMessageDelegate <>9__35_2;

			public static Events.CustomEventHandler <>9__35_0;

			public static Events.CustomEventHandler <>9__35_1;

			internal void <Init>b__35_0()
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				StartedNetworking = true;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
					object obj = <>9__35_2;
					if (obj == null)
					{
						HandleNamedMessageDelegate val = delegate(ulong senderClientId, FastBufferReader reader)
						{
							//IL_0006: Unknown result type (might be due to invalid IL or missing references)
							//IL_000c: Unknown result type (might be due to invalid IL or missing references)
							//IL_003d: 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_0059: Unknown result type (might be due to invalid IL or missing references)
							byte[] bytes = default(byte[]);
							((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
							NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
							networkMessageWrapper.Sender = senderClientId;
							byte[] array = networkMessageWrapper.ToBytes();
							FastBufferWriter val2 = default(FastBufferWriter);
							((FastBufferWriter)(ref val2))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
							try
							{
								((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(array, default(ForPrimitives));
								NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val2, (NetworkDelivery)3);
							}
							finally
							{
								((IDisposable)(FastBufferWriter)(ref val2)).Dispose();
							}
						};
						<>9__35_2 = val;
						obj = (object)val;
					}
					customMessagingManager.RegisterNamedMessageHandler("LC_API_RELAY_MESSAGE", (HandleNamedMessageDelegate)obj);
				}
				RegisterAllMessages();
			}

			internal void <Init>b__35_2(ulong senderClientId, FastBufferReader reader)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: 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_0059: Unknown result type (might be due to invalid IL or missing references)
				byte[] bytes = default(byte[]);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
				NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
				networkMessageWrapper.Sender = senderClientId;
				byte[] array = networkMessageWrapper.ToBytes();
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
				try
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val, (NetworkDelivery)3);
				}
				finally
				{
					((IDisposable)(FastBufferWriter)(ref val)).Dispose();
				}
			}

			internal void <Init>b__35_1()
			{
				StartedNetworking = false;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler("LC_API_RELAY_MESSAGE");
				}
				UnregisterAllMessages();
			}
		}

		internal const string MESSAGE_RELAY_UNIQUE_NAME = "LC_API_RELAY_MESSAGE";

		private static MethodInfo _registerInfo = null;

		private static MethodInfo _registerInfoGeneric = null;

		internal static Dictionary<string, NetworkMessageFinalizerBase> NetworkMessageFinalizers { get; } = new Dictionary<string, NetworkMessageFinalizerBase>();


		internal static bool StartedNetworking { get; set; } = false;


		internal static MethodInfo RegisterInfo
		{
			get
			{
				if (_registerInfo == null)
				{
					MethodInfo[] methods = typeof(Network).GetMethods();
					foreach (MethodInfo methodInfo in methods)
					{
						if (methodInfo.Name == "RegisterMessage" && !methodInfo.IsGenericMethod)
						{
							_registerInfo = methodInfo;
							break;
						}
					}
				}
				return _registerInfo;
			}
		}

		internal static MethodInfo RegisterInfoGeneric
		{
			get
			{
				if (_registerInfo == null)
				{
					MethodInfo[] methods = typeof(Network).GetMethods();
					foreach (MethodInfo methodInfo in methods)
					{
						if (methodInfo.Name == "RegisterMessage" && methodInfo.IsGenericMethod)
						{
							_registerInfoGeneric = methodInfo;
							break;
						}
					}
				}
				return _registerInfoGeneric;
			}
		}

		public static event Events.CustomEventHandler RegisterNetworkMessages;

		internal static event Events.CustomEventHandler UnregisterNetworkMessages;

		internal static byte[] ToBytes(this object @object)
		{
			if (@object == null)
			{
				return null;
			}
			return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@object));
		}

		internal static T ToObject<T>(this byte[] bytes) where T : class
		{
			return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bytes));
		}

		internal static void OnRegisterNetworkMessages()
		{
			Network.RegisterNetworkMessages.InvokeSafely();
		}

		internal static void OnUnregisterNetworkMessages()
		{
			Network.UnregisterNetworkMessages.InvokeSafely();
		}

		internal static void RegisterAllMessages()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			foreach (NetworkMessageFinalizerBase value in NetworkMessageFinalizers.Values)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(value.UniqueName, new HandleNamedMessageDelegate(value.Read));
			}
		}

		internal static void UnregisterAllMessages()
		{
			string[] array = NetworkMessageFinalizers.Keys.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				UnregisterMessage(array[i]);
			}
		}

		public static void RegisterAll()
		{
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly);
			for (int i = 0; i < typesFromAssembly.Length; i++)
			{
				RegisterAll(typesFromAssembly[i]);
			}
		}

		public static void RegisterAll(Type type)
		{
			if (!type.IsClass)
			{
				return;
			}
			NetworkMessage customAttribute = type.GetCustomAttribute<NetworkMessage>();
			if (customAttribute != null)
			{
				if (type.BaseType.Name == "NetworkMessageHandler`1")
				{
					Type type2 = type.BaseType.GetGenericArguments()[0];
					RegisterInfoGeneric.MakeGenericMethod(type2).Invoke(null, new object[3]
					{
						customAttribute.UniqueName,
						customAttribute.RelayToSelf,
						type.GetMethod("Handler").CreateDelegate(typeof(Action<, >).MakeGenericType(typeof(ulong), type2), Activator.CreateInstance(type))
					});
				}
				else if (type.BaseType.Name == "NetworkMessageHandler")
				{
					RegisterInfo.Invoke(null, new object[3]
					{
						customAttribute.UniqueName,
						customAttribute.RelayToSelf,
						type.GetMethod("Handler").CreateDelegate(typeof(Action<>).MakeGenericType(typeof(ulong)), Activator.CreateInstance(type))
					});
				}
				return;
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				customAttribute = methodInfo.GetCustomAttribute<NetworkMessage>();
				if (customAttribute != null)
				{
					if (!methodInfo.IsStatic)
					{
						throw new Exception("Detected NetworkMessage attribute on non-static method. All NetworkMessages on methods must be static.");
					}
					if (methodInfo.GetParameters().Length == 1)
					{
						RegisterInfo.Invoke(null, new object[3]
						{
							customAttribute.UniqueName,
							customAttribute.RelayToSelf,
							methodInfo.CreateDelegate(typeof(Action<>).MakeGenericType(typeof(ulong)))
						});
					}
					else
					{
						Type parameterType = methodInfo.GetParameters()[1].ParameterType;
						RegisterInfoGeneric.MakeGenericMethod(parameterType).Invoke(null, new object[3]
						{
							customAttribute.UniqueName,
							customAttribute.RelayToSelf,
							methodInfo.CreateDelegate(typeof(Action<, >).MakeGenericType(typeof(ulong), parameterType))
						});
					}
				}
			}
		}

		public static void UnregisterAll()
		{
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly);
			for (int i = 0; i < typesFromAssembly.Length; i++)
			{
				UnregisterAll(typesFromAssembly[i]);
			}
		}

		public static void UnregisterAll(Type type)
		{
			if (!type.IsClass)
			{
				return;
			}
			NetworkMessage customAttribute = type.GetCustomAttribute<NetworkMessage>();
			if (customAttribute != null)
			{
				UnregisterMessage(customAttribute.UniqueName);
				return;
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			for (int i = 0; i < methods.Length; i++)
			{
				customAttribute = methods[i].GetCustomAttribute<NetworkMessage>();
				if (customAttribute != null)
				{
					UnregisterMessage(customAttribute.UniqueName);
				}
			}
		}

		public static void RegisterMessage<T>(string uniqueName, bool relayToSelf, Action<ulong, T> onReceived) where T : class
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			if (NetworkMessageFinalizers.ContainsKey(uniqueName))
			{
				throw new Exception(uniqueName + " already registered");
			}
			NetworkMessageFinalizer<T> networkMessageFinalizer = new NetworkMessageFinalizer<T>(uniqueName, relayToSelf, onReceived);
			NetworkMessageFinalizers.Add(uniqueName, networkMessageFinalizer);
			if (StartedNetworking)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(uniqueName, new HandleNamedMessageDelegate(networkMessageFinalizer.Read));
			}
		}

		public static void RegisterMessage(string uniqueName, bool relayToSelf, Action<ulong> onReceived)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			if (NetworkMessageFinalizers.ContainsKey(uniqueName))
			{
				throw new Exception(uniqueName + " already registered");
			}
			NetworkMessageFinalizer networkMessageFinalizer = new NetworkMessageFinalizer(uniqueName, relayToSelf, onReceived);
			NetworkMessageFinalizers.Add(uniqueName, networkMessageFinalizer);
			if (StartedNetworking)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(uniqueName, new HandleNamedMessageDelegate(networkMessageFinalizer.Read));
			}
		}

		public static void UnregisterMessage(string uniqueName)
		{
			if (NetworkMessageFinalizers.Remove(uniqueName))
			{
				NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler(uniqueName);
			}
		}

		public static void Broadcast<T>(string uniqueName, T @object) where T : class
		{
			if (NetworkMessageFinalizers.TryGetValue(uniqueName, out var value))
			{
				if (!(value is NetworkMessageFinalizer<T> networkMessageFinalizer))
				{
					throw new Exception("Network handler for " + uniqueName + " was not broadcast with the right type!");
				}
				networkMessageFinalizer.Send(@object);
			}
		}

		public static void Broadcast(string uniqueName)
		{
			if (NetworkMessageFinalizers.TryGetValue(uniqueName, out var value))
			{
				if (!(value is NetworkMessageFinalizer networkMessageFinalizer))
				{
					throw new Exception("Network handler for " + uniqueName + " was not broadcast with the right type!");
				}
				networkMessageFinalizer.Send();
			}
		}

		internal static void Init()
		{
			RegisterNetworkMessages += delegate
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				StartedNetworking = true;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
					object obj = <>c.<>9__35_2;
					if (obj == null)
					{
						HandleNamedMessageDelegate val = delegate(ulong senderClientId, FastBufferReader reader)
						{
							//IL_0006: Unknown result type (might be due to invalid IL or missing references)
							//IL_000c: Unknown result type (might be due to invalid IL or missing references)
							//IL_003d: 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_0059: Unknown result type (might be due to invalid IL or missing references)
							byte[] bytes = default(byte[]);
							((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
							NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
							networkMessageWrapper.Sender = senderClientId;
							byte[] array = networkMessageWrapper.ToBytes();
							FastBufferWriter val2 = default(FastBufferWriter);
							((FastBufferWriter)(ref val2))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
							try
							{
								((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(array, default(ForPrimitives));
								NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val2, (NetworkDelivery)3);
							}
							finally
							{
								((IDisposable)(FastBufferWriter)(ref val2)).Dispose();
							}
						};
						<>c.<>9__35_2 = val;
						obj = (object)val;
					}
					customMessagingManager.RegisterNamedMessageHandler("LC_API_RELAY_MESSAGE", (HandleNamedMessageDelegate)obj);
				}
				RegisterAllMessages();
			};
			UnregisterNetworkMessages += delegate
			{
				StartedNetworking = false;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler("LC_API_RELAY_MESSAGE");
				}
				UnregisterAllMessages();
			};
			SetupNetworking();
			RegisterAll();
		}

		internal static void SetupNetworking()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			for (int i = 0; i < types.Length; i++)
			{
				MethodInfo[] methods = types[i].GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	public class NetworkMessage : Attribute
	{
		public string UniqueName { get; }

		public bool RelayToSelf { get; }

		public NetworkMessage(string uniqueName, bool relayToSelf = false)
		{
			UniqueName = uniqueName;
			RelayToSelf = relayToSelf;
		}
	}
	public abstract class NetworkMessageHandler<T> where T : class
	{
		public abstract void Handler(ulong sender, T message);
	}
	public abstract class NetworkMessageHandler
	{
		public abstract void Handler(ulong sender);
	}
	internal abstract class NetworkMessageFinalizerBase
	{
		internal abstract string UniqueName { get; }

		internal abstract bool RelayToSelf { get; }

		public abstract void Read(ulong sender, FastBufferReader reader);
	}
	internal class NetworkMessageFinalizer : NetworkMessageFinalizerBase
	{
		internal override string UniqueName { get; }

		internal override bool RelayToSelf { get; }

		internal Action<ulong> OnReceived { get; }

		public NetworkMessageFinalizer(string uniqueName, bool relayToSelf, Action<ulong> onReceived)
		{
			UniqueName = uniqueName;
			RelayToSelf = relayToSelf;
			OnReceived = onReceived;
		}

		public void Send()
		{
			//IL_005d: 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_0091: 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)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater());
				return;
			}
			byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId).ToBytes();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
				if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)3);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)3);
				}
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public override void Read(ulong fakeSender, FastBufferReader reader)
		{
			//IL_0021: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(ReadLater(fakeSender, reader));
				return;
			}
			byte[] bytes = default(byte[]);
			((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
			NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
			if (RelayToSelf || LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId != networkMessageWrapper.Sender)
			{
				OnReceived(networkMessageWrapper.Sender);
			}
		}

		private IEnumerator SendLater()
		{
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to send network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Send();
		}

		private IEnumerator ReadLater(ulong fakeSender, FastBufferReader reader)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to read network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Read(fakeSender, reader);
		}
	}
	internal class NetworkMessageFinalizer<T> : NetworkMessageFinalizerBase where T : class
	{
		internal override string UniqueName { get; }

		internal override bool RelayToSelf { get; }

		internal Action<ulong, T> OnReceived { get; }

		public NetworkMessageFinalizer(string uniqueName, bool relayToSelf, Action<ulong, T> onReceived)
		{
			UniqueName = uniqueName;
			RelayToSelf = relayToSelf;
			OnReceived = onReceived;
		}

		public void Send(T obj)
		{
			//IL_0069: 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_009d: 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)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater(obj));
				return;
			}
			byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId, obj.ToBytes()).ToBytes();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
				if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)3);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)3);
				}
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public override void Read(ulong fakeSender, FastBufferReader reader)
		{
			//IL_0021: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(ReadLater(fakeSender, reader));
				return;
			}
			byte[] bytes = default(byte[]);
			((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
			NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
			if (RelayToSelf || LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId != networkMessageWrapper.Sender)
			{
				OnReceived(networkMessageWrapper.Sender, networkMessageWrapper.Message.ToObject<T>());
			}
		}

		private IEnumerator SendLater(T obj)
		{
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to send network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Send(obj);
		}

		private IEnumerator ReadLater(ulong fakeSender, FastBufferReader reader)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to read network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Read(fakeSender, reader);
		}
	}
	internal class NetworkMessageWrapper
	{
		public string UniqueName { get; set; }

		public ulong Sender { get; set; }

		public byte[] Message { get; set; }

		internal NetworkMessageWrapper(string uniqueName, ulong sender)
		{
			UniqueName = uniqueName;
			Sender = sender;
		}

		internal NetworkMessageWrapper(string uniqueName, ulong sender, byte[] message)
		{
			UniqueName = uniqueName;
			Sender = sender;
			Message = message;
		}

		internal NetworkMessageWrapper()
		{
		}
	}
	internal static class RegisterPatch
	{
		internal static void Postfix()
		{
			Network.OnRegisterNetworkMessages();
		}
	}
	internal static class UnregisterPatch
	{
		internal static void Postfix()
		{
			Network.OnUnregisterNetworkMessages();
		}
	}
}
namespace LC_API.Networking.Serializers
{
	public struct Vector2S
	{
		private Vector2? v2;

		public float x { get; set; }

		public float y { get; set; }

		[JsonIgnore]
		public Vector2 vector2
		{
			get
			{
				//IL_002f: 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)
				if (!v2.HasValue)
				{
					v2 = new Vector2(x, y);
				}
				return v2.Value;
			}
		}

		public Vector2S(float x, float y)
		{
			v2 = null;
			this.x = x;
			this.y = y;
		}

		public static implicit operator Vector2(Vector2S vector2S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector2S.vector2;
		}

		public static implicit operator Vector2S(Vector2 vector2)
		{
			//IL_0000: 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)
			return new Vector2S(vector2.x, vector2.y);
		}
	}
	public struct Vector2IntS
	{
		private Vector2Int? v2;

		public int x { get; set; }

		public int y { get; set; }

		[JsonIgnore]
		public Vector2Int vector2
		{
			get
			{
				//IL_002f: 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)
				if (!v2.HasValue)
				{
					v2 = new Vector2Int(x, y);
				}
				return v2.Value;
			}
		}

		public Vector2IntS(int x, int y)
		{
			v2 = null;
			this.x = x;
			this.y = y;
		}

		public static implicit operator Vector2Int(Vector2IntS vector2S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector2S.vector2;
		}

		public static implicit operator Vector2IntS(Vector2Int vector2)
		{
			return new Vector2IntS(((Vector2Int)(ref vector2)).x, ((Vector2Int)(ref vector2)).y);
		}
	}
	public struct Vector3S
	{
		private Vector3? v3;

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		[JsonIgnore]
		public Vector3 vector3
		{
			get
			{
				//IL_0035: 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)
				if (!v3.HasValue)
				{
					v3 = new Vector3(x, y, z);
				}
				return v3.Value;
			}
		}

		public Vector3S(float x, float y, float z)
		{
			v3 = null;
			this.x = x;
			this.y = y;
			this.z = z;
		}

		public static implicit operator Vector3(Vector3S vector3S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector3S.vector3;
		}

		public static implicit operator Vector3S(Vector3 vector3)
		{
			//IL_0000: 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_000c: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3S(vector3.x, vector3.y, vector3.z);
		}
	}
	public struct Vector3IntS
	{
		private Vector3Int? v3;

		public int x { get; set; }

		public int y { get; set; }

		public int z { get; set; }

		[JsonIgnore]
		public Vector3Int vector3
		{
			get
			{
				//IL_0035: 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)
				if (!v3.HasValue)
				{
					v3 = new Vector3Int(x, y, z);
				}
				return v3.Value;
			}
		}

		public Vector3IntS(int x, int y, int z)
		{
			v3 = null;
			this.x = x;
			this.y = y;
			this.z = z;
		}

		public static implicit operator Vector3Int(Vector3IntS vector3S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector3S.vector3;
		}

		public static implicit operator Vector3IntS(Vector3Int vector3)
		{
			return new Vector3IntS(((Vector3Int)(ref vector3)).x, ((Vector3Int)(ref vector3)).y, ((Vector3Int)(ref vector3)).z);
		}
	}
	public struct Vector4S
	{
		private Vector4? v4;

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public float w { get; set; }

		[JsonIgnore]
		public Vector4 Vector4
		{
			get
			{
				//IL_003b: 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)
				if (!v4.HasValue)
				{
					v4 = new Vector4(x, y, z, w);
				}
				return v4.Value;
			}
		}

		public Vector4S(float x, float y, float z, float w)
		{
			v4 = null;
			this.x = x;
			this.y = y;
			this.z = z;
			this.w = w;
		}

		public static implicit operator Vector4(Vector4S vector4S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector4S.Vector4;
		}

		public static implicit operator Vector4S(Vector4 vector4)
		{
			//IL_0000: 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_000c: 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)
			return new Vector4S(vector4.x, vector4.y, vector4.z, vector4.w);
		}
	}
	public struct QuaternionS
	{
		private Quaternion? q;

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public float w { get; set; }

		[JsonIgnore]
		public Quaternion Quaternion
		{
			get
			{
				//IL_003b: 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)
				if (!q.HasValue)
				{
					q = new Quaternion(x, y, z, w);
				}
				return q.Value;
			}
		}

		public QuaternionS(float x, float y, float z, float w)
		{
			q = null;
			this.x = x;
			this.y = y;
			this.z = z;
			this.w = w;
		}

		public static implicit operator Quaternion(QuaternionS quaternionS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return quaternionS.Quaternion;
		}

		public static implicit operator QuaternionS(Quaternion quaternion)
		{
			//IL_0000: 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_000c: 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)
			return new QuaternionS(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
		}
	}
	public struct ColorS
	{
		private Color? c;

		public float r { get; set; }

		public float g { get; set; }

		public float b { get; set; }

		public float a { get; set; }

		[JsonIgnore]
		public Color Color
		{
			get
			{
				//IL_003b: 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)
				if (!c.HasValue)
				{
					c = new Color(r, g, b, a);
				}
				return c.Value;
			}
		}

		public ColorS(float r, float g, float b, float a)
		{
			c = null;
			this.r = r;
			this.g = g;
			this.b = b;
			this.a = a;
		}

		public static implicit operator Color(ColorS colorS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return colorS.Color;
		}

		public static implicit operator ColorS(Color color)
		{
			//IL_0000: 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_000c: 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)
			return new ColorS(color.r, color.g, color.b, color.a);
		}
	}
	public struct Color32S
	{
		private Color32? c;

		public byte r { get; set; }

		public byte g { get; set; }

		public byte b { get; set; }

		public byte a { get; set; }

		[JsonIgnore]
		public Color32 Color
		{
			get
			{
				//IL_003b: 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)
				if (!c.HasValue)
				{
					c = new Color32(r, g, b, a);
				}
				return c.Value;
			}
		}

		public Color32S(byte r, byte g, byte b, byte a)
		{
			c = null;
			this.r = r;
			this.g = g;
			this.b = b;
			this.a = a;
		}

		public static implicit operator Color32(Color32S colorS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return colorS.Color;
		}

		public static implicit operator Color32S(Color32 color)
		{
			//IL_0000: 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_000c: 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)
			return new Color32S(color.r, color.g, color.b, color.a);
		}
	}
	public struct RayS
	{
		private Ray? r;

		public Vector3S origin { get; set; }

		public Vector3S direction { get; set; }

		[JsonIgnore]
		public Ray Ray
		{
			get
			{
				//IL_0039: 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_0024: Unknown result type (might be due to invalid IL or missing references)
				if (!r.HasValue)
				{
					r = new Ray((Vector3)origin, (Vector3)direction);
				}
				return r.Value;
			}
		}

		public RayS(Vector3 origin, Vector3 direction)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			r = null;
			this.origin = origin;
			this.direction = direction;
		}

		public static implicit operator Ray(RayS rayS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return rayS.Ray;
		}

		public static implicit operator RayS(Ray ray)
		{
			//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 new RayS(((Ray)(ref ray)).origin, ((Ray)(ref ray)).direction);
		}
	}
	public struct Ray2DS
	{
		private Ray2D? r;

		public Vector2S origin { get; set; }

		public Vector2S direction { get; set; }

		[JsonIgnore]
		public Ray2D Ray
		{
			get
			{
				//IL_0039: 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_0024: Unknown result type (might be due to invalid IL or missing references)
				if (!r.HasValue)
				{
					r = new Ray2D((Vector2)origin, (Vector2)direction);
				}
				return r.Value;
			}
		}

		public Ray2DS(Vector2 origin, Vector2 direction)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			r = null;
			this.origin = origin;
			this.direction = direction;
		}

		public static implicit operator Ray2D(Ray2DS ray2DS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return ray2DS.Ray;
		}

		public static implicit operator Ray2DS(Ray2D ray2D)
		{
			//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 new Ray2DS(((Ray2D)(ref ray2D)).origin, ((Ray2D)(ref ray2D)).direction);
		}
	}
}
namespace LC_API.ManualPatches
{
	internal static class ServerPatch
	{
		internal static bool OnLobbyCreate(GameNetworkManager __instance, Result result, Lobby lobby)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if ((int)result != 1)
			{
				Debug.LogError((object)$"Lobby could not be created! {result}", (Object)(object)__instance);
			}
			__instance.lobbyHostSettings.lobbyName = "[MODDED]" + __instance.lobbyHostSettings.lobbyName.ToString();
			Plugin.Log.LogMessage((object)"server pre-setup success");
			return true;
		}

		internal static bool CacheMenuManager(MenuManager __instance)
		{
			LC_APIManager.MenuManager = __instance;
			return true;
		}

		internal static bool ChatCommands(HUDManager __instance, CallbackContext context)
		{
			if (__instance.chatTextField.text.ToLower().Contains("/modcheck"))
			{
				CheatDatabase.OtherPlayerCheatDetector();
				return false;
			}
			return true;
		}

		internal static void GameNetworkManagerAwake(GameNetworkManager __instance)
		{
			if ((Object)(object)GameNetworkManager.Instance == (Object)null)
			{
				ModdedServer.GameVersion = __instance.gameVersionNum;
			}
		}
	}
}
namespace LC_API.GameInterfaceAPI
{
	public static class GameState
	{
		private static readonly Action NothingAction = delegate
		{
		};

		public static int AlivePlayerCount { get; private set; }

		public static ShipState ShipState { get; private set; }

		public static event Action PlayerDied;

		public static event Action LandOnMoon;

		public static event Action WentIntoOrbit;

		public static event Action ShipStartedLeaving;

		internal static void GSUpdate()
		{
			if (!((Object)(object)StartOfRound.Instance == (Object)null))
			{
				if (StartOfRound.Instance.shipHasLanded && ShipState != ShipState.OnMoon)
				{
					ShipState = ShipState.OnMoon;
					GameState.LandOnMoon.InvokeActionSafe();
				}
				if (StartOfRound.Instance.inShipPhase && ShipState != 0)
				{
					ShipState = ShipState.InOrbit;
					GameState.WentIntoOrbit.InvokeActionSafe();
				}
				if (StartOfRound.Instance.shipIsLeaving && ShipState != ShipState.LeavingMoon)
				{
					ShipState = ShipState.LeavingMoon;
					GameState.ShipStartedLeaving.InvokeActionSafe();
				}
				if (AlivePlayerCount < StartOfRound.Instance.livingPlayers)
				{
					GameState.PlayerDied.InvokeActionSafe();
				}
				AlivePlayerCount = StartOfRound.Instance.livingPlayers;
			}
		}

		static GameState()
		{
			GameState.PlayerDied = NothingAction;
			GameState.LandOnMoon = NothingAction;
			GameState.WentIntoOrbit = NothingAction;
			GameState.ShipStartedLeaving = NothingAction;
		}
	}
	public class GameTips
	{
		private static List<string> tipHeaders = new List<string>();

		private static List<string> tipBodys = new List<string>();

		private static float lastMessageTime;

		public static void ShowTip(string header, string body)
		{
			tipHeaders.Add(header);
			tipBodys.Add(body);
		}

		public static void UpdateInternal()
		{
			lastMessageTime -= Time.deltaTime;
			if ((tipHeaders.Count > 0) & (lastMessageTime < 0f))
			{
				lastMessageTime = 5f;
				if ((Object)(object)HUDManager.Instance != (Object)null)
				{
					HUDManager.Instance.DisplayTip(tipHeaders[0], tipBodys[0], false, false, "LC_Tip1");
				}
				tipHeaders.RemoveAt(0);
				tipBodys.RemoveAt(0);
			}
		}
	}
}
namespace LC_API.GameInterfaceAPI.Features
{
	public class Item : NetworkBehaviour
	{
		private bool hasNewProps;

		internal static GameObject ItemNetworkPrefab { get; set; }

		public static Dictionary<GrabbableObject, Item> Dictionary { get; } = new Dictionary<GrabbableObject, Item>();


		public static IReadOnlyCollection<Item> List => Dictionary.Values;

		public GrabbableObject GrabbableObject { get; private set; }

		public Item ItemProperties => GrabbableObject.itemProperties;

		public ScanNodeProperties ScanNodeProperties { get; set; }

		public bool IsHeld => GrabbableObject.isHeld;

		public bool IsTwoHanded => ItemProperties.twoHanded;

		public Player Holder
		{
			get
			{
				if (!IsHeld)
				{
					return null;
				}
				if (!Player.Dictionary.TryGetValue(GrabbableObject.playerHeldBy, out var value))
				{
					return null;
				}
				return value;
			}
		}

		public string Name
		{
			get
			{
				return ItemProperties.itemName;
			}
			set
			{
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set item name on client.");
				}
				string oldName = ItemProperties.itemName.ToLower();
				CloneProperties();
				ItemProperties.itemName = value;
				OverrideTooltips(oldName, value.ToLower());
				ScanNodeProperties.headerText = value;
				SetGrabbableNameClientRpc(value);
			}
		}

		public Vector3 Position
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return ((Component)GrabbableObject).transform.position;
			}
			set
			{
				//IL_0029: 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_0035: 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_0046: 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)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set item position on client.");
				}
				GrabbableObject.startFallingPosition = value;
				GrabbableObject.targetFloorPosition = value;
				((Component)GrabbableObject).transform.position = value;
				SetItemPositionClientRpc(value);
			}
		}

		public Quaternion Rotation
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return ((Component)GrabbableObject).transform.rotation;
			}
			set
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				((Component)GrabbableObject).transform.rotation = value;
			}
		}

		public Vector3 Scale
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return ((Component)GrabbableObject).transform.localScale;
			}
			set
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				((Component)GrabbableObject).transform.localScale = value;
			}
		}

		public bool IsScrap
		{
			get
			{
				return ItemProperties.isScrap;
			}
			set
			{
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set item name on client.");
				}
				CloneProperties();
				ItemProperties.isScrap = value;
				SetIsScrapClientRpc(value);
			}
		}

		public int ScrapValue
		{
			get
			{
				return GrabbableObject.scrapValue;
			}
			set
			{
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set scrap value on client.");
				}
				GrabbableObject.SetScrapValue(value);
				SetScrapValueClientRpc(value);
			}
		}

		[ClientRpc]
		private void SetGrabbableNameClientRpc(string name)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: 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_0088: 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_00ba: 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(66243798u, val, (RpcDelivery)0);
				bool flag = name != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(name, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 66243798u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				string oldName = ItemProperties.itemName.ToLower();
				CloneProperties();
				ItemProperties.itemName = name;
				OverrideTooltips(oldName, name.ToLower());
				ScanNodeProperties.headerText = name;
			}
		}

		private void OverrideTooltips(string oldName, string newName)
		{
			for (int i = 0; i < ItemProperties.toolTips.Length; i++)
			{
				ItemProperties.toolTips[i] = ItemProperties.toolTips[i].ReplaceWithCase(oldName, newName);
			}
			if (IsHeld && (Object)(object)Holder == (Object)(object)Player.LocalPlayer)
			{
				GrabbableObject.SetControlTipsForItem();
			}
		}

		[ClientRpc]
		private void SetItemPositionClientRpc(Vector3 pos)
		{
			//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_0089: 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_00cf: 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_00db: 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)
			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(949135576u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref pos);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 949135576u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					GrabbableObject.startFallingPosition = pos;
					GrabbableObject.targetFloorPosition = pos;
					((Component)GrabbableObject).transform.position = pos;
				}
			}
		}

		public void SetAndSyncRotation(Quaternion rotation)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to sync item rotation from client.");
			}
			SetItemRotationClientRpc(rotation);
		}

		[ClientRpc]
		private void SetItemRotationClientRpc(Quaternion rotation)
		{
			//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_0089: 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)
			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(1528367091u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref rotation);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1528367091u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Rotation = rotation;
				}
			}
		}

		public void SetAndSyncScale(Vector3 scale)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to sync item scale from client.");
			}
			SetItemScaleClientRpc(scale);
		}

		[ClientRpc]
		private void SetItemScaleClientRpc(Vector3 scale)
		{
			//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_0089: 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)
			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(2688253945u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref scale);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2688253945u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Scale = scale;
				}
			}
		}

		[ClientRpc]
		private void SetIsScrapClientRpc(bool isScrap)
		{
			//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(4227417717u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref isScrap, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4227417717u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					CloneProperties();
					ItemProperties.isScrap = isScrap;
				}
			}
		}

		[ClientRpc]
		private void SetScrapValueClientRpc(int scrapValue)
		{
			//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 != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3866863385u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, scrapValue);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3866863385u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					GrabbableObject.SetScrapValue(scrapValue);
				}
			}
		}

		public void RemoveFromHolder(Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion))
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to remove item from player on client.");
			}
			if (IsHeld)
			{
				((NetworkBehaviour)this).NetworkObject.RemoveOwnership();
				Holder.Inventory.RemoveItem(this);
				RemoveFromHolderClientRpc();
				Position = position;
				Rotation = rotation;
			}
		}

		[ClientRpc]
		private void RemoveFromHolderClientRpc()
		{
			//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 != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1050513218u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1050513218u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && IsHeld)
				{
					Holder.Inventory.RemoveItem(this);
				}
			}
		}

		public void EnablePhysics(bool enable)
		{
			GrabbableObject.EnablePhysics(enable);
		}

		public void EnableMeshes(bool enable)
		{
			GrabbableObject.EnableItemMeshes(enable);
		}

		public void FallToGround(bool randomizePosition = false)
		{
			GrabbableObject.FallToGround(randomizePosition);
		}

		public bool PocketItem()
		{
			if (!IsHeld || (Object)(object)Holder.HeldItem != (Object)(object)this || IsTwoHanded)
			{
				return false;
			}
			GrabbableObject.PocketItem();
			return true;
		}

		public bool GiveTo(Player player, bool switchTo = true)
		{
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to give item to player on client.");
			}
			return player.Inventory.TryAddItem(this, switchTo);
		}

		public void InitializeScrap()
		{
			if (RoundManager.Instance.AnomalyRandom != null)
			{
				InitializeScrap((int)((float)RoundManager.Instance.AnomalyRandom.Next(ItemProperties.minValue, ItemProperties.maxValue) * RoundManager.Instance.scrapValueMultiplier));
			}
			else
			{
				InitializeScrap((int)((float)Random.Range(ItemProperties.minValue, ItemProperties.maxValue) * RoundManager.Instance.scrapValueMultiplier));
			}
		}

		public void InitializeScrap(int scrapValue)
		{
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to initialize scrap on client.");
			}
			ScrapValue = scrapValue;
			InitializeScrapClientRpc();
		}

		[ClientRpc]
		private void InitializeScrapClientRpc()
		{
			//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)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1334565671u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1334565671u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			MeshFilter val3 = default(MeshFilter);
			if (((Component)GrabbableObject).gameObject.TryGetComponent<MeshFilter>(ref val3) && ItemProperties.meshVariants != null && ItemProperties.meshVariants.Length != 0)
			{
				if (RoundManager.Instance.ScrapValuesRandom != null)
				{
					val3.mesh = ItemProperties.meshVariants[RoundManager.Instance.ScrapValuesRandom.Next(ItemProperties.meshVariants.Length)];
				}
				else
				{
					val3.mesh = ItemProperties.meshVariants[0];
				}
			}
			MeshRenderer val4 = default(MeshRenderer);
			if (((Component)GrabbableObject).gameObject.TryGetComponent<MeshRenderer>(ref val4) && ItemProperties.materialVariants != null && ItemProperties.materialVariants.Length != 0)
			{
				if (RoundManager.Instance.ScrapValuesRandom != null)
				{
					((Renderer)val4).sharedMaterial = ItemProperties.materialVariants[RoundManager.Instance.ScrapValuesRandom.Next(ItemProperties.materialVariants.Length)];
				}
				else
				{
					((Renderer)val4).sharedMaterial = ItemProperties.materialVariants[0];
				}
			}
		}

		public static Item CreateAndSpawnItem(string itemName, bool andInitialize = true, Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion))
		{
			//IL_006c: 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 (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to create and spawn item on client.");
			}
			string name = itemName.ToLower();
			GameObject val = ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => i.itemName.ToLower().Contains(name)))?.spawnPrefab;
			if ((Object)(object)val != (Object)null)
			{
				GameObject obj = Object.Instantiate<GameObject>(val, position, rotation);
				obj.GetComponent<NetworkObject>().Spawn(false);
				Item component = obj.GetComponent<Item>();
				if (component.IsScrap && andInitialize)
				{
					component.InitializeScrap();
				}
				return component;
			}
			return null;
		}

		public static Item CreateAndGiveItem(string itemName, Player player, bool andInitialize = true, bool switchTo = true)
		{
			//IL_006c: 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: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to create and give item on client.");
			}
			string name = itemName.ToLower();
			GameObject val = ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => i.itemName.ToLower().Contains(name)))?.spawnPrefab;
			if ((Object)(object)val != (Object)null)
			{
				GameObject obj = Object.Instantiate<GameObject>(val, Vector3.zero, default(Quaternion));
				obj.GetComponent<NetworkObject>().Spawn(false);
				Item component = obj.GetComponent<Item>();
				if (component.IsScrap && andInitialize)
				{
					component.InitializeScrap();
				}
				component.GiveTo(player, switchTo);
				return component;
			}
			return null;
		}

		private void Awake()
		{
			GrabbableObject = ((Component)this).GetComponent<GrabbableObject>();
			ScanNodeProperties = ((Component)GrabbableObject).gameObject.GetComponentInChildren<ScanNodeProperties>();
			Dictionary.Add(GrabbableObject, this);
		}

		private void CloneProperties()
		{
			Item itemProperties = Object.Instantiate<Item>(ItemProperties);
			if (hasNewProps)
			{
				Object.Destroy((Object)(object)ItemProperties);
			}
			GrabbableObject.itemProperties = itemProperties;
			hasNewProps = true;
		}

		public override void OnDestroy()
		{
			Dictionary.Remove(GrabbableObject);
			((NetworkBehaviour)this).OnDestroy();
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_Item()
		{
			//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
			NetworkManager.__rpc_func_table.Add(66243798u, new RpcReceiveHandler(__rpc_handler_66243798));
			NetworkManager.__rpc_func_table.Add(949135576u, new RpcReceiveHandler(__rpc_handler_949135576));
			NetworkManager.__rpc_func_table.Add(1528367091u, new RpcReceiveHandler(__rpc_handler_1528367091));
			NetworkManager.__rpc_func_table.Add(2688253945u, new RpcReceiveHandler(__rpc_handler_2688253945));
			NetworkManager.__rpc_func_table.Add(4227417717u, new RpcReceiveHandler(__rpc_handler_4227417717));
			NetworkManager.__rpc_func_table.Add(3866863385u, new RpcReceiveHandler(__rpc_handler_3866863385));
			NetworkManager.__rpc_func_table.Add(1050513218u, new RpcReceiveHandler(__rpc_handler_1050513218));
			NetworkManager.__rpc_func_table.Add(1334565671u, new RpcReceiveHandler(__rpc_handler_1334565671));
		}

		private static void __rpc_handler_66243798(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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string grabbableNameClientRpc = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref grabbableNameClientRpc, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetGrabbableNameClientRpc(grabbableNameClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_949135576(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0036: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Vector3 itemPositionClientRpc = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref itemPositionClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetItemPositionClientRpc(itemPositionClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1528367091(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0036: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Quaternion itemRotationClientRpc = default(Quaternion);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref itemRotationClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetItemRotationClientRpc(itemRotationClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2688253945(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0036: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Vector3 itemScaleClientRpc = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref itemScaleClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetItemScaleClientRpc(itemScaleClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_4227417717(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 isScrapClientRpc = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref isScrapClientRpc, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetIsScrapClientRpc(isScrapClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3866863385(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)
			{
				int scrapValueClientRpc = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref scrapValueClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetScrapValueClientRpc(scrapValueClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1050513218(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;
				((Item)(object)target).RemoveFromHolderClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1334565671(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;
				((Item)(object)target).InitializeScrapClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		protected internal override string __getTypeName()
		{
			return "Item";
		}
	}
	public class Player : NetworkBehaviour
	{
		public class PlayerInventory : NetworkBehaviour
		{
			public Player Player { get; private set; }

			public Item[] Items => Player.PlayerController.ItemSlots.Select((GrabbableObject i) => (!((Object)(object)i != (Object)null)) ? null : Item.Dictionary[i]).ToArray();

			public int CurrentSlot
			{
				get
				{
					return Player.PlayerController.currentItemSlot;
				}
				set
				{
					//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.IsLocalPlayer)
					{
						SetSlotServerRpc(value);
					}
					else if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
					{
						SetSlotClientRpc(value);
					}
				}
			}

			[ServerRpc]
			private void SetSlotServerRpc(int slot, 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_00df: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e9: Invalid comparison between Unknown and I4
				//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_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_00b7: 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_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)base.__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;
					}
					FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1475903090u, serverRpcParams, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val, slot);
					((NetworkBehaviour)this).__endSendServerRpc(ref val, 1475903090u, serverRpcParams, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && serverRpcParams.Receive.SenderClientId == Player.ClientId)
				{
					SetSlotClientRpc(slot);
				}
			}

			[ClientRpc]
			private void SetSlotClientRpc(int slot)
			{
				//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 != 2 && (networkManager.IsServer || networkManager.IsHost))
					{
						ClientRpcParams val = default(ClientRpcParams);
						FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2977994897u, val, (RpcDelivery)0);
						BytePacker.WriteValueBitPacked(val2, slot);
						((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2977994897u, val, (RpcDelivery)0);
					}
					if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
					{
						Player.PlayerController.SwitchToItemSlot(slot, (GrabbableObject)null);
					}
				}
			}

			public int GetFirstEmptySlot()
			{
				return Player.PlayerController.FirstEmptyItemSlot();
			}

			public bool TryGetFirstEmptySlot(out int slot)
			{
				slot = Player.PlayerController.FirstEmptyItemSlot();
				return slot != -1;
			}

			public bool TryAddItem(Item item, bool switchTo = true)
			{
				//IL_0052: 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_005b: 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)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to add item from client.");
				}
				if (TryGetFirstEmptySlot(out var slot))
				{
					if (item.IsTwoHanded && !Player.HasFreeHands)
					{
						return false;
					}
					if (item.IsHeld)
					{
						item.RemoveFromHolder();
					}
					((NetworkBehaviour)item).NetworkObject.ChangeOwnership(Player.ClientId);
					if (item.IsTwoHanded)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (switchTo && Player.HasFreeHands)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (Player.PlayerController.currentItemSlot == slot)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else
					{
						SetItemInSlotClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					return true;
				}
				return false;
			}

			public bool TryAddItemToSlot(Item item, int slot, bool switchTo = true)
			{
				//IL_007a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: 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)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to add item from client.");
				}
				if (slot < Player.PlayerController.ItemSlots.Length && (Object)(object)Player.PlayerController.ItemSlots[slot] == (Object)null)
				{
					if (item.IsTwoHanded && !Player.HasFreeHands)
					{
						return false;
					}
					if (item.IsHeld)
					{
						item.RemoveFromHolder();
					}
					((NetworkBehaviour)item).NetworkObject.ChangeOwnership(Player.ClientId);
					if (item.IsTwoHanded)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (switchTo && Player.HasFreeHands)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (Player.PlayerController.currentItemSlot == slot)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else
					{
						SetItemInSlotClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					return true;
				}
				return false;
			}

			[ClientRpc]
			private void SetItemInSlotClientRpc(int slot, ulong itemId)
			{
				//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 b

BepInEx/plugins/anormaltwig-LateCompany/LateCompanyV1.0.9.dll

Decompiled 10 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
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(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("LateCompany")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+45a32594ae7b3615a3d1703738f777272caa8e30")]
[assembly: AssemblyProduct("LateCompany")]
[assembly: AssemblyTitle("LateCompany")]
[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;
		}
	}
}
namespace LateCompany
{
	public static class PluginInfo
	{
		public const string GUID = "twig.latecompany";

		public const string PrintName = "Late Company";

		public const string Version = "1.0.9";
	}
	[BepInPlugin("twig.latecompany", "Late Company", "1.0.9")]
	internal class Plugin : BaseUnityPlugin
	{
		private ConfigEntry<bool> configLateJoinOrbitOnly;

		public static bool AllowJoiningWhileLanded = false;

		public static bool LobbyJoinable = true;

		public void Awake()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			configLateJoinOrbitOnly = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Allow joining while landed", false, "Allow players to join while the ship is landed. (Will probably break some things)");
			AllowJoiningWhileLanded = configLateJoinOrbitOnly.Value;
			Harmony val = new Harmony("twig.latecompany");
			val.PatchAll(typeof(Plugin).Assembly);
			((BaseUnityPlugin)this).Logger.Log((LogLevel)16, (object)"Late Company loaded!");
		}

		public static void SetLobbyJoinable(bool joinable)
		{
			LobbyJoinable = joinable;
			GameNetworkManager.Instance.SetLobbyJoinable(joinable);
			QuickMenuManager val = Object.FindObjectOfType<QuickMenuManager>();
			if (Object.op_Implicit((Object)(object)val))
			{
				val.inviteFriendsTextAlpha.alpha = (joinable ? 1f : 0.2f);
			}
		}
	}
}
namespace LateCompany.Patches
{
	[HarmonyPatch(typeof(GameNetworkManager), "LeaveLobbyAtGameStart")]
	[HarmonyWrapSafe]
	internal static class LeaveLobbyAtGameStart_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "ConnectionApproval")]
	[HarmonyWrapSafe]
	internal static class ConnectionApproval_Patch
	{
		[HarmonyPostfix]
		private static void Postfix(ConnectionApprovalRequest request, ConnectionApprovalResponse response)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			if (request.ClientNetworkId != NetworkManager.Singleton.LocalClientId && response.Reason.Contains("Game has already started") && Plugin.LobbyJoinable)
			{
				response.Reason = "";
				response.CreatePlayerObject = false;
				response.Approved = true;
				response.Pending = false;
			}
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "DisableInviteFriendsButton")]
	internal static class DisableInviteFriendsButton_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "InviteFriendsButton")]
	internal static class InviteFriendsButton_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			if (Plugin.LobbyJoinable)
			{
				GameNetworkManager.Instance.InviteFriendsUI();
			}
			return false;
		}
	}
	internal class RpcEnum : NetworkBehaviour
	{
		public static int None => 0;

		public static int Client => 2;

		public static int Server => 1;
	}
	internal static class WeatherSync
	{
		public static bool DoOverride = false;

		public static LevelWeatherType CurrentWeather = (LevelWeatherType)(-1);
	}
	[HarmonyPatch(typeof(RoundManager), "__rpc_handler_1193916134")]
	[HarmonyWrapSafe]
	internal static class __rpc_handler_1193916134_Patch
	{
		public static FieldInfo RPCExecStage = typeof(NetworkBehaviour).GetField("__rpc_exec_stage", BindingFlags.Instance | BindingFlags.NonPublic);

		[HarmonyPrefix]
		private static bool Prefix(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002e: 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_0057: 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)
			NetworkManager networkManager = target.NetworkManager;
			if ((Object)(object)networkManager != (Object)null && networkManager.IsListening && !networkManager.IsHost)
			{
				try
				{
					int num = default(int);
					ByteUnpacker.ReadValueBitPacked(reader, ref num);
					int num2 = default(int);
					ByteUnpacker.ReadValueBitPacked(reader, ref num2);
					if (((FastBufferReader)(ref reader)).Position < ((FastBufferReader)(ref reader)).Length)
					{
						int num3 = default(int);
						ByteUnpacker.ReadValueBitPacked(reader, ref num3);
						num3 -= 255;
						if (num3 < 0)
						{
							throw new Exception("In case of emergency, break glass.");
						}
						WeatherSync.CurrentWeather = (LevelWeatherType)num3;
						WeatherSync.DoOverride = true;
					}
					RPCExecStage.SetValue(target, RpcEnum.Client);
					((RoundManager)((target is RoundManager) ? target : null)).GenerateNewLevelClientRpc(num, num2);
					RPCExecStage.SetValue(target, RpcEnum.None);
					return false;
				}
				catch
				{
					WeatherSync.DoOverride = false;
					((FastBufferReader)(ref reader)).Seek(0);
					return true;
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(RoundManager), "SetToCurrentLevelWeather")]
	internal static class SetToCurrentLevelWeather_Patch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			//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)
			if (WeatherSync.DoOverride)
			{
				RoundManager.Instance.currentLevel.currentWeather = WeatherSync.CurrentWeather;
				WeatherSync.DoOverride = false;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnPlayerConnectedClientRpc")]
	[HarmonyWrapSafe]
	internal static class OnPlayerConnectedClientRpc_Patch
	{
		public static MethodInfo BeginSendClientRpc = typeof(RoundManager).GetMethod("__beginSendClientRpc", BindingFlags.Instance | BindingFlags.NonPublic);

		public static MethodInfo EndSendClientRpc = typeof(RoundManager).GetMethod("__endSendClientRpc", BindingFlags.Instance | BindingFlags.NonPublic);

		[HarmonyPostfix]
		private static void Postfix(ulong clientId, int connectedPlayers, ulong[] connectedPlayerIdsOrdered, int assignedPlayerObjectId, int serverMoneyAmount, int levelID, int profitQuota, int timeUntilDeadline, int quotaFulfilled, int randomSeed)
		{
			//IL_0066: 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_008a: 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_0091: 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)
			//IL_00b2: 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_00cf: 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_00f3: 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_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected I4, but got Unknown
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: 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_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_0194: 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)
			StartOfRound instance = StartOfRound.Instance;
			PlayerControllerB val = instance.allPlayerScripts[assignedPlayerObjectId];
			if (instance.connectedPlayersAmount + 1 >= instance.allPlayerScripts.Length)
			{
				Plugin.SetLobbyJoinable(joinable: false);
			}
			val.DisablePlayerModel(instance.allPlayerObjects[assignedPlayerObjectId], true, true);
			if (((NetworkBehaviour)instance).IsServer && !instance.inShipPhase)
			{
				RoundManager instance2 = RoundManager.Instance;
				ClientRpcParams val2 = default(ClientRpcParams);
				val2.Send = new ClientRpcSendParams
				{
					TargetClientIds = new List<ulong> { clientId }
				};
				ClientRpcParams val3 = val2;
				FastBufferWriter val4 = (FastBufferWriter)BeginSendClientRpc.Invoke(instance2, new object[3] { 1193916134u, val3, 0 });
				BytePacker.WriteValueBitPacked(val4, StartOfRound.Instance.randomMapSeed);
				BytePacker.WriteValueBitPacked(val4, StartOfRound.Instance.currentLevelID);
				BytePacker.WriteValueBitPacked(val4, instance2.currentLevel.currentWeather + 255);
				EndSendClientRpc.Invoke(instance2, new object[4] { val4, 1193916134u, val3, 0 });
				FastBufferWriter val5 = (FastBufferWriter)BeginSendClientRpc.Invoke(instance2, new object[3] { 2729232387u, val3, 0 });
				EndSendClientRpc.Invoke(instance2, new object[4] { val5, 2729232387u, val3, 0 });
			}
			instance.livingPlayers = instance.connectedPlayersAmount + 1;
			for (int i = 0; i < instance.allPlayerScripts.Length; i++)
			{
				PlayerControllerB val6 = instance.allPlayerScripts[i];
				if (val6.isPlayerControlled && val6.isPlayerDead)
				{
					instance.livingPlayers--;
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnPlayerDC")]
	[HarmonyWrapSafe]
	internal static class OnPlayerDC_Patch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			if (StartOfRound.Instance.inShipPhase || (Plugin.AllowJoiningWhileLanded && StartOfRound.Instance.shipHasLanded))
			{
				Plugin.SetLobbyJoinable(joinable: true);
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "SetShipReadyToLand")]
	internal static class SetShipReadyToLand_Patch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			if (StartOfRound.Instance.connectedPlayersAmount + 1 < StartOfRound.Instance.allPlayerScripts.Length)
			{
				Plugin.SetLobbyJoinable(joinable: true);
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "StartGame")]
	internal static class StartGame_Patch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			Plugin.SetLobbyJoinable(joinable: false);
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnShipLandedMiscEvents")]
	internal static class OnShipLandedMiscEvents_Patch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			if (Plugin.AllowJoiningWhileLanded && StartOfRound.Instance.connectedPlayersAmount + 1 < StartOfRound.Instance.allPlayerScripts.Length)
			{
				Plugin.SetLobbyJoinable(joinable: true);
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "ShipLeave")]
	internal static class ShipLeave_Patch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			Plugin.SetLobbyJoinable(joinable: false);
		}
	}
}

BepInEx/plugins/BunyaPineTree-ModelReplacementAPI/ModelReplacementAPI.dll

Decompiled 10 months 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 BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LCThirdPerson;
using Microsoft.CodeAnalysis;
using ModelReplacement;
using ModelReplacement.AvatarBodyUpdater;
using ModelReplacement.Modules;
using MoreCompany.Cosmetics;
using Steamworks.Data;
using TooManyEmotes;
using TooManyEmotes.Patches;
using UnityEngine;
using UnityEngine.LowLevel;
using UnityEngine.PlayerLoop;
using UnityEngine.Pool;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.Serialization;
using _3rdPerson.Helper;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ModelReplacementAPI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("https://github.com/BunyaPineTree/LethalCompany_ModelReplacementAPI")]
[assembly: AssemblyProduct("meow.ModelReplacementAPI")]
[assembly: AssemblyCopyright("Copyright © meow 2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("6390E70C-AB5E-42ED-BA29-F173942DC3A9")]
[assembly: AssemblyFileVersion("2.2.0")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.2.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;
		}
	}
}
[HarmonyPatch(typeof(GrabbableObject))]
public class LocateHeldObjectsOnModelReplacementPatch
{
	[HarmonyPatch("LateUpdate")]
	[HarmonyPostfix]
	public static void LateUpdatePatch(ref GrabbableObject __instance)
	{
		//IL_007f: 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_00b9: 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_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: 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_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)__instance.parentObject == (Object)null) && !((Object)(object)__instance.playerHeldBy == (Object)null))
		{
			BodyReplacementBase component = ((Component)__instance.playerHeldBy).gameObject.GetComponent<BodyReplacementBase>();
			if (!((Object)(object)component == (Object)null) && component.viewState.GetViewState() == ViewState.ThirdPerson)
			{
				Transform itemHolder = component.avatar.itemHolder;
				itemHolder.localPosition = component.avatar.itemHolderPositionOffset;
				Transform playerItemHolder = component.avatar.GetPlayerItemHolder();
				((Component)__instance).transform.rotation = playerItemHolder.rotation;
				((Component)__instance).transform.Rotate(__instance.itemProperties.rotationOffset);
				((Component)__instance).transform.position = itemHolder.position;
				Vector3 positionOffset = __instance.itemProperties.positionOffset;
				positionOffset = playerItemHolder.rotation * positionOffset;
				Transform transform = ((Component)__instance).transform;
				transform.position += positionOffset;
			}
		}
	}
}
[HarmonyPatch(typeof(StartOfRound))]
public class RepairBrokenBodyReplacementsPatch
{
	[HarmonyPatch("ReviveDeadPlayers")]
	[HarmonyPostfix]
	public static void ReviveDeadPlayersPatch(ref StartOfRound __instance)
	{
		PlayerControllerB[] allPlayerScripts = __instance.allPlayerScripts;
		foreach (PlayerControllerB val in allPlayerScripts)
		{
			if (val.isPlayerDead && !((Object)(object)((Component)val).gameObject.GetComponent<BodyReplacementBase>() == (Object)null))
			{
				Console.WriteLine("Reinstantiating model replacement for " + val.playerUsername + " ");
				Type type = ((object)((Component)val).gameObject.GetComponent<BodyReplacementBase>()).GetType();
				Object.Destroy((Object)(object)((Component)val).gameObject.GetComponent<BodyReplacementBase>());
				((Component)val).gameObject.AddComponent(type);
			}
		}
	}
}
namespace JigglePhysics
{
	public static class CachedSphereCollider
	{
		private class DestroyListener : MonoBehaviour
		{
			private void OnDestroy()
			{
				_hasSphere = false;
			}
		}

		private static bool _hasSphere;

		private static SphereCollider _sphereCollider;

		public static void StartPass()
		{
			if (TryGet(out var collider))
			{
				((Collider)collider).enabled = true;
			}
		}

		public static void FinishedPass()
		{
			if (TryGet(out var collider))
			{
				((Collider)collider).enabled = false;
			}
		}

		public static bool TryGet(out SphereCollider collider)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			if (_hasSphere)
			{
				collider = _sphereCollider;
				return true;
			}
			try
			{
				GameObject val = new GameObject("JiggleBoneSphereCollider", new Type[2]
				{
					typeof(SphereCollider),
					typeof(DestroyListener)
				})
				{
					hideFlags = (HideFlags)61
				};
				if (Application.isPlaying)
				{
					Object.DontDestroyOnLoad((Object)(object)val);
				}
				_sphereCollider = val.GetComponent<SphereCollider>();
				collider = _sphereCollider;
				((Collider)collider).enabled = false;
				_hasSphere = true;
				return true;
			}
			catch
			{
				if ((Object)(object)_sphereCollider != (Object)null)
				{
					if (Application.isPlaying)
					{
						Object.Destroy((Object)(object)((Component)_sphereCollider).gameObject);
					}
					else
					{
						Object.DestroyImmediate((Object)(object)((Component)_sphereCollider).gameObject);
					}
				}
				_hasSphere = false;
				collider = null;
				throw;
			}
		}
	}
	public class JiggleBone
	{
		private readonly bool hasTransform;

		private readonly PositionSignal targetAnimatedBoneSignal;

		private Vector3 currentFixedAnimatedBonePosition;

		public readonly JiggleBone parent;

		private JiggleBone child;

		private Quaternion boneRotationChangeCheck;

		private Vector3 bonePositionChangeCheck;

		private Quaternion lastValidPoseBoneRotation;

		private float projectionAmount;

		private Vector3 lastValidPoseBoneLocalPosition;

		private float normalizedIndex;

		public readonly Transform transform;

		private readonly PositionSignal particleSignal;

		private Vector3 workingPosition;

		private Vector3? preTeleportPosition;

		private Vector3 extrapolatedPosition;

		private float GetLengthToParent()
		{
			//IL_0018: 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)
			if (parent == null)
			{
				return 0.1f;
			}
			return Vector3.Distance(currentFixedAnimatedBonePosition, parent.currentFixedAnimatedBonePosition);
		}

		public JiggleBone(Transform transform, JiggleBone parent, float projectionAmount = 1f)
		{
			//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_002b: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			this.transform = transform;
			this.parent = parent;
			this.projectionAmount = projectionAmount;
			Vector3 startPosition;
			if ((Object)(object)transform != (Object)null)
			{
				lastValidPoseBoneRotation = transform.localRotation;
				lastValidPoseBoneLocalPosition = transform.localPosition;
				startPosition = transform.position;
			}
			else
			{
				startPosition = GetProjectedPosition();
			}
			targetAnimatedBoneSignal = new PositionSignal(startPosition, Time.timeAsDouble);
			particleSignal = new PositionSignal(startPosition, Time.timeAsDouble);
			hasTransform = (Object)(object)transform != (Object)null;
			if (parent != null)
			{
				this.parent.child = this;
			}
		}

		public void CalculateNormalizedIndex()
		{
			int num = 0;
			JiggleBone jiggleBone = this;
			while (jiggleBone.parent != null)
			{
				jiggleBone = jiggleBone.parent;
				num++;
			}
			int num2 = 0;
			jiggleBone = this;
			while (jiggleBone.child != null)
			{
				jiggleBone = jiggleBone.child;
				num2++;
			}
			int num3 = num + num2;
			float num4 = (float)num / (float)num3;
			normalizedIndex = num4;
		}

		public void VerletPass(JiggleSettingsData jiggleSettings, Vector3 wind, double time)
		{
			//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_004b: 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_005b: 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_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: 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_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_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_00c6: 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_00d8: 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_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_0034: Unknown result type (might be due to invalid IL or missing references)
			currentFixedAnimatedBonePosition = targetAnimatedBoneSignal.SamplePosition(time);
			if (parent == null)
			{
				workingPosition = currentFixedAnimatedBonePosition;
				particleSignal.SetPosition(workingPosition, time);
			}
			else
			{
				Vector3 localSpaceVelocity = particleSignal.GetCurrent() - particleSignal.GetPrevious() - (parent.particleSignal.GetCurrent() - parent.particleSignal.GetPrevious());
				workingPosition = NextPhysicsPosition(particleSignal.GetCurrent(), particleSignal.GetPrevious(), localSpaceVelocity, Time.fixedDeltaTime, jiggleSettings.gravityMultiplier, jiggleSettings.friction, jiggleSettings.airDrag);
				workingPosition += wind * (Time.fixedDeltaTime * jiggleSettings.airDrag);
			}
		}

		public void CollisionPreparePass(JiggleSettingsData jiggleSettings)
		{
			//IL_0004: 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)
			workingPosition = ConstrainLengthBackwards(workingPosition, jiggleSettings.lengthElasticity * jiggleSettings.lengthElasticity * 0.5f);
		}

		public void ConstraintPass(JiggleSettingsData jiggleSettings)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			if (parent != null)
			{
				workingPosition = ConstrainAngle(workingPosition, jiggleSettings.angleElasticity * jiggleSettings.angleElasticity, jiggleSettings.elasticitySoften);
				workingPosition = ConstrainLength(workingPosition, jiggleSettings.lengthElasticity * jiggleSettings.lengthElasticity);
			}
		}

		public void CollisionPass(JiggleSettingsBase jiggleSettings, List<Collider> colliders)
		{
			//IL_006d: 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_0080: 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_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_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)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			if (colliders.Count == 0 || !CachedSphereCollider.TryGet(out var collider))
			{
				return;
			}
			Vector3 val = default(Vector3);
			float num = default(float);
			foreach (Collider collider2 in colliders)
			{
				collider.radius = jiggleSettings.GetRadius(normalizedIndex);
				if (!(collider.radius <= 0f) && Physics.ComputePenetration((Collider)(object)collider, workingPosition, Quaternion.identity, collider2, ((Component)collider2).transform.position, ((Component)collider2).transform.rotation, ref val, ref num))
				{
					workingPosition += val * num;
				}
			}
		}

		public void SignalWritePosition(double time)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			particleSignal.SetPosition(workingPosition, time);
		}

		private Vector3 GetProjectedPosition()
		{
			//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_0028: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = parent.transform.position;
			return parent.transform.TransformPoint(parent.GetParentTransform().InverseTransformPoint(position) * projectionAmount);
		}

		private Vector3 GetTransformPosition()
		{
			//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_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_0027: Unknown result type (might be due to invalid IL or missing references)
			if (!hasTransform)
			{
				return GetProjectedPosition();
			}
			return transform.position;
		}

		private Transform GetParentTransform()
		{
			if (parent != null)
			{
				return parent.transform;
			}
			return transform.parent;
		}

		private void CacheAnimationPosition()
		{
			//IL_0034: 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_0050: 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_0061: 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)
			if (!hasTransform)
			{
				targetAnimatedBoneSignal.SetPosition(GetProjectedPosition(), Time.timeAsDouble);
				return;
			}
			targetAnimatedBoneSignal.SetPosition(transform.position, Time.timeAsDouble);
			lastValidPoseBoneRotation = transform.localRotation;
			lastValidPoseBoneLocalPosition = transform.localPosition;
		}

		private Vector3 ConstrainLengthBackwards(Vector3 newPosition, float elasticity)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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_002c: 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_0034: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_000f: 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_0058: Unknown result type (might be due to invalid IL or missing references)
			if (child == null)
			{
				return newPosition;
			}
			Vector3 val = newPosition - child.workingPosition;
			Vector3 normalized = ((Vector3)(ref val)).normalized;
			return Vector3.Lerp(newPosition, child.workingPosition + normalized * child.GetLengthToParent(), elasticity);
		}

		private Vector3 ConstrainLength(Vector3 newPosition, float elasticity)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: 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_001a: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = newPosition - parent.workingPosition;
			Vector3 normalized = ((Vector3)(ref val)).normalized;
			return Vector3.Lerp(newPosition, parent.workingPosition + normalized * GetLengthToParent(), elasticity);
		}

		public void MatchAnimationInstantly()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: 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)
			double timeAsDouble = Time.timeAsDouble;
			Vector3 transformPosition = GetTransformPosition();
			targetAnimatedBoneSignal.FlattenSignal(timeAsDouble, transformPosition);
			particleSignal.FlattenSignal(timeAsDouble, transformPosition);
		}

		public void PrepareTeleport()
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			preTeleportPosition = GetTransformPosition();
		}

		public void FinishTeleport()
		{
			//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_0024: 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_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_0041: 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_0057: 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_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)
			if (!preTeleportPosition.HasValue)
			{
				MatchAnimationInstantly();
				return;
			}
			Vector3 transformPosition = GetTransformPosition();
			Vector3 val = transformPosition - preTeleportPosition.Value;
			targetAnimatedBoneSignal.FlattenSignal(Time.timeAsDouble, transformPosition);
			particleSignal.OffsetSignal(val);
			workingPosition += val;
		}

		private Vector3 ConstrainAngleBackward(Vector3 newPosition, float elasticity, float elasticitySoften)
		{
			//IL_0034: 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_0049: 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_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_006a: 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_006c: 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_0072: 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_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_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)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: 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_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: 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_00b8: 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_00ef: 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_00fd: 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_0021: 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_010f: Unknown result type (might be due to invalid IL or missing references)
			if (child == null || child.child == null)
			{
				return newPosition;
			}
			Vector3 val = child.child.currentFixedAnimatedBonePosition - child.currentFixedAnimatedBonePosition;
			Vector3 val2 = child.child.workingPosition - child.workingPosition;
			Quaternion val3 = Quaternion.FromToRotation(val, val2);
			Vector3 val4 = newPosition - child.workingPosition;
			Vector3 val5 = val3 * val4;
			Debug.DrawLine(newPosition, child.workingPosition + val5, Color.cyan);
			float num = Vector3.Distance(newPosition, child.workingPosition + val5);
			num /= child.GetLengthToParent();
			num = Mathf.Clamp01(num);
			num = Mathf.Pow(num, elasticitySoften * 2f);
			return Vector3.Lerp(newPosition, child.workingPosition + val5, elasticity * num);
		}

		private Vector3 ConstrainAngle(Vector3 newPosition, float elasticity, float elasticitySoften)
		{
			//IL_0020: 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_0075: 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_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0054: 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_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_0064: 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_011d: 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)
			//IL_0098: 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_009e: 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)
			//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_00b1: 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_00b3: 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)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//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_00c8: 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_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_00d3: 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_00d5: 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_0107: 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_0109: 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_0114: 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)
			if (!hasTransform && projectionAmount == 0f)
			{
				return newPosition;
			}
			Vector3 val;
			Vector3 val2;
			if (parent.parent == null)
			{
				val = parent.currentFixedAnimatedBonePosition + (parent.currentFixedAnimatedBonePosition - currentFixedAnimatedBonePosition);
				val2 = val;
			}
			else
			{
				val2 = parent.parent.workingPosition;
				val = parent.parent.currentFixedAnimatedBonePosition;
			}
			Vector3 val3 = parent.currentFixedAnimatedBonePosition - val;
			Vector3 val4 = parent.workingPosition - val2;
			Quaternion val5 = Quaternion.FromToRotation(val3, val4);
			Vector3 val6 = currentFixedAnimatedBonePosition - val;
			Vector3 val7 = val5 * val6;
			float num = Vector3.Distance(newPosition, val2 + val7);
			num /= GetLengthToParent();
			num = Mathf.Clamp01(num);
			num = Mathf.Pow(num, elasticitySoften * 2f);
			return Vector3.Lerp(newPosition, val2 + val7, elasticity * num);
		}

		public static Vector3 NextPhysicsPosition(Vector3 newPosition, Vector3 previousPosition, Vector3 localSpaceVelocity, float deltaTime, float gravityMultiplier, float friction, float airFriction)
		{
			//IL_0005: 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_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_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_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_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//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_004d: 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)
			float num = deltaTime * deltaTime;
			Vector3 val = newPosition - previousPosition - localSpaceVelocity;
			return newPosition + val * (1f - airFriction) + localSpaceVelocity * (1f - friction) + Physics.gravity * (gravityMultiplier * num);
		}

		public void DebugDraw(Color simulateColor, Color targetColor, bool interpolated)
		{
			//IL_0039: 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_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0068: Unknown result type (might be due to invalid IL or missing references)
			if (parent != null)
			{
				if (interpolated)
				{
					Debug.DrawLine(extrapolatedPosition, parent.extrapolatedPosition, simulateColor, 0f, false);
				}
				else
				{
					Debug.DrawLine(workingPosition, parent.workingPosition, simulateColor, 0f, false);
				}
				Debug.DrawLine(currentFixedAnimatedBonePosition, parent.currentFixedAnimatedBonePosition, targetColor, 0f, false);
			}
		}

		public Vector3 DeriveFinalSolvePosition(Vector3 offset)
		{
			//IL_0002: 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_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_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_0026: Unknown result type (might be due to invalid IL or missing references)
			extrapolatedPosition = offset + particleSignal.SamplePosition(Time.timeAsDouble);
			return extrapolatedPosition;
		}

		public Vector3 GetCachedSolvePosition()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return extrapolatedPosition;
		}

		public void PrepareBone()
		{
			//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_003b: 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_002e: 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)
			if (hasTransform)
			{
				if (boneRotationChangeCheck == transform.localRotation)
				{
					transform.localRotation = lastValidPoseBoneRotation;
				}
				if (bonePositionChangeCheck == transform.localPosition)
				{
					transform.localPosition = lastValidPoseBoneLocalPosition;
				}
			}
			CacheAnimationPosition();
		}

		public void OnDrawGizmos(JiggleSettingsBase jiggleSettings)
		{
			//IL_0036: 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_0087: 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_00c1: 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)
			if ((Object)(object)transform != (Object)null && child != null && (Object)(object)child.transform != (Object)null)
			{
				Gizmos.DrawLine(transform.position, child.transform.position);
			}
			if ((Object)(object)transform != (Object)null && child != null && (Object)(object)child.transform == (Object)null)
			{
				Gizmos.DrawLine(transform.position, child.GetProjectedPosition());
			}
			if ((Object)(object)transform != (Object)null && (Object)(object)jiggleSettings != (Object)null)
			{
				Gizmos.DrawWireSphere(transform.position, jiggleSettings.GetRadius(normalizedIndex));
			}
			if ((Object)(object)transform == (Object)null && (Object)(object)jiggleSettings != (Object)null)
			{
				Gizmos.DrawWireSphere(GetProjectedPosition(), jiggleSettings.GetRadius(normalizedIndex));
			}
		}

		public void PoseBone(float blend)
		{
			//IL_001d: 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_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_003f: 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_0055: 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_00df: 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_00f0: 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_0080: 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_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_0095: 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_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00ad: 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_00ba: 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)
			if (child != null)
			{
				Vector3 val = Vector3.Lerp(targetAnimatedBoneSignal.SamplePosition(Time.timeAsDouble), extrapolatedPosition, blend);
				Vector3 val2 = Vector3.Lerp(child.targetAnimatedBoneSignal.SamplePosition(Time.timeAsDouble), child.extrapolatedPosition, blend);
				if (parent != null)
				{
					transform.position = val;
				}
				Vector3 transformPosition = child.GetTransformPosition();
				Vector3 val3 = transformPosition - transform.position;
				Vector3 val4 = val2 - val;
				Quaternion val5 = Quaternion.FromToRotation(val3, val4);
				transform.rotation = val5 * transform.rotation;
			}
			if (hasTransform)
			{
				boneRotationChangeCheck = transform.localRotation;
				bonePositionChangeCheck = transform.localPosition;
			}
		}
	}
	[DefaultExecutionOrder(200)]
	public class JiggleRigBuilder : MonoBehaviour
	{
		[SerializeField]
		[Tooltip("The root bone from which an individual JiggleRig will be constructed. The JiggleRig encompasses all children of the specified root.")]
		[FormerlySerializedAs("target")]
		private Transform rootTransform;

		[Tooltip("The settings that the rig should update with, create them using the Create->JigglePhysics->Settings menu option.")]
		public JiggleSettingsBase jiggleSettings;

		[SerializeField]
		[Tooltip("The list of transforms to ignore during the jiggle. Each bone listed will also ignore all the children of the specified bone.")]
		private List<Transform> ignoredTransforms;

		public List<Collider> colliders;

		[Tooltip("An air force that is applied to the entire rig, this is useful to plug in some wind volumes from external sources.")]
		public Vector3 wind;

		[Tooltip("Level of detail manager. This system will control how the jiggle rig saves performance cost.")]
		public JiggleRigLOD levelOfDetail;

		[Tooltip("Draws some simple lines to show what the simulation is doing. Generally this should be disabled.")]
		[SerializeField]
		private bool debugDraw;

		private JiggleSettingsData data;

		private bool initialized;

		[HideInInspector]
		protected List<JiggleBone> simulatedPoints;

		private double accumulation;

		private bool dirtyFromEnable = false;

		private bool wasLODActive = true;

		public static float maxCatchupTime => Time.fixedDeltaTime * 4f;

		private bool NeedsCollisions => colliders.Count != 0;

		public Transform GetRootTransform()
		{
			return rootTransform;
		}

		public void PrepareBone(Vector3 position, JiggleRigLOD jiggleRigLOD)
		{
			//IL_0014: 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)
			if (!initialized)
			{
				throw new UnityException("JiggleRig was never initialized. Please call JiggleRig.Initialize() if you're going to manually timestep.");
			}
			foreach (JiggleBone simulatedPoint in simulatedPoints)
			{
				simulatedPoint.PrepareBone();
			}
			data = jiggleSettings.GetData();
			data = (((Object)(object)jiggleRigLOD != (Object)null) ? jiggleRigLOD.AdjustJiggleSettingsData(position, data) : data);
		}

		public void MatchAnimationInstantly()
		{
			foreach (JiggleBone simulatedPoint in simulatedPoints)
			{
				simulatedPoint.MatchAnimationInstantly();
			}
		}

		public void UpdateJiggle(Vector3 wind, double time)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			foreach (JiggleBone simulatedPoint in simulatedPoints)
			{
				simulatedPoint.VerletPass(data, wind, time);
			}
			if (NeedsCollisions)
			{
				for (int num = simulatedPoints.Count - 1; num >= 0; num--)
				{
					simulatedPoints[num].CollisionPreparePass(data);
				}
			}
			foreach (JiggleBone simulatedPoint2 in simulatedPoints)
			{
				simulatedPoint2.ConstraintPass(data);
			}
			if (NeedsCollisions)
			{
				foreach (JiggleBone simulatedPoint3 in simulatedPoints)
				{
					simulatedPoint3.CollisionPass(jiggleSettings, colliders);
				}
			}
			foreach (JiggleBone simulatedPoint4 in simulatedPoints)
			{
				simulatedPoint4.SignalWritePosition(time);
			}
		}

		public void DeriveFinalSolve()
		{
			//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_0017: 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_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			Vector3 val = simulatedPoints[0].DeriveFinalSolvePosition(Vector3.zero);
			Vector3 offset = simulatedPoints[0].transform.position - val;
			foreach (JiggleBone simulatedPoint in simulatedPoints)
			{
				simulatedPoint.DeriveFinalSolvePosition(offset);
			}
		}

		public void Pose(bool debugDraw)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			DeriveFinalSolve();
			foreach (JiggleBone simulatedPoint in simulatedPoints)
			{
				simulatedPoint.PoseBone(data.blend);
				if (debugDraw)
				{
					simulatedPoint.DebugDraw(Color.red, Color.blue, interpolated: true);
				}
			}
		}

		public void PrepareTeleport()
		{
			foreach (JiggleBone simulatedPoint in simulatedPoints)
			{
				simulatedPoint.PrepareTeleport();
			}
		}

		public void FinishTeleport()
		{
			foreach (JiggleBone simulatedPoint in simulatedPoints)
			{
				simulatedPoint.FinishTeleport();
			}
		}

		protected virtual void CreateSimulatedPoints(ICollection<JiggleBone> outputPoints, ICollection<Transform> ignoredTransforms, Transform currentTransform, JiggleBone parentJiggleBone)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			JiggleBone jiggleBone = new JiggleBone(currentTransform, parentJiggleBone);
			outputPoints.Add(jiggleBone);
			if (currentTransform.childCount == 0)
			{
				if (jiggleBone.parent == null)
				{
					if ((Object)(object)jiggleBone.transform.parent == (Object)null)
					{
						throw new UnityException("Can't have a singular jiggle bone with no parents. That doesn't even make sense!");
					}
					outputPoints.Add(new JiggleBone(null, jiggleBone));
				}
				else
				{
					outputPoints.Add(new JiggleBone(null, jiggleBone));
				}
				return;
			}
			for (int i = 0; i < currentTransform.childCount; i++)
			{
				if (!ignoredTransforms.Contains(currentTransform.GetChild(i)))
				{
					CreateSimulatedPoints(outputPoints, ignoredTransforms, currentTransform.GetChild(i), jiggleBone);
				}
			}
		}

		private void Awake()
		{
			Initialize();
		}

		private void OnEnable()
		{
			JiggleRigHandler.AddBuilder(this);
			dirtyFromEnable = true;
		}

		private void OnDisable()
		{
			JiggleRigHandler.RemoveBuilder(this);
			PrepareTeleport();
		}

		public void Initialize()
		{
			accumulation = 0.0;
			simulatedPoints = new List<JiggleBone>();
			if ((Object)(object)rootTransform == (Object)null)
			{
				return;
			}
			CreateSimulatedPoints(simulatedPoints, ignoredTransforms, rootTransform, null);
			foreach (JiggleBone simulatedPoint in simulatedPoints)
			{
				simulatedPoint.CalculateNormalizedIndex();
			}
			initialized = true;
		}

		public virtual void Advance(float deltaTime)
		{
			//IL_001b: 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_00d3: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)levelOfDetail != (Object)null && !levelOfDetail.CheckActive(((Component)this).transform.position))
			{
				if (wasLODActive)
				{
					PrepareTeleport();
				}
				wasLODActive = false;
				return;
			}
			if (!wasLODActive)
			{
				FinishTeleport();
			}
			PrepareBone(((Component)this).transform.position, levelOfDetail);
			if (dirtyFromEnable)
			{
				FinishTeleport();
				dirtyFromEnable = false;
			}
			accumulation = Math.Min(accumulation + (double)deltaTime, maxCatchupTime);
			while (accumulation > (double)Time.fixedDeltaTime)
			{
				accumulation -= Time.fixedDeltaTime;
				double time = Time.timeAsDouble - accumulation;
				UpdateJiggle(wind, time);
			}
			Pose(debugDraw);
			wasLODActive = true;
		}

		private void OnDrawGizmos()
		{
			if (!initialized || simulatedPoints == null)
			{
				Initialize();
			}
			foreach (JiggleBone simulatedPoint in simulatedPoints)
			{
				simulatedPoint.OnDrawGizmos(jiggleSettings);
			}
		}

		private void OnValidate()
		{
			if ((Object)(object)rootTransform == (Object)null)
			{
				rootTransform = ((Component)this).transform;
			}
			if (!Application.isPlaying)
			{
				Initialize();
			}
		}
	}
	public static class JiggleRigHandler
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static UpdateFunction <0>__UpdateJiggleRigs;
		}

		private static bool initialized = false;

		private static HashSet<JiggleRigBuilder> builders = new HashSet<JiggleRigBuilder>();

		private static void Initialize()
		{
			//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_0016: 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_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_0056: 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_0039: Expected O, but got Unknown
			if (!initialized)
			{
				PlayerLoopSystem currentPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
				PlayerLoopSystem self = currentPlayerLoop;
				PlayerLoopSystem systemToInject = default(PlayerLoopSystem);
				object obj = <>O.<0>__UpdateJiggleRigs;
				if (obj == null)
				{
					UpdateFunction val = UpdateJiggleRigs;
					<>O.<0>__UpdateJiggleRigs = val;
					obj = (object)val;
				}
				systemToInject.updateDelegate = (UpdateFunction)obj;
				systemToInject.type = typeof(JiggleRigHandler);
				currentPlayerLoop = self.InjectAt<PostLateUpdate>(systemToInject);
				PlayerLoop.SetPlayerLoop(currentPlayerLoop);
				initialized = true;
			}
		}

		private static void UpdateJiggleRigs()
		{
			CachedSphereCollider.StartPass();
			foreach (JiggleRigBuilder builder in builders)
			{
				builder.Advance(Time.deltaTime);
			}
			CachedSphereCollider.FinishedPass();
		}

		public static void AddBuilder(JiggleRigBuilder builder)
		{
			builders.Add(builder);
			Initialize();
		}

		public static void RemoveBuilder(JiggleRigBuilder builder)
		{
			builders.Remove(builder);
		}

		private static PlayerLoopSystem InjectAt<T>(this PlayerLoopSystem self, PlayerLoopSystem systemToInject)
		{
			//IL_0001: 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_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_0059: 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_007f: 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_0091: 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_0110: 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_00f4: 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_010c: 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_00d6: Expected O, but got Unknown
			int num = FindIndexOfSubsystem<T>(self.subSystemList);
			if (num == -1)
			{
				throw new UnityException($"Failed to find PlayerLoopSystem with type{typeof(T)}");
			}
			List<PlayerLoopSystem> list = new List<PlayerLoopSystem>(self.subSystemList[num].subSystemList);
			foreach (PlayerLoopSystem item2 in list)
			{
				if (item2.type != typeof(JiggleRigBuilder))
				{
					continue;
				}
				Debug.LogWarning((object)$"Tried to inject a PlayerLoopSystem ({systemToInject.type}) more than once! Ignoring the second injection.");
				return self;
			}
			PlayerLoopSystem item = default(PlayerLoopSystem);
			object obj = <>O.<0>__UpdateJiggleRigs;
			if (obj == null)
			{
				UpdateFunction val = UpdateJiggleRigs;
				<>O.<0>__UpdateJiggleRigs = val;
				obj = (object)val;
			}
			item.updateDelegate = (UpdateFunction)obj;
			item.type = typeof(JiggleRigHandler);
			list.Insert(0, item);
			self.subSystemList[num].subSystemList = list.ToArray();
			return self;
		}

		private static int FindIndexOfSubsystem<T>(PlayerLoopSystem[] list, int index = -1)
		{
			if (list == null)
			{
				return -1;
			}
			for (int i = 0; i < list.Length; i++)
			{
				if (list[i].type == typeof(T))
				{
					return i;
				}
			}
			return -1;
		}
	}
	public abstract class JiggleRigLOD : ScriptableObject
	{
		public abstract bool CheckActive(Vector3 position);

		public abstract JiggleSettingsData AdjustJiggleSettingsData(Vector3 position, JiggleSettingsData data);
	}
	[CreateAssetMenu(fileName = "JiggleRigSimpleLOD", menuName = "JigglePhysics/JiggleRigSimpleLOD", order = 1)]
	public class JiggleRigSimpleLOD : JiggleRigLOD
	{
		[Tooltip("Distance to disable the jiggle rig")]
		[SerializeField]
		private float distance;

		[Tooltip("Level of detail manager. This system will control how the jiggle rig saves performance cost.")]
		[SerializeField]
		private float blend;

		[NonSerialized]
		private Camera currentCamera;

		[NonSerialized]
		private Transform cameraTransform;

		private bool TryGetCamera(out Camera camera)
		{
			if ((Object)(object)currentCamera == (Object)null || !((Component)currentCamera).CompareTag("MainCamera"))
			{
				currentCamera = Camera.main;
			}
			camera = currentCamera;
			return (Object)(object)currentCamera != (Object)null;
		}

		public override bool CheckActive(Vector3 position)
		{
			//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)
			if (!TryGetCamera(out var camera))
			{
				return false;
			}
			return Vector3.Distance(((Component)camera).transform.position, position) < distance;
		}

		public override JiggleSettingsData AdjustJiggleSettingsData(Vector3 position, JiggleSettingsData data)
		{
			//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)
			if (!TryGetCamera(out var camera))
			{
				return data;
			}
			float num = (Vector3.Distance(((Component)camera).transform.position, position) - distance + blend) / blend;
			num = Mathf.Clamp01(1f - num);
			data.blend = num;
			return data;
		}
	}
	public struct JiggleSettingsData
	{
		public float gravityMultiplier;

		public float friction;

		public float angleElasticity;

		public float blend;

		public float airDrag;

		public float lengthElasticity;

		public float elasticitySoften;

		public float radiusMultiplier;

		public static JiggleSettingsData Lerp(JiggleSettingsData a, JiggleSettingsData b, float t)
		{
			JiggleSettingsData result = default(JiggleSettingsData);
			result.gravityMultiplier = Mathf.Lerp(a.gravityMultiplier, b.gravityMultiplier, t);
			result.friction = Mathf.Lerp(a.friction, b.friction, t);
			result.angleElasticity = Mathf.Lerp(a.angleElasticity, b.angleElasticity, t);
			result.blend = Mathf.Lerp(a.blend, b.blend, t);
			result.airDrag = Mathf.Lerp(a.airDrag, b.airDrag, t);
			result.lengthElasticity = Mathf.Lerp(a.lengthElasticity, b.lengthElasticity, t);
			result.elasticitySoften = Mathf.Lerp(a.elasticitySoften, b.elasticitySoften, t);
			result.radiusMultiplier = Mathf.Lerp(a.radiusMultiplier, b.radiusMultiplier, t);
			return result;
		}
	}
	[CreateAssetMenu(fileName = "JiggleSettings", menuName = "JigglePhysics/Settings", order = 1)]
	public class JiggleSettings : JiggleSettingsBase
	{
		[SerializeField]
		[Range(0f, 2f)]
		[Tooltip("How much gravity to apply to the simulation, it is a multiplier of the Physics.gravity setting.")]
		private float gravityMultiplier = 1f;

		[SerializeField]
		[Range(0f, 1f)]
		[Tooltip("How much mechanical friction to apply, this is specifically how quickly oscillations come to rest.")]
		private float friction = 0.4f;

		[SerializeField]
		[Range(0f, 1f)]
		[Tooltip("How much angular force is applied to bring it to the target shape.")]
		private float angleElasticity = 0.4f;

		[SerializeField]
		[Range(0f, 1f)]
		[Tooltip("How much of the simulation should be expressed. A value of 0 would make the jiggle have zero effect. A value of 1 gives the full movement as intended. 0.5 would ")]
		private float blend = 1f;

		[FormerlySerializedAs("airFriction")]
		[HideInInspector]
		[SerializeField]
		[Range(0f, 1f)]
		[Tooltip("How much jiggled objects should get dragged behind by moving through the air. Or how \"thick\" the air is.")]
		private float airDrag = 0.1f;

		[HideInInspector]
		[SerializeField]
		[Range(0f, 1f)]
		[Tooltip("How rigidly the rig holds its length. Low values cause lots of squash and stretch!")]
		private float lengthElasticity = 0.8f;

		[HideInInspector]
		[SerializeField]
		[Range(0f, 1f)]
		[Tooltip("How much to allow free bone motion before engaging elasticity.")]
		private float elasticitySoften = 0f;

		[HideInInspector]
		[SerializeField]
		[Tooltip("How much radius points have, only used for collisions. Set to 0 to disable collisions")]
		private float radiusMultiplier = 0f;

		[HideInInspector]
		[SerializeField]
		[Tooltip("How the radius is expressed as a curve along the bone chain from root to child.")]
		private AnimationCurve radiusCurve = new AnimationCurve((Keyframe[])(object)new Keyframe[2]
		{
			new Keyframe(0f, 1f),
			new Keyframe(1f, 0f)
		});

		public override JiggleSettingsData GetData()
		{
			JiggleSettingsData result = default(JiggleSettingsData);
			result.gravityMultiplier = gravityMultiplier;
			result.friction = friction;
			result.airDrag = airDrag;
			result.blend = blend;
			result.angleElasticity = angleElasticity;
			result.elasticitySoften = elasticitySoften;
			result.lengthElasticity = lengthElasticity;
			result.radiusMultiplier = radiusMultiplier;
			return result;
		}

		public void SetData(JiggleSettingsData data)
		{
			gravityMultiplier = data.gravityMultiplier;
			friction = data.friction;
			angleElasticity = data.angleElasticity;
			blend = data.blend;
			airDrag = data.airDrag;
			lengthElasticity = data.lengthElasticity;
			elasticitySoften = data.elasticitySoften;
			radiusMultiplier = data.radiusMultiplier;
		}

		public override float GetRadius(float normalizedIndex)
		{
			return radiusMultiplier * radiusCurve.Evaluate(normalizedIndex);
		}

		public void SetRadiusCurve(AnimationCurve curve)
		{
			radiusCurve = curve;
		}
	}
	public class JiggleSettingsBase : ScriptableObject
	{
		public virtual JiggleSettingsData GetData()
		{
			return default(JiggleSettingsData);
		}

		public virtual float GetRadius(float normalizedIndex)
		{
			return 0f;
		}
	}
	[CreateAssetMenu(fileName = "JiggleSettingsBlend", menuName = "JigglePhysics/Blend Settings", order = 1)]
	public class JiggleSettingsBlend : JiggleSettingsBase
	{
		[Tooltip("The list of jiggle settings to blend between.")]
		public List<JiggleSettings> blendSettings;

		[Range(0f, 1f)]
		[Tooltip("A value from 0 to 1 that linearly blends between all of the blendSettings.")]
		public float normalizedBlend;

		public override JiggleSettingsData GetData()
		{
			int num = blendSettings.Count - 1;
			float num2 = Mathf.Clamp01(normalizedBlend);
			int num3 = Mathf.Clamp(Mathf.FloorToInt(num2 * (float)num), 0, num);
			int index = Mathf.Clamp(Mathf.FloorToInt(num2 * (float)num) + 1, 0, num);
			return JiggleSettingsData.Lerp(blendSettings[num3].GetData(), blendSettings[index].GetData(), Mathf.Clamp01(num2 * (float)num - (float)num3));
		}

		public override float GetRadius(float normalizedIndex)
		{
			float num = Mathf.Clamp01(normalizedBlend);
			int num2 = Mathf.FloorToInt(num * (float)blendSettings.Count);
			int num3 = Mathf.FloorToInt(num * (float)blendSettings.Count) + 1;
			return Mathf.Lerp(blendSettings[Mathf.Clamp(num2, 0, blendSettings.Count - 1)].GetRadius(normalizedIndex), blendSettings[Mathf.Clamp(num3, 0, blendSettings.Count - 1)].GetRadius(normalizedIndex), Mathf.Clamp01(num * (float)blendSettings.Count - (float)num2));
		}
	}
	public class PositionSignal
	{
		private struct Frame
		{
			public Vector3 position;

			public double time;
		}

		private Frame previousFrame;

		private Frame currentFrame;

		public PositionSignal(Vector3 startPosition, double time)
		{
			//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)
			currentFrame = (previousFrame = new Frame
			{
				position = startPosition,
				time = time
			});
		}

		public void SetPosition(Vector3 position, double time)
		{
			//IL_0018: 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)
			previousFrame = currentFrame;
			currentFrame = new Frame
			{
				position = position,
				time = time
			};
		}

		public void OffsetSignal(Vector3 offset)
		{
			//IL_0012: 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_0018: 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_004b: 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_0051: 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)
			previousFrame = new Frame
			{
				position = previousFrame.position + offset,
				time = previousFrame.time
			};
			currentFrame = new Frame
			{
				position = currentFrame.position + offset,
				time = previousFrame.time
			};
		}

		public void FlattenSignal(double time, Vector3 position)
		{
			//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_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)
			previousFrame = new Frame
			{
				position = position,
				time = time - (double)(JiggleRigBuilder.maxCatchupTime * 2f)
			};
			currentFrame = new Frame
			{
				position = position,
				time = time - (double)JiggleRigBuilder.maxCatchupTime
			};
		}

		public Vector3 GetCurrent()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return currentFrame.position;
		}

		public Vector3 GetPrevious()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return previousFrame.position;
		}

		public Vector3 SamplePosition(double time)
		{
			//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_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_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_006b: Unknown result type (might be due to invalid IL or missing references)
			double num = currentFrame.time - previousFrame.time;
			if (num == 0.0)
			{
				return previousFrame.position;
			}
			double num2 = (time - previousFrame.time) / num;
			return Vector3.Lerp(previousFrame.position, currentFrame.position, (float)num2);
		}
	}
}
namespace ModelReplacement
{
	public static class PluginInfo
	{
		public const string GUID = "meow.ModelReplacementAPI";

		public const string NAME = "ModelReplacementAPI";

		public const string VERSION = "2.2.0";

		public const string WEBSITE = "https://github.com/BunyaPineTree/LethalCompany_ModelReplacementAPI";
	}
	[BepInPlugin("meow.ModelReplacementAPI", "ModelReplacementAPI", "2.2.0")]
	[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 ModelReplacementAPI : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(PlayerControllerB))]
		public class PlayerControllerBPatch
		{
			[HarmonyPatch("Update")]
			[HarmonyPostfix]
			public static void ManageRegistryBodyReplacements(ref PlayerControllerB __instance)
			{
				try
				{
					BodyReplacementBase component = ((Component)__instance.thisPlayerBody).gameObject.GetComponent<BodyReplacementBase>();
					if ((Object)(object)component != (Object)null && RegisteredModelReplacementExceptions.Contains(((object)component).GetType()))
					{
						return;
					}
					if (RegisteredModelReplacementOverride != null)
					{
						SetPlayerModelReplacement(__instance, RegisteredModelReplacementOverride);
						return;
					}
					int currentSuitID = __instance.currentSuitID;
					string unlockableName = StartOfRound.Instance.unlockablesList.unlockables[currentSuitID].unlockableName;
					unlockableName = unlockableName.ToLower().Replace(" ", "");
					if (RegisteredModelReplacements.ContainsKey(unlockableName))
					{
						SetPlayerModelReplacement(__instance, RegisteredModelReplacements[unlockableName]);
					}
					else if (RegisteredModelReplacementDefault != null)
					{
						SetPlayerModelReplacement(__instance, RegisteredModelReplacementDefault);
					}
					else
					{
						RemovePlayerModelReplacement(__instance);
					}
				}
				catch (Exception ex)
				{
					Instance.Logger.LogWarning((object)ex);
				}
			}
		}

		public static bool moreCompanyPresent;

		public static bool thirdPersonPresent;

		public static bool LCthirdPersonPresent;

		public static bool mirrorDecorPresent;

		public static bool tooManyEmotesPresent;

		public static bool recordingCameraPresent;

		public static ModelReplacementAPI Instance;

		public ManualLogSource Logger;

		private static List<Type> RegisteredModelReplacementExceptions = new List<Type>();

		private static Dictionary<string, Type> RegisteredModelReplacements = new Dictionary<string, Type>();

		private static Type RegisteredModelReplacementOverride = null;

		private static Type RegisteredModelReplacementDefault = null;

		private static int steamLobbyID
		{
			get
			{
				//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_002c: Unknown result type (might be due to invalid IL or missing references)
				int result;
				if (!GameNetworkManager.Instance.currentLobby.HasValue)
				{
					result = -1;
				}
				else
				{
					Lobby value = GameNetworkManager.Instance.currentLobby.Value;
					result = (int)((Lobby)(ref value)).Id.Value;
				}
				return result;
			}
		}

		public static bool isLan => steamLobbyID == -1;

		private void Awake()
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			Logger = Logger.CreateLogSource("meow.ModelReplacementAPI");
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			moreCompanyPresent = Chainloader.PluginInfos.ContainsKey("me.swipez.melonloader.morecompany");
			thirdPersonPresent = Chainloader.PluginInfos.ContainsKey("verity.3rdperson");
			LCthirdPersonPresent = Chainloader.PluginInfos.ContainsKey("LCThirdPerson");
			mirrorDecorPresent = Chainloader.PluginInfos.ContainsKey("quackandcheese.mirrordecor");
			tooManyEmotesPresent = Chainloader.PluginInfos.ContainsKey("FlipMods.TooManyEmotes");
			recordingCameraPresent = Chainloader.PluginInfos.ContainsKey("com.graze.gorillatag.placeablecamera");
			Harmony val = new Harmony("meow.ModelReplacementAPI");
			val.PatchAll();
			Logger.LogInfo((object)"Plugin meow.ModelReplacementAPI is loaded!");
		}

		public static void RegisterModelReplacementDefault(Type type)
		{
			if (!type.IsSubclassOf(typeof(BodyReplacementBase)))
			{
				Instance.Logger.LogError((object)$"Cannot register body replacement default type {type}, must inherit from BodyReplacementBase");
				return;
			}
			if (RegisteredModelReplacementOverride != null)
			{
				Instance.Logger.LogError((object)$"Cannot register body replacement default, already registered to {RegisteredModelReplacementDefault}.");
				return;
			}
			Instance.Logger.LogInfo((object)$"Registering body replacement default type {type}.");
			RegisteredModelReplacementDefault = type;
		}

		public static void RegisterModelReplacementOverride(Type type)
		{
			if (!type.IsSubclassOf(typeof(BodyReplacementBase)))
			{
				Instance.Logger.LogError((object)$"Cannot register body replacement override type {type}, must inherit from BodyReplacementBase");
				return;
			}
			if (RegisteredModelReplacementOverride != null)
			{
				Instance.Logger.LogError((object)$"Cannot register body replacement override, already registered to {RegisteredModelReplacementOverride}.");
				return;
			}
			Instance.Logger.LogInfo((object)$"Registering body replacement override type {type}.");
			RegisteredModelReplacementOverride = type;
		}

		public static void RegisterModelReplacementException(Type type)
		{
			if (!type.IsSubclassOf(typeof(BodyReplacementBase)))
			{
				Instance.Logger.LogError((object)$"Cannot register body replacement exception type {type}, must inherit from BodyReplacementBase");
				return;
			}
			Instance.Logger.LogInfo((object)$"Registering body replacement exception type {type}.");
			if (!RegisteredModelReplacementExceptions.Contains(type))
			{
				RegisteredModelReplacementExceptions.Add(type);
			}
		}

		public static void RegisterSuitModelReplacement(string suitNameToReplace, Type type)
		{
			suitNameToReplace = suitNameToReplace.ToLower().Replace(" ", "");
			if (!type.IsSubclassOf(typeof(BodyReplacementBase)))
			{
				Instance.Logger.LogError((object)$"Cannot register body replacement type {type}, must inherit from BodyReplacementBase");
				return;
			}
			if (RegisteredModelReplacements.ContainsKey(suitNameToReplace))
			{
				Instance.Logger.LogError((object)$"Cannot register body replacement type {type}, suit name to replace {suitNameToReplace} is already registered.");
				return;
			}
			Instance.Logger.LogInfo((object)$"Registering body replacement type {type} to suit name {suitNameToReplace}.");
			RegisteredModelReplacements.Add(suitNameToReplace, type);
		}

		public static void SetPlayerModelReplacement(PlayerControllerB player, Type type)
		{
			if (!type.IsSubclassOf(typeof(BodyReplacementBase)))
			{
				Instance.Logger.LogError((object)("Cannot set body replacement of type " + type.Name + ", must inherit from BodyReplacementBase"));
			}
			else
			{
				if (!isLan && player.playerSteamId == 0)
				{
					return;
				}
				BodyReplacementBase component = ((Component)player.thisPlayerBody).gameObject.GetComponent<BodyReplacementBase>();
				int currentSuitID = player.currentSuitID;
				string unlockableName = StartOfRound.Instance.unlockablesList.unlockables[currentSuitID].unlockableName;
				if ((Object)(object)component != (Object)null)
				{
					if (((object)component).GetType() == type)
					{
						if (!(component.suitName != unlockableName))
						{
							return;
						}
						Console.WriteLine($"Suit Change detected {component.suitName} => {unlockableName}, Replacing {type}.");
						Object.Destroy((Object)(object)component);
					}
					else
					{
						Console.WriteLine($"Model Replacement Change detected {((object)component).GetType()} => {type}, changing model.");
						Object.Destroy((Object)(object)component);
					}
				}
				BodyReplacementBase bodyReplacementBase = ((Component)player.thisPlayerBody).gameObject.AddComponent(type) as BodyReplacementBase;
				bodyReplacementBase.suitName = unlockableName;
			}
		}

		public static void RemovePlayerModelReplacement(PlayerControllerB player)
		{
			BodyReplacementBase component = ((Component)player.thisPlayerBody).gameObject.GetComponent<BodyReplacementBase>();
			if (Object.op_Implicit((Object)(object)component))
			{
				Object.Destroy((Object)(object)component);
			}
		}
	}
	public abstract class BodyReplacementBase : MonoBehaviour
	{
		public ViewStateManager viewState = null;

		public MoreCompanyCosmeticManager cosmeticManager = null;

		public MaterialHelper materialHelper = null;

		public GameObject replacementModel;

		protected GameObject deadBody = null;

		protected GameObject replacementDeadBody = null;

		private MeshRenderer nameTagObj = null;

		private MeshRenderer nameTagObj2 = null;

		private int danceNumber = 0;

		private int previousDanceNumber = 0;

		public AvatarUpdater cosmeticAvatar = null;

		public bool UseNoPostProcessing = false;

		public bool DontConvertUnsupportedShaders = false;

		private bool emoteOngoing = false;

		public AvatarUpdater avatar { get; private set; }

		public PlayerControllerB controller { get; private set; }

		public AvatarUpdater ragdollAvatar { get; private set; }

		public string suitName { get; set; } = "";


		protected abstract GameObject LoadAssetsAndReturnModel();

		protected virtual void AddModelScripts()
		{
		}

		protected virtual AvatarUpdater GetAvatarUpdater()
		{
			return new AvatarUpdater();
		}

		protected internal virtual void OnHitEnemy(bool dead)
		{
			Console.WriteLine("PLAYER HIT ENEMY " + controller.playerUsername);
		}

		protected internal virtual void OnHitAlly(PlayerControllerB ally, bool dead)
		{
			Console.WriteLine("PLAYER HIT ALLY " + controller.playerUsername);
		}

		protected internal virtual void OnDamageTaken(bool dead)
		{
			Console.WriteLine("PLAYER TAKE DAMAGE  " + controller.playerUsername);
		}

		protected internal virtual void OnDamageTakenByAlly(PlayerControllerB ally, bool dead)
		{
			Console.WriteLine("PLAYER TAKE DAMAGE BY ALLY " + controller.playerUsername);
		}

		protected internal virtual void OnDeath()
		{
			Console.WriteLine("PLAYER DEATH " + controller.playerUsername + " ");
		}

		protected internal virtual void OnEmoteStart(int emoteId)
		{
			Console.WriteLine($"PLAYER EMOTE START {controller.playerUsername} ID {emoteId}");
		}

		protected internal virtual void OnEmoteEnd()
		{
			Console.WriteLine("PLAYER EMOTE END " + controller.playerUsername);
		}

		protected virtual void Awake()
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			//IL_0206: 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_0232: 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_0239: 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_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			controller = ((Component)this).GetComponent<PlayerControllerB>();
			ModelReplacementAPI.Instance.Logger.LogInfo((object)("Awake " + controller.playerUsername));
			replacementModel = LoadAssetsAndReturnModel();
			if ((Object)(object)replacementModel == (Object)null)
			{
				ModelReplacementAPI.Instance.Logger.LogFatal((object)"LoadAssetsAndReturnModel() returned null. Verify that your assetbundle works and your asset name is correct. ");
			}
			materialHelper = new MaterialHelper(this);
			Renderer[] componentsInChildren = replacementModel.GetComponentsInChildren<Renderer>();
			Material sharedMaterial = ((Renderer)((Component)controller.thisPlayerModel).GetComponent<SkinnedMeshRenderer>()).sharedMaterial;
			sharedMaterial = new Material(sharedMaterial);
			Dictionary<Material, Material> dictionary = new Dictionary<Material, Material>();
			List<Material> list = CollectionPool<List<Material>, Material>.Get();
			Renderer[] array = componentsInChildren;
			foreach (Renderer val in array)
			{
				val.GetSharedMaterials(list);
				for (int j = 0; j < list.Count; j++)
				{
					Material val2 = list[j];
					if (!dictionary.TryGetValue(val2, out var value))
					{
						value = (dictionary[val2] = materialHelper.GetReplacementMaterial(sharedMaterial, val2));
					}
					list[j] = value;
				}
				val.SetMaterials(list);
			}
			CollectionPool<List<Material>, Material>.Release(list);
			SkinnedMeshRenderer[] componentsInChildren2 = replacementModel.GetComponentsInChildren<SkinnedMeshRenderer>();
			foreach (SkinnedMeshRenderer val3 in componentsInChildren2)
			{
				val3.updateWhenOffscreen = true;
			}
			try
			{
				AddModelScripts();
			}
			catch (Exception ex)
			{
				ModelReplacementAPI.Instance.Logger.LogError((object)("Could not set all model scripts.\n Error: " + ex.Message));
			}
			replacementModel = Object.Instantiate<GameObject>(replacementModel);
			GameObject obj = replacementModel;
			((Object)obj).name = ((Object)obj).name + "(" + controller.playerUsername + ")";
			replacementModel.transform.localPosition = new Vector3(0f, 0f, 0f);
			replacementModel.SetActive(true);
			Bounds bounds = ((Renderer)controller.thisPlayerModel).bounds;
			Vector3 extents = ((Bounds)(ref bounds)).extents;
			float y = extents.y;
			bounds = GetBounds();
			float num = y / ((Bounds)(ref bounds)).extents.y;
			Transform transform = replacementModel.transform;
			transform.localScale *= num;
			avatar = GetAvatarUpdater();
			cosmeticAvatar = avatar;
			ragdollAvatar = new AvatarUpdater();
			avatar.AssignModelReplacement(((Component)controller).gameObject, replacementModel);
			viewState = new ViewStateManager(this);
			if (ModelReplacementAPI.moreCompanyPresent)
			{
				cosmeticManager = new MoreCompanyCosmeticManager(this);
			}
			MeshRenderer[] componentsInChildren3 = ((Component)controller).gameObject.GetComponentsInChildren<MeshRenderer>();
			nameTagObj = componentsInChildren3.Where((MeshRenderer x) => ((Object)((Component)x).gameObject).name == "LevelSticker").First();
			nameTagObj2 = componentsInChildren3.Where((MeshRenderer x) => ((Object)((Component)x).gameObject).name == "BetaBadge").First();
			viewState.RendererPatches();
			SetAvatarRenderers(enabled: true);
			viewState.SetAllLayers();
			ModelReplacementAPI.Instance.Logger.LogInfo((object)("AwakeEnd " + controller.playerUsername));
		}

		protected virtual void Start()
		{
			viewState.RendererPatches();
		}

		protected virtual void LateUpdate()
		{
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			SetPlayerRenderers(enabled: false);
			viewState.SetAllLayers();
			GameObject val = null;
			try
			{
				val = ((Component)controller.deadBody).gameObject;
			}
			catch
			{
			}
			if (Object.op_Implicit((Object)(object)val) && (Object)(object)replacementDeadBody == (Object)null)
			{
				Console.WriteLine("Set cosmeticAvatar to ragdoll");
				cosmeticAvatar = ragdollAvatar;
				CreateAndParentRagdoll(controller.deadBody);
				OnDeath();
			}
			if (Object.op_Implicit((Object)(object)replacementDeadBody) && (Object)(object)val == (Object)null)
			{
				Console.WriteLine("Set cosmeticAvatar to living");
				cosmeticAvatar = avatar;
				Object.Destroy((Object)(object)replacementDeadBody);
				replacementDeadBody = null;
			}
			avatar.Update();
			ragdollAvatar.Update();
			if (ModelReplacementAPI.moreCompanyPresent)
			{
				cosmeticManager.Update(useAvatarTransforms: true);
			}
			previousDanceNumber = danceNumber;
			AnimatorStateInfo currentAnimatorStateInfo = controller.playerBodyAnimator.GetCurrentAnimatorStateInfo(1);
			int fullPathHash = ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash;
			if (controller.performingEmote)
			{
				switch (fullPathHash)
				{
				case -462656950:
					danceNumber = 1;
					break;
				case 2103786480:
					danceNumber = 2;
					break;
				default:
					danceNumber = 3;
					break;
				}
			}
			else
			{
				danceNumber = 0;
			}
			if (ModelReplacementAPI.tooManyEmotesPresent)
			{
				danceNumber = SafeGetEmoteID(danceNumber);
			}
			if (danceNumber != previousDanceNumber)
			{
				if (previousDanceNumber == 0)
				{
					((MonoBehaviour)this).StartCoroutine(WaitForDanceNumberChange());
				}
				else if (danceNumber == 0)
				{
					OnEmoteEnd();
				}
				else if (!emoteOngoing)
				{
					OnEmoteStart(danceNumber);
				}
			}
		}

		protected virtual void OnDestroy()
		{
			ModelReplacementAPI.Instance.Logger.LogInfo((object)("Destroy body component for " + controller.playerUsername));
			SetPlayerRenderers(enabled: true);
			if (ModelReplacementAPI.moreCompanyPresent)
			{
				cosmeticManager.Update(useAvatarTransforms: false);
			}
			Object.Destroy((Object)(object)replacementModel);
			Object.Destroy((Object)(object)replacementDeadBody);
		}

		private void CreateAndParentRagdoll(DeadBodyInfo bodyinfo)
		{
			deadBody = ((Component)bodyinfo).gameObject;
			SkinnedMeshRenderer componentInChildren = deadBody.GetComponentInChildren<SkinnedMeshRenderer>();
			replacementDeadBody = Object.Instantiate<GameObject>(replacementModel);
			GameObject obj = replacementDeadBody;
			((Object)obj).name = ((Object)obj).name + "(Ragdoll)";
			ragdollAvatar.AssignModelReplacement(deadBody, replacementDeadBody);
			Renderer[] componentsInChildren = replacementDeadBody.GetComponentsInChildren<Renderer>();
			foreach (Renderer val in componentsInChildren)
			{
				val.enabled = true;
				val.shadowCastingMode = (ShadowCastingMode)1;
				((Component)val).gameObject.layer = viewState.VisibleLayer;
			}
			((Renderer)componentInChildren).enabled = false;
			GameObject[] bodyBloodDecals = bodyinfo.bodyBloodDecals;
			foreach (GameObject val2 in bodyBloodDecals)
			{
				Transform parent = val2.transform.parent;
				Transform avatarTransformFromBoneName = ragdollAvatar.GetAvatarTransformFromBoneName(((Object)parent).name);
				if (Object.op_Implicit((Object)(object)avatarTransformFromBoneName))
				{
					Object.Instantiate<GameObject>(val2, avatarTransformFromBoneName);
				}
			}
		}

		private void SetAvatarRenderers(bool enabled)
		{
			Renderer[] componentsInChildren = replacementModel.GetComponentsInChildren<Renderer>();
			foreach (Renderer val in componentsInChildren)
			{
				val.enabled = enabled;
			}
		}

		private void SetPlayerRenderers(bool enabled)
		{
			((Renderer)controller.thisPlayerModel).enabled = enabled;
			((Renderer)controller.thisPlayerModelLOD1).enabled = enabled;
			((Renderer)controller.thisPlayerModelLOD2).enabled = enabled;
			((Renderer)nameTagObj).enabled = enabled;
			((Renderer)nameTagObj2).enabled = enabled;
		}

		private Bounds GetBounds()
		{
			//IL_0003: 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_0067: 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_00a0: 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_00d9: 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_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: 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_0149: 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_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_0187: 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_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)
			//IL_01b0: 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)
			Bounds result = default(Bounds);
			IEnumerable<Bounds> source = from r in replacementModel.GetComponentsInChildren<SkinnedMeshRenderer>()
				select ((Renderer)r).bounds;
			Bounds val = source.OrderByDescending((Bounds x) => ((Bounds)(ref x)).max.x).First();
			float x2 = ((Bounds)(ref val)).max.x;
			val = source.OrderByDescending((Bounds x) => ((Bounds)(ref x)).max.y).First();
			float y = ((Bounds)(ref val)).max.y;
			val = source.OrderByDescending((Bounds x) => ((Bounds)(ref x)).max.z).First();
			float z = ((Bounds)(ref val)).max.z;
			val = source.OrderBy((Bounds x) => ((Bounds)(ref x)).min.x).First();
			float x3 = ((Bounds)(ref val)).min.x;
			val = source.OrderBy((Bounds x) => ((Bounds)(ref x)).min.y).First();
			float y2 = ((Bounds)(ref val)).min.y;
			val = source.OrderBy((Bounds x) => ((Bounds)(ref x)).min.z).First();
			float z2 = ((Bounds)(ref val)).min.z;
			((Bounds)(ref result)).SetMinMax(new Vector3(x3, y2, z2), new Vector3(x2, y, z));
			return result;
		}

		private IEnumerator WaitForDanceNumberChange()
		{
			if (emoteOngoing)
			{
				yield break;
			}
			emoteOngoing = true;
			for (int frame = 0; frame < 20; frame++)
			{
				if (danceNumber == 0)
				{
					emoteOngoing = false;
					yield break;
				}
				yield return (object)new WaitForEndOfFrame();
			}
			if (danceNumber != 0)
			{
				emoteOngoing = false;
				OnEmoteStart(danceNumber);
			}
		}

		private int SafeGetEmoteID(int currentID)
		{
			return DangerousGetEmoteID(currentID);
		}

		private int DangerousGetEmoteID(int currentID)
		{
			UnlockableEmote currentlyPlayingEmote = PlayerPatcher.GetCurrentlyPlayingEmote(controller);
			if (currentlyPlayingEmote == null)
			{
				return currentID;
			}
			if (currentlyPlayingEmote.emoteId == 1)
			{
				return -1;
			}
			if (currentlyPlayingEmote.emoteId == 2)
			{
				return -2;
			}
			if (currentlyPlayingEmote.emoteId == 3)
			{
				return -3;
			}
			return currentlyPlayingEmote.emoteId;
		}
	}
}
namespace ModelReplacement.Patches
{
	[HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageClientRpc")]
	internal class CosmeticPatch
	{
		private static void Postfix()
		{
			//IL_00a6: 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)
			if (!Chainloader.PluginInfos.ContainsKey("me.swipez.melonloader.morecompany"))
			{
				return;
			}
			CosmeticApplication val = Object.FindObjectOfType<CosmeticApplication>();
			if (CosmeticRegistry.locallySelectedCosmetics.Count <= 0 || val.spawnedCosmetics.Count > 0)
			{
				return;
			}
			foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics)
			{
				val.ApplyCosmetic(locallySelectedCosmetic, true);
			}
			foreach (CosmeticInstance spawnedCosmetic in val.spawnedCosmetics)
			{
				Transform transform = ((Component)spawnedCosmetic).transform;
				transform.localScale *= 0.38f;
				SetAllChildrenLayer(((Component)spawnedCosmetic).transform, 3);
			}
		}

		private static void SetAllChildrenLayer(Transform transform, string layerName)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			int layer = LayerMask.NameToLayer(layerName);
			((Component)transform).gameObject.layer = layer;
			foreach (object item in transform)
			{
				SetAllChildrenLayer((Transform)item, layerName);
			}
		}

		private static void SetAllChildrenLayer(Transform transform, int layer)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			((Component)transform).gameObject.layer = layer;
			foreach (object item in transform)
			{
				SetAllChildrenLayer((Transform)item, layer);
			}
		}
	}
	[HarmonyPatch(typeof(EnemyAI))]
	public class EnemyAIPatch
	{
		[HarmonyPatch("HitEnemy")]
		[HarmonyPrefix]
		[HarmonyAfter(new string[] { })]
		public static void HitEnemy(ref EnemyAI __instance, int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
		{
			if (!((Object)(object)playerWhoHit == (Object)null))
			{
				BodyReplacementBase component = ((Component)playerWhoHit.thisPlayerBody).gameObject.GetComponent<BodyReplacementBase>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.OnHitEnemy(__instance.isEnemyDead);
				}
			}
		}
	}
	[HarmonyPatch(typeof(MaskedPlayerEnemy))]
	public class MaskedPlayerEnemyPatch
	{
		[HarmonyPatch("SetSuit")]
		[HarmonyPrefix]
		public static void SetModelReplacement(ref MaskedPlayerEnemy __instance, int suitId)
		{
			BodyReplacementBase component = ((Component)__instance.mimickingPlayer.thisPlayerBody).gameObject.GetComponent<BodyReplacementBase>();
			if (!((Object)(object)component == (Object)null))
			{
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SpawnPlayerAnimation")]
	internal class PlayerPatch
	{
		[HarmonyPatch(typeof(PlayerControllerB))]
		public class PlayerControllerBPatch
		{
			[HarmonyPatch("DamagePlayerFromOtherClientClientRpc")]
			[HarmonyPrefix]
			public static void DamagePlayerFromOtherClientClientRpc(ref PlayerControllerB __instance, int damageAmount, Vector3 hitDirection, int playerWhoHit, int newHealthAmount)
			{
				PlayerControllerB val = __instance.playersManager.allPlayerScripts[playerWhoHit];
				if (!((Object)(object)val == (Object)null))
				{
					BodyReplacementBase component = ((Component)val.thisPlayerBody).gameObject.GetComponent<BodyReplacementBase>();
					if (Object.op_Implicit((Object)(object)component))
					{
						component.OnHitAlly(__instance, __instance.isPlayerDead);
					}
				}
			}

			[HarmonyPatch("DamagePlayerClientRpc")]
			[HarmonyPrefix]
			public static void DamagePlayerClientRpc(ref PlayerControllerB __instance, int damageNumber, int newHealthAmount)
			{
				if (!((Object)(object)__instance == (Object)null))
				{
					BodyReplacementBase component = ((Component)__instance.thisPlayerBody).gameObject.GetComponent<BodyReplacementBase>();
					Console.WriteLine("PLAYER TAKE DAMAGE " + __instance.playerUsername);
					if (Object.op_Implicit((Object)(object)component))
					{
						component.OnDamageTaken(__instance.isPlayerDead);
					}
				}
			}
		}

		[HarmonyAfter(new string[] { "quackandcheese.mirrordecor" })]
		private static void Postfix(ref PlayerControllerB __instance)
		{
			if ((Object)(object)__instance == (Object)(object)GameNetworkManager.Instance.localPlayerController)
			{
				PlayerControllerB val = __instance;
				((Renderer)val.thisPlayerModel).shadowCastingMode = (ShadowCastingMode)1;
				((Component)val.thisPlayerModel).gameObject.layer = ViewStateManager.modelLayer;
				((Component)val.thisPlayerModelArms).gameObject.layer = ViewStateManager.armsLayer;
				val.gameplayCamera.cullingMask = ViewStateManager.CullingMaskFirstPerson;
			}
		}
	}
}
namespace ModelReplacement.Modules
{
	public class MaterialHelper
	{
		private BodyReplacementBase bodyReplacement;

		private static readonly string[] shaderPrefixWhitelist = new string[9] { "HDRP/", "GUI/", "Sprites/", "UI/", "Unlit/", "Toon", "lilToon", "Shader Graphs/", "Hidden/" };

		private bool DontConvertUnsupportedShaders => bodyReplacement.DontConvertUnsupportedShaders;

		public MaterialHelper(BodyReplacementBase bodyreplacement)
		{
			bodyReplacement = bodyreplacement;
		}

		public virtual Material GetReplacementMaterial(Material gameMaterial, Material modelMaterial)
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			//IL_0089: 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_00bf: Unknown result type (might be due to invalid IL or missing references)
			if (DontConvertUnsupportedShaders || shaderPrefixWhitelist.Any((string prefix) => ((Object)modelMaterial.shader).name.StartsWith(prefix)))
			{
				return modelMaterial;
			}
			ModelReplacementAPI.Instance.Logger.LogInfo((object)("Creating replacement material for material " + ((Object)modelMaterial).name + " / shader " + ((Object)modelMaterial.shader).name));
			Material val = new Material(gameMaterial);
			val.color = modelMaterial.color;
			val.mainTexture = modelMaterial.mainTexture;
			val.mainTextureOffset = modelMaterial.mainTextureOffset;
			val.mainTextureScale = modelMaterial.mainTextureScale;
			val.EnableKeyword("_EMISSION");
			val.EnableKeyword("_NORMALMAP");
			val.EnableKeyword("_SPECGLOSSMAP");
			val.SetFloat("_NormalScale", 0f);
			HDMaterial.ValidateMaterial(val);
			return val;
		}
	}
	public class MoreCompanyCosmeticManager
	{
		public enum CosmeticType2
		{
			HAT,
			WRIST,
			CHEST,
			R_LOWER_ARM,
			HIP,
			L_SHIN,
			R_SHIN
		}

		private BodyReplacementBase bodyReplacement;

		private PlayerControllerB controller;

		private GameObject replacementModel;

		private Dictionary<CosmeticType2, Transform> cosmeticTransformPairs = new Dictionary<CosmeticType2, Transform>();

		private AvatarUpdater cosmeticAvatar => bodyReplacement.cosmeticAvatar;

		public MoreCompanyCosmeticManager(BodyReplacementBase bodyreplacement)
		{
			bodyReplacement = bodyreplacement;
			controller = bodyreplacement.controller;
			replacementModel = bodyreplacement.replacementModel;
		}

		public void Update(bool useAvatarTransforms)
		{
			if (ModelReplacementAPI.moreCompanyPresent)
			{
				SafeRenderCosmetics(useAvatarTransforms);
			}
		}

		private void SafeRenderCosmetics(bool useAvatarTransforms)
		{
			DangerousRenderCosmetics(useAvatarTransforms);
		}

		private void RefreshCosmetics()
		{
			if (cosmeticTransformPairs.Count == 0)
			{
				cosmeticTransformPairs.Add(CosmeticType2.HAT, cosmeticAvatar.GetAvatarTransformFromBoneName("spine.004"));
				cosmeticTransformPairs.Add(CosmeticType2.CHEST, cosmeticAvatar.GetAvatarTransformFromBoneName("spine.003"));
				cosmeticTransformPairs.Add(CosmeticType2.R_LOWER_ARM, cosmeticAvatar.GetAvatarTransformFromBoneName("arm.R_lower"));
				cosmeticTransformPairs.Add(CosmeticType2.HIP, cosmeticAvatar.GetAvatarTransformFromBoneName("spine"));
				cosmeticTransformPairs.Add(CosmeticType2.L_SHIN, cosmeticAvatar.GetAvatarTransformFromBoneName("shin.L"));
				cosmeticTransformPairs.Add(CosmeticType2.R_SHIN, cosmeticAvatar.GetAvatarTransformFromBoneName("shin.R"));
			}
		}

		private void DangerousRenderCosmetics(bool useAvatarTransforms)
		{
			//IL_0054: 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_005b: 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_0082: Expected I4, but got Unknown
			//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)
			RefreshCosmetics();
			CosmeticApplication componentInChildren = ((Component)controller).gameObject.GetComponentInChildren<CosmeticApplication>();
			if ((Object)(object)componentInChildren == (Object)null)
			{
				return;
			}
			if (useAvatarTransforms)
			{
				foreach (CosmeticInstance spawnedCosmetic in componentInChildren.spawnedCosmetics)
				{
					Transform val = null;
					CosmeticType cosmeticType = spawnedCosmetic.cosmeticType;
					CosmeticType val2 = cosmeticType;
					switch ((int)val2)
					{
					case 0:
						val = cosmeticTransformPairs[CosmeticType2.HAT];
						break;
					case 2:
						val = cosmeticTransformPairs[CosmeticType2.CHEST];
						break;
					case 3:
						val = cosmeticTransformPairs[CosmeticType2.R_LOWER_ARM];
						break;
					case 4:
						val = cosmeticTransformPairs[CosmeticType2.HIP];
						break;
					case 5:
						val = cosmeticTransformPairs[CosmeticType2.L_SHIN];
						break;
					case 6:
						val = cosmeticTransformPairs[CosmeticType2.R_SHIN];
						break;
					}
					((Component)spawnedCosmetic).transform.parent = null;
					((Component)spawnedCosmetic).transform.SetPositionAndRotation(val.position, val.rotation);
				}
				return;
			}
			componentInChildren.RefreshAllCosmeticPositions();
		}
	}
	public enum ViewState
	{
		None,
		ThirdPerson,
		FirstPerson,
		Debug
	}
	public class ViewStateManager
	{
		private static int CullingMaskThirdPerson = 960174079;

		public static int CullingMaskFirstPerson = 1765480439;

		pr

BepInEx/plugins/EladNLG-EladsHUD/EladsHUD.dll

Decompiled 10 months 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.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using CustomHUD;
using GameNetcodeStuff;
using HarmonyLib;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;
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("EladsHUD")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Custom HUD for lethal company :]")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("EladsHUD")]
[assembly: AssemblyTitle("EladsHUD")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.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;
		}
	}
}
internal class CustomHUD_Mono : MonoBehaviour
{
	public static CustomHUD_Mono instance;

	[Header("Health")]
	public CanvasGroup healthGroup;

	public Image healthBar;

	public TextMeshProUGUI healthText;

	[Header("Stamina")]
	public CanvasGroup staminaGroup;

	public Image staminaBar;

	public Image staminaBarChangeFG;

	public TextMeshProUGUI staminaText;

	public TextMeshProUGUI carryText;

	[Header("Battery")]
	public CanvasGroup batteryGroup;

	public Image batteryBar;

	public TextMeshProUGUI batteryText;

	[Header("Flashlight")]
	public CanvasGroup flashlightGroup;

	public Image flashlightBar;

	public TextMeshProUGUI flashlightText;

	private Color staminaColor;

	private Color staminaWarnColor = new Color(255f, 0f, 0f);

	private float colorLerp;

	private int lastHealth = 100;

	private float lastHealthChange = 0f;

	private void Awake()
	{
		if ((Object)(object)instance != (Object)null)
		{
			throw new Exception("2 instances of CustomHUD_Mono!");
		}
		instance = this;
	}

	private void Start()
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		staminaColor = ((Graphic)staminaBar).color;
	}

	public void UpdateFromPlayer(PlayerControllerB player)
	{
		//IL_017d: 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_018e: 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_01f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0204: Unknown result type (might be due to invalid IL or missing references)
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		lastHealthChange += Time.deltaTime;
		if (lastHealth != player.health)
		{
			lastHealth = player.health;
			lastHealthChange = 0f;
		}
		bool privateField = player.GetPrivateField<bool>("isWalking");
		int health = player.health;
		float sprintMeter = player.sprintMeter;
		float sprintTime = player.sprintTime;
		float num = 1f;
		if ((double)player.drunkness > 0.019999999552965164)
		{
			num *= Mathf.Abs(StartOfRound.Instance.drunknessSpeedEffect.Evaluate(player.drunkness) - 1.25f);
		}
		float num2 = (player.isSprinting ? (-1f / sprintTime * player.carryWeight * num) : ((player.isMovementHindered > 0 && privateField) ? (-1f / sprintTime * num * 0.5f) : ((!privateField) ? (1f / (sprintTime + 4f) * num) : (1f / (sprintTime + 9f) * num))));
		float num3 = num2 * 100f;
		if ((double)sprintMeter < 0.3)
		{
			colorLerp = Mathf.Clamp01(colorLerp + Time.deltaTime * 8f);
		}
		else
		{
			colorLerp = Mathf.Clamp01(colorLerp - Time.deltaTime * 8f);
		}
		((Graphic)staminaBar).color = Color.Lerp(staminaColor, staminaWarnColor, colorLerp);
		int num4 = Mathf.RoundToInt(sprintMeter * 100f);
		float num5 = Mathf.Sign(num2);
		float num6 = num5;
		if (num6 != -1f)
		{
			if (num6 != 0f)
			{
				if (num6 != 1f)
				{
				}
				staminaBar.fillAmount = sprintMeter;
				staminaBarChangeFG.fillAmount = 0f;
				((TMP_Text)staminaText).text = string.Format("{0}<size=75%><voffset=1>%</voffset></size> | +{1}<size=75%>/sec</size>", num4, num3.ToString("0.0"));
			}
			else
			{
				staminaBar.fillAmount = sprintMeter;
				staminaBarChangeFG.fillAmount = 0f;
				((TMP_Text)staminaText).text = $"{num4}<size=75%><voffset=1>%</voffset></size> | +0.0<size=75%>/sec</size>";
			}
		}
		else
		{
			staminaBar.fillAmount = sprintMeter - Mathf.Abs(num2);
			((Graphic)staminaBarChangeFG).color = Color.Lerp(Color.white, staminaWarnColor, colorLerp);
			staminaBarChangeFG.fillAmount = Mathf.Min(sprintMeter, Mathf.Abs(num2));
			((Transform)((Graphic)staminaBarChangeFG).rectTransform).localPosition = new Vector3(270f * Mathf.Max(0f, sprintMeter - Mathf.Abs(num2)), 0f);
			((TMP_Text)staminaText).text = string.Format("{0}<size=75%><voffset=1>%</voffset></size> | {1}<size=75%>/sec</size>", num4, num3.ToString("0.0"));
		}
		float num7 = Mathf.RoundToInt(Mathf.Clamp(player.carryWeight - 1f, 0f, 100f) * 105f);
		if (Plugin.shouldDoKGConversion)
		{
			num7 *= 0.453592f;
			((TMP_Text)carryText).text = $"{num7}<size=60%>kg</size>";
		}
		else
		{
			((TMP_Text)carryText).text = $"{num7}<size=60%>lb</size>";
		}
		healthBar.fillAmount = (float)health / 100f;
		((TMP_Text)healthText).text = health.ToString();
		healthGroup.alpha = Mathf.InverseLerp(5f, 4f, lastHealthChange);
		((Component)flashlightGroup).gameObject.SetActive(UpdateFlashlight(player));
		((Component)batteryGroup).gameObject.SetActive(UpdateBattery(player));
	}

	private bool UpdateFlashlight(PlayerControllerB player)
	{
		if (!((Behaviour)player.helmetLight).enabled)
		{
			return false;
		}
		GrabbableObject pocketedFlashlight = player.pocketedFlashlight;
		if ((Object)(object)pocketedFlashlight == (Object)null)
		{
			return false;
		}
		if (!pocketedFlashlight.itemProperties.requiresBattery)
		{
			return false;
		}
		flashlightBar.fillAmount = pocketedFlashlight.insertedBattery.charge;
		int num = Mathf.CeilToInt(pocketedFlashlight.insertedBattery.charge * pocketedFlashlight.itemProperties.batteryUsage);
		((TMP_Text)flashlightText).text = string.Format("{0}% <size=60%>{1}:{2}", Mathf.CeilToInt(pocketedFlashlight.insertedBattery.charge * 100f), num / 60, (num % 60).ToString("D2"));
		return true;
	}

	private bool UpdateBattery(PlayerControllerB player)
	{
		GrabbableObject currentlyHeldObjectServer = player.currentlyHeldObjectServer;
		if ((Object)(object)currentlyHeldObjectServer == (Object)null)
		{
			return false;
		}
		if (!currentlyHeldObjectServer.itemProperties.requiresBattery)
		{
			return false;
		}
		batteryBar.fillAmount = currentlyHeldObjectServer.insertedBattery.charge;
		int num = (int)(currentlyHeldObjectServer.insertedBattery.charge / currentlyHeldObjectServer.itemProperties.batteryUsage);
		int num2 = Mathf.CeilToInt(currentlyHeldObjectServer.insertedBattery.charge * currentlyHeldObjectServer.itemProperties.batteryUsage);
		if (currentlyHeldObjectServer.itemProperties.itemIsTrigger)
		{
			((TMP_Text)batteryText).text = $"{Mathf.CeilToInt(currentlyHeldObjectServer.insertedBattery.charge * 100f)}% ({num} uses remaining)";
		}
		else
		{
			((TMP_Text)batteryText).text = string.Format("{0}% ({1}:{2} remaining)", Mathf.CeilToInt(currentlyHeldObjectServer.insertedBattery.charge * 100f), num2 / 60, (num2 % 60).ToString("D2"));
		}
		return true;
	}
}
namespace EladsHUD
{
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "EladsHUD";

		public const string PLUGIN_NAME = "EladsHUD";

		public const string PLUGIN_VERSION = "1.1.0";
	}
}
namespace CustomHUD
{
	[BepInPlugin("me.eladnlg.customhud", "Elads HUD", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		public AssetBundle assets;

		public GameObject HUD;

		public static bool shouldDoKGConversion;

		private void Awake()
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			if ((Object)(object)instance != (Object)null)
			{
				throw new Exception("what the cuck??? more than 1 plugin instance.");
			}
			instance = this;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Elad's HUD is loaded!");
			assets = AssetUtils.LoadAssetBundleFromResources("customhud", typeof(PlayerPatches).Assembly);
			HUD = assets.LoadAsset<GameObject>("PlayerInfo");
			Harmony val = new Harmony("me.eladnlg.customhud");
			val.PatchAll(Assembly.GetExecutingAssembly());
		}

		private void Start()
		{
			shouldDoKGConversion = Chainloader.PluginInfos.Any((KeyValuePair<string, PluginInfo> pair) => pair.Value.Metadata.GUID == "com.zduniusz.lethalcompany.lbtokg");
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	public class HUDPatches
	{
		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		private static void Awake_Postfix(HUDManager __instance)
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			HUDElement[] privateField = __instance.GetPrivateField<HUDElement[]>("HUDElements");
			privateField[2].canvasGroup.alpha = 0f;
			GameObject val = Object.Instantiate<GameObject>(Plugin.instance.HUD, ((Component)privateField[2].canvasGroup).transform.parent);
			val.transform.localScale = new Vector3(0.75f, 0.75f, 0.75f);
			privateField[2].canvasGroup = val.GetComponent<CanvasGroup>();
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	public static class PlayerPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch("LateUpdate")]
		private static void LateUpdate_Prefix(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject) && !((Object)(object)CustomHUD_Mono.instance == (Object)null))
			{
				CustomHUD_Mono.instance.UpdateFromPlayer(__instance);
			}
		}
	}
	internal static class ReflectionUtils
	{
		public static T GetPrivateField<T>(this object obj, string field)
		{
			return (T)obj.GetType().GetField(field, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
		}
	}
}
namespace Jotunn.Utils
{
	public static class AssetUtils
	{
		public const char AssetBundlePathSeparator = '$';

		public static Texture2D LoadTexture(string texturePath, bool relativePath = true)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			string text = texturePath;
			if (relativePath)
			{
				text = Path.Combine(Paths.PluginPath, texturePath);
			}
			if (!File.Exists(text))
			{
				return null;
			}
			if (!text.EndsWith(".png") && !text.EndsWith(".jpg"))
			{
				throw new Exception("LoadTexture can only load png or jpg textures");
			}
			byte[] array = File.ReadAllBytes(text);
			Texture2D val = new Texture2D(2, 2);
			val.LoadRawTextureData(array);
			return val;
		}

		public static Sprite LoadSpriteFromFile(string spritePath)
		{
			//IL_002e: 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: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = LoadTexture(spritePath);
			if ((Object)(object)val != (Object)null)
			{
				return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), default(Vector2), 100f);
			}
			return null;
		}

		public static AssetBundle LoadAssetBundle(string bundlePath)
		{
			string text = Path.Combine(Paths.PluginPath, bundlePath);
			if (!File.Exists(text))
			{
				return null;
			}
			return AssetBundle.LoadFromFile(text);
		}

		public static AssetBundle LoadAssetBundleFromResources(string bundleName, Assembly resourceAssembly)
		{
			if (resourceAssembly == null)
			{
				throw new ArgumentNullException("Parameter resourceAssembly can not be null.");
			}
			string text = null;
			try
			{
				text = resourceAssembly.GetManifestResourceNames().Single((string str) => str.EndsWith(bundleName));
			}
			catch (Exception)
			{
			}
			if (text == null)
			{
				Debug.LogError((object)("AssetBundle " + bundleName + " not found in assembly manifest"));
				return null;
			}
			AssetBundle result;
			using (Stream stream = resourceAssembly.GetManifestResourceStream(text))
			{
				result = AssetBundle.LoadFromStream(stream);
			}
			return result;
		}

		public static string LoadText(string path)
		{
			string text = Path.Combine(Paths.PluginPath, path);
			if (!File.Exists(text))
			{
				Debug.LogError((object)("Error, failed to load contents from non-existant path: $" + text));
				return null;
			}
			return File.ReadAllText(text);
		}

		public static Sprite LoadSprite(string assetPath)
		{
			//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)
			string text = Path.Combine(Paths.PluginPath, assetPath);
			if (!File.Exists(text))
			{
				return null;
			}
			if (text.Contains('$'.ToString()))
			{
				string[] array = text.Split('$');
				string text2 = array[0];
				string text3 = array[1];
				AssetBundle val = AssetBundle.LoadFromFile(text2);
				Sprite result = val.LoadAsset<Sprite>(text3);
				val.Unload(false);
				return result;
			}
			Texture2D val2 = LoadTexture(text, relativePath: false);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return null;
			}
			return Sprite.Create(val2, new Rect(0f, 0f, (float)((Texture)val2).width, (float)((Texture)val2).height), Vector2.zero);
		}
	}
}

BepInEx/plugins/EliteMasterEric-Coroner/Coroner.dll

Decompiled 10 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
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.Xml.Linq;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Coroner.LCAPI;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.ServerAPI;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("EliteMasterEric")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Rework the Performance Report with new info, including cause of death.")]
[assembly: AssemblyFileVersion("1.5.3.0")]
[assembly: AssemblyInformationalVersion("1.5.3+3f9dc5379bdbfe1ac1cf1b0df31bb040630db71f")]
[assembly: AssemblyProduct("Coroner")]
[assembly: AssemblyTitle("Coroner")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.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 Coroner
{
	public class AdvancedDeathTracker
	{
		public const int PLAYER_CAUSE_OF_DEATH_DROPSHIP = 300;

		private static readonly Dictionary<int, AdvancedCauseOfDeath> PlayerCauseOfDeath = new Dictionary<int, AdvancedCauseOfDeath>();

		public static void ClearDeathTracker()
		{
			PlayerCauseOfDeath.Clear();
		}

		public static void SetCauseOfDeath(int playerIndex, AdvancedCauseOfDeath causeOfDeath, bool broadcast = true)
		{
			PlayerCauseOfDeath[playerIndex] = causeOfDeath;
			if (broadcast)
			{
				DeathBroadcaster.BroadcastCauseOfDeath(playerIndex, causeOfDeath);
			}
		}

		public static void SetCauseOfDeath(int playerIndex, CauseOfDeath causeOfDeath, bool broadcast = true)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			SetCauseOfDeath(playerIndex, ConvertCauseOfDeath(causeOfDeath), broadcast);
		}

		public static void SetCauseOfDeath(PlayerControllerB playerController, CauseOfDeath causeOfDeath, bool broadcast = true)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			SetCauseOfDeath((int)playerController.playerClientId, ConvertCauseOfDeath(causeOfDeath), broadcast);
		}

		public static void SetCauseOfDeath(PlayerControllerB playerController, AdvancedCauseOfDeath causeOfDeath, bool broadcast = true)
		{
			SetCauseOfDeath((int)playerController.playerClientId, causeOfDeath, broadcast);
		}

		public static AdvancedCauseOfDeath GetCauseOfDeath(int playerIndex)
		{
			PlayerControllerB playerController = StartOfRound.Instance.allPlayerScripts[playerIndex];
			return GetCauseOfDeath(playerController);
		}

		public static AdvancedCauseOfDeath GetCauseOfDeath(PlayerControllerB playerController)
		{
			if (!PlayerCauseOfDeath.ContainsKey((int)playerController.playerClientId))
			{
				Plugin.Instance.PluginLogger.LogDebug($"Player {playerController.playerClientId} has no custom cause of death stored! Using fallback...");
				return GuessCauseOfDeath(playerController);
			}
			Plugin.Instance.PluginLogger.LogDebug($"Player {playerController.playerClientId} has custom cause of death stored! {PlayerCauseOfDeath[(int)playerController.playerClientId]}");
			return PlayerCauseOfDeath[(int)playerController.playerClientId];
		}

		public static AdvancedCauseOfDeath GuessCauseOfDeath(PlayerControllerB playerController)
		{
			//IL_0041: 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: Invalid comparison between Unknown and I4
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Invalid comparison between Unknown and I4
			if (playerController.isPlayerDead)
			{
				if (IsHoldingJetpack(playerController))
				{
					if ((int)playerController.causeOfDeath == 2)
					{
						return AdvancedCauseOfDeath.Player_Jetpack_Gravity;
					}
					if ((int)playerController.causeOfDeath == 3)
					{
						return AdvancedCauseOfDeath.Player_Jetpack_Blast;
					}
				}
				return ConvertCauseOfDeath(playerController.causeOfDeath);
			}
			return AdvancedCauseOfDeath.Unknown;
		}

		public static bool IsHoldingJetpack(PlayerControllerB playerController)
		{
			GrabbableObject currentlyHeldObjectServer = playerController.currentlyHeldObjectServer;
			if ((Object)(object)currentlyHeldObjectServer == (Object)null)
			{
				return false;
			}
			GameObject gameObject = ((Component)currentlyHeldObjectServer).gameObject;
			if ((Object)(object)gameObject == (Object)null)
			{
				return false;
			}
			GrabbableObject component = gameObject.GetComponent<GrabbableObject>();
			if ((Object)(object)component == (Object)null)
			{
				return false;
			}
			if (component is JetpackItem)
			{
				return true;
			}
			return false;
		}

		public static AdvancedCauseOfDeath ConvertCauseOfDeath(CauseOfDeath causeOfDeath)
		{
			//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_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected I4, but got Unknown
			return (int)causeOfDeath switch
			{
				0 => AdvancedCauseOfDeath.Unknown, 
				1 => AdvancedCauseOfDeath.Bludgeoning, 
				2 => AdvancedCauseOfDeath.Gravity, 
				3 => AdvancedCauseOfDeath.Blast, 
				4 => AdvancedCauseOfDeath.Strangulation, 
				5 => AdvancedCauseOfDeath.Suffocation, 
				6 => AdvancedCauseOfDeath.Mauling, 
				7 => AdvancedCauseOfDeath.Gunshots, 
				8 => AdvancedCauseOfDeath.Crushing, 
				9 => AdvancedCauseOfDeath.Drowning, 
				10 => AdvancedCauseOfDeath.Abandoned, 
				11 => AdvancedCauseOfDeath.Electrocution, 
				_ => AdvancedCauseOfDeath.Unknown, 
			};
		}

		public static string StringifyCauseOfDeath(CauseOfDeath causeOfDeath)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return StringifyCauseOfDeath(ConvertCauseOfDeath(causeOfDeath), Plugin.RANDOM);
		}

		public static string StringifyCauseOfDeath(AdvancedCauseOfDeath? causeOfDeath)
		{
			return StringifyCauseOfDeath(causeOfDeath, Plugin.RANDOM);
		}

		public static string StringifyCauseOfDeath(AdvancedCauseOfDeath? causeOfDeath, Random random)
		{
			string[] array = SelectCauseOfDeath(causeOfDeath);
			if (array.Length > 1 && (!causeOfDeath.HasValue || !Plugin.Instance.PluginConfig.ShouldUseSeriousDeathMessages()))
			{
				return array[random.Next(array.Length)];
			}
			return array[0];
		}

		public static string[] SelectCauseOfDeath(AdvancedCauseOfDeath? causeOfDeath)
		{
			if (!causeOfDeath.HasValue)
			{
				return LanguageHandler.GetValuesByTag("FunnyNote");
			}
			return causeOfDeath switch
			{
				AdvancedCauseOfDeath.Bludgeoning => LanguageHandler.GetValuesByTag("DeathBludgeoning"), 
				AdvancedCauseOfDeath.Gravity => LanguageHandler.GetValuesByTag("DeathGravity"), 
				AdvancedCauseOfDeath.Blast => LanguageHandler.GetValuesByTag("DeathBlast"), 
				AdvancedCauseOfDeath.Strangulation => LanguageHandler.GetValuesByTag("DeathStrangulation"), 
				AdvancedCauseOfDeath.Suffocation => LanguageHandler.GetValuesByTag("DeathSuffocation"), 
				AdvancedCauseOfDeath.Mauling => LanguageHandler.GetValuesByTag("DeathMauling"), 
				AdvancedCauseOfDeath.Gunshots => LanguageHandler.GetValuesByTag("DeathGunshots"), 
				AdvancedCauseOfDeath.Crushing => LanguageHandler.GetValuesByTag("DeathCrushing"), 
				AdvancedCauseOfDeath.Drowning => LanguageHandler.GetValuesByTag("DeathDrowning"), 
				AdvancedCauseOfDeath.Abandoned => LanguageHandler.GetValuesByTag("DeathAbandoned"), 
				AdvancedCauseOfDeath.Electrocution => LanguageHandler.GetValuesByTag("DeathElectrocution"), 
				AdvancedCauseOfDeath.Kicking => LanguageHandler.GetValuesByTag("DeathKicking"), 
				AdvancedCauseOfDeath.Enemy_Bracken => LanguageHandler.GetValuesByTag("DeathEnemyBracken"), 
				AdvancedCauseOfDeath.Enemy_EyelessDog => LanguageHandler.GetValuesByTag("DeathEnemyEyelessDog"), 
				AdvancedCauseOfDeath.Enemy_ForestGiant => LanguageHandler.GetValuesByTag("DeathEnemyForestGiant"), 
				AdvancedCauseOfDeath.Enemy_CircuitBees => LanguageHandler.GetValuesByTag("DeathEnemyCircuitBees"), 
				AdvancedCauseOfDeath.Enemy_GhostGirl => LanguageHandler.GetValuesByTag("DeathEnemyGhostGirl"), 
				AdvancedCauseOfDeath.Enemy_EarthLeviathan => LanguageHandler.GetValuesByTag("DeathEnemyEarthLeviathan"), 
				AdvancedCauseOfDeath.Enemy_BaboonHawk => LanguageHandler.GetValuesByTag("DeathEnemyBaboonHawk"), 
				AdvancedCauseOfDeath.Enemy_Jester => LanguageHandler.GetValuesByTag("DeathEnemyJester"), 
				AdvancedCauseOfDeath.Enemy_CoilHead => LanguageHandler.GetValuesByTag("DeathEnemyCoilHead"), 
				AdvancedCauseOfDeath.Enemy_SnareFlea => LanguageHandler.GetValuesByTag("DeathEnemySnareFlea"), 
				AdvancedCauseOfDeath.Enemy_Hygrodere => LanguageHandler.GetValuesByTag("DeathEnemyHygrodere"), 
				AdvancedCauseOfDeath.Enemy_HoarderBug => LanguageHandler.GetValuesByTag("DeathEnemyHoarderBug"), 
				AdvancedCauseOfDeath.Enemy_SporeLizard => LanguageHandler.GetValuesByTag("DeathEnemySporeLizard"), 
				AdvancedCauseOfDeath.Enemy_BunkerSpider => LanguageHandler.GetValuesByTag("DeathEnemyBunkerSpider"), 
				AdvancedCauseOfDeath.Enemy_Thumper => LanguageHandler.GetValuesByTag("DeathEnemyThumper"), 
				AdvancedCauseOfDeath.Enemy_MaskedPlayer_Wear => LanguageHandler.GetValuesByTag("DeathEnemyMaskedPlayerWear"), 
				AdvancedCauseOfDeath.Enemy_MaskedPlayer_Victim => LanguageHandler.GetValuesByTag("DeathEnemyMaskedPlayerVictim"), 
				AdvancedCauseOfDeath.Enemy_Nutcracker_Kicked => LanguageHandler.GetValuesByTag("DeathEnemyNutcrackerKicked"), 
				AdvancedCauseOfDeath.Enemy_Nutcracker_Shot => LanguageHandler.GetValuesByTag("DeathEnemyNutcrackerShot"), 
				AdvancedCauseOfDeath.Player_Jetpack_Gravity => LanguageHandler.GetValuesByTag("DeathPlayerJetpackGravity"), 
				AdvancedCauseOfDeath.Player_Jetpack_Blast => LanguageHandler.GetValuesByTag("DeathPlayerJetpackBlast"), 
				AdvancedCauseOfDeath.Player_Murder_Melee => LanguageHandler.GetValuesByTag("DeathPlayerMurderMelee"), 
				AdvancedCauseOfDeath.Player_Murder_Shotgun => LanguageHandler.GetValuesByTag("DeathPlayerMurderShotgun"), 
				AdvancedCauseOfDeath.Player_Quicksand => LanguageHandler.GetValuesByTag("DeathPlayerQuicksand"), 
				AdvancedCauseOfDeath.Player_StunGrenade => LanguageHandler.GetValuesByTag("DeathPlayerStunGrenade"), 
				AdvancedCauseOfDeath.Other_DepositItemsDesk => LanguageHandler.GetValuesByTag("DeathOtherDepositItemsDesk"), 
				AdvancedCauseOfDeath.Other_Dropship => LanguageHandler.GetValuesByTag("DeathOtherItemDropship"), 
				AdvancedCauseOfDeath.Other_Landmine => LanguageHandler.GetValuesByTag("DeathOtherLandmine"), 
				AdvancedCauseOfDeath.Other_Turret => LanguageHandler.GetValuesByTag("DeathOtherTurret"), 
				AdvancedCauseOfDeath.Other_Lightning => LanguageHandler.GetValuesByTag("DeathOtherLightning"), 
				_ => LanguageHandler.GetValuesByTag("DeathUnknown"), 
			};
		}

		internal static void SetCauseOfDeath(PlayerControllerB playerControllerB, object enemy_BaboonHawk)
		{
			throw new NotImplementedException();
		}
	}
	public enum AdvancedCauseOfDeath
	{
		Unknown,
		Bludgeoning,
		Gravity,
		Blast,
		Strangulation,
		Suffocation,
		Mauling,
		Gunshots,
		Crushing,
		Drowning,
		Abandoned,
		Electrocution,
		Kicking,
		Enemy_BaboonHawk,
		Enemy_Bracken,
		Enemy_CircuitBees,
		Enemy_CoilHead,
		Enemy_EarthLeviathan,
		Enemy_EyelessDog,
		Enemy_ForestGiant,
		Enemy_GhostGirl,
		Enemy_Hygrodere,
		Enemy_Jester,
		Enemy_SnareFlea,
		Enemy_SporeLizard,
		Enemy_HoarderBug,
		Enemy_Thumper,
		Enemy_BunkerSpider,
		Enemy_MaskedPlayer_Wear,
		Enemy_MaskedPlayer_Victim,
		Enemy_Nutcracker_Kicked,
		Enemy_Nutcracker_Shot,
		Player_Jetpack_Gravity,
		Player_Jetpack_Blast,
		Player_Quicksand,
		Player_Murder_Melee,
		Player_Murder_Shotgun,
		Player_StunGrenade,
		Other_Landmine,
		Other_Turret,
		Other_Lightning,
		Other_DepositItemsDesk,
		Other_Dropship
	}
	internal class DeathBroadcaster
	{
		private const string SIGNATURE_DEATH = "com.elitemastereric.coroner.death";

		public static void Initialize()
		{
			if (Plugin.Instance.IsLCAPIPresent)
			{
				DeathBroadcasterLCAPI.Initialize();
			}
			else
			{
				Plugin.Instance.PluginLogger.LogInfo("LC_API is not present! Skipping registration...");
			}
		}

		public static void BroadcastCauseOfDeath(int playerId, AdvancedCauseOfDeath causeOfDeath)
		{
			AttemptBroadcast(BuildDataCauseOfDeath(playerId, causeOfDeath), "com.elitemastereric.coroner.death");
		}

		private static string BuildDataCauseOfDeath(int playerId, AdvancedCauseOfDeath causeOfDeath)
		{
			string text = playerId.ToString();
			int num = (int)causeOfDeath;
			return text + "|" + num;
		}

		private static void AttemptBroadcast(string data, string signature)
		{
			if (Plugin.Instance.IsLCAPIPresent)
			{
				DeathBroadcasterLCAPI.AttemptBroadcast(data, signature);
			}
			else
			{
				Plugin.Instance.PluginLogger.LogInfo("LC_API is not present! Skipping broadcast...");
			}
		}
	}
	internal class LanguageHandler
	{
		public const string DEFAULT_LANGUAGE = "en";

		public static readonly string[] AVAILABLE_LANGUAGES = new string[4] { "en", "ru", "nl", "fr" };

		public const string TAG_FUNNY_NOTES = "FunnyNote";

		public const string TAG_UI_NOTES = "UINotes";

		public const string TAG_UI_DEATH = "UICauseOfDeath";

		public const string TAG_DEATH_GENERIC_BLUDGEONING = "DeathBludgeoning";

		public const string TAG_DEATH_GENERIC_GRAVITY = "DeathGravity";

		public const string TAG_DEATH_GENERIC_BLAST = "DeathBlast";

		public const string TAG_DEATH_GENERIC_STRANGULATION = "DeathStrangulation";

		public const string TAG_DEATH_GENERIC_SUFFOCATION = "DeathSuffocation";

		public const string TAG_DEATH_GENERIC_MAULING = "DeathMauling";

		public const string TAG_DEATH_GENERIC_GUNSHOTS = "DeathGunshots";

		public const string TAG_DEATH_GENERIC_CRUSHING = "DeathCrushing";

		public const string TAG_DEATH_GENERIC_DROWNING = "DeathDrowning";

		public const string TAG_DEATH_GENERIC_ABANDONED = "DeathAbandoned";

		public const string TAG_DEATH_GENERIC_ELECTROCUTION = "DeathElectrocution";

		public const string TAG_DEATH_GENERIC_KICKING = "DeathKicking";

		public const string TAG_DEATH_ENEMY_BRACKEN = "DeathEnemyBracken";

		public const string TAG_DEATH_ENEMY_EYELESS_DOG = "DeathEnemyEyelessDog";

		public const string TAG_DEATH_ENEMY_FOREST_GIANT = "DeathEnemyForestGiant";

		public const string TAG_DEATH_ENEMY_CIRCUIT_BEES = "DeathEnemyCircuitBees";

		public const string TAG_DEATH_ENEMY_GHOST_GIRL = "DeathEnemyGhostGirl";

		public const string TAG_DEATH_ENEMY_EARTH_LEVIATHAN = "DeathEnemyEarthLeviathan";

		public const string TAG_DEATH_ENEMY_BABOON_HAWK = "DeathEnemyBaboonHawk";

		public const string TAG_DEATH_ENEMY_JESTER = "DeathEnemyJester";

		public const string TAG_DEATH_ENEMY_COILHEAD = "DeathEnemyCoilHead";

		public const string TAG_DEATH_ENEMY_SNARE_FLEA = "DeathEnemySnareFlea";

		public const string TAG_DEATH_ENEMY_HYGRODERE = "DeathEnemyHygrodere";

		public const string TAG_DEATH_ENEMY_HOARDER_BUG = "DeathEnemyHoarderBug";

		public const string TAG_DEATH_ENEMY_SPORE_LIZARD = "DeathEnemySporeLizard";

		public const string TAG_DEATH_ENEMY_BUNKER_SPIDER = "DeathEnemyBunkerSpider";

		public const string TAG_DEATH_ENEMY_THUMPER = "DeathEnemyThumper";

		public const string TAG_DEATH_ENEMY_MASKED_PLAYER_WEAR = "DeathEnemyMaskedPlayerWear";

		public const string TAG_DEATH_ENEMY_MASKED_PLAYER_VICTIM = "DeathEnemyMaskedPlayerVictim";

		public const string TAG_DEATH_ENEMY_NUTCRACKER_KICKED = "DeathEnemyNutcrackerKicked";

		public const string TAG_DEATH_ENEMY_NUTCRACKER_SHOT = "DeathEnemyNutcrackerShot";

		public const string TAG_DEATH_PLAYER_JETPACK_GRAVITY = "DeathPlayerJetpackGravity";

		public const string TAG_DEATH_PLAYER_JETPACK_BLAST = "DeathPlayerJetpackBlast";

		public const string TAG_DEATH_PLAYER_MURDER_MELEE = "DeathPlayerMurderMelee";

		public const string TAG_DEATH_PLAYER_MURDER_SHOTGUN = "DeathPlayerMurderShotgun";

		public const string TAG_DEATH_PLAYER_QUICKSAND = "DeathPlayerQuicksand";

		public const string TAG_DEATH_PLAYER_STUN_GRENADE = "DeathPlayerStunGrenade";

		public const string TAG_DEATH_OTHER_DEPOSIT_ITEMS_DESK = "DeathOtherDepositItemsDesk";

		public const string TAG_DEATH_OTHER_ITEM_DROPSHIP = "DeathOtherItemDropship";

		public const string TAG_DEATH_OTHER_LANDMINE = "DeathOtherLandmine";

		public const string TAG_DEATH_OTHER_TURRET = "DeathOtherTurret";

		public const string TAG_DEATH_OTHER_LIGHTNING = "DeathOtherLightning";

		public const string TAG_DEATH_UNKNOWN = "DeathUnknown";

		private static XDocument languageData;

		public static void Initialize()
		{
			Plugin.Instance.PluginLogger.LogInfo("Coroner Language Support: " + Plugin.Instance.PluginConfig.GetSelectedLanguage());
			ValidateLanguage(Plugin.Instance.PluginConfig.GetSelectedLanguage());
			LoadLanguageData(Plugin.Instance.PluginConfig.GetSelectedLanguage());
		}

		private static void ValidateLanguage(string languageCode)
		{
			if (!AVAILABLE_LANGUAGES.Contains(languageCode))
			{
				Plugin.Instance.PluginLogger.LogWarning("Coroner Unknown language code: " + languageCode);
				Plugin.Instance.PluginLogger.LogWarning("Coroner There may be issues loading language data.");
			}
		}

		private static void LoadLanguageData(string languageCode)
		{
			try
			{
				languageData = XDocument.Load(Plugin.AssemblyDirectory + "/Strings_" + languageCode + ".xml");
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Coroner Error loading language data: " + ex.Message);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
				if (languageCode != "en")
				{
					LoadLanguageData("en");
				}
			}
		}

		public static string GetLanguageList()
		{
			return "(" + string.Join(", ", AVAILABLE_LANGUAGES) + ")";
		}

		public static string GetValueByTag(string tag)
		{
			return languageData.Descendants(tag).FirstOrDefault()?.Attribute("text")?.Value;
		}

		public static string[] GetValuesByTag(string tag)
		{
			IEnumerable<XElement> source = languageData.Descendants(tag);
			IEnumerable<string> source2 = source.Select((XElement item) => item.Attribute("text")?.Value);
			IEnumerable<string> source3 = source2.Where((string item) => item != null);
			return source3.ToArray();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_ID = "Coroner";

		public const string PLUGIN_NAME = "Coroner";

		public const string PLUGIN_AUTHOR = "EliteMasterEric";

		public const string PLUGIN_VERSION = "1.5.3";

		public const string PLUGIN_GUID = "com.elitemastereric.coroner";
	}
	[BepInPlugin("com.elitemastereric.coroner", "Coroner", "1.5.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static readonly Random RANDOM = new Random();

		public PluginLogger PluginLogger;

		public PluginConfig PluginConfig;

		public bool IsLCAPIPresent = false;

		public static Plugin Instance { get; private set; }

		public static string AssemblyDirectory
		{
			get
			{
				string codeBase = Assembly.GetExecutingAssembly().CodeBase;
				UriBuilder uriBuilder = new UriBuilder(codeBase);
				string path = Uri.UnescapeDataString(uriBuilder.Path);
				return Path.GetDirectoryName(path);
			}
		}

		private void Awake()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			Instance = this;
			PluginLogger = new PluginLogger(((BaseUnityPlugin)this).Logger, (LogLevel)16);
			Harmony val = new Harmony("com.elitemastereric.coroner");
			val.PatchAll();
			PluginLogger.LogInfo("Plugin Coroner (com.elitemastereric.coroner) is loaded!");
			LoadConfig();
			LanguageHandler.Initialize();
			QueryLCAPI();
			DeathBroadcaster.Initialize();
		}

		private void QueryLCAPI()
		{
			PluginLogger.LogInfo("Checking for LC_API...");
			if (Chainloader.PluginInfos.ContainsKey("LC_API"))
			{
				Chainloader.PluginInfos.TryGetValue("LC_API", out var value);
				if (value == null)
				{
					PluginLogger.LogError("Detected LC_API, but could not get plugin info!");
					IsLCAPIPresent = false;
				}
				else
				{
					PluginLogger.LogInfo("LCAPI is present! " + value.Metadata.GUID + ":" + value.Metadata.Version);
					IsLCAPIPresent = true;
				}
			}
			else
			{
				PluginLogger.LogInfo("LCAPI is not present.");
				IsLCAPIPresent = false;
			}
		}

		private void LoadConfig()
		{
			PluginConfig = new PluginConfig();
			PluginConfig.BindConfig(((BaseUnityPlugin)this).Config);
		}
	}
	public class PluginLogger
	{
		private ManualLogSource manualLogSource;

		private LogLevel logLevel;

		public PluginLogger(ManualLogSource manualLogSource, LogLevel logLevel = 16)
		{
			//IL_0010: 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)
			this.manualLogSource = manualLogSource;
			this.logLevel = logLevel;
		}

		public void LogFatal(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 1)
			{
				manualLogSource.LogFatal(data);
			}
		}

		public void LogError(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 2)
			{
				manualLogSource.LogError(data);
			}
		}

		public void LogWarning(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 4)
			{
				manualLogSource.LogWarning(data);
			}
		}

		public void LogMessage(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 8)
			{
				manualLogSource.LogMessage(data);
			}
		}

		public void LogInfo(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 16)
			{
				manualLogSource.LogInfo(data);
			}
		}

		public void LogDebug(object data)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			if ((int)logLevel >= 32)
			{
				manualLogSource.LogDebug(data);
			}
		}
	}
	public class PluginConfig
	{
		private ConfigEntry<bool> DisplayCauseOfDeath;

		private ConfigEntry<bool> SeriousDeathMessages;

		private ConfigEntry<bool> DisplayFunnyNotes;

		private ConfigEntry<bool> DeathReplacesNotes;

		private ConfigEntry<string> LanguagePicker;

		public void BindConfig(ConfigFile _config)
		{
			DisplayCauseOfDeath = _config.Bind<bool>("General", "DisplayCauseOfDeath", true, "Display the cause of death in the player notes.");
			SeriousDeathMessages = _config.Bind<bool>("General", "SeriousDeathMessages", false, "Cause of death messages are more to-the-point.");
			DisplayFunnyNotes = _config.Bind<bool>("General", "DisplayFunnyNotes", true, "Display a random note when the player has no notes.");
			DeathReplacesNotes = _config.Bind<bool>("General", "DeathReplacesNotes", true, "True to replace notes when the player dies, false to append.");
			LanguagePicker = _config.Bind<string>("Language", "LanguagePicker", "en", "Select a language to use " + LanguageHandler.GetLanguageList());
		}

		public bool ShouldDisplayCauseOfDeath()
		{
			return DisplayCauseOfDeath.Value;
		}

		public bool ShouldUseSeriousDeathMessages()
		{
			return SeriousDeathMessages.Value;
		}

		public bool ShouldDisplayFunnyNotes()
		{
			return DisplayFunnyNotes.Value;
		}

		public bool ShouldDeathReplaceNotes()
		{
			return DeathReplacesNotes.Value;
		}

		public string GetSelectedLanguage()
		{
			return LanguagePicker.Value;
		}
	}
}
namespace Coroner.Patch
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	[HarmonyPatch("KillPlayer")]
	internal class PlayerControllerBKillPlayerPatch
	{
		public static void Prefix(PlayerControllerB __instance, ref CauseOfDeath causeOfDeath)
		{
			try
			{
				if ((int)causeOfDeath == 300)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player died from item dropship! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Other_Dropship);
					causeOfDeath = (CauseOfDeath)8;
				}
				else if (__instance.isSinking && (int)causeOfDeath == 5)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player died of suffociation while sinking in quicksand! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Quicksand);
				}
				else if ((int)causeOfDeath != 3)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is dying! No cause of death registered in hook...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in PlayerControllerBKillPlayerPatch.Prefix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(DepositItemsDesk))]
	[HarmonyPatch("AnimationGrabPlayer")]
	internal class DepositItemsDeskAnimationGrabPlayerPatch
	{
		public static void Postfix(int playerID)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after tentacle devouring...");
				PlayerControllerB playerController = StartOfRound.Instance.allPlayerScripts[playerID];
				Plugin.Instance.PluginLogger.LogDebug("Player is dying! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(playerController, AdvancedCauseOfDeath.Other_DepositItemsDesk);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in DepositItemsDeskAnimationGrabPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(JesterAI))]
	[HarmonyPatch("killPlayerAnimation")]
	internal class JesterAIKillPlayerAnimationPatch
	{
		public static void Postfix(int playerId)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after Jester mauling...");
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerId];
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_Jester);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in JesterAIKillPlayerAnimationPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(SandWormAI))]
	[HarmonyPatch("EatPlayer")]
	internal class SandWormAIEatPlayerPatch
	{
		public static void Postfix(PlayerControllerB playerScript)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after Sand Worm devouring...");
				if ((Object)(object)playerScript == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(playerScript, AdvancedCauseOfDeath.Enemy_EarthLeviathan);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in SandWormAIEatPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(RedLocustBees))]
	[HarmonyPatch("BeeKillPlayerOnLocalClient")]
	internal class RedLocustBeesBeeKillPlayerOnLocalClientPatch
	{
		public static void Postfix(int playerId)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after Circuit Bee electrocution...");
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerId];
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (val.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_CircuitBees);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in RedLocustBeesBeeKillPlayerOnLocalClientPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(DressGirlAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class DressGirlAIOnCollideWithPlayerPatch
	{
		public static void Postfix(DressGirlAI __instance)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Processing Ghost Girl player collision...");
				if ((Object)(object)__instance.hauntingPlayer == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after collision!");
				}
				else if (__instance.hauntingPlayer.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(__instance.hauntingPlayer, AdvancedCauseOfDeath.Enemy_GhostGirl);
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in DressGirlAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(FlowermanAI))]
	[HarmonyPatch("killAnimation")]
	internal class FlowermanAIKillAnimationPatch
	{
		public static void Postfix(FlowermanAI __instance)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after Bracken snapping neck...");
				if ((Object)(object)((EnemyAI)__instance).inSpecialAnimationWithPlayer == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after snapping neck!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(((EnemyAI)__instance).inSpecialAnimationWithPlayer, AdvancedCauseOfDeath.Enemy_Bracken);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in FlowermanAIKillAnimationPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(ForestGiantAI))]
	[HarmonyPatch("EatPlayerAnimation")]
	internal class ForestGiantAIEatPlayerAnimationPatch
	{
		public static void Postfix(PlayerControllerB playerBeingEaten)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after Forest Giant devouring...");
				if ((Object)(object)playerBeingEaten == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(playerBeingEaten, AdvancedCauseOfDeath.Enemy_ForestGiant);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in ForestGiantAIEatPlayerAnimationPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(MouthDogAI))]
	[HarmonyPatch("KillPlayer")]
	internal class MouthDogAIKillPlayerPatch
	{
		public static void Postfix(int playerId)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Accessing state after dog devouring...");
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerId];
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_EyelessDog);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in MouthDogAIKillPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(CentipedeAI))]
	[HarmonyPatch("DamagePlayerOnIntervals")]
	internal class CentipedeAIDamagePlayerOnIntervalsPatch
	{
		public static void Postfix(CentipedeAI __instance)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Invalid comparison between Unknown and I4
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Snare Flea damage...");
				if ((Object)(object)__instance.clingingToPlayer == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player being clung to!");
				}
				else if (__instance.clingingToPlayer.isPlayerDead && (int)__instance.clingingToPlayer.causeOfDeath == 5)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(__instance.clingingToPlayer, AdvancedCauseOfDeath.Enemy_SnareFlea);
				}
				else if (__instance.clingingToPlayer.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player somehow died while attacked by Snare Flea! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in CentipedeAIDamagePlayerOnIntervalsPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(BaboonBirdAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class BaboonBirdAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Baboon Hawk damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_BaboonHawk);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in BaboonBirdAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	[HarmonyPatch("DamagePlayerFromOtherClientClientRpc")]
	internal class PlayerControllerBDamagePlayerFromOtherClientClientRpcPatch
	{
		public static void Postfix(PlayerControllerB __instance)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Invalid comparison between Unknown and I4
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Invalid comparison between Unknown and I4
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Invalid comparison between Unknown and I4
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling friendly fire damage...");
				if ((Object)(object)__instance == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access victim after death!");
				}
				else if (__instance.isPlayerDead)
				{
					if ((int)__instance.causeOfDeath == 1)
					{
						Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
						AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Murder_Melee);
					}
					else if ((int)__instance.causeOfDeath == 6)
					{
						Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
						AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Murder_Melee);
					}
					else if ((int)__instance.causeOfDeath == 7)
					{
						Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
						AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Murder_Shotgun);
					}
					else
					{
						Plugin.Instance.PluginLogger.LogWarning("Player was killed by someone else but we don't know how! " + ((object)(CauseOfDeath)(ref __instance.causeOfDeath)).ToString());
					}
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in PlayerControllerBDamagePlayerFromOtherClientClientRpcPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(PufferAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class PufferAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Spore Lizard damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_SporeLizard);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in PufferAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(SpringManAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class SpringManAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Coil Head damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_CoilHead);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in SpringManAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(BlobAI))]
	[HarmonyPatch("SlimeKillPlayerEffectServerRpc")]
	internal class BlobAISlimeKillPlayerEffectServerRpcPatch
	{
		public static void Postfix(int playerKilled)
		{
			try
			{
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerKilled];
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (val.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_Hygrodere);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in BlobAISlimeKillPlayerEffectServerRpcPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(HoarderBugAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class HoarderBugAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Hoarder Bug damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_HoarderBug);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in HoarderBugAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(CrawlerAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class CrawlerAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Thumper damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_Thumper);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in CrawlerAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(SandSpiderAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class SandSpiderAIOnCollideWithPlayerPatch
	{
		public static void Postfix(Collider other)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling Bunker Spider damage...");
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (component.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_BunkerSpider);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in SandSpiderAIOnCollideWithPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(NutcrackerEnemyAI))]
	[HarmonyPatch("LegKickPlayer")]
	internal class NutcrackerEnemyAILegKickPlayerPatch
	{
		public static void Postfix(int playerId)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Nutcracker kicked a player to death!");
				PlayerControllerB playerController = StartOfRound.Instance.allPlayerScripts[playerId];
				Plugin.Instance.PluginLogger.LogDebug("Player is dying! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(playerController, AdvancedCauseOfDeath.Enemy_Nutcracker_Kicked);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in NutcrackerEnemyAILegKickPlayerPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(ShotgunItem))]
	[HarmonyPatch("ShootGun")]
	internal class ShotgunItemShootGunPatch
	{
		public static void Postfix(ShotgunItem __instance)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Invalid comparison between Unknown and I4
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Handling shotgun shot...");
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if ((Object)(object)localPlayerController == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access local player after shotgun shot!");
				}
				else if (localPlayerController.isPlayerDead && (int)localPlayerController.causeOfDeath == 7)
				{
					if (((GrabbableObject)__instance).isHeldByEnemy)
					{
						Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
						AdvancedDeathTracker.SetCauseOfDeath(localPlayerController, AdvancedCauseOfDeath.Enemy_Nutcracker_Shot);
					}
					else
					{
						Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
						AdvancedDeathTracker.SetCauseOfDeath(localPlayerController, AdvancedCauseOfDeath.Player_Murder_Shotgun);
					}
				}
				else if (localPlayerController.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogWarning("Player died while attacked by shotgun? Skipping... " + ((object)(CauseOfDeath)(ref localPlayerController.causeOfDeath)).ToString());
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in ShotgunItemShootGunPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(MaskedPlayerEnemy))]
	[HarmonyPatch("killAnimation")]
	internal class MaskedPlayerEnemykillAnimationPatch
	{
		public static void Postfix(MaskedPlayerEnemy __instance)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Masked Player killed someone...");
				PlayerControllerB inSpecialAnimationWithPlayer = ((EnemyAI)__instance).inSpecialAnimationWithPlayer;
				if ((Object)(object)inSpecialAnimationWithPlayer == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
					return;
				}
				Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
				AdvancedDeathTracker.SetCauseOfDeath(inSpecialAnimationWithPlayer, AdvancedCauseOfDeath.Enemy_MaskedPlayer_Victim);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in MaskedPlayerEnemykillAnimationPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(HauntedMaskItem))]
	[HarmonyPatch("FinishAttaching")]
	internal class HauntedMaskItemFinishAttachingPatch
	{
		public static void Postfix(HauntedMaskItem __instance)
		{
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Masked Player killed someone...");
				PlayerControllerB value = Traverse.Create((object)__instance).Field("previousPlayerHeldBy").GetValue<PlayerControllerB>();
				if ((Object)(object)value == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!");
				}
				else if (value.isPlayerDead)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(value, AdvancedCauseOfDeath.Enemy_MaskedPlayer_Wear);
				}
				else
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping...");
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in HauntedMaskItemFinishAttachingPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(ExtensionLadderItem))]
	[HarmonyPatch("StartLadderAnimation")]
	internal class ExtensionLadderItemStartLadderAnimationPatch
	{
		public static void Postfix(ExtensionLadderItem __instance)
		{
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Extension ladder started animation! Modifying kill trigger...");
				GameObject gameObject = ((Component)__instance).gameObject;
				if ((Object)(object)gameObject == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch GameObject from ExtensionLadderItem.");
				}
				Transform val = gameObject.transform.Find("AnimContainer/MeshContainer/LadderMeshContainer/BaseLadder/LadderSecondPart/KillTrigger");
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger Transform from ExtensionLadderItem.");
				}
				GameObject gameObject2 = ((Component)val).gameObject;
				if ((Object)(object)gameObject2 == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger GameObject from ExtensionLadderItem.");
				}
				KillLocalPlayer component = gameObject2.GetComponent<KillLocalPlayer>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillLocalPlayer from KillTrigger GameObject.");
				}
				component.causeOfDeath = (CauseOfDeath)8;
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in ExtensionLadderItemStartLadderAnimationPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(ItemDropship))]
	[HarmonyPatch("Start")]
	internal class ItemDropshipStartPatch
	{
		public static void Postfix(ItemDropship __instance)
		{
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Plugin.Instance.PluginLogger.LogDebug("Item dropship spawned! Modifying kill trigger...");
				GameObject gameObject = ((Component)__instance).gameObject;
				if ((Object)(object)gameObject == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch GameObject from ItemDropship.");
				}
				Transform val = gameObject.transform.Find("ItemShip/KillTrigger");
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger Transform from ItemDropship.");
				}
				GameObject gameObject2 = ((Component)val).gameObject;
				if ((Object)(object)gameObject2 == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger GameObject from ItemDropship.");
				}
				KillLocalPlayer component = gameObject2.GetComponent<KillLocalPlayer>();
				if ((Object)(object)component == (Object)null)
				{
					Plugin.Instance.PluginLogger.LogError("Could not fetch KillLocalPlayer from KillTrigger GameObject.");
				}
				component.causeOfDeath = (CauseOfDeath)300;
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in ItemDropshipStartPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}
	}
	[HarmonyPatch(typeof(Turret))]
	[HarmonyPatch("Update")]
	public class TurretUpdatePatch
	{
		public static void Postfix(Turret __instance)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			if ((int)__instance.turretMode == 2)
			{
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if (localPlayerController.isPlayerDead && (int)localPlayerController.causeOfDeath == 7)
				{
					Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death...");
					AdvancedDeathTracker.SetCauseOfDeath(localPlayerController, AdvancedCauseOfDeath.Other_Turret);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Landmine))]
	[HarmonyPatch("SpawnExplosion")]
	public class LandmineSpawnExplosionPatch
	{
		private const string KILL_PLAYER_SIGNATURE = "Void KillPlayer(UnityEngine.Vector3, Boolean, CauseOfDeath, Int32)";

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase method)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			List<CodeInstruction> list2 = BuildInstructionsToInsert(method);
			if (list2 == null)
			{
				Plugin.Instance.PluginLogger.LogError("Could not build instructions to insert in LandmineSpawnExplosionPatch! Safely aborting...");
				return instructions;
			}
			int num = -1;
			for (int i = 0; i < list.Count; i++)
			{
				CodeInstruction val = list[i];
				if (val.opcode == OpCodes.Callvirt && val.operand.ToString() == "Void KillPlayer(UnityEngine.Vector3, Boolean, CauseOfDeath, Int32)")
				{
					num = i;
					break;
				}
			}
			if (num == -1)
			{
				Plugin.Instance.PluginLogger.LogError("Could not find PlayerControllerB.KillPlayer call in LandmineSpawnExplosionPatch! Safely aborting...");
				return instructions;
			}
			Plugin.Instance.PluginLogger.LogInfo("Injecting patch into Landmine.SpawnExplosion...");
			list.InsertRange(num, list2);
			Plugin.Instance.PluginLogger.LogInfo("Done.");
			return list;
		}

		private static List<CodeInstruction> BuildInstructionsToInsert(MethodBase method)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: 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_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			int num = 2;
			IList<LocalVariableInfo> localVariables = method.GetMethodBody().LocalVariables;
			LocalVariableInfo localVariableInfo = null;
			for (int i = 0; i < localVariables.Count; i++)
			{
				LocalVariableInfo localVariableInfo2 = localVariables[i];
				if (localVariableInfo2.LocalType == typeof(PlayerControllerB))
				{
					if (localVariableInfo != null)
					{
						Plugin.Instance.PluginLogger.LogError("Found multiple PlayerControllerB local variables in LandmineSpawnExplosionPatch!");
						return null;
					}
					localVariableInfo = localVariableInfo2;
					break;
				}
			}
			list.Add(new CodeInstruction(OpCodes.Ldloc_S, (object)localVariableInfo.LocalIndex));
			list.Add(new CodeInstruction(OpCodes.Ldarg, (object)num));
			list.Add(new CodeInstruction(OpCodes.Call, (object)typeof(LandmineSpawnExplosionPatch).GetMethod("RewriteCauseOfDeath")));
			return list;
		}

		public static void RewriteCauseOfDeath(PlayerControllerB targetPlayer, float killRange)
		{
			AdvancedCauseOfDeath causeOfDeath = AdvancedCauseOfDeath.Blast;
			if (killRange == 5f)
			{
				causeOfDeath = AdvancedCauseOfDeath.Player_Jetpack_Blast;
			}
			else if (killRange == 5.7f)
			{
				causeOfDeath = AdvancedCauseOfDeath.Other_Landmine;
			}
			else if (killRange == 2.4f)
			{
				causeOfDeath = AdvancedCauseOfDeath.Other_Lightning;
			}
			AdvancedDeathTracker.SetCauseOfDeath(targetPlayer, causeOfDeath);
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	[HarmonyPatch("FillEndGameStats")]
	internal class HUDManagerFillEndGameStatsPatch
	{
		private const string EMPTY_NOTES = "Notes: \n";

		public static void Postfix(HUDManager __instance)
		{
			try
			{
				OverridePerformanceReport(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Instance.PluginLogger.LogError("Error in HUDManagerFillEndGameStatsPatch.Postfix: " + ex);
				Plugin.Instance.PluginLogger.LogError(ex.StackTrace);
			}
		}

		private static Random BuildSyncedRandom()
		{
			int randomMapSeed = StartOfRound.Instance.randomMapSeed;
			Plugin.Instance.PluginLogger.LogDebug("Syncing randomization to map seed: '" + randomMapSeed + "'");
			return new Random(randomMapSeed);
		}

		private static void OverridePerformanceReport(HUDManager __instance)
		{
			Plugin.Instance.PluginLogger.LogDebug("Applying Coroner patches to player notes...");
			Random random = BuildSyncedRandom();
			for (int i = 0; i < __instance.statsUIElements.playerNotesText.Length; i++)
			{
				PlayerControllerB val = __instance.playersManager.allPlayerScripts[i];
				if (!val.disconnectedMidGame && !val.isPlayerDead && !val.isPlayerControlled)
				{
					Plugin.Instance.PluginLogger.LogInfo("Player " + i + " is not controlled by a player. Skipping...");
					continue;
				}
				TextMeshProUGUI val2 = __instance.statsUIElements.playerNotesText[i];
				if (val.isPlayerDead)
				{
					if (Plugin.Instance.PluginConfig.ShouldDisplayCauseOfDeath())
					{
						if (Plugin.Instance.PluginConfig.ShouldDeathReplaceNotes())
						{
							Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " is dead! Replacing notes with Cause of Death...");
							((TMP_Text)val2).text = LanguageHandler.GetValueByTag("UICauseOfDeath") + "\n";
						}
						else
						{
							Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " is dead! Appending notes with Cause of Death...");
						}
						AdvancedCauseOfDeath causeOfDeath = AdvancedDeathTracker.GetCauseOfDeath(val);
						((TMP_Text)val2).text = ((TMP_Text)val2).text + "* " + AdvancedDeathTracker.StringifyCauseOfDeath(causeOfDeath, random) + "\n";
					}
					else
					{
						Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " is dead, but Config says leave it be...");
					}
				}
				else if (((TMP_Text)val2).text == "Notes: \n")
				{
					if (Plugin.Instance.PluginConfig.ShouldDisplayFunnyNotes())
					{
						Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " has no notes! Injecting something funny...");
						((TMP_Text)val2).text = LanguageHandler.GetValueByTag("UINotes") + "\n";
						((TMP_Text)val2).text = ((TMP_Text)val2).text + "* " + AdvancedDeathTracker.StringifyCauseOfDeath(null, random) + "\n";
					}
					else
					{
						Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " has no notes, but Config says leave it be...");
					}
				}
				else
				{
					Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " has notes, don't override them...");
				}
			}
			AdvancedDeathTracker.ClearDeathTracker();
		}
	}
}
namespace Coroner.LCAPI
{
	internal class DeathBroadcasterLCAPI
	{
		private const string SIGNATURE_DEATH = "com.elitemastereric.coroner.death";

		public static void Initialize()
		{
			Plugin.Instance.PluginLogger.LogDebug("Initializing DeathBroadcaster...");
			if (Plugin.Instance.IsLCAPIPresent)
			{
				Plugin.Instance.PluginLogger.LogDebug("LC_API is present! Registering signature...");
				Networking.GetString = (Action<string, string>)Delegate.Combine(Networking.GetString, new Action<string, string>(OnBroadcastString));
			}
			else
			{
				Plugin.Instance.PluginLogger.LogError("LC_API is not present! Why did you try to register the DeathBroadcaster?");
			}
		}

		private static void OnBroadcastString(string data, string signature)
		{
			if (signature == "com.elitemastereric.coroner.death")
			{
				Plugin.Instance.PluginLogger.LogDebug("Broadcast has been received from LC_API!");
				string[] array = data.Split('|');
				int playerIndex = int.Parse(array[0]);
				int num = int.Parse(array[1]);
				AdvancedCauseOfDeath advancedCauseOfDeath = (AdvancedCauseOfDeath)num;
				Plugin.Instance.PluginLogger.LogDebug("Player " + playerIndex + " died of " + AdvancedDeathTracker.StringifyCauseOfDeath((AdvancedCauseOfDeath?)advancedCauseOfDeath));
				AdvancedDeathTracker.SetCauseOfDeath(playerIndex, advancedCauseOfDeath, broadcast: false);
			}
		}

		public static void AttemptBroadcast(string data, string signature)
		{
			if (Plugin.Instance.IsLCAPIPresent)
			{
				Plugin.Instance.PluginLogger.LogDebug("LC_API is present! Broadcasting...");
				Networking.Broadcast(data, signature);
			}
			else
			{
				Plugin.Instance.PluginLogger.LogDebug("LC_API is not present! Skipping broadcast...");
			}
		}
	}
}

BepInEx/plugins/FlipMods-LetMeLookDown/LetMeLookDown.dll

Decompiled 10 months 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.1")]
	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();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LetMeLookDown mod loaded");
			instance = this;
		}

		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.1";
	}
}
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/FlipMods-TooManyEmotes/TooManyEmotes.dll

Decompiled 10 months 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.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using Dissonance.Integrations.Unity_NFGO;
using GameNetcodeStuff;
using HarmonyLib;
using MoreCompany.Cosmetics;
using TMPro;
using TooManyEmotes.Config;
using TooManyEmotes.Networking;
using TooManyEmotes.Patches;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Animations.Rigging;
using UnityEngine.EventSystems;
using UnityEngine.Experimental.Rendering;
using UnityEngine.InputSystem;
using UnityEngine.Rendering;
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: AssemblyTitle("TooManyEmotes")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TooManyEmotes")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("d6950625-e3a1-4896-a183-87110491bf18")]
[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 TooManyEmotes
{
	[HarmonyPatch]
	public static class EmoteMenuManager
	{
		public static GameObject menuGameObject;

		public static RectTransform menuTransform;

		public static CanvasGroup canvasGroup;

		public static RawImage renderTextureImageUI;

		public static TextMeshPro swapPageText;

		public static TextMeshPro currentEmoteText;

		public static RenderTexture renderTexture;

		public static Camera renderingCamera;

		public static GameObject previewPlayerObject;

		public static SkinnedMeshRenderer previewPlayerMesh;

		public static Animator previewPlayerAnimator;

		public static AnimatorOverrideController previewPlayerAnimatorController;

		public static int playerLayer = LayerMask.NameToLayer("Player");

		public static float hoveredAlpha = 0.75f;

		public static float unhoveredAlpha = 0.75f;

		public static Color defaultUIColor = new Color(0.3f, 0.3f, 0.3f);

		public static List<EmoteUIElement> emoteUIElementsList;

		public static int hoveredEmoteUIIndex = -1;

		public static int currentPage = 0;

		public static List<EmoteLoadoutUIElement> emoteLoadoutUIElementsList;

		public static List<List<UnlockableEmote>> emoteLoadouts;

		public static Color selectedLoadoutUIColor = new Color(0.2f, 0.2f, 1f);

		public static int currentLoadoutIndex = -1;

		public static int numLoadouts = 3;

		public static int hoveredLoadoutUIIndex = -1;

		public static QuickMenuManager quickMenuManager => StartOfRound.Instance?.localPlayerController?.quickMenuManager;

		public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController;

		public static int playerLayerMask => 1 << playerLayer;

		public static int hoveredEmoteIndex => (hoveredEmoteUIIndex >= 0) ? (hoveredEmoteUIIndex + 8 * currentPage) : (-1);

		public static int numPages => Mathf.Max((currentLoadoutEmotesList.Count - 1) / emoteUIElementsList.Count, 0) + 1;

		public static UnlockableEmote previewingEmote => (hoveredEmoteIndex >= 0 && hoveredEmoteIndex < currentLoadoutEmotesList.Count) ? currentLoadoutEmotesList[hoveredEmoteIndex] : null;

		public static List<UnlockableEmote> currentLoadoutEmotesList => emoteLoadouts[currentLoadoutIndex];

		public static bool isMenuOpen => menuGameObject.activeSelf;

		[HarmonyPatch(typeof(HUDManager), "Start")]
		[HarmonyPostfix]
		public static void InitializeUI(HUDManager __instance)
		{
			if (!((Object)(object)Plugin.radialMenuPrefab == (Object)null))
			{
				menuGameObject = Object.Instantiate<GameObject>(Plugin.radialMenuPrefab, __instance.HUDContainer.transform.parent);
				menuGameObject.transform.SetAsLastSibling();
				((Object)menuGameObject).name = "EmotesRadialMenu";
				menuTransform = menuGameObject.GetComponent<RectTransform>();
				renderTextureImageUI = menuGameObject.GetComponentInChildren<RawImage>();
				Transform transform = ((Component)((Transform)menuTransform).Find("RadialMenuUI/RadialElements")).transform;
				swapPageText = ((Component)((Transform)menuTransform).Find("RadialMenuUI/RadialBase/SwapPageText")).GetComponent<TextMeshPro>();
				currentEmoteText = ((Component)((Transform)menuTransform).Find("RadialMenuUI/RadialBase/CurrentEmoteText")).GetComponent<TextMeshPro>();
				((TMP_Text)currentEmoteText).text = "";
				emoteUIElementsList = new List<EmoteUIElement>();
				currentPage = 0;
				hoveredEmoteUIIndex = -1;
				for (int i = 0; i < transform.childCount; i++)
				{
					Transform child = transform.GetChild(i);
					EmoteUIElement item = new EmoteUIElement
					{
						uiGameObject = ((Component)child).gameObject,
						id = i,
						backgroundImage = ((Component)child).GetComponentInChildren<Image>(),
						textContainer = ((Component)child).GetComponentInChildren<TextMeshPro>()
					};
					emoteUIElementsList.Add(item);
				}
				EmoteLoadoutUIElement.uiCount = 0;
				Transform transform2 = ((Component)((Transform)menuTransform).Find("RadialMenuUI/EmoteLoadouts")).transform;
				((Component)transform2).gameObject.AddComponent<EmoteLoadoutUIContainer>();
				emoteLoadoutUIElementsList = new List<EmoteLoadoutUIElement>();
				emoteLoadoutUIElementsList.Add(((Component)transform2.GetChild(0)).gameObject.AddComponent<EmoteLoadoutUIElement>());
				emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2));
				emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2));
				emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2));
				emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2));
				emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2));
				emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2));
				for (int j = 0; j < emoteLoadoutUIElementsList.Count; j++)
				{
					((Object)emoteLoadoutUIElementsList[j]).name = "EmoteLoadout_" + j;
				}
				emoteLoadoutUIElementsList[0].loadoutName = "Favorites";
				emoteLoadoutUIElementsList[1].loadoutName = $"<color={UnlockableEmote.rarityColorCodes[3]}>Legendary</color>";
				emoteLoadoutUIElementsList[2].loadoutName = $"<color={UnlockableEmote.rarityColorCodes[2]}>Rare</color>";
				emoteLoadoutUIElementsList[3].loadoutName = $"<color={UnlockableEmote.rarityColorCodes[1]}>Uncommon</color>";
				emoteLoadoutUIElementsList[4].loadoutName = $"<color={UnlockableEmote.rarityColorCodes[0]}>Common</color>";
				emoteLoadoutUIElementsList[5].loadoutName = "Complementary";
				emoteLoadoutUIElementsList[6].loadoutName = "All";
				SaveManager.LoadFavoritedEmotes();
				emoteLoadouts = new List<List<UnlockableEmote>>
				{
					StartOfRoundPatcher.unlockedFavoriteEmotes,
					StartOfRoundPatcher.unlockedEmotesTier3,
					StartOfRoundPatcher.unlockedEmotesTier2,
					StartOfRoundPatcher.unlockedEmotesTier1,
					StartOfRoundPatcher.unlockedEmotesTier0,
					StartOfRoundPatcher.complementaryEmotes,
					StartOfRoundPatcher.unlockedEmotes
				};
				if (currentLoadoutIndex < 0 || currentLoadoutIndex >= emoteLoadouts.Count)
				{
					currentLoadoutIndex = emoteLoadouts.Count - 1;
				}
				InitializeAnimationRenderer();
				menuGameObject.SetActive(false);
			}
		}

		[HarmonyPatch(typeof(HUDManager), "Update")]
		[HarmonyPostfix]
		public static void GetInput()
		{
			//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_0080: 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_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_00ac: 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)
			if ((Object)(object)previewPlayerAnimatorController == (Object)null || !isMenuOpen)
			{
				return;
			}
			if (EmoteLoadoutUIContainer.hovered || hoveredLoadoutUIIndex != -1)
			{
				if (hoveredEmoteUIIndex != -1)
				{
					OnHoveredNewElement(-1);
				}
				return;
			}
			Vector2 val = ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue();
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor((float)(Screen.width / 2), (float)(Screen.height / 2));
			Vector2 val3 = val - val2;
			int num = -1;
			if (((Vector2)(ref val3)).magnitude / (float)Screen.height >= 0.17f)
			{
				float num2 = Mathf.Atan2(val3.y, 0f - val3.x) * 57.29578f - 67.5f;
				if (num2 < 0f)
				{
					num2 += 360f;
				}
				num = Mathf.FloorToInt(num2 / 45f);
			}
			if (num != hoveredEmoteUIIndex)
			{
				OnHoveredNewElement(num);
			}
		}

		public static void OnHoveredNewLoadoutElement(int index)
		{
			if (hoveredLoadoutUIIndex == index)
			{
				return;
			}
			hoveredLoadoutUIIndex = index;
			foreach (EmoteLoadoutUIElement emoteLoadoutUIElements in emoteLoadoutUIElementsList)
			{
				emoteLoadoutUIElements.OnHover(emoteLoadoutUIElements.id == index);
			}
		}

		public static void OnHoveredNewElement(int index)
		{
			if (hoveredEmoteUIIndex != -1 && hoveredEmoteUIIndex != index)
			{
				emoteUIElementsList[hoveredEmoteUIIndex].OnHover(hovered: false);
			}
			if (index != -1)
			{
				emoteUIElementsList[index].OnHover();
			}
			hoveredEmoteUIIndex = index;
			SetPreviewAnimation(hoveredEmoteIndex);
		}

		public static void SwapPrevPage()
		{
			currentPage--;
			if (currentPage < 0)
			{
				currentPage = numPages - 1;
			}
			UpdateEmoteWheel();
		}

		public static void SwapNextPage()
		{
			currentPage++;
			if (currentPage >= numPages)
			{
				currentPage = 0;
			}
			UpdateEmoteWheel();
		}

		public static void UpdateEmoteWheel()
		{
			//IL_00b8: 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_010f: 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)
			currentPage = Mathf.Clamp(currentPage, 0, numPages - 1);
			((TMP_Text)swapPageText).text = $"[{currentPage + 1} / {numPages}]\n[Mouse Scroll]";
			for (int i = 0; i < emoteLoadoutUIElementsList.Count; i++)
			{
				EmoteLoadoutUIElement emoteLoadoutUIElement = emoteLoadoutUIElementsList[i];
				emoteLoadoutUIElement.OnHover(hoveredLoadoutUIIndex == emoteLoadoutUIElement.id);
			}
			for (int j = 0; j < emoteUIElementsList.Count; j++)
			{
				EmoteUIElement emoteUIElement = emoteUIElementsList[j];
				int num = j + 8 * currentPage;
				((TMP_Text)emoteUIElement.textContainer).text = "";
				emoteUIElement.emote = null;
				Color baseColor = defaultUIColor;
				if (num < currentLoadoutEmotesList.Count)
				{
					UnlockableEmote unlockableEmote = currentLoadoutEmotesList[num];
					if (unlockableEmote != null)
					{
						emoteUIElement.emote = unlockableEmote;
						((TMP_Text)emoteUIElement.textContainer).text = unlockableEmote.displayName;
					}
				}
				emoteUIElement.baseColor = baseColor;
				emoteUIElement.OnHover(hovered: false);
			}
			if (hoveredEmoteUIIndex >= 0 && hoveredEmoteUIIndex < 8)
			{
				OnHoveredNewElement(hoveredEmoteUIIndex);
			}
		}

		public static void SetPreviewAnimation(int emoteIndex)
		{
			if (emoteIndex >= 0 && emoteIndex < currentLoadoutEmotesList.Count && currentLoadoutEmotesList[emoteIndex] != null)
			{
				UnlockableEmote unlockableEmote = currentLoadoutEmotesList[emoteIndex];
				previewPlayerObject.SetActive(true);
				((Behaviour)renderingCamera).enabled = true;
				previewPlayerAnimatorController["EmoteStart"] = unlockableEmote.animationClip;
				previewPlayerAnimatorController["EmoteLoop"] = (((Object)(object)unlockableEmote.transitionsToClip != (Object)null) ? unlockableEmote.transitionsToClip : null);
				previewPlayerAnimator.SetBool("hasTransition", (Object)(object)unlockableEmote.transitionsToClip != (Object)null);
				previewPlayerAnimator.Play("EmoteStart", 0, 0f);
				((TMP_Text)currentEmoteText).text = "[" + unlockableEmote.displayNameColorCoded + "]\n[MMB] " + (StartOfRoundPatcher.allFavoriteEmotes.Contains(unlockableEmote.emoteName) ? "Unfavorite" : "Favorite");
			}
			else
			{
				previewPlayerAnimatorController["EmoteStart"] = null;
				previewPlayerAnimatorController["EmoteLoop"] = null;
				previewPlayerObject.SetActive(false);
				((TMP_Text)currentEmoteText).text = "";
				DisableRenderCameraNextFrame();
			}
		}

		public static void DisableRenderCameraNextFrame()
		{
			((MonoBehaviour)HUDManager.Instance).StartCoroutine(DisableRenderCameraNextFrameCoroutine());
			static IEnumerator DisableRenderCameraNextFrameCoroutine()
			{
				yield return null;
				((Behaviour)renderingCamera).enabled = false;
			}
		}

		public static void SetCurrentEmoteLoadout(int loadoutIndex)
		{
			if (currentLoadoutIndex != loadoutIndex)
			{
				currentPage = 0;
				currentLoadoutIndex = loadoutIndex;
				UpdateEmoteWheel();
			}
		}

		public static void ToggleFavoriteHoveredEmote()
		{
			if (isMenuOpen && previewingEmote != null)
			{
				string emoteName = previewingEmote.emoteName;
				if (StartOfRoundPatcher.allFavoriteEmotes.Contains(emoteName))
				{
					StartOfRoundPatcher.allFavoriteEmotes.Remove(emoteName);
				}
				else
				{
					StartOfRoundPatcher.allFavoriteEmotes.Add(emoteName);
				}
				StartOfRoundPatcher.UpdateUnlockedFavoriteEmotes();
				SaveManager.SaveFavoritedEmotes();
				UpdateEmoteWheel();
			}
		}

		public static void ToggleEmoteMenu()
		{
			if (!isMenuOpen)
			{
				OpenEmoteMenu();
			}
			else
			{
				CloseEmoteMenu();
			}
		}

		public static void OpenEmoteMenu()
		{
			menuGameObject.SetActive(true);
			Cursor.lockState = (CursorLockMode)0;
			Cursor.visible = true;
			quickMenuManager.isMenuOpen = true;
			((Renderer)previewPlayerMesh).material = ((Renderer)localPlayerController.thisPlayerModel).material;
			UpdateEmoteWheel();
		}

		public static void CloseEmoteMenu()
		{
			Cursor.lockState = (CursorLockMode)1;
			Cursor.visible = false;
			localPlayerController.isFreeCamera = false;
			menuGameObject.SetActive(false);
			quickMenuManager.CloseQuickMenu();
		}

		public static bool CanOpenEmoteMenu()
		{
			if ((quickMenuManager.isMenuOpen && !isMenuOpen) || (Object)(object)previewPlayerObject == (Object)null)
			{
				return false;
			}
			if (localPlayerController.isPlayerDead || localPlayerController.inTerminalMenu || localPlayerController.isTypingChat || localPlayerController.isPlayerDead || localPlayerController.inSpecialInteractAnimation || localPlayerController.inShockingMinigame || localPlayerController.isClimbingLadder || localPlayerController.isSinking)
			{
				return false;
			}
			return true;
		}

		private static void InitializeAnimationRenderer()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			//IL_00ee: 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_0118: 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_0162: 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)
			renderingCamera = new GameObject("AnimationRenderingCamera").AddComponent<Camera>();
			Object.Destroy((Object)(object)((Component)renderingCamera).GetComponent<AudioListener>());
			renderingCamera.cullingMask = playerLayerMask;
			renderingCamera.clearFlags = (CameraClearFlags)2;
			renderingCamera.cameraType = (CameraType)4;
			renderingCamera.backgroundColor = new Color(0.1f, 0.1f, 0.1f, 0f);
			renderingCamera.allowHDR = false;
			renderingCamera.allowMSAA = false;
			renderingCamera.farClipPlane = 5f;
			renderTexture = new RenderTexture(1024, 1024, 24);
			renderTexture.format = (RenderTextureFormat)0;
			renderTexture.graphicsFormat = (GraphicsFormat)8;
			renderTexture.depthStencilFormat = (GraphicsFormat)92;
			renderingCamera.targetTexture = renderTexture;
			((Component)renderingCamera).transform.position = Vector3.down * 1000f;
			renderTextureImageUI.texture = (Texture)(object)renderTexture;
			Light val = new GameObject("Spotlight").AddComponent<Light>();
			val.type = (LightType)0;
			((Component)val).transform.position = ((Component)renderingCamera).transform.position;
			((Component)val).transform.parent = ((Component)renderingCamera).transform;
			((Component)val).transform.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity);
			val.intensity = 50f;
			val.range = 40f;
			val.innerSpotAngle = 100f;
			val.spotAngle = 120f;
			((Component)val).gameObject.layer = playerLayer;
			DisableRenderCameraNextFrame();
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void InitializePlayerCloneRenderObject(PlayerControllerB __instance)
		{
			if (!((Object)(object)Plugin.radialMenuPrefab == (Object)null))
			{
				((MonoBehaviour)__instance).StartCoroutine(InitPlayerCloneAfterSpawnAnimation());
			}
			IEnumerator InitPlayerCloneAfterSpawnAnimation()
			{
				yield return (object)new WaitForSeconds(2f);
				previewPlayerObject = Object.Instantiate<GameObject>(((Component)__instance).gameObject, ((Component)renderingCamera).transform);
				((Object)previewPlayerObject).name = "PreviewPlayerAnimationObject";
				GameObject modelGameObject = ((Component)previewPlayerObject.transform.Find("ScavengerModel")).gameObject;
				GameObject metarigGameObject = ((Component)modelGameObject.transform.Find("metarig")).gameObject;
				PlayerControllerB copyPlayerController = previewPlayerObject.GetComponentInChildren<PlayerControllerB>();
				((Renderer)copyPlayerController.thisPlayerModel).shadowCastingMode = (ShadowCastingMode)1;
				previewPlayerMesh = copyPlayerController.thisPlayerModel;
				Object.Destroy((Object)(object)modelGameObject.GetComponentInChildren<LODGroup>());
				Object.DestroyImmediate((Object)(object)metarigGameObject.GetComponentInChildren<RigBuilder>());
				Object.DestroyImmediate((Object)(object)copyPlayerController.playerBodyAnimator);
				previewPlayerAnimator = metarigGameObject.AddComponent<Animator>();
				previewPlayerAnimatorController = new AnimatorOverrideController(Plugin.previewAnimatorController);
				previewPlayerAnimator.runtimeAnimatorController = (RuntimeAnimatorController)(object)previewPlayerAnimatorController;
				previewPlayerAnimator.Play("EmoteStart", 0, 0f);
				Object.Destroy((Object)(object)previewPlayerObject.GetComponent<NfgoPlayer>());
				foreach (Transform item in previewPlayerObject.transform)
				{
					Transform child3 = item;
					if (((Object)child3).name != "ScavengerModel")
					{
						Object.Destroy((Object)(object)((Component)child3).gameObject);
					}
				}
				foreach (Transform item2 in modelGameObject.transform)
				{
					Transform child2 = item2;
					if (((Object)child2).name != "LOD1" && ((Object)child2).name != "metarig")
					{
						Object.Destroy((Object)(object)((Component)child2).gameObject);
					}
				}
				foreach (Transform item3 in metarigGameObject.transform)
				{
					Transform child = item3;
					if (((Object)child).name != "spine")
					{
						Object.Destroy((Object)(object)((Component)child).gameObject);
					}
				}
				previewPlayerObject.transform.position = ((Component)renderingCamera).transform.position + ((Component)renderingCamera).transform.forward * 2.8f + Vector3.down * 1.35f;
				previewPlayerObject.transform.LookAt(new Vector3(((Component)renderingCamera).transform.position.x, previewPlayerObject.transform.position.y, ((Component)renderingCamera).transform.position.z));
				SetObjectLayerRecursive(previewPlayerObject, playerLayer);
				MonoBehaviour[] components = previewPlayerObject.GetComponents<MonoBehaviour>();
				foreach (MonoBehaviour script in components)
				{
					Object.Destroy((Object)(object)script);
				}
			}
		}

		private static void SetObjectLayerRecursive(GameObject obj, int layer)
		{
			if (!((Object)(object)obj == (Object)null))
			{
				obj.layer = layer;
				for (int i = 0; i < obj.transform.childCount; i++)
				{
					Transform child = obj.transform.GetChild(i);
					SetObjectLayerRecursive((child != null) ? ((Component)child).gameObject : null, layer);
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ScrollMouse_performed")]
		[HarmonyPrefix]
		public static bool OnScrollMouse(CallbackContext context, PlayerControllerB __instance)
		{
			if (!isMenuOpen || (Object)(object)__instance != (Object)(object)localPlayerController || !((CallbackContext)(ref context)).performed)
			{
				return true;
			}
			if (((CallbackContext)(ref context)).ReadValue<float>() < 0f && !ConfigSettings.reverseEmoteWheelScrollDirection.Value)
			{
				SwapNextPage();
			}
			else
			{
				SwapPrevPage();
			}
			return false;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ItemSecondaryUse_performed")]
		[HarmonyPrefix]
		public static bool PreventItemSecondaryUseInMenu(CallbackContext context)
		{
			return !isMenuOpen;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ItemTertiaryUse_performed")]
		[HarmonyPrefix]
		public static bool PreventItemTertiaryUseInMenu(CallbackContext context)
		{
			return !isMenuOpen;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Interact_performed")]
		[HarmonyPrefix]
		public static bool PreventInteractInMenu(CallbackContext context)
		{
			return !isMenuOpen;
		}

		[HarmonyPatch(typeof(QuickMenuManager), "OpenQuickMenu")]
		[HarmonyPrefix]
		public static bool OnOpenQuickMenu()
		{
			if (isMenuOpen)
			{
				CloseEmoteMenu();
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(QuickMenuManager), "CloseQuickMenu")]
		[HarmonyPostfix]
		public static void OnCloseQuickMenu()
		{
			if (isMenuOpen)
			{
				CloseEmoteMenu();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
		[HarmonyPostfix]
		public static void OnLocalPlayerDeath(Vector3 bodyVelocity, PlayerControllerB __instance)
		{
			if ((Object)(object)__instance == (Object)(object)localPlayerController && isMenuOpen && __instance.isPlayerDead)
			{
				CloseEmoteMenu();
			}
		}
	}
	public class EmoteUIElement
	{
		public GameObject uiGameObject;

		public int id;

		public Image backgroundImage;

		public TextMeshPro textContainer;

		public Color baseColor;

		public UnlockableEmote emote;

		public void OnHover(bool hovered = true)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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)
			Color color = baseColor * (hovered ? 1f : 0.5f);
			color.a = (hovered ? EmoteMenuManager.hoveredAlpha : EmoteMenuManager.unhoveredAlpha);
			((Graphic)backgroundImage).color = color;
		}
	}
	public class EmoteLoadoutUIElement : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public static int uiCount;

		public int id;

		public string loadoutName;

		public Image backgroundImage;

		public TextMeshPro textContainer;

		private void Awake()
		{
			id = uiCount++;
			backgroundImage = ((Component)this).GetComponentInChildren<Image>();
			textContainer = ((Component)this).GetComponentInChildren<TextMeshPro>();
		}

		private void Start()
		{
			((TMP_Text)textContainer).text = loadoutName;
		}

		public void OnHover(bool hovered = true)
		{
			//IL_0015: 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_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_004b: Unknown result type (might be due to invalid IL or missing references)
			Color color = ((EmoteMenuManager.currentLoadoutIndex == id) ? EmoteMenuManager.selectedLoadoutUIColor : EmoteMenuManager.defaultUIColor) * (hovered ? 1f : 0.5f);
			color.a = (hovered ? EmoteMenuManager.hoveredAlpha : EmoteMenuManager.unhoveredAlpha);
			((Graphic)backgroundImage).color = color;
		}

		public void OnPointerEnter(PointerEventData eventData)
		{
			EmoteMenuManager.OnHoveredNewLoadoutElement(id);
			OnHover();
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			EmoteMenuManager.OnHoveredNewLoadoutElement(-1);
			OnHover(hovered: false);
		}
	}
	public class EmoteLoadoutUIContainer : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public static bool hovered;

		public void OnPointerEnter(PointerEventData eventData)
		{
			hovered = true;
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			hovered = false;
		}
	}
	public class UnlockableEmote
	{
		public int emoteId;

		public string emoteName;

		public string randomEmotePoolName = "";

		public string displayName = "";

		public bool purchasable = true;

		public AnimationClip animationClip;

		public AnimationClip transitionsToClip = null;

		public List<UnlockableEmote> randomEmotePool;

		public bool complementary = false;

		public bool isPose = false;

		public bool canSyncEmote = false;

		public bool favorite = false;

		public int rarity = 0;

		public static string[] rarityColorCodes = new string[4]
		{
			ConfigSettings.emoteNameColorTier0.Value,
			ConfigSettings.emoteNameColorTier1.Value,
			ConfigSettings.emoteNameColorTier2.Value,
			ConfigSettings.emoteNameColorTier3.Value
		};

		public string displayNameColorCoded => $"<color={nameColor}>{displayName}</color>";

		public string rarityText
		{
			get
			{
				if (rarity == 0)
				{
					return "Common";
				}
				if (rarity == 1)
				{
					return "Uncommon";
				}
				if (rarity == 2)
				{
					return "Rare";
				}
				if (rarity == 3)
				{
					return "Legendary";
				}
				return "Invalid";
			}
		}

		public int price
		{
			get
			{
				int num = -1;
				if (complementary)
				{
					num = 0;
				}
				else if (rarity == 0)
				{
					num = ConfigSync.instance.syncBasePriceEmoteTier0;
				}
				else if (rarity == 1)
				{
					num = ConfigSync.instance.syncBasePriceEmoteTier1;
				}
				else if (rarity == 2)
				{
					num = ConfigSync.instance.syncBasePriceEmoteTier2;
				}
				else if (rarity == 3)
				{
					num = ConfigSync.instance.syncBasePriceEmoteTier3;
				}
				return (int)Mathf.Max((float)num * ConfigSync.instance.syncPriceMultiplierEmotesStore, 0f);
			}
		}

		public string nameColor => rarityColorCodes[rarity];
	}
	[HarmonyPatch]
	public static class Keybinds
	{
		private static InputAction OpenEmoteMenuAction;

		private static InputAction SelectEmoteUIAction;

		private static InputAction NextEmotePageAction;

		private static InputAction PrevEmotePageAction;

		private static InputAction FavoriteEmoteAction;

		public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController;

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void InitializeHotkeys(PlayerControllerB __instance)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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
			Plugin.Log("Initializing custom emote hotkeys.");
			OpenEmoteMenuAction = new InputAction((string)null, (InputActionType)0, ConfigSettings.openEmoteMenuKeybind.Value, "Press", (string)null, (string)null);
			SelectEmoteUIAction = new InputAction((string)null, (InputActionType)0, "<Mouse>/leftButton", "Press", (string)null, (string)null);
			PrevEmotePageAction = new InputAction((string)null, (InputActionType)0, "<Keyboard>/q", "Press", (string)null, (string)null);
			NextEmotePageAction = new InputAction((string)null, (InputActionType)0, "<Keyboard>/e", "Press", (string)null, (string)null);
			FavoriteEmoteAction = new InputAction((string)null, (InputActionType)0, "<Mouse>/middleButton", "Press", (string)null, (string)null);
			if (((Component)__instance).gameObject.activeSelf)
			{
				SubscribeToEvents();
			}
		}

		private static void SubscribeToEvents()
		{
			Plugin.Log("Subscribing to OnPressCustomEmoteKey events");
			OpenEmoteMenuAction.performed += OnPressOpenEmoteMenu;
			OpenEmoteMenuAction.canceled += OnPressOpenEmoteMenu;
			SelectEmoteUIAction.performed += OnSelectEmoteUI;
			PrevEmotePageAction.performed += OnSwapPrevEmotePage;
			NextEmotePageAction.performed += OnSwapNextEmotePage;
			FavoriteEmoteAction.performed += OnFavoriteEmote;
			OpenEmoteMenuAction.Enable();
			SelectEmoteUIAction.Enable();
			PrevEmotePageAction.Enable();
			NextEmotePageAction.Enable();
			FavoriteEmoteAction.Enable();
		}

		[HarmonyPatch(typeof(PlayerControllerB), "OnEnable")]
		[HarmonyPostfix]
		public static void OnEnable(PlayerControllerB __instance)
		{
			if (!((Object)(object)__instance != (Object)(object)localPlayerController))
			{
				SubscribeToEvents();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "OnDisable")]
		[HarmonyPostfix]
		public static void OnDisable(PlayerControllerB __instance)
		{
			if (!((Object)(object)__instance != (Object)(object)localPlayerController))
			{
				Plugin.Log("Unsubscribing from OnPressCustomEmoteKey events.");
				OpenEmoteMenuAction.performed -= OnPressOpenEmoteMenu;
				OpenEmoteMenuAction.canceled -= OnPressOpenEmoteMenu;
				SelectEmoteUIAction.performed -= OnSelectEmoteUI;
				PrevEmotePageAction.performed -= OnSwapPrevEmotePage;
				NextEmotePageAction.performed -= OnSwapNextEmotePage;
				FavoriteEmoteAction.performed -= OnFavoriteEmote;
				OpenEmoteMenuAction.Disable();
				SelectEmoteUIAction.Disable();
				PrevEmotePageAction.Disable();
				NextEmotePageAction.Disable();
				FavoriteEmoteAction.Disable();
			}
		}

		private static void OnPressOpenEmoteMenu(CallbackContext context)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)localPlayerController == (Object)null)
			{
				return;
			}
			if (!EmoteMenuManager.isMenuOpen)
			{
				if (((CallbackContext)(ref context)).performed && EmoteMenuManager.CanOpenEmoteMenu())
				{
					EmoteMenuManager.OpenEmoteMenu();
				}
			}
			else if (ConfigSettings.toggleEmoteMenu.Value)
			{
				if (((CallbackContext)(ref context)).performed)
				{
					EmoteMenuManager.CloseEmoteMenu();
				}
			}
			else if (((CallbackContext)(ref context)).canceled)
			{
				if (EmoteMenuManager.hoveredEmoteIndex != -1)
				{
					PerformEmoteLocal(context);
				}
				EmoteMenuManager.CloseEmoteMenu();
			}
		}

		private static void OnSelectEmoteUI(CallbackContext context)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && EmoteMenuManager.isMenuOpen)
			{
				if (EmoteMenuManager.hoveredLoadoutUIIndex != -1 && EmoteMenuManager.hoveredLoadoutUIIndex != EmoteMenuManager.currentLoadoutIndex)
				{
					EmoteMenuManager.SetCurrentEmoteLoadout(EmoteMenuManager.hoveredLoadoutUIIndex);
				}
				else if (EmoteMenuManager.hoveredEmoteIndex >= 0 && EmoteMenuManager.hoveredEmoteIndex < EmoteMenuManager.currentLoadoutEmotesList.Count)
				{
					PerformEmoteLocal(context);
					EmoteMenuManager.CloseEmoteMenu();
				}
			}
		}

		private static void OnSwapPrevEmotePage(CallbackContext context)
		{
			if (!((Object)(object)localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && EmoteMenuManager.isMenuOpen && EmoteMenuManager.numPages > 1)
			{
				EmoteMenuManager.SwapPrevPage();
			}
		}

		private static void OnSwapNextEmotePage(CallbackContext context)
		{
			if (!((Object)(object)localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && EmoteMenuManager.isMenuOpen && EmoteMenuManager.numPages > 1)
			{
				EmoteMenuManager.SwapNextPage();
			}
		}

		public static void PerformEmoteLocal(CallbackContext context)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			if (EmoteMenuManager.hoveredEmoteIndex >= 0 && EmoteMenuManager.hoveredEmoteIndex < EmoteMenuManager.currentLoadoutEmotesList.Count)
			{
				UnlockableEmote unlockableEmote = EmoteMenuManager.currentLoadoutEmotesList[EmoteMenuManager.hoveredEmoteIndex];
				if (unlockableEmote != null)
				{
					localPlayerController.PerformEmote(context, -(unlockableEmote.emoteId + 1));
				}
			}
		}

		public static void OnFavoriteEmote(CallbackContext context)
		{
			if (!((Object)(object)localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && EmoteMenuManager.isMenuOpen && EmoteMenuManager.hoveredEmoteUIIndex != -1 && EmoteMenuManager.previewingEmote != null)
			{
				EmoteMenuManager.ToggleFavoriteHoveredEmote();
			}
		}
	}
	[BepInPlugin("FlipMods.TooManyEmotes", "TooManyEmotes", "1.5.10")]
	public class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		public static Plugin instance;

		public static List<AnimationClip> customAnimationClips;

		public static Dictionary<string, AnimationClip> customAnimationClipsLoopDict = new Dictionary<string, AnimationClip>();

		public static List<AnimationClip> complementaryAnimationClips;

		public static List<AnimationClip> animationClipsTier0;

		public static List<AnimationClip> animationClipsTier1;

		public static List<AnimationClip> animationClipsTier2;

		public static List<AnimationClip> animationClipsTier3;

		public static GameObject radialMenuPrefab;

		public static RuntimeAnimatorController previewAnimatorController;

		public static Dictionary<string, AudioClip> musicClips;

		private void Awake()
		{
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Expected O, but got Unknown
			instance = this;
			ConfigSettings.BindConfigSettings();
			customAnimationClips = new List<AnimationClip>();
			customAnimationClipsLoopDict = new Dictionary<string, AnimationClip>();
			complementaryAnimationClips = new List<AnimationClip>(LoadEmoteAssetBundle("Assets/emotes_complementary"));
			animationClipsTier0 = new List<AnimationClip>(LoadEmoteAssetBundle("Assets/emotes_0"));
			animationClipsTier1 = new List<AnimationClip>(LoadEmoteAssetBundle("Assets/emotes_1"));
			animationClipsTier2 = new List<AnimationClip>(LoadEmoteAssetBundle("Assets/emotes_2"));
			animationClipsTier3 = new List<AnimationClip>(LoadEmoteAssetBundle("Assets/emotes_3"));
			customAnimationClips.AddRange(complementaryAnimationClips);
			customAnimationClips.AddRange(animationClipsTier0);
			customAnimationClips.AddRange(animationClipsTier1);
			customAnimationClips.AddRange(animationClipsTier2);
			customAnimationClips.AddRange(animationClipsTier3);
			foreach (AnimationClip customAnimationClip in customAnimationClips)
			{
				if (((Object)customAnimationClip).name.StartsWith("fn_"))
				{
					((Object)customAnimationClip).name = ((Object)customAnimationClip).name.Replace("fn_", "");
				}
				if (((Object)customAnimationClip).name.EndsWith("_loop"))
				{
					customAnimationClipsLoopDict.Add(((Object)customAnimationClip).name, customAnimationClip);
				}
			}
			foreach (AnimationClip value in customAnimationClipsLoopDict.Values)
			{
				customAnimationClips.Remove(value);
			}
			LoadRadialMenuAsset();
			_harmony = new Harmony("TooManyEmotes");
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"TooManyEmotes loaded");
		}

		public static bool IsModLoaded(string guid)
		{
			return Chainloader.PluginInfos.ContainsKey(guid);
		}

		private static AnimationClip[] LoadEmoteAssetBundle(string assetBundleName)
		{
			try
			{
				string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)instance).Info.Location), assetBundleName);
				AssetBundle val = AssetBundle.LoadFromFile(text);
				AnimationClip[] array = val.LoadAllAssets<AnimationClip>();
				Log($"Successfully loaded {array.Length} animation clips from asset bundle: {assetBundleName}");
				return array;
			}
			catch
			{
				LogError("Failed to load emotes asset bundle: " + assetBundleName + ".");
				return (AnimationClip[])(object)new AnimationClip[0];
			}
		}

		public static void LoadRadialMenuAsset()
		{
			try
			{
				string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)instance).Info.Location), "Assets/radial_menu");
				AssetBundle val = AssetBundle.LoadFromFile(text);
				radialMenuPrefab = val.LoadAsset<GameObject>("RadialMenu");
				previewAnimatorController = val.LoadAsset<RuntimeAnimatorController>("PreviewAnimatorController");
				Log("Successfully loaded radial menu asset.");
			}
			catch
			{
				LogError("Failed to load radial menu asset.");
			}
		}

		public static void Log(string message)
		{
			((BaseUnityPlugin)instance).Logger.LogInfo((object)message);
		}

		public static void LogWarning(string message)
		{
			((BaseUnityPlugin)instance).Logger.LogWarning((object)message);
		}

		public static void LogError(string message)
		{
			((BaseUnityPlugin)instance).Logger.LogError((object)message);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FlipMods.TooManyEmotes";

		public const string PLUGIN_NAME = "TooManyEmotes";

		public const string PLUGIN_VERSION = "1.5.10";
	}
}
namespace TooManyEmotes.Config
{
	public static class ConfigSettings
	{
		public static ConfigEntry<bool> unlockEverything;

		public static ConfigEntry<bool> disableRaritySystem;

		public static ConfigEntry<int> basePriceEmoteRaritySystemDisabled;

		public static ConfigEntry<int> startingEmoteCredits;

		public static ConfigEntry<float> addEmoteCreditsMultiplier;

		public static ConfigEntry<bool> purchaseEmotesWithDefaultCurrency;

		public static ConfigEntry<float> priceMultiplierEmotesStore;

		public static ConfigEntry<int> basePriceEmoteTier0;

		public static ConfigEntry<int> basePriceEmoteTier1;

		public static ConfigEntry<int> basePriceEmoteTier2;

		public static ConfigEntry<int> basePriceEmoteTier3;

		public static ConfigEntry<int> numEmotesStoreRotation;

		public static ConfigEntry<float> rotationChanceEmoteTier0;

		public static ConfigEntry<float> rotationChanceEmoteTier1;

		public static ConfigEntry<float> rotationChanceEmoteTier2;

		public static ConfigEntry<float> rotationChanceEmoteTier3;

		public static ConfigEntry<string> openEmoteMenuKeybind;

		public static ConfigEntry<bool> toggleEmoteMenu;

		public static ConfigEntry<bool> reverseEmoteWheelScrollDirection;

		public static ConfigEntry<string> emoteNameColorTier0;

		public static ConfigEntry<string> emoteNameColorTier1;

		public static ConfigEntry<string> emoteNameColorTier2;

		public static ConfigEntry<string> emoteNameColorTier3;

		public static Dictionary<string, ConfigEntryBase> currentConfigEntries = new Dictionary<string, ConfigEntryBase>();

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			unlockEverything = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Server settings", "I am a Party Pooper", false, "[Host only] If true, every emote will be unlocked in your emote wheel at the start of the game.");
			disableRaritySystem = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Server settings", "DisableRaritySystem", false, "[Host only] If true, every emote will have the same likelyhood of appearing in the emote store.");
			basePriceEmoteRaritySystemDisabled = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server settings", "BasePriceEmote - Rarity System Disabled", 100, "[Host only] Base price of emotes if the rarity system is disabled.");
			startingEmoteCredits = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server settings", "StartingEmoteCredits", 100, "[Host only] The number of emote credits you start each game with.");
			addEmoteCreditsMultiplier = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Server settings", "AddEmoteCreditsMultiplier", 0.5f, "[Host only] You gain emote credits based off this multiplier of normal group credits earned. Example: If set to the default, 0.5, and you earn 200 group credits, you will also gain 100 emote credits.");
			purchaseEmotesWithDefaultCurrency = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Server settings", "PurchaseEmotesWithDefaultCredits", false, "[Host only] Setting this to true will allow you to purchase emotes with normal group credits once you run out of emote credits.");
			purchaseEmotesWithDefaultCurrency = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Server settings", "PurchaseEmotesWithDefaultCredits", false, "[Host only] Setting this to true will allow you to purchase emotes with normal group credits once you run out of emote credits.");
			priceMultiplierEmotesStore = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Server settings", "PriceMultiplierEmotesStore", 1f, "[Host only] Price multiplier for emotes in the store. Only applies if UnlockEverythingAtStart is false.");
			basePriceEmoteTier0 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server settings", "PriceCommonEmote", 50, "[Host only] The base price of [common]emotes in the store.");
			basePriceEmoteTier1 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server settings", "PriceUncommonEmote", 100, "[Host only] The base price of [uncommon] emotes in the store.");
			basePriceEmoteTier2 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server settings", "PriceRareEmote", 200, "[Host only] The base price of [rare] emotes in the store.");
			basePriceEmoteTier3 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server settings", "PriceLegendaryEmote", 300, "[Host only] The base price of [legendary] emotes in the store.");
			numEmotesStoreRotation = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server settings", "EmotesInStoreRotation", 6, "[Host only] The number of emotes that will be available at a time in the store. Only applies if UnlockEverythingAtStart is false.");
			rotationChanceEmoteTier0 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Server settings", "RotationWeightCommonEmote", 0.55f, "[Host only] The likelyhood of [common] emotes appearing (per slot) in the store rotation.");
			rotationChanceEmoteTier1 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Server settings", "RotationWeightUncommonEmote", 0.35f, "[Host only] The likelyhood of [uncommon] emotes appearing (per slot) in the store rotation.");
			rotationChanceEmoteTier2 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Server settings", "RotationWeightRareEmote", 0.08f, "[Host only] The likelyhood of [rare] emotes appearing (per slot) in the store rotation.");
			rotationChanceEmoteTier3 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Server settings", "RotationWeightLegendaryEmote", 0.02f, "[Host only] The likelyhood of [legendary] emotes appearing (per slot) in the store rotation.");
			openEmoteMenuKeybind = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Client", "OpenEmoteMenuKeybind", "<Keyboard>/backquote", "Keybind for opening the emote radial menu.");
			toggleEmoteMenu = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client", "ToggleEmoteMenu", true, "If set to false, the emote menu will open upon pressing the related keybind, and close upon releasing, and will play the currently hovered emote.");
			reverseEmoteWheelScrollDirection = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client", "ReverseEmoteWheelScrollDirection", false, "Reverses the page swapping direction in your emote when scrolling.");
			emoteNameColorTier0 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Accessibility", "CommonEmoteNameColor", "#00FF00", "The color of the [common] emote name in the terminal.");
			emoteNameColorTier1 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Accessibility", "UncommonEmoteNameColor", "#2828FF", "The color of the [uncommon] emote name in the terminal.");
			emoteNameColorTier2 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Accessibility", "RareEmoteNameColor", "#AA00EE", "The color of the [rare] emote name in the terminal.");
			emoteNameColorTier3 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Accessibility", "LegendaryEmoteNameColor", "#FF2222", "The color of the [legendary] emote name in the terminal.");
			currentConfigEntries.Add(((ConfigEntryBase)unlockEverything).Definition.Key, (ConfigEntryBase)(object)unlockEverything);
			currentConfigEntries.Add(((ConfigEntryBase)disableRaritySystem).Definition.Key, (ConfigEntryBase)(object)disableRaritySystem);
			currentConfigEntries.Add(((ConfigEntryBase)basePriceEmoteRaritySystemDisabled).Definition.Key, (ConfigEntryBase)(object)basePriceEmoteRaritySystemDisabled);
			currentConfigEntries.Add(((ConfigEntryBase)startingEmoteCredits).Definition.Key, (ConfigEntryBase)(object)startingEmoteCredits);
			currentConfigEntries.Add(((ConfigEntryBase)addEmoteCreditsMultiplier).Definition.Key, (ConfigEntryBase)(object)addEmoteCreditsMultiplier);
			currentConfigEntries.Add(((ConfigEntryBase)purchaseEmotesWithDefaultCurrency).Definition.Key, (ConfigEntryBase)(object)purchaseEmotesWithDefaultCurrency);
			currentConfigEntries.Add(((ConfigEntryBase)priceMultiplierEmotesStore).Definition.Key, (ConfigEntryBase)(object)priceMultiplierEmotesStore);
			currentConfigEntries.Add(((ConfigEntryBase)basePriceEmoteTier0).Definition.Key, (ConfigEntryBase)(object)basePriceEmoteTier0);
			currentConfigEntries.Add(((ConfigEntryBase)basePriceEmoteTier1).Definition.Key, (ConfigEntryBase)(object)basePriceEmoteTier1);
			currentConfigEntries.Add(((ConfigEntryBase)basePriceEmoteTier2).Definition.Key, (ConfigEntryBase)(object)basePriceEmoteTier2);
			currentConfigEntries.Add(((ConfigEntryBase)basePriceEmoteTier3).Definition.Key, (ConfigEntryBase)(object)basePriceEmoteTier3);
			currentConfigEntries.Add(((ConfigEntryBase)numEmotesStoreRotation).Definition.Key, (ConfigEntryBase)(object)numEmotesStoreRotation);
			currentConfigEntries.Add(((ConfigEntryBase)rotationChanceEmoteTier0).Definition.Key, (ConfigEntryBase)(object)rotationChanceEmoteTier0);
			currentConfigEntries.Add(((ConfigEntryBase)rotationChanceEmoteTier1).Definition.Key, (ConfigEntryBase)(object)rotationChanceEmoteTier1);
			currentConfigEntries.Add(((ConfigEntryBase)rotationChanceEmoteTier2).Definition.Key, (ConfigEntryBase)(object)rotationChanceEmoteTier2);
			currentConfigEntries.Add(((ConfigEntryBase)rotationChanceEmoteTier3).Definition.Key, (ConfigEntryBase)(object)rotationChanceEmoteTier3);
			currentConfigEntries.Add(((ConfigEntryBase)openEmoteMenuKeybind).Definition.Key, (ConfigEntryBase)(object)openEmoteMenuKeybind);
			currentConfigEntries.Add(((ConfigEntryBase)toggleEmoteMenu).Definition.Key, (ConfigEntryBase)(object)toggleEmoteMenu);
			currentConfigEntries.Add(((ConfigEntryBase)reverseEmoteWheelScrollDirection).Definition.Key, (ConfigEntryBase)(object)reverseEmoteWheelScrollDirection);
			currentConfigEntries.Add(((ConfigEntryBase)emoteNameColorTier0).Definition.Key, (ConfigEntryBase)(object)emoteNameColorTier0);
			currentConfigEntries.Add(((ConfigEntryBase)emoteNameColorTier1).Definition.Key, (ConfigEntryBase)(object)emoteNameColorTier1);
			currentConfigEntries.Add(((ConfigEntryBase)emoteNameColorTier2).Definition.Key, (ConfigEntryBase)(object)emoteNameColorTier2);
			currentConfigEntries.Add(((ConfigEntryBase)emoteNameColorTier3).Definition.Key, (ConfigEntryBase)(object)emoteNameColorTier3);
			float value = rotationChanceEmoteTier0.Value;
			value += rotationChanceEmoteTier1.Value;
			value += rotationChanceEmoteTier2.Value;
			value += rotationChanceEmoteTier3.Value;
			if (value != 1f && value != 0f)
			{
				ConfigEntry<float> obj = rotationChanceEmoteTier0;
				obj.Value /= value;
				ConfigEntry<float> obj2 = rotationChanceEmoteTier1;
				obj2.Value /= value;
				ConfigEntry<float> obj3 = rotationChanceEmoteTier2;
				obj3.Value /= value;
				ConfigEntry<float> obj4 = rotationChanceEmoteTier3;
				obj4.Value /= value;
				((BaseUnityPlugin)Plugin.instance).Config.Save();
			}
			TryRemoveOldConfigSettings();
			ConfigSync.BuildDefaultConfigSync();
		}

		public static void TryRemoveOldConfigSettings()
		{
			HashSet<string> hashSet = new HashSet<string>();
			HashSet<string> hashSet2 = new HashSet<string>();
			foreach (ConfigEntryBase value in currentConfigEntries.Values)
			{
				hashSet.Add(value.Definition.Section);
				hashSet2.Add(value.Definition.Key);
			}
			try
			{
				Plugin.Log("Cleaning old config entries");
				ConfigFile config = ((BaseUnityPlugin)Plugin.instance).Config;
				string configFilePath = config.ConfigFilePath;
				if (!File.Exists(configFilePath))
				{
					return;
				}
				string text = File.ReadAllText(configFilePath);
				string[] array = File.ReadAllLines(configFilePath);
				string text2 = "";
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = array[i].Replace("\n", "");
					if (array[i].Length <= 0)
					{
						continue;
					}
					if (array[i].StartsWith("["))
					{
						if (text2 != "" && !hashSet.Contains(text2))
						{
							text2 = "[" + text2 + "]";
							int num = text.IndexOf(text2);
							int num2 = text.IndexOf(array[i]);
							text = text.Remove(num, num2 - num);
						}
						text2 = array[i].Replace("[", "").Replace("]", "").Trim();
					}
					else
					{
						if (!(text2 != ""))
						{
							continue;
						}
						if (i <= array.Length - 4 && array[i].StartsWith("##"))
						{
							int j;
							for (j = 1; i + j < array.Length && array[i + j].Length > 3; j++)
							{
							}
							if (hashSet.Contains(text2))
							{
								int num3 = array[i + j - 1].IndexOf("=");
								string item = array[i + j - 1].Substring(0, num3 - 1);
								if (!hashSet2.Contains(item))
								{
									int num4 = text.IndexOf(array[i]);
									int num5 = text.IndexOf(array[i + j - 1]) + array[i + j - 1].Length;
									text = text.Remove(num4, num5 - num4);
								}
							}
							i += j - 1;
						}
						else if (array[i].Length > 3)
						{
							text = text.Replace(array[i], "");
						}
					}
				}
				if (!hashSet.Contains(text2))
				{
					text2 = "[" + text2 + "]";
					int num6 = text.IndexOf(text2);
					text = text.Remove(num6, text.Length - num6);
				}
				while (text.Contains("\n\n\n"))
				{
					text = text.Replace("\n\n\n", "\n\n");
				}
				File.WriteAllText(configFilePath, text);
				config.Reload();
			}
			catch
			{
			}
		}
	}
}
namespace TooManyEmotes.Networking
{
	[Serializable]
	[HarmonyPatch]
	public class ConfigSync
	{
		public static bool isSynced;

		public static ConfigSync defaultConfig;

		public static ConfigSync instance;

		public bool syncUnlockEverything;

		public bool syncDisableRaritySystem;

		public int syncStartingEmoteCredits;

		public float syncAddEmoteCreditsMultiplier;

		public bool syncPurchaseEmotesWithDefaultCurrency;

		public float syncPriceMultiplierEmotesStore;

		public int syncBasePriceEmoteTier0;

		public int syncBasePriceEmoteTier1;

		public int syncBasePriceEmoteTier2;

		public int syncBasePriceEmoteTier3;

		public int syncNumEmotesStoreRotation;

		public float syncRotationChanceEmoteTier0;

		public float syncRotationChanceEmoteTier1;

		public float syncRotationChanceEmoteTier2;

		public float syncRotationChanceEmoteTier3;

		public ConfigSync()
		{
			syncUnlockEverything = ConfigSettings.unlockEverything.Value;
			syncDisableRaritySystem = ConfigSettings.disableRaritySystem.Value;
			syncStartingEmoteCredits = ConfigSettings.startingEmoteCredits.Value;
			syncAddEmoteCreditsMultiplier = ConfigSettings.addEmoteCreditsMultiplier.Value;
			syncPurchaseEmotesWithDefaultCurrency = ConfigSettings.purchaseEmotesWithDefaultCurrency.Value;
			syncPriceMultiplierEmotesStore = ConfigSettings.priceMultiplierEmotesStore.Value;
			syncNumEmotesStoreRotation = ConfigSettings.numEmotesStoreRotation.Value;
			syncRotationChanceEmoteTier0 = ConfigSettings.rotationChanceEmoteTier0.Value;
			syncRotationChanceEmoteTier1 = ConfigSettings.rotationChanceEmoteTier1.Value;
			syncRotationChanceEmoteTier2 = ConfigSettings.rotationChanceEmoteTier2.Value;
			syncRotationChanceEmoteTier3 = ConfigSettings.rotationChanceEmoteTier3.Value;
			if (ConfigSettings.disableRaritySystem.Value)
			{
				syncBasePriceEmoteTier0 = ConfigSettings.basePriceEmoteRaritySystemDisabled.Value;
				syncBasePriceEmoteTier1 = ConfigSettings.basePriceEmoteRaritySystemDisabled.Value;
				syncBasePriceEmoteTier2 = ConfigSettings.basePriceEmoteRaritySystemDisabled.Value;
				syncBasePriceEmoteTier3 = ConfigSettings.basePriceEmoteRaritySystemDisabled.Value;
			}
			else
			{
				syncBasePriceEmoteTier0 = ConfigSettings.basePriceEmoteTier0.Value;
				syncBasePriceEmoteTier1 = ConfigSettings.basePriceEmoteTier1.Value;
				syncBasePriceEmoteTier2 = ConfigSettings.basePriceEmoteTier2.Value;
				syncBasePriceEmoteTier3 = ConfigSettings.basePriceEmoteTier3.Value;
			}
		}

		public static void BuildDefaultConfigSync()
		{
			defaultConfig = new ConfigSync();
			instance = new ConfigSync();
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void Init(PlayerControllerB __instance)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Expected O, but got Unknown
			if (!((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)(object)__instance))
			{
				return;
			}
			isSynced = false;
			if (NetworkManager.Singleton.IsServer)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnRequestConfigSyncServerRpc", new HandleNamedMessageDelegate(OnRequestConfigSyncServerRpc));
				isSynced = true;
				if (!instance.syncUnlockEverything)
				{
					return;
				}
				{
					foreach (UnlockableEmote allUnlockableEmote in StartOfRoundPatcher.allUnlockableEmotes)
					{
						StartOfRoundPatcher.UnlockEmoteLocal(allUnlockableEmote);
					}
					return;
				}
			}
			foreach (UnlockableEmote allUnlockableEmote2 in StartOfRoundPatcher.allUnlockableEmotes)
			{
				StartOfRoundPatcher.UnlockEmoteLocal(allUnlockableEmote2);
			}
			NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnRequestConfigSyncClientRpc", new HandleNamedMessageDelegate(OnRequestConfigSyncClientRpc));
			RequestConfigSync();
		}

		public static void RequestConfigSync()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsClient)
			{
				Plugin.Log("Requesting config sync from server");
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(0, (Allocator)2, -1);
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnRequestConfigSyncServerRpc", 0uL, val, (NetworkDelivery)3);
			}
			else
			{
				Plugin.LogError("Failed to send unlocked emote update to server.");
			}
		}

		private static void OnRequestConfigSyncServerRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_004e: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsServer)
			{
				Plugin.Log("Receiving config sync request from client: " + clientId);
				byte[] array = SerializeConfigToByteArray(instance);
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(4 + array.Length, (Allocator)2, -1);
				int num = array.Length;
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0);
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnRequestConfigSyncClientRpc", clientId, val, (NetworkDelivery)3);
			}
		}

		private static void OnRequestConfigSyncClientRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_002d: 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)
			if (!NetworkManager.Singleton.IsClient)
			{
				return;
			}
			if (((FastBufferReader)(ref reader)).TryBeginRead(4))
			{
				int num = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
				if (((FastBufferReader)(ref reader)).TryBeginRead(num))
				{
					Plugin.Log("Receiving config sync from server.");
					byte[] data = new byte[num];
					((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
					instance = DeserializeFromByteArray(data);
					isSynced = true;
					if (StartOfRoundPatcher.allUnlockableEmotes != null && StartOfRoundPatcher.unlockedEmotes != null)
					{
						StartOfRoundPatcher.ResetEmotesLocal();
						if (instance.syncUnlockEverything)
						{
							StartOfRoundPatcher.UnlockEmotesLocal(StartOfRoundPatcher.allUnlockableEmotes);
						}
						else
						{
							StartOfRoundPatcher.UnlockEmotesLocal(StartOfRoundPatcher.complementaryEmotes);
						}
						StartOfRoundPatcher.UpdateUnlockedFavoriteEmotes();
					}
				}
				else
				{
					Plugin.LogError("Error receiving sync from server.");
				}
			}
			else
			{
				Plugin.LogError("Error receiving bytes length.");
			}
		}

		public static byte[] SerializeConfigToByteArray(ConfigSync config)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			MemoryStream memoryStream = new MemoryStream();
			binaryFormatter.Serialize(memoryStream, config);
			return memoryStream.ToArray();
		}

		public static ConfigSync DeserializeFromByteArray(byte[] data)
		{
			MemoryStream serializationStream = new MemoryStream(data);
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			return (ConfigSync)binaryFormatter.Deserialize(serializationStream);
		}
	}
	[HarmonyPatch]
	public static class EmoteSyncManager
	{
		public static bool requestedSync;

		public static bool isSynced;

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void Init()
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			isSynced = NetworkManager.Singleton.IsServer;
			requestedSync = NetworkManager.Singleton.IsServer;
			if (NetworkManager.Singleton.IsServer)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnRequestSyncServerRpc", new HandleNamedMessageDelegate(OnRequestSyncServerRpc));
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnUnlockEmoteServerRpc", new HandleNamedMessageDelegate(OnUnlockEmoteServerRpc));
			}
			else
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnRequestSyncClientRpc", new HandleNamedMessageDelegate(OnRequestSyncClientRpc));
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnUnlockEmoteClientRpc", new HandleNamedMessageDelegate(OnUnlockEmoteClientRpc));
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnRotateEmotesClientRpc", new HandleNamedMessageDelegate(RotateEmoteSelectionClientRpc));
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		public static void RequestSyncAfterConfigUpdate(PlayerControllerB __instance)
		{
			if (!isSynced && !requestedSync && ConfigSync.isSynced && (Object)(object)__instance == (Object)(object)StartOfRound.Instance.localPlayerController)
			{
				SendSyncRequest();
				requestedSync = true;
			}
		}

		public static void SendSyncRequest()
		{
			//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_005a: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsClient)
			{
				Plugin.Log("Sending sync request to server.");
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(8, (Allocator)2, -1);
				((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref StartOfRound.Instance.localPlayerController.actualClientId, default(ForPrimitives));
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnRequestSyncServerRpc", 0uL, val, (NetworkDelivery)3);
			}
		}

		private static void OnRequestSyncServerRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_0033: 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_00a6: 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_00bd: 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_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: 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_0148: 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)
			if (NetworkManager.Singleton.IsServer)
			{
				bool flag = true;
				ulong num = 0uL;
				if (((FastBufferReader)(ref reader)).TryBeginRead(8))
				{
					((FastBufferReader)(ref reader)).ReadValue<ulong>(ref num, default(ForPrimitives));
					flag = false;
					Plugin.Log("Receiving sync request from client: " + clientId);
				}
				else
				{
					Plugin.Log("Syncing with all clients.");
				}
				int num2 = 0;
				if (!ConfigSync.instance.syncUnlockEverything)
				{
					num2 = StartOfRoundPatcher.unlockedEmotes.Count;
				}
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(12 + 4 * Mathf.Max(num2, 0), (Allocator)2, -1);
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref TerminalPatcher.currentEmoteCredits, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref TerminalPatcher.emoteStoreSeed, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num2, default(ForPrimitives));
				for (int i = 0; i < num2; i++)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref StartOfRoundPatcher.unlockedEmotes[i].emoteId, default(ForPrimitives));
				}
				if (flag)
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("TooManyEmotes-OnRequestSyncClientRpc", val, (NetworkDelivery)3);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnRequestSyncClientRpc", num, val, (NetworkDelivery)3);
				}
			}
		}

		private static void OnRequestSyncClientRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_0037: 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_004d: 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_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: 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)
			if (!NetworkManager.Singleton.IsClient)
			{
				return;
			}
			isSynced = true;
			if (((FastBufferReader)(ref reader)).TryBeginRead(12))
			{
				((FastBufferReader)(ref reader)).ReadValue<int>(ref TerminalPatcher.currentEmoteCredits, default(ForPrimitives));
				((FastBufferReader)(ref reader)).ReadValue<int>(ref TerminalPatcher.emoteStoreSeed, default(ForPrimitives));
				int num = default(int);
				((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives));
				StartOfRoundPatcher.ResetEmotesLocal();
				TerminalPatcher.RotateNewEmoteSelection();
				if (num <= 0)
				{
					if (num == -1)
					{
						StartOfRoundPatcher.ResetEmotesLocal();
					}
				}
				else
				{
					if (!((FastBufferReader)(ref reader)).TryBeginRead(4 * num))
					{
						Plugin.LogError("Error receiving emotes sync from server.");
						return;
					}
					int emoteId = default(int);
					for (int i = 0; i < num; i++)
					{
						((FastBufferReader)(ref reader)).ReadValue<int>(ref emoteId, default(ForPrimitives));
						StartOfRoundPatcher.UnlockEmoteLocal(emoteId);
					}
				}
				isSynced = true;
				Plugin.Log("Received sync from server.");
			}
			else
			{
				Plugin.LogError("Error receiving sync from server.");
			}
		}

		public static void SendOnUnlockEmoteUpdate(int emoteId, int emoteCreditsUsed = -1)
		{
			//IL_0029: 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)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: 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)
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(12, (Allocator)2, -1);
			Plugin.Log("Sending unlocked emote update to server. Emote id: " + emoteId);
			((FastBufferWriter)(ref val)).WriteValue<int>(ref emoteCreditsUsed, default(ForPrimitives));
			int num = 1;
			((FastBufferWriter)(ref val)).WriteValue<int>(ref num, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValue<int>(ref emoteId, default(ForPrimitives));
			NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnUnlockEmoteServerRpc", 0uL, val, (NetworkDelivery)3);
		}

		public static void SendOnUnlockEmoteUpdateMulti(int emoteCreditsUsed = -1)
		{
			//IL_0029: 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)
			//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_0076: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(8 + 4 * StartOfRoundPatcher.unlockedEmotes.Count, (Allocator)2, -1);
			Plugin.Log("Sending all unlocked emotes update to server.");
			((FastBufferWriter)(ref val)).WriteValue<int>(ref emoteCreditsUsed, default(ForPrimitives));
			int count = StartOfRoundPatcher.unlockedEmotes.Count;
			((FastBufferWriter)(ref val)).WriteValue<int>(ref count, default(ForPrimitives));
			foreach (UnlockableEmote unlockedEmote in StartOfRoundPatcher.unlockedEmotes)
			{
				((FastBufferWriter)(ref val)).WriteValue<int>(ref unlockedEmote.emoteId, default(ForPrimitives));
			}
			NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnUnlockEmoteServerRpc", 0uL, val, (NetworkDelivery)3);
		}

		private static void OnUnlockEmoteServerRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_002d: 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_0041: 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_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_00a9: 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_00d4: 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_00f0: 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_011f: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer)
			{
				return;
			}
			if (((FastBufferReader)(ref reader)).TryBeginRead(8))
			{
				int num = default(int);
				((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives));
				int num2 = default(int);
				((FastBufferReader)(ref reader)).ReadValue<int>(ref num2, default(ForPrimitives));
				if (num != -1)
				{
					TerminalPatcher.currentEmoteCredits = num;
				}
				Plugin.Log("Receiving unlocked emote update from client for " + num2 + " emotes.");
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(8 + 4 * num2, (Allocator)2, -1);
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref TerminalPatcher.currentEmoteCredits, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num2, default(ForPrimitives));
				if (((FastBufferReader)(ref reader)).TryBeginRead(4 * num2))
				{
					int emoteId = default(int);
					for (int i = 0; i < num2; i++)
					{
						((FastBufferReader)(ref reader)).ReadValue<int>(ref emoteId, default(ForPrimitives));
						StartOfRoundPatcher.UnlockEmoteLocal(emoteId);
						((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref emoteId, default(ForPrimitives));
					}
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("TooManyEmotes-OnUnlockEmoteClientRpc", val, (NetworkDelivery)3);
				}
				else
				{
					Plugin.LogError("Failed to receive unlocked emote updates from client. Expected updates: " + num2);
				}
			}
			else
			{
				Plugin.LogError("Failed to receive unlocked emote update from client.");
			}
		}

		private static void OnUnlockEmoteClientRpc(ulong clientId, FastBufferReader reader)
		{
			//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_004d: 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_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsClient || NetworkManager.Singleton.IsServer)
			{
				return;
			}
			if (((FastBufferReader)(ref reader)).TryBeginRead(8))
			{
				int num = default(int);
				((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives));
				int num2 = default(int);
				((FastBufferReader)(ref reader)).ReadValue<int>(ref num2, default(ForPrimitives));
				if (num != -1)
				{
					TerminalPatcher.currentEmoteCredits = num;
				}
				if (((FastBufferReader)(ref reader)).TryBeginRead(4 * num2))
				{
					int emoteId = default(int);
					for (int i = 0; i < num2; i++)
					{
						((FastBufferReader)(ref reader)).ReadValue<int>(ref emoteId, default(ForPrimitives));
						Plugin.Log("Receiving unlocked emote update from server. Emote id: " + emoteId);
						StartOfRoundPatcher.UnlockEmoteLocal(emoteId);
					}
				}
				else
				{
					Plugin.LogError("Failed to receive unlocked emote updates from client. Expected updates: " + num2);
				}
			}
			else
			{
				Plugin.LogError("Failed to receive unlocked emote update from client.");
			}
		}

		public static void RotateEmoteSelectionServerRpc(int overrideSeed = 0)
		{
			//IL_005c: 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_0078: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
			{
				if (overrideSeed == 0)
				{
					TerminalPatcher.emoteStoreSeed = Random.Range(0, 1000000000);
				}
				else
				{
					TerminalPatcher.emoteStoreSeed = overrideSeed;
				}
				TerminalPatcher.RotateNewEmoteSelection();
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1);
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref TerminalPatcher.emoteStoreSeed, default(ForPrimitives));
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("TooManyEmotes-OnRotateEmotesClientRpc", val, (NetworkDelivery)3);
			}
		}

		private static void RotateEmoteSelectionClientRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_0042: 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)
			if (NetworkManager.Singleton.IsClient && !NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost && ((FastBufferReader)(ref reader)).TryBeginRead(4))
			{
				((FastBufferReader)(ref reader)).ReadValue<int>(ref TerminalPatcher.emoteStoreSeed, default(ForPrimitives));
				TerminalPatcher.RotateNewEmoteSelection();
			}
		}
	}
}
namespace TooManyEmotes.CompatibilityPatcher
{
	[HarmonyPatch]
	public class MoreEmotesPatcher
	{
		public static bool loadedMoreEmotes;

		[HarmonyPatch(typeof(PreInitSceneScript), "Awake")]
		[HarmonyPostfix]
		public static void ApplyPatch()
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected O, but got Unknown
			if (!Plugin.IsModLoaded("MoreEmotes") || !Chainloader.PluginInfos.TryGetValue("MoreEmotes", out var value))
			{
				return;
			}
			Assembly assembly = ((object)value.Instance).GetType().Assembly;
			if (assembly != null)
			{
				Plugin.Log("Applying compatibility patch for More_Emotes");
				Type type = assembly.GetType("MoreEmotes.Patch.EmotePatch");
				FieldInfo field = type.GetField("local", BindingFlags.Static | BindingFlags.Public);
				RuntimeAnimatorController val = (RuntimeAnimatorController)field.GetValue(null);
				if ((Object)(object)val != (Object)null && !(val is AnimatorOverrideController))
				{
					field.SetValue(null, (object?)new AnimatorOverrideController(val));
				}
				FieldInfo field2 = type.GetField("others", BindingFlags.Static | BindingFlags.Public);
				RuntimeAnimatorController val2 = (RuntimeAnimatorController)field2.GetValue(null);
				if ((Object)(object)val2 != (Object)null && !(val2 is AnimatorOverrideController))
				{
					field2.SetValue(null, (object?)new AnimatorOverrideController(val2));
				}
			}
		}
	}
	internal class BiggerLobbyPatcher
	{
		public static bool loadedBiggerLobby;

		[HarmonyPatch(typeof(NetworkSceneManager), "PopulateScenePlacedObjects")]
		[HarmonyPostfix]
		public static void ApplyPatch()
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			if (!Plugin.IsModLoaded("BiggerLobby"))
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			for (int i = 0; i < instance.allPlayerScripts.Length; i++)
			{
				PlayerControllerB obj = instance.allPlayerScripts[i];
				object obj2;
				if (obj == null)
				{
					obj2 = null;
				}
				else
				{
					Animator playerBodyAnimator = obj.playerBodyAnimator;
					obj2 = ((playerBodyAnimator != null) ? playerBodyAnimator.runtimeAnimatorController : null);
				}
				if ((Object)obj2 != (Object)null)
				{
					instance.allPlayerScripts[i].playerBodyAnimator.runtimeAnimatorController = (RuntimeAnimatorController)new AnimatorOverrideController(instance.otherClientsAnimatorController);
				}
			}
			loadedBiggerLobby = true;
		}
	}
	[HarmonyPatch]
	internal class MoreCompanyPatcher
	{
		public static bool loadedMoreCompany = false;

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

		[HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageClientRpc")]
		[HarmonyPostfix]
		public static void ApplyPatch()
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.IsModLoaded("me.swipez.melonloader.morecompany"))
			{
				return;
			}
			try
			{
				CosmeticApplication val = Object.FindObjectOfType<CosmeticApplication>();
				if (val.spawnedCosmetics.Count > 0)
				{
					return;
				}
				foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics)
				{
					val.ApplyCosmetic(locallySelectedCosmetic, true);
				}
				foreach (CosmeticInstance spawnedCosmetic in val.spawnedCosmetics)
				{
					Transform transform = ((Component)spawnedCosmetic).transform;
					transform.localScale *= 0.38f;
					SetAllChildrenLayer(((Component)spawnedCosmetic).transform, 23);
				}
				loadedMoreCompany = true;
				Plugin.Log("Applied patch for MoreCompany Cosmetics");
			}
			catch
			{
			}
		}

		private static void SetAllChildrenLayer(Transform transform, int layer)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			((Component)transform).gameObject.layer = layer;
			foreach (Transform item in transform)
			{
				Transform transform2 = item;
				SetAllChildrenLayer(transform2, layer);
			}
		}
	}
	[HarmonyPatch]
	internal class MirrorDecorPatcher
	{
		public static bool loadedMirrorDecor;

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPrefix]
		public static void ApplyPatch()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.IsModLoaded("quackandcheese.mirrordecor"))
			{
				loadedMirrorDecor = true;
				ThirdPersonEmoteController.localPlayerBodyLayer = 23;
				ThirdPersonEmoteController.defaultShadowCastingMode = (ShadowCastingMode)1;
				Plugin.Log("Applied patch for MirrorDecor");
			}
		}
	}
}
namespace TooManyEmotes.Patches
{
	[HarmonyPatch]
	public static class BoomboxMusicPlayer
	{
		public static List<BoomboxItem> allBoomboxes = new List<BoomboxItem>();

		[HarmonyPatch(typeof(BoomboxItem), "Start")]
		[HarmonyPostfix]
		public static void AddBoomboxToPool(BoomboxItem __instance)
		{
		}

		public static void OnPlayEmoteWithMusic(UnlockableEmote emote, PlayerControllerB playerController)
		{
			if (Plugin.musicClips.ContainsKey(emote.emoteName))
			{
				BoomboxItem nearestBoombox = GetNearestBoombox(playerController);
				if (!((Object)(object)nearestBoombox == (Object)null) && (!nearestBoombox.isPlayingMusic || !Plugin.musicClips.ContainsKey(((Object)nearestBoombox.boomboxAudio.clip).name)))
				{
					AudioClip val = Plugin.musicClips[emote.emoteName];
					nearestBoombox.boomboxAudio.PlayOneShot(val);
				}
			}
		}

		public static BoomboxItem GetNearestBoombox(PlayerControllerB playerController)
		{
			//IL_0026: 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)
			BoomboxItem result = null;
			float num = 10f;
			foreach (BoomboxItem allBoombox in allBoomboxes)
			{
				float num2 = Vector3.Distance(((Component)playerController).transform.position, ((Component)allBoombox).transform.position);
				if ((Object)(object)allBoombox != (Object)null && num2 < num)
				{
					result = allBoombox;
					num = num2;
				}
			}
			return result;
		}
	}
	[HarmonyPatch]
	public static class StartOfRoundPatcher
	{
		public static List<UnlockableEmote> allUnlockableEmotes;

		public static Dictionary<string, UnlockableEmote> allUnlockableEmotesDict;

		public static List<UnlockableEmote> complementaryEmotes;

		public static List<UnlockableEmote> unlockedFavoriteEmotes;

		public static List<string> allFavoriteEmotes;

		public static List<UnlockableEmote> allEmotesTier0;

		public static List<UnlockableEmote> allEmotesTier1;

		public static List<UnlockableEmote> allEmotesTier2;

		public static List<UnlockableEmote> allEmotesTier3;

		public static List<UnlockableEmote> unlockedEmotes;

		public static List<UnlockableEmote> unlockedEmotesTier0;

		public static List<UnlockableEmote> unlockedEmotesTier1;

		public static List<UnlockableEmote> unlockedEmotesTier2;

		public static List<UnlockableEmote> unlockedEmotesTier3;

		[HarmonyPatch(typeof(PreInitSceneScript), "Awake")]
		[HarmonyPostfix]
		public static void CreateEmoteLists()
		{
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPostfix]
		public static void InitializeEmotes(StartOfRound __instance)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: 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
			__instance.localClientAnimatorController = (RuntimeAnimatorController)new AnimatorOverrideController(__instance.localClientAnimatorController);
			__instance.otherClientsAnimatorController = (RuntimeAnimatorController)new AnimatorOverrideController(__instance.otherClientsAnimatorController);
			allUnlockableEmotes = new List<UnlockableEmote>();
			allUnlockableEmotesDict = new Dictionary<string, UnlockableEmote>();
			unlockedEmotes = new List<UnlockableEmote>();
			unlockedEmotesTier0 = new List<UnlockableEmote>();
			unlockedEmotesTier1 = new List<UnlockableEmote>();
			unlockedEmotesTier2 = new List<UnlockableEmote>();
			unlockedEmotesTier3 = new List<UnlockableEmote>();
			complementaryEmotes = new List<UnlockableEmote>();
			unlockedFavoriteEmotes = new List<UnlockableEmote>();
			allFavoriteEmotes = new List<string>();
			allEmotesTier0 = new List<UnlockableEmote>();
			allEmotesTier1 = new List<UnlockableEmote>();
			allEmotesTier2 = new List<UnlockableEmote>();
			allEmotesTier3 = new List<UnlockableEmote>();
			Dictionary<string, List<UnlockableEmote>> dictionary = new Dictionary<string, List<UnlockableEmote>>();
			for (int i = 0; i < Plugin.customAnimationClips.Count; i++)
			{
				AnimationClip val = Plugin.customAnimationClips[i];
				UnlockableEmote unlockableEmote = new UnlockableEmote
				{
					emoteId = i,
					emoteName = ((Object)val).name,
					displayName = "",
					animationClip = val,
					rarity = 0
				};
				unlockableEmote.rarity = (Plugin.animationClipsTier1.Contains(val) ? 1 : (Plugin.animationClipsTier2.Contains(val) ? 2 : (Plugin.animationClipsTier3.Contains(val) ? 3 : 0)));
				if (unlockableEmote.emoteName.Contains("_start"))
				{
					string key = unlockableEmote.emoteName.Replace("_start", "_loop");
					AnimationClip transitionsToClip = Plugin.customAnimationClipsLoopDict[key];
					unlockableEmote.transitionsToClip = transitionsToClip;
					unlockableEmote.emoteName = unlockableEmote.emoteName.Replace("_start", "");
				}
				if (unlockableEmote.emoteName.Contains("_pose"))
				{
					unlockableEmote.emoteName = unlockableEmote.emoteName.Replace("_pose", "");
					unlockableEmote.isPose = true;
				}
				if (unlockableEmote.emoteName.Contains("_sync"))
				{
					unlockableEmote.emoteName = unlockableEmote.emoteName.Replace("_syncable", "");
					unlockableEmote.canSyncEmote = true;
				}
				if (unlockableEmote.emoteName.Contains("_random"))
				{
					unlockableEmote.randomEmotePoolName = unlockableEmote.emoteName.Substring(0, unlockableEmote.emoteName.IndexOf("_random"));
					if (!dictionary.ContainsKey(unlockableEmote.randomEmotePoolName))
					{
						dictionary.Add(unlockableEmote.randomEmotePoolName, new List<UnlockableEmote> { unlockableEmote });
					}
					else
					{
						unlockableEmote.purchasable = false;
						dictionary[unlockableEmote.randomEmotePoolName].Add(unlockableEmote);
					}
					unlockableEmote.randomEmotePool = dictionary[unlockableEmote.randomEmotePoolName];
					unlockableEmote.emoteName = unlockableEmote.emoteName.Replace("_random", "");
					unlockableEmote.displayName = unlockableEmote.randomEmotePoolName;
				}
				if (unlockableEmote.displayName == "")
				{
					unlockableEmote.displayName = unlockableEmote.emoteName;
				}
				unlockableEmote.displayName = unlockableEmote.displayName.Replace('_', ' ').Trim(new char[1] { ' ' });
				unlockableEmote.displayName = char.ToUpper(unlockableEmote.displayName[0]) + unlockableEmote.displayName.Substring(1).ToLower();
				if (!allUnlockableEmotes.Contains(unlockableEmote))
				{
					allUnlockableEmotes.Add(unlockableEmote);
					allUnlockableEmotesDict.Add(unlockableEmote.emoteName, unlockableEmote);
				}
				if (Plugin.complementaryAnimationClips.Contains(val) && unlockableEmote.purchasable)
				{
					unlockableEmote.complementary = true;
					complementaryEmotes.Add(unlockableEmote);
				}
			}
			allUnlockableEmotes = (from item in allUnlockableEmotes
				orderby item.rarity, item.emoteName
				select item).ToList();
			int num = 0;
			foreach (UnlockableEmote allUnlockableEmote in allUnlockableEmotes)
			{
				allUnlockableEmote.emoteId = num++;
				if (allUnlockableEmote.rarity == 0)
				{
					allEmotesTier0.Add(allUnlockableEmote);
				}
				else if (allUnlockableEmote.rarity == 1)
				{
					allEmotesTier1.Add(allUnlockableEmote);
				}
				else if (allUnlockableEmote.rarity == 2)
				{
					allEmotesTier2.Add(allUnlockableEmote);
				}
				else if (allUnlockableEmote.rarity == 3)
				{
					allEmotesTier3.Add(allUnlockableEmote);
				}
			}
			SaveManager.LoadFavoritedEmotes();
			for (int j = 0; j < __instance.allPlayerScripts.Length; j++)
			{
				PlayerControllerB obj = __instance.allPlayerScripts[j];
				object obj2;
				if (obj == null)
				{
					obj2 = null;
				}
				else
				{
					Animator playerBodyAnimator = obj.playerBodyAnimator;
					obj2 = ((playerBodyAnimator != null) ? playerBodyAnimator.runtimeAnimatorController : null);
				}
				if ((Object)obj2 != (Object)null)
				{
					__instance.allPlayerScripts[j].playerBodyAnimator.runtimeAnimatorController = (RuntimeAnimatorController)new AnimatorOverrideController(__instance.otherClientsAnimatorController);
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "Start")]
		[HarmonyPostfix]
		public static void OnServerStart(StartOfRound __instance)
		{
			if (((NetworkBehaviour)__instance).IsServer)
			{
				UnlockEmotesLocal(ConfigSync.instance.syncUnlockEverything ? allUnlockableEmotes : complementaryEmotes);
				EmoteSyncManager.RotateEmoteSelectionServerRpc(TerminalPatcher.emoteStoreSeed);
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "StartGame")]
		[HarmonyPostfix]
		public static void ResetOverrideSeedFlag(StartOfRound __instance)
		{
			__instance.overrideRandomSeed = false;
		}

		[HarmonyPatch(typeof(StartOfRound), "ResetShip")]
		[HarmonyPostfix]
		public static void ResetEmotesOnShipReset(StartOfRound __instance)
		{
			if (!ConfigSync.instance.syncUnlockEverything)
			{
				ResetEmotesLocal();
			}
			if (NetworkManager.Singleton.IsServer)
			{
				EmoteSyncManager.RotateEmoteSelectionServerRpc();
			}
		}

		public static void ResetEmotesLocal()
		{
			Plugin.Log("Resetting progression.");
			unlockedEmotes.Clear();
			unlockedEmotesTier0.Clear();
			unlockedEmotesTier1.Clear();
			unlockedEmotesTier2.Clear();
			unlockedEmotesTier3.Clear();
			UnlockEmotesLocal(ConfigSync.instance.syncUnlockEverything ? allUnlockableEmotes : complementaryEmotes);
			UpdateUnlockedFavoriteEmotes();
			TerminalPatcher.currentEmoteCredits = ConfigSync.instance.syncStartingEmoteCredits;
			TerminalPatcher.emoteStoreSeed = 0;
		}

		public static void UpdateUnlockedFavoriteEmotes()
		{
			unlockedFavoriteEmotes.Clear();
			foreach (string allFavoriteEmote in allFavoriteEmotes)
			{
				if (allUnlockableEmotesDict.ContainsKey(allFavoriteEmote))
				{
					UnlockableEmote unlockableEmote = allUnlockableEmotesDict[allFavoriteEmote];
					if (unlockableEmote != null && unlockedEmotes.Contains(unlockableEmote))
					{
						unlockedFavoriteEmotes.Add(unlockableEmote);
					}
				}
				else
				{
					Plugin.LogWarning("Error loading favorited emote. Emote does not exist. The emote has likely been temporarily removed in this update.");
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesServerRpc")]
		[HarmonyPostfix]
		public static void SyncUnlockedEmotesWithClients(StartOfRound __instance)
		{
			if ((NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost) && !ConfigSync.instance.syncUnlockEverything)
			{
				Plugin.Log("Syncing unlocked emotes with clients.");
				EmoteSyncManager.SendOnUnlockEmoteUpdateMulti(TerminalPatcher.currentEmoteCredits);
			}
		}

		public static void UnlockEmotesLocal(List<UnlockableEmote> emotes)
		{
			foreach (UnlockableEmote emote in emotes)
			{
				UnlockEmoteLocal(emote);
			}
		}

		public static void UnlockEmoteLocal(int emoteId)
		{
			UnlockEmoteLocal((emoteId >= 0 && emoteId < allUnlockableEmotes.Count) ? allUnlockableEmotes[emoteId] : null);
		}

		public static void UnlockEmoteLocal(UnlockableEmote emote)
		{
			if (emote == null || unlockedEmotes.Contains(emote))
			{
				return;
			}
			if (emote.randomEmotePool != null)
			{
				foreach (UnlockableEmote item in emote.randomEmotePool)
				{
					if (unlockedEmotes.Contains(item))
					{
						return;
					}
				}
			}
			unlockedEmotes.Add(emote);
			if (emote.rarity == 3)
			{
				unlockedEmotesTier3.Add(emote);
			}
			else if (emote.rarity == 2)
			{
				unlockedEmotesTier2.Add(emote);
			}
			else if (emote.rarity == 1)
			{
				unlockedEmotesTier1.Add(emote);
			}
			else
			{
				unlockedEmotesTier0.Add(emote);
			}
			if (allFavoriteEmotes.Contains(emote.emoteName) && !unlockedFavoriteEmotes.Contains(emote))
			{
				unlockedFavoriteEmotes.Add(emote);
			}
		}

		public static void SortUnlockedEmotes()
		{
			unlockedEmotes = (from item in unlockedEmotes
				orderby item.rarity, item.emoteName
				select item).ToList();
		}
	}
	[HarmonyPatch]
	public class ThirdPersonEmoteController
	{
		public static GameObject playerHUDHelmetModel;

		public static Camera gameplayCamera;

		public static Camera emoteCamera;

		public static Transform emoteCameraPivot;

		public static float thirdPersonCameraDistance = 3f;

		public static int cameraCollideLayerMask = (1 << LayerMask.NameToLayer("Room")) | (1 << LayerMask.NameToLayer("PlaceableShipObject")) | (1 << LayerMask.NameToLayer("Terrain")) | (1 << LayerMask.NameToLayer("MiscLevelGeometry"));

		public static int localPlayerBodyLayer = 0;

		public static ShadowCastingMode defaultShadowCastingMode = (ShadowCastingMode)3;

		public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController;

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void InitLocalPlayerController(PlayerControllerB __instance)
		{
			//IL_0021: 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)
			gameplayCamera = __instance.gameplayCamera;
			if ((Object)(object)emoteCamera == (Object)null)
			{
				emoteCameraPivot = new GameObject("EmoteCameraPivot").transform;
				emoteCamera = new GameObject("EmoteCamera").AddComponent<Camera>();
				emoteCamera.CopyFrom(gameplayCamera);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SpawnPlayerAnimation")]
		[HarmonyPostfix]
		public static void OnPlayerSpawn(PlayerControllerB __instance)
		{
			//IL_0077: 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_011a: 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_0149: 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_0158: Unknown result type (might be due to invalid IL or missing references)
			((Behaviour)emoteCamera).enabled = false;
			StartOfRound.Instance.SwitchCamera(StartOfRound.Instance.activeCamera);
			((Component)__instance.thisPlayerModelLOD1).gameObject.layer = 5;
			((Renderer)__instance.thisPlayerModelLOD1).shadowCastingMode = (ShadowCastingMode)3;
			((Renderer)__instance.thisPlayerModelLOD2).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)__instance.thisPlayerModelLOD2).enabled = false;
			((Component)__instance.thisPlayerModel).gameObject.layer = localPlayerBodyLayer;
			((Renderer)__instance.thisPlayerModel).shadowCastingMode = defaultShadowCastingMode;
			((Component)__instance.thisPlayerModelArms).gameObject.layer = 5;
			Camera obj = gameplayCamera;
			obj.cullingMask &= -8388609;
			Camera obj2 = emoteCamera;
			obj2.cullingMask |= 0x800000;
			Camera obj3 = emoteCamera;
			obj3.cullingMask |= 1 << localPlayerBodyLayer;
			Camera obj4 = emoteCamera;
			obj4.cullingMask &= -161;
			((Component)emoteCameraPivot).transform.parent = ((Component)__instance).transform;
			emoteCameraPivot.SetLocalPositionAndRotation(Vector3.up * 1.8f, Quaternion.identity);
			((Component)emoteCamera).transform.parent = emoteCameraPivot;
			((Component)emoteCamera).transform.SetLocalPositionAndRotation(Vector3.back * thirdPersonCameraDistance, Quaternion.identity);
		}

		[HarmonyPatch(typeof(PlayerControllerB), "PlayerLookInput")]
		[HarmonyPrefix]
		public static bool UseFreeCamWhileEmoting(PlayerControllerB __instance)
		{
			//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_004a: 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_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_0079: 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_0094: 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_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: 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_0112: 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_017a: 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_0159: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)(object)localPlayerController && PlayerPatcher.performingCustomEmoteLocal != null && !localPlayerController.quickMenuManager.isMenuOpen)
			{
				MovementActions movement = localPlayerController.playerActions.Movement;
				Vector2 val = ((MovementActions)(ref movement)).Look.ReadValue<Vector2>() * 0.008f * (float)IngamePlayerSettings.Instance.settings.lookSensitivity;
				emoteCameraPivot.Rotate(new Vector3(0f, val.x, 0f));
				float num = emoteCameraPivot.localEulerAngles.x - val.y;
				num = ((num > 180f) ? (num - 360f) : num);
				num = Mathf.Clamp(num, -45f, 45f);
				((Component)emoteCameraPivot).transform.eulerAngles = new Vector3(num, emoteCameraPivot.eulerAngles.y, 0f);
				RaycastHit val2 = default(RaycastHit);
				if (Physics.Raycast(emoteCameraPivot.position, -emoteCameraPivot.forward * thirdPersonCameraDistance, ref val2, thirdPersonCameraDistance, cameraCollideLayerMask))
				{
					((Component)emoteCamera).transform.localPosition = Vector3.back * Mathf.Clamp(((RaycastHit)(ref val2)).distance - 0.1f, 0f, thirdPersonCameraDistance);
				}
				else
				{
					((Component)emoteCamera).transform.localPosition = Vector3.back * thirdPersonCameraDistance;
				}
				return false;
			}
			return true;
		}

		public static void OnStartCustomEmoteLocal()
		{
			//IL_0048: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			if (!((Behaviour)emoteCamera).enabled)
			{
				StartOfRound.Instance.SwitchCamera(emoteCamera);
				localPlayerController.playerBodyAnimator.SetInteger("emoteNumber", 1);
				emoteCameraPivot.eulerAngles = ((Component)gameplayCamera).transform.eulerAngles + new Vector3(0f, 0f, 0f);
			}
			((Renderer)localPlayerController.thisPlayerModel).shadowCastingMode = (ShadowCastingMode)1;
		}

		public static void OnStopCustomEmoteLocal()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			((Behaviour)emoteCamera).enabled = false;
			StartOfRound.Instance.SwitchCamera(gameplayCamera);
			((Renderer)localPlayerController.thisPlayerModel).shadowCastingMode = defaultShadowCastingMode;
		}
	}
	[HarmonyPatch]
	public static class SaveManager
	{
		[HarmonyPatch(typeof(GameNetworkManager), "SaveGameValues")]
		[HarmonyPostfix]
		public static void SaveUnlockedEmotes(GameNetworkManager __instance)
		{
			if (!__instance.isHostingGame || !StartOfRound.Instance.inShipPhase)
			{
				return;
			}
			try
			{
				string[] array = new string[StartOfRoundPatcher.unlockedEmotes.Count];
				int num = 0;
				foreach (UnlockableEmote unlockedEmote in StartOfRoundPatcher.u

BepInEx/plugins/FoxGod-ThiccCompanyModelReplacement/ThiccCompanyModelReplacementVer1.1.1.dll

Decompiled 10 months 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 HarmonyLib;
using Microsoft.CodeAnalysis;
using ModelReplacement;
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: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("ThiccCompanyModelReplacementVer1.1.1")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+badbd0bab98c875770ae72a5a894bf6ff2f74eda")]
[assembly: AssemblyProduct("ThiccCompanyModelReplacementVer1.1.1")]
[assembly: AssemblyTitle("ThiccCompanyModelReplacementVer1.1.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
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 ThiccModelReplacement
{
	public class BodyReplacementThicc : BodyReplacementBase
	{
		protected override GameObject LoadAssetsAndReturnModel()
		{
			string text = "ThiccCompany_V1_1_1Prefab";
			return Assets.MainAssetBundle.LoadAsset<GameObject>(text);
		}

		protected override void AddModelScripts()
		{
		}

		protected override void OnEmoteStart(int emoteId)
		{
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(29, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(44, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(49, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(58, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(60, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(83, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(84, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(25, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(45, 0f);
			if (emoteId == 1)
			{
				base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(83, 100f);
				base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(84, 100f);
				base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(25, 60f);
				base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(45, 100f);
			}
			if (emoteId == 2)
			{
				base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(29, 100f);
				base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(44, 100f);
				base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(49, 100f);
				base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(58, 100f);
				base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(60, 70f);
			}
		}

		protected override void OnEmoteEnd()
		{
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(83, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(84, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(25, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(45, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(29, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(44, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(49, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(58, 0f);
			base.replacementModel.GetComponentInChildren<SkinnedMeshRenderer>().SetBlendShapeWeight(60, 0f);
		}
	}
	[BepInPlugin("foxgod.ThiccCompany", "Thicc Model", "1.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static ConfigFile config;

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

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

		public static ConfigEntry<string> suitNamesToEnableThicc { get; private set; }

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

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

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

		private static void InitConfig()
		{
			enableThiccForAllSuits = config.Bind<bool>("Suits to Replace Settings", "Enable Thicc for all Suits", false, "Enable to replace every suit with Thicc Model. Set to false to specify suits");
			enableThiccAsDefault = config.Bind<bool>("Suits to Replace Settings", "Enable Thicc Model as default", false, "Enable to replace every suit that hasn't been otherwise registered with Thicc Model.");
			suitNamesToEnableThicc = config.Bind<string>("Suits to Replace Settings", "Suits to enable Thicc Model for", "Default,Orange suit", "Enter a comma separated list of suit names.(Additionally, [Green suit,Pajama suit,Hazard suit])");
			UpdateRate = config.Bind<float>("Dynamic Bone Settings", "Update rate", 60f, "Refreshes dynamic bones more times per second the higher the number");
			disablePhysicsAtRange = config.Bind<bool>("Dynamic Bone Settings", "Disable physics at range", false, "Enable to disable physics past the specified range");
			distanceDisablePhysics = config.Bind<float>("Dynamic Bone Settings", "Distance to disable physics", 20f, "If Disable physics at range is enabled, this is the range after which physics is disabled.");
		}

		private void Awake()
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Expected O, but got Unknown
			config = ((BaseUnityPlugin)this).Config;
			InitConfig();
			Assets.PopulateAssets();
			if (enableThiccForAllSuits.Value)
			{
				ModelReplacementAPI.RegisterModelReplacementOverride(typeof(BodyReplacementThicc));
			}
			if (enableThiccAsDefault.Value)
			{
				ModelReplacementAPI.RegisterModelReplacementDefault(typeof(BodyReplacementThicc));
			}
			string[] array = suitNamesToEnableThicc.Value.Split(',');
			string[] array2 = array;
			foreach (string text in array2)
			{
				ModelReplacementAPI.RegisterSuitModelReplacement(text, typeof(BodyReplacementThicc));
			}
			Harmony val = new Harmony("foxgod.ThiccCompany");
			val.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin foxgod.ThiccCompany is loaded!");
		}
	}
	public static class Assets
	{
		public static string mainAssetBundleName = "thicccompany_v1_1_1bundle";

		public static AssetBundle MainAssetBundle = null;

		private static string GetAssemblyName()
		{
			return Assembly.GetExecutingAssembly().GetName().Name;
		}

		public static void PopulateAssets()
		{
			if ((Object)(object)MainAssetBundle == (Object)null)
			{
				Console.WriteLine(GetAssemblyName() + "." + mainAssetBundleName);
				using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(GetAssemblyName() + "." + mainAssetBundleName);
				MainAssetBundle = AssetBundle.LoadFromStream(stream);
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}

BepInEx/plugins/matsuura-HealthMetrics/HealthMetrics.dll

Decompiled 10 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("HealthMetrics")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HealthMetrics")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("eba7b111-51e5-4353-807d-1268e6290901")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HealthMetrics
{
	[BepInPlugin("Matsuura.HealthMetrics", "HealthMetrics", "1.0.0")]
	public class HealthMetricsBase : BaseUnityPlugin
	{
		private const string modGUID = "Matsuura.HealthMetrics";

		private const string modName = "HealthMetrics";

		private const string modVersion = "1.0.0";

		private readonly Harmony _harmony = new Harmony("Matsuura.HealthMetrics");

		private static HealthMetricsBase _instance;

		private static ManualLogSource _logSource;

		internal void Awake()
		{
			if ((Object)(object)_instance == (Object)null)
			{
				_instance = this;
			}
			if (_logSource == null)
			{
				_logSource = Logger.CreateLogSource("Matsuura.HealthMetrics");
			}
			_harmony.PatchAll();
			_logSource.LogInfo((object)"HealthMetrics Awake");
		}

		internal static void Log(string message)
		{
			if (_logSource != null)
			{
				_logSource.LogInfo((object)message);
			}
		}

		internal static void LogD(string message)
		{
			if (_logSource != null)
			{
				_logSource.LogDebug((object)message);
			}
		}
	}
}
namespace HealthMetrics.Patches
{
	[HarmonyPatch(typeof(HUDManager))]
	internal class HealthHUDPatches
	{
		private static TextMeshProUGUI _healthText;

		private static readonly string DefaultValueHealthText = " ¤";

		public static int _oldValuehealthValueForUpdater = 0;

		public static int _healthValueForUpdater = 100;

		private static readonly Color _healthyColor = Color32.op_Implicit(new Color32((byte)0, byte.MaxValue, (byte)0, byte.MaxValue));

		private static readonly Color _criticalHealthColor = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)0, (byte)0, byte.MaxValue));

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void Start(ref HUDManager __instance)
		{
			//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_0039: 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)
			GameObject val = new GameObject("HealthHUDDisplay");
			val.AddComponent<RectTransform>();
			TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>();
			RectTransform rectTransform = ((TMP_Text)obj).rectTransform;
			((Transform)rectTransform).SetParent(((Component)__instance.PTTIcon).transform, false);
			rectTransform.anchoredPosition = new Vector2(8f, -57f);
			((TMP_Text)obj).font = ((TMP_Text)__instance.controlTipLines[0]).font;
			((TMP_Text)obj).fontSize = 16f;
			((TMP_Text)obj).text = "100";
			((Graphic)obj).color = _healthyColor;
			((TMP_Text)obj).overflowMode = (TextOverflowModes)0;
			((Behaviour)obj).enabled = true;
			_healthText = obj;
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void Update()
		{
			//IL_007d: 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_0088: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_healthText != (Object)null && _healthValueForUpdater != _oldValuehealthValueForUpdater)
			{
				_oldValuehealthValueForUpdater = _healthValueForUpdater;
				if (_healthValueForUpdater > 0)
				{
					((TMP_Text)_healthText).text = _healthValueForUpdater.ToString().PadLeft((_healthValueForUpdater < 10) ? 2 : 3, ' ');
				}
				else
				{
					((TMP_Text)_healthText).text = DefaultValueHealthText;
				}
				double percentage = (double)_healthValueForUpdater / 100.0;
				((Graphic)_healthText).color = ColorInterpolation(_criticalHealthColor, _healthyColor, percentage);
			}
		}

		public static int LinearInterpolation(int start, int end, double percentage)
		{
			return start + (int)Math.Round(percentage * (double)(end - start));
		}

		public static Color ColorInterpolation(Color start, Color end, double percentage)
		{
			//IL_0000: 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_0021: 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_0042: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			return new Color(hexToFloat(LinearInterpolation(floatToHex(start.r), floatToHex(end.r), percentage)), hexToFloat(LinearInterpolation(floatToHex(start.g), floatToHex(end.g), percentage)), hexToFloat(LinearInterpolation(floatToHex(start.b), floatToHex((int)end.b), percentage)), 1f);
		}

		public static float hexToFloat(int hex)
		{
			return (float)hex / 255f;
		}

		public static int floatToHex(float f)
		{
			return (int)f * 255;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch("LateUpdate")]
		private static void LateUpdate_Prefix(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject))
			{
				HealthHUDPatches._healthValueForUpdater = ((__instance.health >= 0) ? __instance.health : 0);
			}
		}
	}
}

BepInEx/plugins/MonAmiral-PlayerDogModel/PlayerDogModel/PlayerDogModel.dll

Decompiled 10 months ago
using System;
using System.Collections;
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 GameNetcodeStuff;
using HarmonyLib;
using LC_API.BundleAPI;
using LC_API.ServerAPI;
using Newtonsoft.Json;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("PlayerDogModel")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A mod to replace Player models with a dog for Lethal Company")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2")]
[assembly: AssemblyProduct("PlayerDogModel")]
[assembly: AssemblyTitle("PlayerDogModel")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.2.0")]
[module: UnverifiableCode]
namespace PlayerDogModel;

[DefaultExecutionOrder(-1)]
public class PlayerModelReplacer : MonoBehaviour
{
	[JsonObject]
	internal class ToggleData
	{
		[JsonProperty]
		public ulong ownerSteamId { get; set; }

		[JsonProperty]
		public bool isDog { get; set; }

		[JsonProperty]
		public bool playAudio { get; set; }
	}

	public static PlayerModelReplacer LocalReplacer;

	private static bool loaded;

	private static string exceptionMessage;

	private static Exception exception;

	private PlayerControllerB playerController;

	private GameObject dogGameObject;

	private GameObject[] humanGameObjects;

	private SkinnedMeshRenderer[] dogRenderers;

	private Transform dogTorso;

	private PositionConstraint torsoConstraint;

	private static AudioClip humanClip;

	private static AudioClip dogClip;

	private Vector3 humanCameraPosition;

	private Transform localItemAnchor;

	private Transform serverItemAnchor;

	private static Image healthFill;

	private static Image healthOutline;

	private static Sprite humanFill;

	private static Sprite humanOutline;

	private static Sprite dogFill;

	private static Sprite dogOutline;

	private bool isDogActive;

	public bool IsDog => isDogActive;

	private void Awake()
	{
		if (!loaded)
		{
			loaded = true;
			LoadImageResources();
			((MonoBehaviour)this).StartCoroutine(LoadAudioResources());
		}
	}

	private void Start()
	{
		//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)
		playerController = ((Component)this).GetComponent<PlayerControllerB>();
		if (((NetworkBehaviour)playerController).IsOwner)
		{
			LocalReplacer = this;
		}
		humanCameraPosition = ((Component)playerController.gameplayCamera).transform.localPosition;
		Debug.Log((object)$"Adding PlayerModelReplacer on {playerController.playerUsername} ({((NetworkBehaviour)playerController).IsOwner})");
		SpawnDogModel();
		EnableHumanModel(playAudio: false);
		Networking.GetString = (Action<string, string>)Delegate.Combine(Networking.GetString, new Action<string, string>(Networking_GetString));
	}

	private void Update()
	{
		//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_0091: 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_00a2: 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_0179: Unknown result type (might be due to invalid IL or missing references)
		//IL_0189: 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_013e: 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)
		if (!string.IsNullOrEmpty(exceptionMessage))
		{
			return;
		}
		Vector3 val = humanCameraPosition;
		if (isDogActive && !playerController.inTerminalMenu && !playerController.inSpecialInteractAnimation)
		{
			if (!playerController.isCrouching)
			{
				((Vector3)(ref val))..ctor(0f, -1.1f, 0.3f);
			}
			else
			{
				((Vector3)(ref val))..ctor(0f, -0.5f, 0.3f);
			}
		}
		((Component)playerController.gameplayCamera).transform.localPosition = Vector3.MoveTowards(((Component)playerController.gameplayCamera).transform.localPosition, val, Time.deltaTime * 2f);
		if (playerController.isCrouching)
		{
			torsoConstraint.weight = Mathf.MoveTowards(torsoConstraint.weight, 0.5f, Time.deltaTime * 3f);
		}
		else
		{
			torsoConstraint.weight = Mathf.MoveTowards(torsoConstraint.weight, 1f, Time.deltaTime * 3f);
		}
		if (playerController.isClimbingLadder)
		{
			dogTorso.localRotation = Quaternion.RotateTowards(dogTorso.localRotation, Quaternion.Euler(90f, 0f, 0f), Time.deltaTime * 360f);
		}
		else
		{
			dogTorso.localRotation = Quaternion.RotateTowards(dogTorso.localRotation, Quaternion.Euler(180f, 0f, 0f), Time.deltaTime * 360f);
		}
	}

	private void LateUpdate()
	{
		//IL_0063: 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_0036: 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_0087: 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_00c3: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)localItemAnchor == (Object)null) && !((Object)(object)serverItemAnchor == (Object)null))
		{
			if (isDogActive)
			{
				playerController.localItemHolder.position = localItemAnchor.position;
				playerController.serverItemHolder.position = serverItemAnchor.position;
			}
			if (((Renderer)dogRenderers[0]).shadowCastingMode != ((Renderer)playerController.thisPlayerModel).shadowCastingMode)
			{
				Debug.Log((object)$"Dog model is on the wrong shadow casting mode. ({((Renderer)dogRenderers[0]).shadowCastingMode} instead of {((Renderer)playerController.thisPlayerModel).shadowCastingMode})");
				((Renderer)dogRenderers[0]).shadowCastingMode = ((Renderer)playerController.thisPlayerModel).shadowCastingMode;
			}
			if (((Component)dogRenderers[0]).gameObject.layer != ((Component)playerController.thisPlayerModel).gameObject.layer)
			{
				Debug.Log((object)("Dog model is on the wrong layer. (" + LayerMask.LayerToName(((Component)dogRenderers[0]).gameObject.layer) + " instead of " + LayerMask.LayerToName(((Component)playerController.thisPlayerModel).gameObject.layer) + ")"));
				((Component)dogRenderers[0]).gameObject.layer = ((Component)playerController.thisPlayerModel).gameObject.layer;
			}
		}
	}

	private void SpawnDogModel()
	{
		//IL_002e: 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_005f: 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_00c6: 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_00fe: 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_0137: 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_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: 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_017f: 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_0187: 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_018f: 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_02e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fd: 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_0329: 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_035f: Unknown result type (might be due to invalid IL or missing references)
		//IL_037a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0385: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f7: 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_041d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0443: Unknown result type (might be due to invalid IL or missing references)
		//IL_045e: 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_048f: Unknown result type (might be due to invalid IL or missing references)
		//IL_04aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			GameObject loadedAsset = BundleLoader.GetLoadedAsset<GameObject>("assets/Dog.fbx");
			dogGameObject = Object.Instantiate<GameObject>(loadedAsset, ((Component)this).transform);
			dogGameObject.transform.position = ((Component)this).transform.position;
			dogGameObject.transform.eulerAngles = ((Component)this).transform.eulerAngles;
			Transform transform = dogGameObject.transform;
			transform.localScale *= 2f;
		}
		catch (Exception ex)
		{
			exceptionMessage = "Failed to spawn dog model.";
			exception = ex;
			Debug.LogError((object)exceptionMessage);
			Debug.LogException(exception);
		}
		dogRenderers = dogGameObject.GetComponentsInChildren<SkinnedMeshRenderer>();
		UpdateMaterial();
		try
		{
			LODGroup val = dogGameObject.AddComponent<LODGroup>();
			val.fadeMode = (LODFadeMode)0;
			LOD val2 = default(LOD);
			val2.screenRelativeTransitionHeight = 0.4564583f;
			val2.renderers = (Renderer[])(object)new Renderer[1] { (Renderer)dogRenderers[0] };
			val2.fadeTransitionWidth = 0f;
			LOD val3 = val2;
			val2 = default(LOD);
			val2.screenRelativeTransitionHeight = 0.1795709f;
			val2.renderers = (Renderer[])(object)new Renderer[1] { (Renderer)dogRenderers[1] };
			val2.fadeTransitionWidth = 0f;
			LOD val4 = val2;
			val2 = default(LOD);
			val2.screenRelativeTransitionHeight = 0.009000001f;
			val2.renderers = (Renderer[])(object)new Renderer[1] { (Renderer)dogRenderers[2] };
			val2.fadeTransitionWidth = 0.435f;
			LOD val5 = val2;
			val.SetLODs((LOD[])(object)new LOD[3] { val3, val4, val5 });
		}
		catch (Exception ex2)
		{
			exceptionMessage = "Failed to set up the LOD.";
			exception = ex2;
			Debug.LogError((object)exceptionMessage);
			Debug.LogException(exception);
		}
		try
		{
			dogTorso = dogGameObject.transform.Find("Armature").Find("torso");
			Transform val6 = dogTorso.Find("head");
			Transform val7 = dogTorso.Find("arm.L");
			Transform val8 = dogTorso.Find("arm.R");
			Transform val9 = dogTorso.Find("butt").Find("leg.L");
			Transform val10 = dogTorso.Find("butt").Find("leg.R");
			Transform val11 = ((Component)this).transform.Find("ScavengerModel").Find("metarig").Find("spine");
			Transform sourceTransform = val11.Find("spine.001").Find("spine.002").Find("spine.003")
				.Find("spine.004");
			Transform sourceTransform2 = val11.Find("thigh.L");
			Transform sourceTransform3 = val11.Find("thigh.R");
			try
			{
				torsoConstraint = ((Component)dogTorso).gameObject.AddComponent<PositionConstraint>();
				PositionConstraint obj = torsoConstraint;
				ConstraintSource val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = val11;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj.AddSource(val12);
				torsoConstraint.translationAtRest = dogTorso.localPosition;
				torsoConstraint.translationOffset = dogTorso.InverseTransformPoint(val11.position);
				torsoConstraint.constraintActive = true;
				torsoConstraint.locked = true;
				RotationConstraint obj2 = ((Component)val6).gameObject.AddComponent<RotationConstraint>();
				val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = sourceTransform;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj2.AddSource(val12);
				obj2.rotationAtRest = val6.localEulerAngles;
				obj2.constraintActive = true;
				obj2.locked = true;
				RotationConstraint obj3 = ((Component)val7).gameObject.AddComponent<RotationConstraint>();
				val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = sourceTransform3;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj3.AddSource(val12);
				obj3.rotationAtRest = val7.localEulerAngles;
				obj3.constraintActive = true;
				obj3.locked = true;
				RotationConstraint obj4 = ((Component)val8).gameObject.AddComponent<RotationConstraint>();
				val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = sourceTransform2;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj4.AddSource(val12);
				obj4.rotationAtRest = val8.localEulerAngles;
				obj4.constraintActive = true;
				obj4.locked = true;
				RotationConstraint obj5 = ((Component)val9).gameObject.AddComponent<RotationConstraint>();
				val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = sourceTransform2;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj5.AddSource(val12);
				obj5.rotationAtRest = val9.localEulerAngles;
				obj5.constraintActive = true;
				obj5.locked = true;
				RotationConstraint obj6 = ((Component)val10).gameObject.AddComponent<RotationConstraint>();
				val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = sourceTransform3;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj6.AddSource(val12);
				obj6.rotationAtRest = val10.localEulerAngles;
				obj6.constraintActive = true;
				obj6.locked = true;
			}
			catch (Exception ex3)
			{
				exceptionMessage = "Failed to set up the constraints.";
				exception = ex3;
				Debug.LogError((object)exceptionMessage);
				Debug.LogException(exception);
			}
			serverItemAnchor = val6.Find("serverItem");
			localItemAnchor = val6.Find("localItem");
		}
		catch (Exception ex4)
		{
			exceptionMessage = "Failed to retrieve bones. What the hell?";
			exception = ex4;
			Debug.LogError((object)exceptionMessage);
			Debug.LogException(exception);
		}
		humanGameObjects = (GameObject[])(object)new GameObject[6];
		humanGameObjects[0] = ((Component)playerController.thisPlayerModel).gameObject;
		humanGameObjects[1] = ((Component)playerController.thisPlayerModelLOD1).gameObject;
		humanGameObjects[2] = ((Component)playerController.thisPlayerModelLOD2).gameObject;
		humanGameObjects[3] = ((Component)playerController.thisPlayerModelArms).gameObject;
		humanGameObjects[4] = ((Component)playerController.playerBetaBadgeMesh).gameObject;
		humanGameObjects[5] = ((Component)((Component)playerController.playerBetaBadgeMesh).transform.parent.Find("LevelSticker")).gameObject;
	}

	private void EnableHumanModel(bool playAudio = true)
	{
		isDogActive = false;
		dogGameObject.SetActive(false);
		GameObject[] array = humanGameObjects;
		for (int i = 0; i < array.Length; i++)
		{
			array[i].SetActive(true);
		}
		if (playAudio)
		{
			playerController.movementAudio.PlayOneShot(humanClip);
		}
		if (((NetworkBehaviour)playerController).IsOwner && Object.op_Implicit((Object)(object)healthFill))
		{
			healthFill.sprite = humanFill;
			healthOutline.sprite = humanOutline;
		}
	}

	private void EnableDogModel(bool playAudio = true)
	{
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		isDogActive = true;
		dogGameObject.SetActive(true);
		((Renderer)dogRenderers[0]).shadowCastingMode = ((Renderer)playerController.thisPlayerModel).shadowCastingMode;
		GameObject[] array = humanGameObjects;
		for (int i = 0; i < array.Length; i++)
		{
			array[i].SetActive(false);
		}
		if (playAudio)
		{
			playerController.movementAudio.PlayOneShot(dogClip);
		}
		if (((NetworkBehaviour)playerController).IsOwner)
		{
			if (!Object.op_Implicit((Object)(object)healthFill))
			{
				healthFill = ((Component)HUDManager.Instance.selfRedCanvasGroup).GetComponent<Image>();
				healthOutline = ((Component)((Component)HUDManager.Instance.selfRedCanvasGroup).transform.parent.Find("Self")).GetComponent<Image>();
				humanFill = healthFill.sprite;
				humanOutline = healthOutline.sprite;
			}
			healthFill.sprite = dogFill;
			healthOutline.sprite = dogOutline;
		}
	}

	public void UpdateMaterial()
	{
		if (dogRenderers == null)
		{
			Debug.LogWarning((object)"Skipping material replacement on dog because there was an error earlier.");
			return;
		}
		SkinnedMeshRenderer[] array = dogRenderers;
		for (int i = 0; i < array.Length; i++)
		{
			((Renderer)array[i]).material = ((Renderer)playerController.thisPlayerModel).material;
		}
	}

	public void ToggleAndBroadcast(bool playAudio = true)
	{
		if (isDogActive)
		{
			EnableHumanModel();
		}
		else
		{
			EnableDogModel();
		}
		BroadcastSelectedModel(playAudio);
	}

	public void BroadcastSelectedModel(bool playAudio)
	{
		Debug.Log((object)$"Sent dog={isDogActive} on {playerController.playerSteamId} ({playerController.playerUsername}).");
		Networking.Broadcast(JsonConvert.SerializeObject((object)new ToggleData
		{
			ownerSteamId = playerController.playerSteamId,
			isDog = isDogActive,
			playAudio = playAudio
		}), "modelswitch");
	}

	public static void RequestSelectedModelBroadcast()
	{
		Networking.Broadcast("hello this is dog", "modelinfo");
	}

	private static void LoadImageResources()
	{
		//IL_0024: 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_006b: 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)
		try
		{
			Texture2D loadedAsset = BundleLoader.GetLoadedAsset<Texture2D>("assets/TPoseFilled.png");
			dogFill = Sprite.Create(loadedAsset, new Rect(0f, 0f, (float)((Texture)loadedAsset).width, (float)((Texture)loadedAsset).height), new Vector2(0.5f, 0.5f), 100f);
			Texture2D loadedAsset2 = BundleLoader.GetLoadedAsset<Texture2D>("assets/TPoseOutline.png");
			dogOutline = Sprite.Create(loadedAsset2, new Rect(0f, 0f, (float)((Texture)loadedAsset2).width, (float)((Texture)loadedAsset2).height), new Vector2(0.5f, 0.5f), 100f);
		}
		catch (Exception ex)
		{
			exceptionMessage = "Failed to retrieve images.";
			exception = ex;
			Debug.LogError((object)exceptionMessage);
			Debug.LogException(exception);
		}
	}

	private static IEnumerator LoadAudioResources()
	{
		string fullPath2 = GetAssemblyFullPath("ChangeSuitToHuman.wav");
		UnityWebRequest request2 = UnityWebRequestMultimedia.GetAudioClip(fullPath2, (AudioType)20);
		yield return request2.SendWebRequest();
		if (request2.error == null)
		{
			humanClip = DownloadHandlerAudioClip.GetContent(request2);
			((Object)humanClip).name = Path.GetFileName(fullPath2);
		}
		fullPath2 = GetAssemblyFullPath("ChangeSuitToDog.wav");
		request2 = UnityWebRequestMultimedia.GetAudioClip(fullPath2, (AudioType)20);
		yield return request2.SendWebRequest();
		if (request2.error == null)
		{
			dogClip = DownloadHandlerAudioClip.GetContent(request2);
			((Object)dogClip).name = Path.GetFileName(fullPath2);
		}
	}

	private static string GetAssemblyFullPath(string additionalPath)
	{
		string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
		return Path.GetFullPath((additionalPath != null) ? Path.Combine(directoryName, ".\\" + additionalPath) : directoryName);
	}

	private void Networking_GetString(string data, string signature)
	{
		if (!(signature == "modelswitch"))
		{
			if (signature == "modelinfo")
			{
				BroadcastSelectedModel(playAudio: false);
			}
			return;
		}
		if (!Object.op_Implicit((Object)(object)dogGameObject))
		{
			Debug.LogError((object)"Dog encountered an error when it was initialized and it can't be toggled. Check the log for more info.");
			return;
		}
		ToggleData toggleData = JsonConvert.DeserializeObject<ToggleData>(data);
		if (playerController.playerSteamId == toggleData.ownerSteamId)
		{
			Debug.Log((object)$"Received dog={toggleData.isDog} for {playerController.playerSteamId} ({playerController.playerUsername}).");
			if (toggleData.isDog)
			{
				EnableDogModel(toggleData.playAudio);
			}
			else
			{
				EnableHumanModel(toggleData.playAudio);
			}
		}
	}
}
public class PlayerModelSwitcher : MonoBehaviour
{
	private void Start()
	{
		//IL_001b: 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_003b: 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_0105: 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_0167: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		GameObject obj = Object.Instantiate<GameObject>(BundleLoader.GetLoadedAsset<GameObject>("assets/Helmets.fbx"), ((Component)this).transform);
		obj.transform.localPosition = Vector3.zero;
		obj.transform.localRotation = Quaternion.identity;
		obj.transform.localScale = Vector3.one * 0.75f;
		Renderer component = obj.GetComponent<Renderer>();
		Material[] materials = component.materials;
		for (int i = 0; i < StartOfRound.Instance.unlockablesList.unlockables.Count; i++)
		{
			if (Object.op_Implicit((Object)(object)StartOfRound.Instance.unlockablesList.unlockables[0].suitMaterial))
			{
				materials[0] = StartOfRound.Instance.unlockablesList.unlockables[0].suitMaterial;
				break;
			}
		}
		materials[1] = ((Component)this).GetComponent<Renderer>().material;
		component.materials = materials;
		GameObject gameObject = ((Component)Object.Instantiate<ScanNodeProperties>(Object.FindObjectOfType<ScanNodeProperties>())).gameObject;
		gameObject.transform.parent = ((Component)this).transform;
		gameObject.transform.localPosition = new Vector3(0.75f, 0f, 0.8f);
		ScanNodeProperties component2 = gameObject.GetComponent<ScanNodeProperties>();
		component2.headerText = "Dog equipment";
		component2.subText = "Switch to the dog model here.";
		InteractTrigger obj2 = Object.Instantiate<InteractTrigger>(((Component)GameObject.Find("SpeakerAudio").transform.parent).GetComponentInChildren<InteractTrigger>());
		((Component)obj2).transform.position = ((Component)this).transform.TransformPoint(new Vector3(0.75f, 0f, 0.9f));
		((Component)obj2).transform.localScale = new Vector3(0.3f, 0.7f, 0.3f);
		obj2.hoverTip = "Switch model";
		obj2.interactable = true;
		obj2.cooldownTime = 1f;
		((UnityEventBase)obj2.onCancelAnimation).RemoveAllListeners();
		((UnityEventBase)obj2.onInteractEarly).RemoveAllListeners();
		((UnityEventBase)obj2.onStopInteract).RemoveAllListeners();
		((UnityEventBase)obj2.onInteract).RemoveAllListeners();
		((UnityEvent<PlayerControllerB>)(object)obj2.onInteract).AddListener((UnityAction<PlayerControllerB>)Interacted);
	}

	private void Interacted(PlayerControllerB player)
	{
		((Component)player).GetComponentInChildren<PlayerModelReplacer>().ToggleAndBroadcast();
	}
}
[BepInPlugin("PlayerDogModel", "PlayerDogModel", "1.0.2")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInProcess("Lethal Company.exe")]
public class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		[HarmonyPatch("SpawnPlayerAnimation")]
		[HarmonyPostfix]
		public static void SpawnPlayerAnimationPatch(ref PlayerControllerB __instance)
		{
			GameObject[] allPlayerObjects = StartOfRound.Instance.allPlayerObjects;
			foreach (GameObject val in allPlayerObjects)
			{
				if (!Object.op_Implicit((Object)(object)val.GetComponent<PlayerModelReplacer>()))
				{
					val.gameObject.AddComponent<PlayerModelReplacer>();
				}
			}
			PlayerModelReplacer.RequestSelectedModelBroadcast();
		}
	}

	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("PositionSuitsOnRack")]
		[HarmonyPostfix]
		public static void PositionSuitsOnRackPatch(ref StartOfRound __instance)
		{
			if (!Object.op_Implicit((Object)(object)Object.FindObjectOfType<PlayerModelSwitcher>()))
			{
				GameObject.Find("NurbsPath.002").AddComponent<PlayerModelSwitcher>();
			}
		}
	}

	[HarmonyPatch(typeof(UnlockableSuit))]
	internal class UnlockableSuitPatch
	{
		[HarmonyPatch("SwitchSuitForPlayer")]
		[HarmonyPostfix]
		public static void SwitchSuitForPlayerPatch(PlayerControllerB player, int suitID, bool playAudio = true)
		{
			PlayerModelReplacer component = ((Component)player).GetComponent<PlayerModelReplacer>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.UpdateMaterial();
			}
		}
	}

	[HarmonyPatch(typeof(DeadBodyInfo))]
	internal class DeadBodyPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void StartPatch(ref DeadBodyInfo __instance)
		{
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: 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_01cf: 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_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: 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_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: 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_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0322: Unknown result type (might be due to invalid IL or missing references)
			if (((Component)__instance.playerScript).GetComponent<PlayerModelReplacer>().IsDog)
			{
				SkinnedMeshRenderer component = ((Component)__instance).GetComponent<SkinnedMeshRenderer>();
				((Renderer)component).enabled = false;
				Material material = ((Renderer)component).material;
				Transform obj = ((Component)__instance).transform.Find("spine.001");
				Transform sourceTransform = obj.Find("spine.002").Find("spine.003").Find("spine.004");
				Transform sourceTransform2 = obj.Find("spine.002").Find("spine.003").Find("shoulder.L")
					.Find("arm.L_upper");
				Transform sourceTransform3 = obj.Find("spine.002").Find("spine.003").Find("shoulder.R")
					.Find("arm.R_upper");
				Transform sourceTransform4 = obj.Find("thigh.L");
				Transform sourceTransform5 = obj.Find("thigh.R");
				GameObject val = Object.Instantiate<GameObject>(BundleLoader.GetLoadedAsset<GameObject>("assets/DogRagdoll.fbx"), ((Component)__instance).transform);
				val.transform.position = ((Component)__instance).transform.position;
				val.transform.eulerAngles = ((Component)__instance).transform.eulerAngles;
				Transform transform = val.transform;
				transform.localScale *= 1.8f;
				SkinnedMeshRenderer[] componentsInChildren = val.GetComponentsInChildren<SkinnedMeshRenderer>();
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					((Renderer)componentsInChildren[i]).material = material;
				}
				Transform obj2 = val.transform.Find("Armature").Find("torso");
				Transform val2 = obj2.Find("head");
				Transform val3 = obj2.Find("arm.L");
				Transform val4 = obj2.Find("arm.R");
				Transform val5 = obj2.Find("butt").Find("leg.L");
				Transform val6 = obj2.Find("butt").Find("leg.R");
				RotationConstraint obj3 = ((Component)val2).gameObject.AddComponent<RotationConstraint>();
				ConstraintSource val7 = default(ConstraintSource);
				((ConstraintSource)(ref val7)).sourceTransform = sourceTransform;
				((ConstraintSource)(ref val7)).weight = 1f;
				obj3.AddSource(val7);
				obj3.rotationAtRest = val2.localEulerAngles;
				obj3.constraintActive = true;
				obj3.locked = true;
				RotationConstraint obj4 = ((Component)val3).gameObject.AddComponent<RotationConstraint>();
				val7 = default(ConstraintSource);
				((ConstraintSource)(ref val7)).sourceTransform = sourceTransform3;
				((ConstraintSource)(ref val7)).weight = 1f;
				obj4.AddSource(val7);
				obj4.rotationAtRest = val3.localEulerAngles;
				obj4.constraintActive = true;
				obj4.locked = true;
				RotationConstraint obj5 = ((Component)val4).gameObject.AddComponent<RotationConstraint>();
				val7 = default(ConstraintSource);
				((ConstraintSource)(ref val7)).sourceTransform = sourceTransform2;
				((ConstraintSource)(ref val7)).weight = 1f;
				obj5.AddSource(val7);
				obj5.rotationAtRest = val4.localEulerAngles;
				obj5.constraintActive = true;
				obj5.locked = true;
				RotationConstraint obj6 = ((Component)val5).gameObject.AddComponent<RotationConstraint>();
				val7 = default(ConstraintSource);
				((ConstraintSource)(ref val7)).sourceTransform = sourceTransform4;
				((ConstraintSource)(ref val7)).weight = 1f;
				obj6.AddSource(val7);
				obj6.rotationAtRest = val5.localEulerAngles;
				obj6.constraintActive = true;
				obj6.locked = true;
				RotationConstraint obj7 = ((Component)val6).gameObject.AddComponent<RotationConstraint>();
				val7 = default(ConstraintSource);
				((ConstraintSource)(ref val7)).sourceTransform = sourceTransform5;
				((ConstraintSource)(ref val7)).weight = 1f;
				obj7.AddSource(val7);
				obj7.rotationAtRest = val6.localEulerAngles;
				obj7.constraintActive = true;
				obj7.locked = true;
			}
		}
	}

	public static Harmony _harmony;

	private void Awake()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Expected O, but got Unknown
		_harmony = new Harmony("PlayerDogModel");
		_harmony.PatchAll();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"PlayerDogModel loaded");
		BundleLoader.LoadAssetBundle(GetAssemblyFullPath("playerdog"), true);
	}

	private static string GetAssemblyFullPath(string additionalPath)
	{
		string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
		return Path.GetFullPath((additionalPath != null) ? Path.Combine(directoryName, ".\\" + additionalPath) : directoryName);
	}
}
public static class PluginInfo
{
	public const string PLUGIN_GUID = "PlayerDogModel";

	public const string PLUGIN_NAME = "PlayerDogModel";

	public const string PLUGIN_VERSION = "1.0.2";
}

BepInEx/plugins/notnotnotswipez-MoreCompany/MoreCompany.dll

Decompiled 10 months 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.Text;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using MoreCompany.Cosmetics;
using MoreCompany.Utils;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
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: AssemblyTitle("MoreCompany")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MoreCompany")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("511a1e5e-0611-49f1-b60f-cec69c668fd8")]
[assembly: AssemblyFileVersion("1.7.2")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.7.2.0")]
namespace MoreCompany
{
	[HarmonyPatch(typeof(AudioMixer), "SetFloat")]
	public static class AudioMixerSetFloatPatch
	{
		public static bool Prefix(string name, float value)
		{
			if (name.StartsWith("PlayerVolume") || name.StartsWith("PlayerPitch"))
			{
				string s = name.Replace("PlayerVolume", "").Replace("PlayerPitch", "");
				int num = int.Parse(s);
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[num];
				AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource;
				if ((Object)(object)val != (Object)null && Object.op_Implicit((Object)(object)currentVoiceChatAudioSource))
				{
					if (name.StartsWith("PlayerVolume"))
					{
						currentVoiceChatAudioSource.volume = value / 16f;
					}
					else if (name.StartsWith("PlayerPitch"))
					{
						currentVoiceChatAudioSource.pitch = value;
					}
				}
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddTextToChatOnServer")]
	public static class SendChatToServerPatch
	{
		public static bool Prefix(HUDManager __instance, string chatMessage, int playerId = -1)
		{
			if (((NetworkBehaviour)StartOfRound.Instance).IsHost && chatMessage.StartsWith("/mc") && DebugCommandRegistry.commandEnabled)
			{
				string text = chatMessage.Replace("/mc ", "");
				DebugCommandRegistry.HandleCommand(text.Split(new char[1] { ' ' }));
				return false;
			}
			if (chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				ReflectionUtils.InvokeMethod(__instance, "AddPlayerChatMessageServerRpc", new object[2] { chatMessage, 99 });
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageServerRpc")]
	public static class ServerReceiveMessagePatch
	{
		public static string previousDataMessage = "";

		public static bool Prefix(HUDManager __instance, ref string chatMessage, int playerId)
		{
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening)
			{
				return false;
			}
			if (chatMessage.StartsWith("[morecompanycosmetics]") && networkManager.IsServer)
			{
				previousDataMessage = chatMessage;
				chatMessage = "[replacewithdata]";
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
	public static class ConnectClientToPlayerObjectPatch
	{
		public static void Postfix(PlayerControllerB __instance)
		{
			string text = "[morecompanycosmetics]";
			text = text + ";" + __instance.playerClientId;
			foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics)
			{
				text = text + ";" + locallySelectedCosmetic;
			}
			HUDManager.Instance.AddTextToChatOnServer(text, -1);
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddChatMessage")]
	public static class AddChatMessagePatch
	{
		public static bool Prefix(HUDManager __instance, string chatMessage, string nameOfUserWhoTyped = "")
		{
			if (chatMessage.StartsWith("[replacewithdata]") || chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageClientRpc")]
	public static class ClientReceiveMessagePatch
	{
		public static bool ignoreSample;

		public static bool Prefix(HUDManager __instance, ref string chatMessage, int playerId)
		{
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening)
			{
				return false;
			}
			if (networkManager.IsServer)
			{
				if (chatMessage.StartsWith("[replacewithdata]"))
				{
					chatMessage = ServerReceiveMessagePatch.previousDataMessage;
					HandleDataMessage(chatMessage);
				}
				else if (chatMessage.StartsWith("[morecompanycosmetics]"))
				{
					return false;
				}
			}
			else if (chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				HandleDataMessage(chatMessage);
			}
			return true;
		}

		private static void HandleDataMessage(string chatMessage)
		{
			//IL_0160: 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)
			if (ignoreSample)
			{
				return;
			}
			chatMessage = chatMessage.Replace("[morecompanycosmetics]", "");
			string[] array = chatMessage.Split(new char[1] { ';' });
			string text = array[1];
			int num = int.Parse(text);
			CosmeticApplication component = ((Component)((Component)StartOfRound.Instance.allPlayerScripts[num]).transform.Find("ScavengerModel").Find("metarig")).gameObject.GetComponent<CosmeticApplication>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.ClearCosmetics();
				Object.Destroy((Object)(object)component);
			}
			CosmeticApplication cosmeticApplication = ((Component)((Component)StartOfRound.Instance.allPlayerScripts[num]).transform.Find("ScavengerModel").Find("metarig")).gameObject.AddComponent<CosmeticApplication>();
			cosmeticApplication.ClearCosmetics();
			List<string> list = new List<string>();
			string[] array2 = array;
			foreach (string text2 in array2)
			{
				if (!(text2 == text))
				{
					list.Add(text2);
					if (MainClass.showCosmetics)
					{
						cosmeticApplication.ApplyCosmetic(text2, startEnabled: true);
					}
				}
			}
			if (num == StartOfRound.Instance.thisClientPlayerId)
			{
				cosmeticApplication.ClearCosmetics();
			}
			foreach (CosmeticInstance spawnedCosmetic in cosmeticApplication.spawnedCosmetics)
			{
				Transform transform = ((Component)spawnedCosmetic).transform;
				transform.localScale *= 0.38f;
			}
			MainClass.playerIdsAndCosmetics.Remove(num);
			MainClass.playerIdsAndCosmetics.Add(num, list);
			if (!GameNetworkManager.Instance.isHostingGame || num == 0)
			{
				return;
			}
			ignoreSample = true;
			foreach (KeyValuePair<int, List<string>> playerIdsAndCosmetic in MainClass.playerIdsAndCosmetics)
			{
				string text3 = "[morecompanycosmetics]";
				text3 = text3 + ";" + playerIdsAndCosmetic.Key;
				foreach (string item in playerIdsAndCosmetic.Value)
				{
					text3 = text3 + ";" + item;
				}
				HUDManager.Instance.AddTextToChatOnServer(text3, -1);
			}
			ignoreSample = false;
		}
	}
	public class DebugCommandRegistry
	{
		public static bool commandEnabled;

		public static void HandleCommand(string[] args)
		{
			//IL_00cc: 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_00e1: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: 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_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: 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_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			if (!commandEnabled)
			{
				return;
			}
			PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
			switch (args[0])
			{
			case "money":
			{
				int groupCredits = int.Parse(args[1]);
				Terminal val5 = Resources.FindObjectsOfTypeAll<Terminal>().First();
				val5.groupCredits = groupCredits;
				break;
			}
			case "spawnscrap":
			{
				string text = "";
				for (int i = 1; i < args.Length; i++)
				{
					text = text + args[i] + " ";
				}
				text = text.Trim();
				Vector3 val = ((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 2f;
				SpawnableItemWithRarity val2 = null;
				foreach (SpawnableItemWithRarity item in StartOfRound.Instance.currentLevel.spawnableScrap)
				{
					if (item.spawnableItem.itemName.ToLower() == text.ToLower())
					{
						val2 = item;
						break;
					}
				}
				GameObject val3 = Object.Instantiate<GameObject>(val2.spawnableItem.spawnPrefab, val, Quaternion.identity, (Transform)null);
				GrabbableObject component = val3.GetComponent<GrabbableObject>();
				((Component)component).transform.rotation = Quaternion.Euler(component.itemProperties.restingRotation);
				component.fallTime = 0f;
				NetworkObject component2 = val3.GetComponent<NetworkObject>();
				component2.Spawn(false);
				break;
			}
			case "spawnenemy":
			{
				string text2 = "";
				for (int j = 1; j < args.Length; j++)
				{
					text2 = text2 + args[j] + " ";
				}
				text2 = text2.Trim();
				SpawnableEnemyWithRarity val4 = null;
				foreach (SpawnableEnemyWithRarity enemy in StartOfRound.Instance.currentLevel.Enemies)
				{
					if (enemy.enemyType.enemyName.ToLower() == text2.ToLower())
					{
						val4 = enemy;
						break;
					}
				}
				RoundManager.Instance.SpawnEnemyGameObject(((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 2f, 0f, -1, val4.enemyType);
				break;
			}
			case "listall":
				MainClass.StaticLogger.LogInfo((object)"Spawnable scrap:");
				foreach (SpawnableItemWithRarity item2 in StartOfRound.Instance.currentLevel.spawnableScrap)
				{
					MainClass.StaticLogger.LogInfo((object)item2.spawnableItem.itemName);
				}
				MainClass.StaticLogger.LogInfo((object)"Spawnable enemies:");
				{
					foreach (SpawnableEnemyWithRarity enemy2 in StartOfRound.Instance.currentLevel.Enemies)
					{
						MainClass.StaticLogger.LogInfo((object)enemy2.enemyType.enemyName);
					}
					break;
				}
			}
		}
	}
	[HarmonyPatch(typeof(ForestGiantAI), "LookForPlayers")]
	public static class LookForPlayersForestGiantPatch
	{
		public static void Prefix(ForestGiantAI __instance)
		{
			if (__instance.playerStealthMeters.Length != MainClass.newPlayerCount)
			{
				__instance.playerStealthMeters = new float[MainClass.newPlayerCount];
				for (int i = 0; i < MainClass.newPlayerCount; i++)
				{
					__instance.playerStealthMeters[i] = 0f;
				}
			}
		}
	}
	[HarmonyPatch(typeof(SpringManAI), "Update")]
	public static class SpringManAIUpdatePatch
	{
		public static bool Prefix(SpringManAI __instance, ref float ___timeSinceHittingPlayer, ref float ___stopAndGoMinimumInterval, ref bool ___wasOwnerLastFrame, ref bool ___stoppingMovement, ref float ___currentChaseSpeed, ref bool ___hasStopped, ref float ___currentAnimSpeed, ref float ___updateDestinationInterval, ref Vector3 ___tempVelocity, ref float ___targetYRotation, ref float ___setDestinationToPlayerInterval, ref float ___previousYRotation)
		{
			//IL_0241: 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_0278: 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_0118: 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_014c: 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)
			UpdateBase((EnemyAI)(object)__instance, ref ___updateDestinationInterval, ref ___tempVelocity, ref ___targetYRotation, ref ___setDestinationToPlayerInterval, ref ___previousYRotation);
			if (((EnemyAI)__instance).isEnemyDead)
			{
				return false;
			}
			int currentBehaviourStateIndex = ((EnemyAI)__instance).currentBehaviourStateIndex;
			if (currentBehaviourStateIndex != 0 && currentBehaviourStateIndex == 1)
			{
				if (___timeSinceHittingPlayer >= 0f)
				{
					___timeSinceHittingPlayer -= Time.deltaTime;
				}
				if (((NetworkBehaviour)__instance).IsOwner)
				{
					if (___stopAndGoMinimumInterval > 0f)
					{
						___stopAndGoMinimumInterval -= Time.deltaTime;
					}
					if (!___wasOwnerLastFrame)
					{
						___wasOwnerLastFrame = true;
						if (!___stoppingMovement && ___timeSinceHittingPlayer < 0.12f)
						{
							((EnemyAI)__instance).agent.speed = ___currentChaseSpeed;
						}
						else
						{
							((EnemyAI)__instance).agent.speed = 0f;
						}
					}
					bool flag = false;
					for (int i = 0; i < MainClass.newPlayerCount; i++)
					{
						if (((EnemyAI)__instance).PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false) && StartOfRound.Instance.allPlayerScripts[i].HasLineOfSightToPosition(((Component)__instance).transform.position + Vector3.up * 1.6f, 68f, 60, -1f) && Vector3.Distance(((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position, ((EnemyAI)__instance).eye.position) > 0.3f)
						{
							flag = true;
						}
					}
					if (((EnemyAI)__instance).stunNormalizedTimer > 0f)
					{
						flag = true;
					}
					if (flag != ___stoppingMovement && ___stopAndGoMinimumInterval <= 0f)
					{
						___stopAndGoMinimumInterval = 0.15f;
						if (flag)
						{
							__instance.SetAnimationStopServerRpc();
						}
						else
						{
							__instance.SetAnimationGoServerRpc();
						}
						___stoppingMovement = flag;
					}
				}
				if (___stoppingMovement)
				{
					if (__instance.animStopPoints.canAnimationStop)
					{
						if (!___hasStopped)
						{
							___hasStopped = true;
							__instance.mainCollider.isTrigger = false;
							if (GameNetworkManager.Instance.localPlayerController.HasLineOfSightToPosition(((Component)__instance).transform.position, 70f, 25, -1f))
							{
								float num = Vector3.Distance(((Component)__instance).transform.position, ((Component)GameNetworkManager.Instance.localPlayerController).transform.position);
								if (num < 4f)
								{
									GameNetworkManager.Instance.localPlayerController.JumpToFearLevel(0.9f, true);
								}
								else if (num < 9f)
								{
									GameNetworkManager.Instance.localPlayerController.JumpToFearLevel(0.4f, true);
								}
							}
							if (___currentAnimSpeed > 2f)
							{
								RoundManager.PlayRandomClip(((EnemyAI)__instance).creatureVoice, __instance.springNoises, false, 1f, 0);
								if (__instance.animStopPoints.animationPosition == 1)
								{
									((EnemyAI)__instance).creatureAnimator.SetTrigger("springBoing");
								}
								else
								{
									((EnemyAI)__instance).creatureAnimator.SetTrigger("springBoingPosition2");
								}
							}
						}
						((EnemyAI)__instance).creatureAnimator.SetFloat("walkSpeed", 0f);
						___currentAnimSpeed = 0f;
						if (((NetworkBehaviour)__instance).IsOwner)
						{
							((EnemyAI)__instance).agent.speed = 0f;
							return false;
						}
					}
				}
				else
				{
					if (___hasStopped)
					{
						___hasStopped = false;
						__instance.mainCollider.isTrigger = true;
					}
					___currentAnimSpeed = Mathf.Lerp(___currentAnimSpeed, 6f, 5f * Time.deltaTime);
					((EnemyAI)__instance).creatureAnimator.SetFloat("walkSpeed", ___currentAnimSpeed);
					if (((NetworkBehaviour)__instance).IsOwner)
					{
						((EnemyAI)__instance).agent.speed = Mathf.Lerp(((EnemyAI)__instance).agent.speed, ___currentChaseSpeed, 4.5f * Time.deltaTime);
					}
				}
			}
			return false;
		}

		private static void UpdateBase(EnemyAI __instance, ref float updateDestinationInterval, ref Vector3 tempVelocity, ref float targetYRotation, ref float setDestinationToPlayerInterval, ref float previousYRotation)
		{
			//IL_011a: 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_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_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: 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_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)
			//IL_0267: 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_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bd: 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_0364: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: 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_0425: Unknown result type (might be due to invalid IL or missing references)
			//IL_0454: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.enemyType.isDaytimeEnemy && !__instance.daytimeEnemyLeaving)
			{
				ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "CheckTimeOfDayToLeave", null);
			}
			if (__instance.stunnedIndefinitely <= 0)
			{
				if ((double)__instance.stunNormalizedTimer >= 0.0)
				{
					__instance.stunNormalizedTimer -= Time.deltaTime / __instance.enemyType.stunTimeMultiplier;
				}
				else
				{
					__instance.stunnedByPlayer = null;
					if ((double)__instance.postStunInvincibilityTimer >= 0.0)
					{
						__instance.postStunInvincibilityTimer -= Time.deltaTime * 5f;
					}
				}
			}
			if (!__instance.ventAnimationFinished && (double)__instance.timeSinceSpawn < (double)__instance.exitVentAnimationTime + 0.004999999888241291 * (double)RoundManager.Instance.numberOfEnemiesInScene)
			{
				__instance.timeSinceSpawn += Time.deltaTime;
				if (!((NetworkBehaviour)__instance).IsOwner)
				{
					Vector3 serverPosition = __instance.serverPosition;
					if (__instance.serverPosition != Vector3.zero)
					{
						((Component)__instance).transform.position = __instance.serverPosition;
						((Component)__instance).transform.eulerAngles = new Vector3(((Component)__instance).transform.eulerAngles.x, targetYRotation, ((Component)__instance).transform.eulerAngles.z);
					}
				}
				else if ((double)updateDestinationInterval >= 0.0)
				{
					updateDestinationInterval -= Time.deltaTime;
				}
				else
				{
					__instance.SyncPositionToClients();
					updateDestinationInterval = 0.1f;
				}
				return;
			}
			if (!__instance.ventAnimationFinished)
			{
				__instance.ventAnimationFinished = true;
				if ((Object)(object)__instance.creatureAnimator != (Object)null)
				{
					__instance.creatureAnimator.SetBool("inSpawningAnimation", false);
				}
			}
			if (!((NetworkBehaviour)__instance).IsOwner)
			{
				if (__instance.currentSearch.inProgress)
				{
					__instance.StopSearch(__instance.currentSearch, true);
				}
				__instance.SetClientCalculatingAI(false);
				if (!__instance.inSpecialAnimation)
				{
					((Component)__instance).transform.position = Vector3.SmoothDamp(((Component)__instance).transform.position, __instance.serverPosition, ref tempVelocity, __instance.syncMovementSpeed);
					((Component)__instance).transform.eulerAngles = new Vector3(((Component)__instance).transform.eulerAngles.x, Mathf.LerpAngle(((Component)__instance).transform.eulerAngles.y, targetYRotation, 15f * Time.deltaTime), ((Component)__instance).transform.eulerAngles.z);
				}
				__instance.timeSinceSpawn += Time.deltaTime;
				return;
			}
			if (__instance.isEnemyDead)
			{
				__instance.SetClientCalculatingAI(false);
				return;
			}
			if (!__instance.inSpecialAnimation)
			{
				__instance.SetClientCalculatingAI(true);
			}
			if (__instance.movingTowardsTargetPlayer && (Object)(object)__instance.targetPlayer != (Object)null)
			{
				if ((double)setDestinationToPlayerInterval <= 0.0)
				{
					setDestinationToPlayerInterval = 0.25f;
					__instance.destination = RoundManager.Instance.GetNavMeshPosition(((Component)__instance.targetPlayer).transform.position, RoundManager.Instance.navHit, 2.7f, -1);
				}
				else
				{
					__instance.destination = new Vector3(((Component)__instance.targetPlayer).transform.position.x, __instance.destination.y, ((Component)__instance.targetPlayer).transform.position.z);
					setDestinationToPlayerInterval -= Time.deltaTime;
				}
			}
			if (__instance.inSpecialAnimation)
			{
				return;
			}
			if ((double)updateDestinationInterval >= 0.0)
			{
				updateDestinationInterval -= Time.deltaTime;
			}
			else
			{
				__instance.DoAIInterval();
				updateDestinationInterval = __instance.AIIntervalTime;
			}
			if (!((double)Mathf.Abs(previousYRotation - ((Component)__instance).transform.eulerAngles.y) <= 6.0))
			{
				previousYRotation = ((Component)__instance).transform.eulerAngles.y;
				targetYRotation = previousYRotation;
				if (((NetworkBehaviour)__instance).IsServer)
				{
					ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "UpdateEnemyRotationClientRpc", new object[1] { (short)previousYRotation });
				}
				else
				{
					ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "UpdateEnemyRotationServerRpc", new object[1] { (short)previousYRotation });
				}
			}
		}
	}
	[HarmonyPatch(typeof(SpringManAI), "DoAIInterval")]
	public static class SpringManAIIntervalPatch
	{
		public static bool Prefix(SpringManAI __instance)
		{
			//IL_0013: 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_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: 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_0250: 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_01e6: Unknown result type (might be due to invalid IL or missing references)
			if (((EnemyAI)__instance).moveTowardsDestination)
			{
				((EnemyAI)__instance).agent.SetDestination(((EnemyAI)__instance).destination);
			}
			((EnemyAI)__instance).SyncPositionToClients();
			if (StartOfRound.Instance.allPlayersDead)
			{
				return false;
			}
			if (((EnemyAI)__instance).isEnemyDead)
			{
				return false;
			}
			switch (((EnemyAI)__instance).currentBehaviourStateIndex)
			{
			default:
				return false;
			case 1:
				if (__instance.searchForPlayers.inProgress)
				{
					((EnemyAI)__instance).StopSearch(__instance.searchForPlayers, true);
				}
				if (((EnemyAI)__instance).TargetClosestPlayer(1.5f, false, 70f))
				{
					PlayerControllerB fieldValue = ReflectionUtils.GetFieldValue<PlayerControllerB>(__instance, "previousTarget");
					if ((Object)(object)fieldValue != (Object)(object)((EnemyAI)__instance).targetPlayer)
					{
						ReflectionUtils.SetFieldValue(__instance, "previousTarget", ((EnemyAI)__instance).targetPlayer);
						((EnemyAI)__instance).ChangeOwnershipOfEnemy(((EnemyAI)__instance).targetPlayer.actualClientId);
					}
					((EnemyAI)__instance).movingTowardsTargetPlayer = true;
					return false;
				}
				((EnemyAI)__instance).SwitchToBehaviourState(0);
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(StartOfRound.Instance.allPlayerScripts[0].actualClientId);
				break;
			case 0:
			{
				if (!((NetworkBehaviour)__instance).IsServer)
				{
					((EnemyAI)__instance).ChangeOwnershipOfEnemy(StartOfRound.Instance.allPlayerScripts[0].actualClientId);
					return false;
				}
				for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
				{
					if (((EnemyAI)__instance).PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false) && !Physics.Linecast(((Component)__instance).transform.position + Vector3.up * 0.5f, ((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position, StartOfRound.Instance.collidersAndRoomMaskAndDefault) && Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < 30f)
					{
						((EnemyAI)__instance).SwitchToBehaviourState(1);
						return false;
					}
				}
				if (!__instance.searchForPlayers.inProgress)
				{
					((EnemyAI)__instance).movingTowardsTargetPlayer = false;
					((EnemyAI)__instance).StartSearch(((Component)__instance).transform.position, __instance.searchForPlayers);
					return false;
				}
				break;
			}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(EnemyAI), "GetClosestPlayer")]
	public static class GetClosestPlayerPatch
	{
		public static bool Prefix(EnemyAI __instance, ref PlayerControllerB __result, bool requireLineOfSight = false, bool cannotBeInShip = false, bool cannotBeNearShip = false)
		{
			//IL_00dc: 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_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)
			//IL_0074: 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)
			PlayerControllerB val = null;
			__instance.mostOptimalDistance = 2000f;
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				if (!__instance.PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], cannotBeInShip, false))
				{
					continue;
				}
				if (cannotBeNearShip)
				{
					if (StartOfRound.Instance.allPlayerScripts[i].isInElevator)
					{
						continue;
					}
					bool flag = false;
					for (int j = 0; j < RoundManager.Instance.spawnDenialPoints.Length; j++)
					{
						if (Vector3.Distance(RoundManager.Instance.spawnDenialPoints[j].transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < 10f)
						{
							flag = true;
							break;
						}
					}
					if (flag)
					{
						continue;
					}
				}
				if (!requireLineOfSight || !Physics.Linecast(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position, 256))
				{
					__instance.tempDist = Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position);
					if (__instance.tempDist < __instance.mostOptimalDistance)
					{
						__instance.mostOptimalDistance = __instance.tempDist;
						val = StartOfRound.Instance.allPlayerScripts[i];
					}
				}
			}
			__result = val;
			return false;
		}
	}
	[HarmonyPatch(typeof(EnemyAI), "GetAllPlayersInLineOfSight")]
	public static class GetAllPlayersInLineOfSightPatch
	{
		public static bool Prefix(EnemyAI __instance, ref PlayerControllerB[] __result, float width = 45f, int range = 60, Transform eyeObject = null, float proximityCheck = -1f, int layerMask = -1)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Invalid comparison between Unknown and I4
			//IL_00b3: 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)
			//IL_00c0: 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_00d2: 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_00f6: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: 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_010d: 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_0134: Unknown result type (might be due to invalid IL or missing references)
			if (layerMask == -1)
			{
				layerMask = StartOfRound.Instance.collidersAndRoomMaskAndDefault;
			}
			if ((Object)(object)eyeObject == (Object)null)
			{
				eyeObject = __instance.eye;
			}
			if (__instance.enemyType.isOutsideEnemy && !__instance.enemyType.canSeeThroughFog && (int)TimeOfDay.Instance.currentLevelWeather == 3)
			{
				range = Mathf.Clamp(range, 0, 30);
			}
			List<PlayerControllerB> list = new List<PlayerControllerB>(MainClass.newPlayerCount);
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				if (!__instance.PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false))
				{
					continue;
				}
				Vector3 position = ((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position;
				if (Vector3.Distance(__instance.eye.position, position) < (float)range && !Physics.Linecast(eyeObject.position, position, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))
				{
					Vector3 val = position - eyeObject.position;
					if (Vector3.Angle(eyeObject.forward, val) < width || Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < proximityCheck)
					{
						list.Add(StartOfRound.Instance.allPlayerScripts[i]);
					}
				}
			}
			if (list.Count == MainClass.newPlayerCount)
			{
				__result = StartOfRound.Instance.allPlayerScripts;
				return false;
			}
			if (list.Count > 0)
			{
				__result = list.ToArray();
				return false;
			}
			__result = null;
			return false;
		}
	}
	[HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")]
	public static class DressGirlHauntPatch
	{
		public static bool Prefix(DressGirlAI __instance)
		{
			ReflectionUtils.SetFieldValue(__instance, "timesChoosingAPlayer", ReflectionUtils.GetFieldValue<int>(__instance, "timesChoosingAPlayer") + 1);
			if (ReflectionUtils.GetFieldValue<int>(__instance, "timesChoosingAPlayer") > 1)
			{
				__instance.timer = __instance.hauntInterval - 1f;
			}
			__instance.SFXVolumeLerpTo = 0f;
			((EnemyAI)__instance).creatureVoice.Stop();
			__instance.heartbeatMusic.volume = 0f;
			if (!ReflectionUtils.GetFieldValue<bool>(__instance, "initializedRandomSeed"))
			{
				ReflectionUtils.SetFieldValue(__instance, "ghostGirlRandom", new Random(StartOfRound.Instance.randomMapSeed + 158));
			}
			float num = 0f;
			float num2 = 0f;
			int num3 = 0;
			int num4 = 0;
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				if (StartOfRound.Instance.gameStats.allPlayerStats[i].turnAmount > num3)
				{
					num3 = StartOfRound.Instance.gameStats.allPlayerStats[i].turnAmount;
					num4 = i;
				}
				if (StartOfRound.Instance.allPlayerScripts[i].insanityLevel > num)
				{
					num = StartOfRound.Instance.allPlayerScripts[i].insanityLevel;
					num2 = i;
				}
			}
			int[] array = new int[MainClass.newPlayerCount];
			for (int j = 0; j < MainClass.newPlayerCount; j++)
			{
				if (!StartOfRound.Instance.allPlayerScripts[j].isPlayerControlled)
				{
					array[j] = 0;
					continue;
				}
				array[j] += 80;
				if (num2 == (float)j && num > 1f)
				{
					array[j] += 50;
				}
				if (num4 == j)
				{
					array[j] += 30;
				}
				if (!StartOfRound.Instance.allPlayerScripts[j].hasBeenCriticallyInjured)
				{
					array[j] += 10;
				}
				if ((Object)(object)StartOfRound.Instance.allPlayerScripts[j].currentlyHeldObjectServer != (Object)null && StartOfRound.Instance.allPlayerScripts[j].currentlyHeldObjectServer.scrapValue > 150)
				{
					array[j] += 30;
				}
			}
			__instance.hauntingPlayer = StartOfRound.Instance.allPlayerScripts[RoundManager.Instance.GetRandomWeightedIndex(array, ReflectionUtils.GetFieldValue<Random>(__instance, "ghostGirlRandom"))];
			if (__instance.hauntingPlayer.isPlayerDead)
			{
				for (int k = 0; k < StartOfRound.Instance.allPlayerScripts.Length; k++)
				{
					if (!StartOfRound.Instance.allPlayerScripts[k].isPlayerDead)
					{
						__instance.hauntingPlayer = StartOfRound.Instance.allPlayerScripts[k];
						break;
					}
				}
			}
			Debug.Log((object)$"Little girl: Haunting player with playerClientId: {__instance.hauntingPlayer.playerClientId}; actualClientId: {__instance.hauntingPlayer.actualClientId}");
			((EnemyAI)__instance).ChangeOwnershipOfEnemy(__instance.hauntingPlayer.actualClientId);
			__instance.hauntingLocalPlayer = (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)(object)__instance.hauntingPlayer;
			if (ReflectionUtils.GetFieldValue<Coroutine>(__instance, "switchHauntedPlayerCoroutine") != null)
			{
				((MonoBehaviour)__instance).StopCoroutine(ReflectionUtils.GetFieldValue<Coroutine>(__instance, "switchHauntedPlayerCoroutine"));
			}
			ReflectionUtils.SetFieldValue(__instance, "switchHauntedPlayerCoroutine", ((MonoBehaviour)__instance).StartCoroutine(ReflectionUtils.InvokeMethod<IEnumerator>(__instance, "setSwitchingHauntingPlayer", null)));
			return false;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddChatMessage")]
	public static class HudChatPatch
	{
		public static void Prefix(HUDManager __instance, ref string chatMessage, string nameOfUserWhoTyped = "")
		{
			if (!(__instance.lastChatMessage == chatMessage))
			{
				StringBuilder stringBuilder = new StringBuilder(chatMessage);
				for (int i = 0; i < MainClass.newPlayerCount; i++)
				{
					string oldValue = $"[playerNum{i}]";
					string playerUsername = StartOfRound.Instance.allPlayerScripts[i].playerUsername;
					stringBuilder.Replace(oldValue, playerUsername);
				}
				chatMessage = stringBuilder.ToString();
			}
		}
	}
	[HarmonyPatch(typeof(MenuManager), "Awake")]
	public static class MenuManagerLogoOverridePatch
	{
		public static void Postfix(MenuManager __instance)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameObject gameObject = ((Component)((Component)__instance).transform.parent).gameObject;
				GameObject gameObject2 = ((Component)gameObject.transform.Find("MenuContainer").Find("MainButtons").Find("HeaderImage")).gameObject;
				Image component = gameObject2.GetComponent<Image>();
				MainClass.ReadSettingsFromFile();
				component.sprite = Sprite.Create(MainClass.mainLogo, new Rect(0f, 0f, (float)((Texture)MainClass.mainLogo).width, (float)((Texture)MainClass.mainLogo).height), new Vector2(0.5f, 0.5f));
				CosmeticRegistry.SpawnCosmeticGUI();
				Transform val = gameObject.transform.Find("MenuContainer").Find("LobbyHostSettings").Find("Panel")
					.Find("LobbyHostOptions")
					.Find("OptionsNormal");
				GameObject val2 = Object.Instantiate<GameObject>(MainClass.crewCountUI, val);
				RectTransform component2 = val2.GetComponent<RectTransform>();
				((Transform)component2).localPosition = new Vector3(96.9f, -70f, -6.7f);
				TMP_InputField inputField = ((Component)val2.transform.Find("InputField (TMP)")).GetComponent<TMP_InputField>();
				inputField.characterLimit = 3;
				inputField.text = MainClass.newPlayerCount.ToString();
				((UnityEvent<string>)(object)inputField.onValueChanged).AddListener((UnityAction<string>)delegate(string s)
				{
					if (int.TryParse(s, out var result))
					{
						MainClass.newPlayerCount = result;
						MainClass.newPlayerCount = Mathf.Clamp(MainClass.newPlayerCount, 1, MainClass.maxPlayerCount);
						inputField.text = MainClass.newPlayerCount.ToString();
						MainClass.SaveSettingsToFile();
					}
					else if (s.Length != 0)
					{
						inputField.text = MainClass.newPlayerCount.ToString();
						inputField.caretPosition = 1;
					}
				});
			}
			catch (Exception)
			{
			}
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "AddUserToPlayerList")]
	public static class AddUserPlayerListPatch
	{
		public static bool Prefix(QuickMenuManager __instance, ulong steamId, string playerName, int playerObjectId)
		{
			QuickmenuVisualInjectPatch.PopulateQuickMenu(__instance);
			MainClass.EnablePlayerObjectsBasedOnConnected();
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "RemoveUserFromPlayerList")]
	public static class RemoveUserPlayerListPatch
	{
		public static bool Prefix(QuickMenuManager __instance)
		{
			QuickmenuVisualInjectPatch.PopulateQuickMenu(__instance);
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "Update")]
	public static class QuickMenuUpdatePatch
	{
		public static bool Prefix(QuickMenuManager __instance)
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "NonHostPlayerSlotsEnabled")]
	public static class QuickMenuDisplayPatch
	{
		public static bool Prefix(QuickMenuManager __instance, ref bool __result)
		{
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "Start")]
	public static class QuickmenuVisualInjectPatch
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__2_2;

			internal void <PopulateQuickMenu>b__2_2()
			{
				if (!GameNetworkManager.Instance.disableSteam)
				{
				}
			}
		}

		public static GameObject quickMenuScrollInstance;

		public static void Postfix(QuickMenuManager __instance)
		{
			//IL_0050: 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)
			GameObject gameObject = ((Component)__instance.playerListPanel.transform.Find("Image")).gameObject;
			GameObject val = Object.Instantiate<GameObject>(MainClass.quickMenuScrollParent);
			val.transform.SetParent(gameObject.transform);
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).localPosition = new Vector3(0f, -31.2f, 0f);
			((Transform)component).localScale = Vector3.one;
			quickMenuScrollInstance = val;
		}

		public static void PopulateQuickMenu(QuickMenuManager __instance)
		{
			//IL_0147: 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_016b: 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_0281: Expected O, but got Unknown
			//IL_02d8: 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_02e3: Expected O, but got Unknown
			int childCount = quickMenuScrollInstance.transform.Find("Holder").childCount;
			List<GameObject> list = new List<GameObject>();
			for (int i = 0; i < childCount; i++)
			{
				list.Add(((Component)quickMenuScrollInstance.transform.Find("Holder").GetChild(i)).gameObject);
			}
			foreach (GameObject item in list)
			{
				Object.Destroy((Object)(object)item);
			}
			if (!Object.op_Implicit((Object)(object)StartOfRound.Instance))
			{
				return;
			}
			for (int j = 0; j < StartOfRound.Instance.allPlayerScripts.Length; j++)
			{
				PlayerControllerB playerScript = StartOfRound.Instance.allPlayerScripts[j];
				if (!playerScript.isPlayerControlled && !playerScript.isPlayerDead)
				{
					continue;
				}
				GameObject val = Object.Instantiate<GameObject>(MainClass.playerEntry, quickMenuScrollInstance.transform.Find("Holder"));
				RectTransform component = val.GetComponent<RectTransform>();
				((Transform)component).localScale = Vector3.one;
				((Transform)component).localPosition = new Vector3(0f, 0f - ((Transform)component).localPosition.y, 0f);
				TextMeshProUGUI component2 = ((Component)val.transform.Find("PlayerNameButton").Find("PName")).GetComponent<TextMeshProUGUI>();
				((TMP_Text)component2).text = playerScript.playerUsername;
				Slider playerVolume = ((Component)val.transform.Find("PlayerVolumeSlider")).GetComponent<Slider>();
				int finalIndex = j;
				((UnityEvent<float>)(object)playerVolume.onValueChanged).AddListener((UnityAction<float>)delegate(float f)
				{
					if (playerScript.isPlayerControlled || playerScript.isPlayerDead)
					{
						float num = f / playerVolume.maxValue + 1f;
						if (num <= -1f)
						{
							SoundManager.Instance.playerVoiceVolumes[finalIndex] = -70f;
						}
						else
						{
							SoundManager.Instance.playerVoiceVolumes[finalIndex] = num;
						}
					}
				});
				if (StartOfRound.Instance.localPlayerController.playerClientId == playerScript.playerClientId)
				{
					((Component)playerVolume).gameObject.SetActive(false);
					((Component)val.transform.Find("Text (1)")).gameObject.SetActive(false);
				}
				Button component3 = ((Component)val.transform.Find("KickButton")).GetComponent<Button>();
				((UnityEvent)component3.onClick).AddListener((UnityAction)delegate
				{
					__instance.KickUserFromServer(finalIndex);
				});
				if (!GameNetworkManager.Instance.isHostingGame)
				{
					((Component)component3).gameObject.SetActive(false);
				}
				Button component4 = ((Component)val.transform.Find("ProfileIcon")).GetComponent<Button>();
				ButtonClickedEvent onClick = component4.onClick;
				object obj = <>c.<>9__2_2;
				if (obj == null)
				{
					UnityAction val2 = delegate
					{
						if (!GameNetworkManager.Instance.disableSteam)
						{
						}
					};
					<>c.<>9__2_2 = val2;
					obj = (object)val2;
				}
				((UnityEvent)onClick).AddListener((UnityAction)obj);
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager), "UpdateBoxesSpectateUI")]
	public static class SpectatorBoxUpdatePatch
	{
		public static void Postfix(HUDManager __instance)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<Animator, PlayerControllerB> fieldValue = ReflectionUtils.GetFieldValue<Dictionary<Animator, PlayerControllerB>>(__instance, "spectatingPlayerBoxes");
			int num = -64;
			int num2 = 0;
			int num3 = 0;
			int num4 = -70;
			int num5 = 230;
			int num6 = 4;
			foreach (KeyValuePair<Animator, PlayerControllerB> item in fieldValue)
			{
				if (((Component)item.Key).gameObject.activeInHierarchy)
				{
					GameObject gameObject = ((Component)item.Key).gameObject;
					RectTransform component = gameObject.GetComponent<RectTransform>();
					int num7 = (int)Math.Floor((double)num3 / (double)num6);
					int num8 = num3 % num6;
					int num9 = num8 * num4;
					int num10 = num7 * num5;
					component.anchoredPosition = Vector2.op_Implicit(new Vector3((float)(num + num10), (float)(num2 + num9), 0f));
					num3++;
				}
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager), "FillEndGameStats")]
	public static class HudFillEndGameFix
	{
		public static bool Prefix(HUDManager __instance, EndOfGameStats stats)
		{
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Invalid comparison between Unknown and I4
			int num = 0;
			int num2 = 0;
			for (int i = 0; i < __instance.statsUIElements.playerNamesText.Length; i++)
			{
				PlayerControllerB val = __instance.playersManager.allPlayerScripts[i];
				((TMP_Text)__instance.statsUIElements.playerNamesText[i]).text = "";
				((Behaviour)__instance.statsUIElements.playerStates[i]).enabled = false;
				((TMP_Text)__instance.statsUIElements.playerNotesText[i]).text = "Notes: \n";
				if (val.disconnectedMidGame || val.isPlayerDead || val.isPlayerControlled)
				{
					if (val.isPlayerDead)
					{
						num++;
					}
					else if (val.isPlayerControlled)
					{
						num2++;
					}
					((TMP_Text)__instance.statsUIElements.playerNamesText[i]).text = __instance.playersManager.allPlayerScripts[i].playerUsername;
					((Behaviour)__instance.statsUIElements.playerStates[i]).enabled = true;
					if (__instance.playersManager.allPlayerScripts[i].isPlayerDead)
					{
						if ((int)__instance.playersManager.allPlayerScripts[i].causeOfDeath == 10)
						{
							__instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.missingIcon;
						}
						else
						{
							__instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.deceasedIcon;
						}
					}
					else
					{
						__instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.aliveIcon;
					}
					for (int j = 0; j < 3 && j < stats.allPlayerStats[i].playerNotes.Count; j++)
					{
						TextMeshProUGUI val2 = __instance.statsUIElements.playerNotesText[i];
						((TMP_Text)val2).text = ((TMP_Text)val2).text + "* " + stats.allPlayerStats[i].playerNotes[j] + "\n";
					}
				}
				else
				{
					((TMP_Text)__instance.statsUIElements.playerNotesText[i]).text = "";
				}
			}
			((TMP_Text)__instance.statsUIElements.quotaNumerator).text = RoundManager.Instance.scrapCollectedInLevel.ToString();
			((TMP_Text)__instance.statsUIElements.quotaDenominator).text = RoundManager.Instance.totalScrapValueInLevel.ToString();
			if (StartOfRound.Instance.allPlayersDead)
			{
				((Behaviour)__instance.statsUIElements.allPlayersDeadOverlay).enabled = true;
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "F";
				return false;
			}
			((Behaviour)__instance.statsUIElements.allPlayersDeadOverlay).enabled = false;
			int num3 = 0;
			float num4 = (float)RoundManager.Instance.scrapCollectedInLevel / RoundManager.Instance.totalScrapValueInLevel;
			if (num2 == StartOfRound.Instance.connectedPlayersAmount + 1)
			{
				num3++;
			}
			else if (num > 1)
			{
				num3--;
			}
			if (num4 >= 0.99f)
			{
				num3 += 2;
			}
			else if (num4 >= 0.6f)
			{
				num3++;
			}
			else if (num4 <= 0.25f)
			{
				num3--;
			}
			switch (num3)
			{
			case -1:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "D";
				return false;
			case 0:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "C";
				return false;
			case 1:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "B";
				return false;
			case 2:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "A";
				return false;
			case 3:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "S";
				return false;
			default:
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager), "Start")]
	public static class HudStartPatch
	{
		public static void Postfix(HUDManager __instance)
		{
			//IL_0082: 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_00bc: 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_00f6: 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)
			EndOfGameStatUIElements statsUIElements = __instance.statsUIElements;
			GameObject gameObject = ((Component)((Component)statsUIElements.playerNamesText[0]).gameObject.transform.parent).gameObject;
			GameObject gameObject2 = ((Component)gameObject.transform.parent.parent).gameObject;
			GameObject gameObject3 = ((Component)gameObject2.transform.Find("BGBoxes")).gameObject;
			gameObject2.transform.parent.Find("DeathScreen").SetSiblingIndex(3);
			gameObject3.transform.localScale = new Vector3(2.5f, 1f, 1f);
			MakePlayerHolder(4, gameObject, statsUIElements, new Vector3(426.9556f, -0.7932f, 0f));
			MakePlayerHolder(5, gameObject, statsUIElements, new Vector3(426.9556f, -115.4483f, 0f));
			MakePlayerHolder(6, gameObject, statsUIElements, new Vector3(-253.6783f, -115.4483f, 0f));
			MakePlayerHolder(7, gameObject, statsUIElements, new Vector3(-253.6783f, -0.7932f, 0f));
			for (int i = 8; i < MainClass.newPlayerCount; i++)
			{
				MakePlayerHolder(i, gameObject, statsUIElements, new Vector3(10000f, 10000f, 0f));
			}
		}

		public static void MakePlayerHolder(int index, GameObject original, EndOfGameStatUIElements uiElements, Vector3 localPosition)
		{
			//IL_0049: 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_009f: Unknown result type (might be due to invalid IL or missing references)
			if (index + 1 <= MainClass.newPlayerCount)
			{
				GameObject val = Object.Instantiate<GameObject>(original);
				RectTransform component = val.GetComponent<RectTransform>();
				RectTransform component2 = original.GetComponent<RectTransform>();
				((Transform)component).SetParent(((Transform)component2).parent);
				((Transform)component).localScale = new Vector3(1f, 1f, 1f);
				((Transform)component).localPosition = localPosition;
				GameObject gameObject = ((Component)val.transform.Find("PlayerName1")).gameObject;
				GameObject gameObject2 = ((Component)val.transform.Find("Notes")).gameObject;
				((Transform)gameObject2.GetComponent<RectTransform>()).localPosition = new Vector3(-95.7222f, 43.3303f, 0f);
				GameObject gameObject3 = ((Component)val.transform.Find("Symbol")).gameObject;
				if (index >= uiElements.playerNamesText.Length)
				{
					Array.Resize(ref uiElements.playerNamesText, index + 1);
					Array.Resize(ref uiElements.playerStates, index + 1);
					Array.Resize(ref uiElements.playerNotesText, index + 1);
				}
				uiElements.playerNamesText[index] = gameObject.GetComponent<TextMeshProUGUI>();
				uiElements.playerNotesText[index] = gameObject2.GetComponent<TextMeshProUGUI>();
				uiElements.playerStates[index] = gameObject3.GetComponent<Image>();
			}
		}
	}
	public static class PluginInformation
	{
		public const string PLUGIN_NAME = "MoreCompany";

		public const string PLUGIN_VERSION = "1.7.2";

		public const string PLUGIN_GUID = "me.swipez.melonloader.morecompany";
	}
	[BepInPlugin("me.swipez.melonloader.morecompany", "MoreCompany", "1.7.2")]
	public class MainClass : BaseUnityPlugin
	{
		public static int newPlayerCount = 32;

		public static int maxPlayerCount = 50;

		public static bool showCosmetics = true;

		public static List<PlayerControllerB> notSupposedToExistPlayers = new List<PlayerControllerB>();

		public static Texture2D mainLogo;

		public static GameObject quickMenuScrollParent;

		public static GameObject playerEntry;

		public static GameObject crewCountUI;

		public static GameObject cosmeticGUIInstance;

		public static GameObject cosmeticButton;

		public static ManualLogSource StaticLogger;

		public static Dictionary<int, List<string>> playerIdsAndCosmetics = new Dictionary<int, List<string>>();

		public static string cosmeticSavePath = Application.persistentDataPath + "/morecompanycosmetics.txt";

		public static string moreCompanySave = Application.persistentDataPath + "/morecompanysave.txt";

		public static string dynamicCosmeticsPath = Paths.PluginPath + "/MoreCompanyCosmetics";

		private void Awake()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			StaticLogger = ((BaseUnityPlugin)this).Logger;
			Harmony val = new Harmony("me.swipez.melonloader.morecompany");
			try
			{
				val.PatchAll();
			}
			catch (Exception ex)
			{
				StaticLogger.LogError((object)("Failed to patch: " + ex));
			}
			ManualHarmonyPatches.ManualPatch(val);
			StaticLogger.LogInfo((object)"Loading MoreCompany...");
			StaticLogger.LogInfo((object)("Checking: " + dynamicCosmeticsPath));
			if (!Directory.Exists(dynamicCosmeticsPath))
			{
				StaticLogger.LogInfo((object)"Creating cosmetics directory");
				Directory.CreateDirectory(dynamicCosmeticsPath);
			}
			ReadSettingsFromFile();
			ReadCosmeticsFromFile();
			StaticLogger.LogInfo((object)"Read settings and cosmetics");
			AssetBundle bundle = BundleUtilities.LoadBundleFromInternalAssembly("morecompany.assets", Assembly.GetExecutingAssembly());
			AssetBundle val2 = BundleUtilities.LoadBundleFromInternalAssembly("morecompany.cosmetics", Assembly.GetExecutingAssembly());
			CosmeticRegistry.LoadCosmeticsFromBundle(val2);
			val2.Unload(false);
			SteamFriends.OnGameLobbyJoinRequested += delegate(Lobby lobby, SteamId steamId)
			{
				newPlayerCount = ((Lobby)(ref lobby)).MaxMembers;
			};
			SteamMatchmaking.OnLobbyEntered += delegate(Lobby lobby)
			{
				newPlayerCount = ((Lobby)(ref lobby)).MaxMembers;
			};
			StaticLogger.LogInfo((object)"Loading USER COSMETICS...");
			RecursiveCosmeticLoad(Paths.PluginPath);
			LoadAssets(bundle);
			StaticLogger.LogInfo((object)"Loaded MoreCompany FULLY");
		}

		private void RecursiveCosmeticLoad(string directory)
		{
			string[] directories = Directory.GetDirectories(directory);
			foreach (string directory2 in directories)
			{
				RecursiveCosmeticLoad(directory2);
			}
			string[] files = Directory.GetFiles(directory);
			foreach (string text in files)
			{
				if (text.EndsWith(".cosmetics"))
				{
					AssetBundle val = AssetBundle.LoadFromFile(text);
					CosmeticRegistry.LoadCosmeticsFromBundle(val);
					val.Unload(false);
				}
			}
		}

		private void ReadCosmeticsFromFile()
		{
			if (File.Exists(cosmeticSavePath))
			{
				string[] array = File.ReadAllLines(cosmeticSavePath);
				string[] array2 = array;
				foreach (string item in array2)
				{
					CosmeticRegistry.locallySelectedCosmetics.Add(item);
				}
			}
		}

		public static void WriteCosmeticsToFile()
		{
			string text = "";
			foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics)
			{
				text = text + locallySelectedCosmetic + "\n";
			}
			File.WriteAllText(cosmeticSavePath, text);
		}

		public static void SaveSettingsToFile()
		{
			string text = "";
			text = text + newPlayerCount + "\n";
			text = text + showCosmetics + "\n";
			File.WriteAllText(moreCompanySave, text);
		}

		public static void ReadSettingsFromFile()
		{
			if (File.Exists(moreCompanySave))
			{
				string[] array = File.ReadAllLines(moreCompanySave);
				try
				{
					newPlayerCount = int.Parse(array[0]);
					showCosmetics = bool.Parse(array[1]);
				}
				catch (Exception)
				{
					StaticLogger.LogError((object)"Failed to read settings from file, resetting to default");
					newPlayerCount = 32;
					showCosmetics = true;
				}
			}
		}

		private static void LoadAssets(AssetBundle bundle)
		{
			if (Object.op_Implicit((Object)(object)bundle))
			{
				mainLogo = bundle.LoadPersistentAsset<Texture2D>("assets/morecompanyassets/morecompanytransparentred.png");
				quickMenuScrollParent = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/quickmenuoverride.prefab");
				playerEntry = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/playerlistslot.prefab");
				cosmeticGUIInstance = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/testoverlay.prefab");
				cosmeticButton = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/cosmeticinstance.prefab");
				crewCountUI = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/crewcountfield.prefab");
				bundle.Unload(false);
			}
		}

		public static void ResizePlayerCache(Dictionary<uint, Dictionary<int, NetworkObject>> ScenePlacedObjects)
		{
			//IL_0091: 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_01be: 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)
			//IL_0261: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			if (instance.allPlayerObjects.Length == newPlayerCount)
			{
				return;
			}
			playerIdsAndCosmetics.Clear();
			uint num = 10000u;
			int num2 = newPlayerCount - instance.allPlayerObjects.Length;
			int num3 = instance.allPlayerObjects.Length;
			GameObject val = instance.allPlayerObjects[3];
			for (int i = 0; i < num2; i++)
			{
				uint num4 = num + (uint)i;
				GameObject val2 = Object.Instantiate<GameObject>(val);
				NetworkObject component = val2.GetComponent<NetworkObject>();
				ReflectionUtils.SetFieldValue(component, "GlobalObjectIdHash", num4);
				Scene scene = ((Component)component).gameObject.scene;
				int handle = ((Scene)(ref scene)).handle;
				uint num5 = num4;
				if (!ScenePlacedObjects.ContainsKey(num5))
				{
					ScenePlacedObjects.Add(num5, new Dictionary<int, NetworkObject>());
				}
				if (ScenePlacedObjects[num5].ContainsKey(handle))
				{
					string arg = (((Object)(object)ScenePlacedObjects[num5][handle] != (Object)null) ? ((Object)ScenePlacedObjects[num5][handle]).name : "Null Entry");
					throw new Exception(((Object)component).name + " tried to registered with ScenePlacedObjects which already contains " + string.Format("the same {0} value {1} for {2}!", "GlobalObjectIdHash", num5, arg));
				}
				ScenePlacedObjects[num5].Add(handle, component);
				((Object)val2).name = $"Player ({4 + i})";
				val2.transform.parent = null;
				PlayerControllerB componentInChildren = val2.GetComponentInChildren<PlayerControllerB>();
				notSupposedToExistPlayers.Add(componentInChildren);
				componentInChildren.playerClientId = (ulong)(4 + i);
				componentInChildren.isPlayerControlled = false;
				componentInChildren.isPlayerDead = false;
				componentInChildren.DropAllHeldItems(false, false);
				componentInChildren.TeleportPlayer(instance.notSpawnedPosition.position, false, 0f, false, true);
				UnlockableSuit.SwitchSuitForPlayer(componentInChildren, 0, false);
				Array.Resize(ref instance.allPlayerObjects, instance.allPlayerObjects.Length + 1);
				Array.Resize(ref instance.allPlayerScripts, instance.allPlayerScripts.Length + 1);
				Array.Resize(ref instance.gameStats.allPlayerStats, instance.gameStats.allPlayerStats.Length + 1);
				Array.Resize(ref instance.playerSpawnPositions, instance.playerSpawnPositions.Length + 1);
				instance.allPlayerObjects[num3 + i] = val2;
				instance.gameStats.allPlayerStats[num3 + i] = new PlayerStats();
				instance.allPlayerScripts[num3 + i] = componentInChildren;
				instance.playerSpawnPositions[num3 + i] = instance.playerSpawnPositions[3];
			}
		}

		public static void EnablePlayerObjectsBasedOnConnected()
		{
			int connectedPlayersAmount = StartOfRound.Instance.connectedPlayersAmount;
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				for (int j = 0; j < connectedPlayersAmount + 1; j++)
				{
					if (!val.isPlayerControlled)
					{
						((Component)val).gameObject.SetActive(false);
					}
					else
					{
						((Component)val).gameObject.SetActive(true);
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesServerRpc")]
	public static class SendNewPlayerValuesServerRpcPatch
	{
		public static ulong lastId;

		public static void Prefix(PlayerControllerB __instance, ulong newPlayerSteamId)
		{
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if (!((Object)(object)networkManager == (Object)null) && networkManager.IsListening && networkManager.IsServer)
			{
				lastId = newPlayerSteamId;
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesClientRpc")]
	public static class SendNewPlayerValuesClientRpcPatch
	{
		public static void Prefix(PlayerControllerB __instance, ref ulong[] playerSteamIds)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening)
			{
				return;
			}
			if (StartOfRound.Instance.mapScreen.radarTargets.Count != MainClass.newPlayerCount)
			{
				List<PlayerControllerB> useless = new List<PlayerControllerB>();
				foreach (PlayerControllerB notSupposedToExistPlayer in MainClass.notSupposedToExistPlayers)
				{
					if (Object.op_Implicit((Object)(object)notSupposedToExistPlayer))
					{
						StartOfRound.Instance.mapScreen.radarTargets.Add(new TransformAndName(((Component)notSupposedToExistPlayer).transform, notSupposedToExistPlayer.playerUsername, false));
					}
					else
					{
						useless.Add(notSupposedToExistPlayer);
					}
				}
				MainClass.notSupposedToExistPlayers.RemoveAll((PlayerControllerB x) => useless.Contains(x));
			}
			if (!networkManager.IsServer)
			{
				return;
			}
			List<ulong> list = new List<ulong>();
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				if (i == (int)__instance.playerClientId)
				{
					list.Add(SendNewPlayerValuesServerRpcPatch.lastId);
				}
				else
				{
					list.Add(__instance.playersManager.allPlayerScripts[i].playerSteamId);
				}
			}
			playerSteamIds = list.ToArray();
		}
	}
	public static class HUDManagerBullshitPatch
	{
		public static bool ManualPrefix(HUDManager __instance)
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")]
	public static class SyncShipUnlockablePatch
	{
		public static void Prefix(StartOfRound __instance, ref int[] playerSuitIDs, bool shipLightsOn, Vector3[] placeableObjectPositions, Vector3[] placeableObjectRotations, int[] placeableObjects, int[] storedItems, int[] scrapValues, int[] itemSaveData)
		{
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if (!((Object)(object)networkManager == (Object)null) && networkManager.IsListening && networkManager.IsServer)
			{
				int[] array = new int[MainClass.newPlayerCount];
				for (int i = 0; i < MainClass.newPlayerCount; i++)
				{
					array[i] = __instance.allPlayerScripts[i].currentSuitID;
				}
				playerSuitIDs = array;
			}
		}
	}
	[HarmonyPatch(typeof(NetworkSceneManager), "PopulateScenePlacedObjects")]
	public static class ScenePlacedObjectsInitPatch
	{
		public static void Postfix(ref Dictionary<uint, Dictionary<int, NetworkObject>> ___ScenePlacedObjects)
		{
			MainClass.ResizePlayerCache(___ScenePlacedObjects);
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "LobbyDataIsJoinable")]
	public static class LobbyDataJoinablePatch
	{
		public static bool Prefix(ref bool __result)
		{
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(NetworkConnectionManager), "HandleConnectionApproval")]
	public static class ConnectionApprovalTest
	{
		public static void Prefix(ulong ownerClientId, ConnectionApprovalResponse response)
		{
			if (Object.op_Implicit((Object)(object)StartOfRound.Instance))
			{
				if (StartOfRound.Instance.connectedPlayersAmount >= MainClass.newPlayerCount)
				{
					response.Approved = false;
					response.Reason = "Server is full";
				}
				else
				{
					response.Approved = true;
				}
			}
		}
	}
	[HarmonyPatch(typeof(SteamMatchmaking), "CreateLobbyAsync")]
	public static class LobbyThingPatch
	{
		public static void Prefix(ref int maxMembers)
		{
			MainClass.ReadSettingsFromFile();
			maxMembers = MainClass.newPlayerCount;
		}
	}
	public class ManualHarmonyPatches
	{
		public static void ManualPatch(Harmony HarmonyInstance)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeof(HUDManager), "SyncAllPlayerLevelsServerRpc", new Type[0], (Type[])null), new HarmonyMethod(typeof(HUDManagerBullshitPatch).GetMethod("ManualPrefix")), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
	}
	public class MimicPatches
	{
		[HarmonyPatch(typeof(MaskedPlayerEnemy), "SetEnemyOutside")]
		public class MaskedPlayerEnemyOnEnablePatch
		{
			public static void Postfix(MaskedPlayerEnemy __instance)
			{
				//IL_00d2: 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)
				if (!((Object)(object)__instance.mimickingPlayer != (Object)null))
				{
					return;
				}
				List<string> list = MainClass.playerIdsAndCosmetics[(int)__instance.mimickingPlayer.playerClientId];
				Transform val = ((Component)__instance).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);
				}
				component = ((Component)val).gameObject.AddComponent<CosmeticApplication>();
				foreach (string item in list)
				{
					component.ApplyCosmetic(item, startEnabled: true);
				}
				foreach (CosmeticInstance spawnedCosmetic in component.spawnedCosmetics)
				{
					Transform transform = ((Component)spawnedCosmetic).transform;
					transform.localScale *= 0.38f;
				}
			}
		}
	}
	public class ReflectionUtils
	{
		public static void InvokeMethod(object obj, string methodName, object[] parameters)
		{
			Type type = obj.GetType();
			MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			method.Invoke(obj, parameters);
		}

		public static void InvokeMethod(object obj, Type forceType, string methodName, object[] parameters)
		{
			MethodInfo method = forceType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			method.Invoke(obj, parameters);
		}

		public static void SetPropertyValue(object obj, string propertyName, object value)
		{
			Type type = obj.GetType();
			PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			property.SetValue(obj, value);
		}

		public static T InvokeMethod<T>(object obj, string methodName, object[] parameters)
		{
			Type type = obj.GetType();
			MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			return (T)method.Invoke(obj, parameters);
		}

		public static T GetFieldValue<T>(object obj, string fieldName)
		{
			Type type = obj.GetType();
			FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			return (T)field.GetValue(obj);
		}

		public static void SetFieldValue(object obj, string fieldName, object value)
		{
			Type type = obj.GetType();
			FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			field.SetValue(obj, value);
		}
	}
	[HarmonyPatch(typeof(ShipTeleporter), "Awake")]
	public static class ShipTeleporterAwakePatch
	{
		public static void Postfix(ShipTeleporter __instance)
		{
			int[] array = new int[MainClass.newPlayerCount];
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				array[i] = -1;
			}
			ReflectionUtils.SetFieldValue(__instance, "playersBeingTeleported", array);
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SpectateNextPlayer")]
	public static class SpectatePatches
	{
		public static bool Prefix(PlayerControllerB __instance)
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			if ((Object)(object)__instance.spectatedPlayerScript != (Object)null)
			{
				num = (int)__instance.spectatedPlayerScript.playerClientId;
			}
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				num = (num + 1) % MainClass.newPlayerCount;
				if (!__instance.playersManager.allPlayerScripts[num].isPlayerDead && __instance.playersManager.allPlayerScripts[num].isPlayerControlled && (Object)(object)__instance.playersManager.allPlayerScripts[num] != (Object)(object)__instance)
				{
					__instance.spectatedPlayerScript = __instance.playersManager.allPlayerScripts[num];
					__instance.SetSpectatedPlayerEffects(false);
					return false;
				}
			}
			if ((Object)(object)__instance.deadBody != (Object)null && ((Component)__instance.deadBody).gameObject.activeSelf)
			{
				__instance.spectateCameraPivot.position = __instance.deadBody.bodyParts[0].position;
				ReflectionUtils.InvokeMethod(__instance, "RaycastSpectateCameraAroundPivot", null);
			}
			StartOfRound.Instance.SetPlayerSafeInShip();
			return false;
		}
	}
	[HarmonyPatch(typeof(SoundManager), "Start")]
	public static class SoundManagerStartPatch
	{
		public static void Postfix()
		{
			int num = MainClass.newPlayerCount - 4;
			int num2 = 4;
			for (int i = 0; i < num; i++)
			{
				Array.Resize(ref SoundManager.Instance.playerVoicePitches, SoundManager.Instance.playerVoicePitches.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoicePitchTargets, SoundManager.Instance.playerVoicePitchTargets.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoiceVolumes, SoundManager.Instance.playerVoiceVolumes.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoicePitchLerpSpeed, SoundManager.Instance.playerVoicePitchLerpSpeed.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoiceMixers, SoundManager.Instance.playerVoiceMixers.Length + 1);
				AudioMixerGroup val = ((IEnumerable<AudioMixerGroup>)Resources.FindObjectsOfTypeAll<AudioMixerGroup>()).FirstOrDefault((Func<AudioMixerGroup, bool>)((AudioMixerGroup x) => ((Object)x).name.Contains("Voice")));
				SoundManager.Instance.playerVoicePitches[num2 + i] = 1f;
				SoundManager.Instance.playerVoicePitchTargets[num2 + i] = 1f;
				SoundManager.Instance.playerVoiceVolumes[num2 + i] = 0.5f;
				SoundManager.Instance.playerVoicePitchLerpSpeed[num2 + i] = 3f;
				SoundManager.Instance.playerVoiceMixers[num2 + i] = val;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "GetPlayerSpawnPosition")]
	public static class SpawnPositionClampPatch
	{
		public static void Prefix(ref int playerNum, bool simpleTeleport = false)
		{
			if (playerNum > 3)
			{
				playerNum = 3;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnClientConnect")]
	public static class OnClientConnectedPatch
	{
		public static bool Prefix(StartOfRound __instance, ulong clientId)
		{
			if (!((NetworkBehaviour)__instance).IsServer)
			{
				return false;
			}
			Debug.Log((object)"player connected");
			Debug.Log((object)$"connected players #: {__instance.connectedPlayersAmount}");
			try
			{
				List<int> list = __instance.ClientPlayerList.Values.ToList();
				Debug.Log((object)$"Connecting new player on host; clientId: {clientId}");
				int num = 0;
				for (int i = 1; i < MainClass.newPlayerCount; i++)
				{
					if (!list.Contains(i))
					{
						num = i;
						break;
					}
				}
				__instance.allPlayerScripts[num].actualClientId = clientId;
				__instance.allPlayerObjects[num].GetComponent<NetworkObject>().ChangeOwnership(clientId);
				Debug.Log((object)$"New player assigned object id: {__instance.allPlayerObjects[num]}");
				List<ulong> list2 = new List<ulong>();
				for (int j = 0; j < __instance.allPlayerObjects.Length; j++)
				{
					NetworkObject component = __instance.allPlayerObjects[j].GetComponent<NetworkObject>();
					if (!component.IsOwnedByServer)
					{
						list2.Add(component.OwnerClientId);
					}
					else if (j == 0)
					{
						list2.Add(NetworkManager.Singleton.LocalClientId);
					}
					else
					{
						list2.Add(999uL);
					}
				}
				int groupCredits = Object.FindObjectOfType<Terminal>().groupCredits;
				int profitQuota = TimeOfDay.Instance.profitQuota;
				int quotaFulfilled = TimeOfDay.Instance.quotaFulfilled;
				int num2 = (int)TimeOfDay.Instance.timeUntilDeadline;
				ReflectionUtils.InvokeMethod(__instance, "OnPlayerConnectedClientRpc", new object[10]
				{
					clientId,
					__instance.connectedPlayersAmount,
					list2.ToArray(),
					num,
					groupCredits,
					__instance.currentLevelID,
					profitQuota,
					num2,
					quotaFulfilled,
					__instance.randomMapSeed
				});
				__instance.ClientPlayerList.Add(clientId, num);
				Debug.Log((object)$"client id connecting: {clientId} ; their corresponding player object id: {num}");
			}
			catch (Exception arg)
			{
				Debug.LogError((object)$"Error occured in OnClientConnected! Shutting server down. clientId: {clientId}. Error: {arg}");
				GameNetworkManager.Instance.disconnectionReasonMessage = "Error occured when a player attempted to join the server! Restart the application and please report the glitch!";
				GameNetworkManager.Instance.Disconnect();
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(SteamLobbyManager), "LoadServerList")]
	public static class LoadServerListPatch
	{
		public static bool Prefix(SteamLobbyManager __instance)
		{
			OverrideMethod(__instance);
			return false;
		}

		private static async void OverrideMethod(SteamLobbyManager __instance)
		{
			if (GameNetworkManager.Instance.waitingForLobbyDataRefresh)
			{
				return;
			}
			ReflectionUtils.SetFieldValue(__instance, "refreshServerListTimer", 0f);
			((TMP_Text)__instance.serverListBlankText).text = "Loading server list...";
			ReflectionUtils.GetFieldValue<Lobby[]>(__instance, "currentLobbyList");
			LobbySlot[] array = Object.FindObjectsOfType<LobbySlot>();
			for (int i = 0; i < array.Length; i++)
			{
				Object.Destroy((Object)(object)((Component)array[i]).gameObject);
			}
			LobbyQuery val;
			switch (__instance.sortByDistanceSetting)
			{
			case 0:
				val = SteamMatchmaking.LobbyList;
				((LobbyQuery)(ref val)).FilterDistanceClose();
				break;
			case 1:
				val = SteamMatchmaking.LobbyList;
				((LobbyQuery)(ref val)).FilterDistanceFar();
				break;
			case 2:
				val = SteamMatchmaking.LobbyList;
				((LobbyQuery)(ref val)).FilterDistanceWorldwide();
				break;
			}
			Debug.Log((object)"Requested server list");
			GameNetworkManager.Instance.waitingForLobbyDataRefresh = true;
			Lobby[] currentLobbyList;
			switch (__instance.sortByDistanceSetting)
			{
			case 0:
				val = SteamMatchmaking.LobbyList;
				val = ((LobbyQuery)(ref val)).FilterDistanceClose();
				val = ((LobbyQuery)(ref val)).WithSlotsAvailable(1);
				val = ((LobbyQuery)(ref val)).WithKeyValue("vers", GameNetworkManager.Instance.gameVersionNum.ToString());
				currentLobbyList = await ((LobbyQuery)(ref val)).RequestAsync();
				break;
			case 1:
				val = SteamMatchmaking.LobbyList;
				val = ((LobbyQuery)(ref val)).FilterDistanceFar();
				val = ((LobbyQuery)(ref val)).WithSlotsAvailable(1);
				val = ((LobbyQuery)(ref val)).WithKeyValue("vers", GameNetworkManager.Instance.gameVersionNum.ToString());
				currentLobbyList = await ((LobbyQuery)(ref val)).RequestAsync();
				break;
			default:
				val = SteamMatchmaking.LobbyList;
				val = ((LobbyQuery)(ref val)).FilterDistanceWorldwide();
				val = ((LobbyQuery)(ref val)).WithSlotsAvailable(1);
				val = ((LobbyQuery)(ref val)).WithKeyValue("vers", GameNetworkManager.Instance.gameVersionNum.ToString());
				currentLobbyList = await ((LobbyQuery)(ref val)).RequestAsync();
				break;
			}
			GameNetworkManager.Instance.waitingForLobbyDataRefresh = false;
			if (currentLobbyList != null)
			{
				Debug.Log((object)"Got lobby list!");
				ReflectionUtils.InvokeMethod(__instance, "DebugLogServerList", null);
				if (currentLobbyList.Length == 0)
				{
					((TMP_Text)__instance.serverListBlankText).text = "No available servers to join.";
				}
				else
				{
					((TMP_Text)__instance.serverListBlankText).text = "";
				}
				ReflectionUtils.SetFieldValue(__instance, "lobbySlotPositionOffset", 0f);
				for (int j = 0; j < currentLobbyList.Length; j++)
				{
					Friend[] array2 = SteamFriends.GetBlocked().ToArray();
					if (array2 != null)
					{
						for (int k = 0; k < array2.Length; k++)
						{
							Debug.Log((object)$"blocked user: {((Friend)(ref array2[k])).Name}; id: {array2[k].Id}");
							if (((Lobby)(ref currentLobbyList[j])).IsOwnedBy(array2[k].Id))
							{
								Debug.Log((object)("Hiding lobby by blocked user: " + ((Friend)(ref array2[k])).Name));
							}
						}
					}
					else
					{
						Debug.Log((object)"Blocked users list is null");
					}
					GameObject gameObject = Object.Instantiate<GameObject>(__instance.LobbySlotPrefab, __instance.levelListContainer);
					gameObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(0f, 0f + ReflectionUtils.GetFieldValue<float>(__instance, "lobbySlotPositionOffset"));
					ReflectionUtils.SetFieldValue(__instance, "lobbySlotPositionOffset", ReflectionUtils.GetFieldValue<float>(__instance, "lobbySlotPositionOffset") - 42f);
					LobbySlot componentInChildren = gameObject.GetComponentInChildren<LobbySlot>();
					((TMP_Text)componentInChildren.LobbyName).text = ((Lobby)(ref currentLobbyList[j])).GetData("name");
					((TMP_Text)componentInChildren.playerCount).text = $"{((Lobby)(ref currentLobbyList[j])).MemberCount} / {((Lobby)(ref currentLobbyList[j])).MaxMembers}";
					componentInChildren.lobbyId = ((Lobby)(ref currentLobbyList[j])).Id;
					componentInChildren.thisLobby = currentLobbyList[j];
					ReflectionUtils.SetFieldValue(__instance, "currentLobbyList", currentLobbyList);
				}
			}
			else
			{
				Debug.Log((object)"Lobby list is null after request.");
				((TMP_Text)__instance.serverListBlankText).text = "No available servers to join.";
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "Awake")]
	public static class GameNetworkAwakePatch
	{
		public static int originalVersion;

		public static void Postfix(GameNetworkManager __instance)
		{
			originalVersion = __instance.gameVersionNum;
			if (!AssemblyChecker.HasAssemblyLoaded("lc_api"))
			{
				__instance.gameVersionNum = 9999;
			}
		}
	}
	[HarmonyPatch(typeof(MenuManager), "Awake")]
	public static class MenuManagerVersionDisplayPatch
	{
		public static void Postfix(MenuManager __instance)
		{
			if ((Object)(object)GameNetworkManager.Instance != (Object)null && (Object)(object)__instance.versionNumberText != (Object)null)
			{
				((TMP_Text)__instance.versionNumberText).text = $"v{GameNetworkAwakePatch.originalVersion} (MC)";
			}
		}
	}
}
namespace MoreCompany.Utils
{
	public class AssemblyChecker
	{
		public static bool HasAssemblyLoaded(string name)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			Assembly[] array = assemblies;
			foreach (Assembly assembly in array)
			{
				if (assembly.GetName().Name.ToLower().Equals(name))
				{
					return true;
				}
			}
			return false;
		}
	}
	public class BundleUtilities
	{
		public static byte[] GetResourceBytes(string filename, Assembly assembly)
		{
			string[] manifestResourceNames = assembly.GetManifestResourceNames();
			foreach (string text in manifestResourceNames)
			{
				if (!text.Contains(filename))
				{
					continue;
				}
				using Stream stream = assembly.GetManifestResourceStream(text);
				if (stream == null)
				{
					return null;
				}
				byte[] array = new byte[stream.Length];
				stream.Read(array, 0, array.Length);
				return array;
			}
			return null;
		}

		public static AssetBundle LoadBundleFromInternalAssembly(string filename, Assembly assembly)
		{
			return AssetBundle.LoadFromMemory(GetResourceBytes(filename, assembly));
		}
	}
	public static class AssetBundleExtension
	{
		public static T LoadPersistentAsset<T>(this AssetBundle bundle, string name) where T : Object
		{
			Object val = bundle.LoadAsset(name);
			if (val != (Object)null)
			{
				val.hideFlags = (HideFlags)32;
				return (T)(object)val;
			}
			return default(T);
		}
	}
}
namespace MoreCompany.Cosmetics
{
	public class CosmeticApplication : MonoBehaviour
	{
		public Transform head;

		public Transform hip;

		public Transform lowerArmRight;

		public Transform shinLeft;

		public Transform shinRight;

		public Transform chest;

		public List<CosmeticInstance> spawnedCosmetics = new List<CosmeticInstance>();

		public void Awake()
		{
			head = ((Component)this).transform.Find("spine").Find("spine.001").Find("spine.002")
				.Find("spine.003")
				.Find("spine.004");
			chest = ((Component)this).transform.Find("spine").Find("spine.001").Find("spine.002")
				.Find("spine.003");
			lowerArmRight = ((Component)this).transform.Find("spine").Find("spine.001").Find("spine.002")
				.Find("spine.003")
				.Find("shoulder.R")
				.Find("arm.R_upper")
				.Find("arm.R_lower");
			hip = ((Component)this).transform.Find("spine");
			shinLeft = ((Component)this).transform.Find("spine").Find("thigh.L").Find("shin.L");
			shinRight = ((Component)this).transform.Find("spine").Find("thigh.R").Find("shin.R");
			RefreshAllCosmeticPositions();
		}

		private void OnDisable()
		{
			foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics)
			{
				((Component)spawnedCosmetic).gameObject.SetActive(false);
			}
		}

		private void OnEnable()
		{
			foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics)
			{
				((Component)spawnedCosmetic).gameObject.SetActive(true);
			}
		}

		public void ClearCosmetics()
		{
			foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics)
			{
				Object.Destroy((Object)(object)((Component)spawnedCosmetic).gameObject);
			}
			spawnedCosmetics.Clear();
		}

		public void ApplyCosmetic(string cosmeticId, bool startEnabled)
		{
			if (CosmeticRegistry.cosmeticInstances.ContainsKey(cosmeticId))
			{
				CosmeticInstance cosmeticInstance = CosmeticRegistry.cosmeticInstances[cosmeticId];
				GameObject val = Object.Instantiate<GameObject>(((Component)cosmeticInstance).gameObject);
				val.SetActive(startEnabled);
				CosmeticInstance component = val.GetComponent<CosmeticInstance>();
				spawnedCosmetics.Add(component);
				if (startEnabled)
				{
					ParentCosmetic(component);
				}
			}
		}

		public void RefreshAllCosmeticPositions()
		{
			foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics)
			{
				ParentCosmetic(spawnedCosmetic);
			}
		}

		private void ParentCosmetic(CosmeticInstance cosmeticInstance)
		{
			//IL_006d: 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)
			Transform val = null;
			switch (cosmeticInstance.cosmeticType)
			{
			case CosmeticType.HAT:
				val = head;
				break;
			case CosmeticType.R_LOWER_ARM:
				val = lowerArmRight;
				break;
			case CosmeticType.HIP:
				val = hip;
				break;
			case CosmeticType.L_SHIN:
				val = shinLeft;
				break;
			case CosmeticType.R_SHIN:
				val = shinRight;
				break;
			case CosmeticType.CHEST:
				val = chest;
				break;
			}
			((Component)cosmeticInstance).transform.position = val.position;
			((Component)cosmeticInstance).transform.rotation = val.rotation;
			((Component)cosmeticInstance).transform.parent = val;
		}
	}
	public class CosmeticInstance : MonoBehaviour
	{
		public CosmeticType cosmeticType;

		public string cosmeticId;

		public Texture2D icon;
	}
	public class CosmeticGeneric
	{
		public virtual string gameObjectPath { get; }

		public virtual string cosmeticId { get; }

		public virtual string textureIconPath { get; }

		public CosmeticType cosmeticType { get; }

		public void LoadFromBundle(AssetBundle bundle)
		{
			GameObject val = bundle.LoadPersistentAsset<GameObject>(gameObjectPath);
			Texture2D icon = bundle.LoadPersistentAsset<Texture2D>(textureIconPath);
			CosmeticInstance cosmeticInstance = val.AddComponent<CosmeticInstance>();
			cosmeticInstance.cosmeticId = cosmeticId;
			cosmeticInstance.icon = icon;
			cosmeticInstance.cosmeticType = cosmeticType;
			MainClass.StaticLogger.LogInfo((object)("Loaded cosmetic: " + cosmeticId + " from bundle: " + ((Object)bundle).name));
			CosmeticRegistry.cosmeticInstances.Add(cosmeticId, cosmeticInstance);
		}
	}
	public enum CosmeticType
	{
		HAT,
		WRIST,
		CHEST,
		R_LOWER_ARM,
		HIP,
		L_SHIN,
		R_SHIN
	}
	public class CosmeticRegistry
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__8_0;

			public static UnityAction <>9__8_1;

			internal void <SpawnCosmeticGUI>b__8_0()
			{
				MainClass.showCosmetics = true;
				MainClass.SaveSettingsToFile();
			}

			internal void <SpawnCosmeticGUI>b__8_1()
			{
				MainClass.showCosmetics = false;
				MainClass.SaveSettingsToFile();
			}
		}

		public static Dictionary<string, CosmeticInstance> cosmeticInstances = new Dictionary<string, CosmeticInstance>();

		public static GameObject cosmeticGUI;

		private static GameObject displayGuy;

		private static CosmeticApplication cosmeticApplication;

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

		public const float COSMETIC_PLAYER_SCALE_MULT = 0.38f;

		public static void LoadCosmeticsFromBundle(AssetBundle bundle)
		{
			string[] allAssetNames = bundle.GetAllAssetNames();
			foreach (string text in allAssetNames)
			{
				if (text.EndsWith(".prefab"))
				{
					GameObject val = bundle.LoadPersistentAsset<GameObject>(text);
					CosmeticInstance component = val.GetComponent<CosmeticInstance>();
					if (!((Object)(object)component == (Object)null))
					{
						MainClass.StaticLogger.LogInfo((object)("Loaded cosmetic: " + component.cosmeticId + " from bundle"));
						cosmeticInstances.Add(component.cosmeticId, component);
					}
				}
			}
		}

		public static void LoadCosmeticsFromAssembly(Assembly assembly, AssetBundle bundle)
		{
			Type[] types = assembly.GetTypes();
			foreach (Type type in types)
			{
				if (type.IsSubclassOf(typeof(CosmeticGeneric)))
				{
					CosmeticGeneric cosmeticGeneric = (CosmeticGeneric)type.GetConstructor(new Type[0]).Invoke(new object[0]);
					cosmeticGeneric.LoadFromBundle(bundle);
				}
			}
		}

		public static void SpawnCosmeticGUI()
		{
			//IL_0042: 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_010e: Expected O, but got Unknown
			//IL_016b: 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_0176: Expected O, but got Unknown
			cosmeticGUI = Object.Instantiate<GameObject>(MainClass.cosmeticGUIInstance);
			((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale")).transform.localScale = new Vector3(2f, 2f, 2f);
			displayGuy = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("ObjectHolder")
				.Find("ScavengerModel")
				.Find("metarig")).gameObject;
			cosmeticApplication = displayGuy.AddComponent<CosmeticApplication>();
			GameObject gameObject = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("EnableButton")).gameObject;
			ButtonClickedEvent onClick = gameObject.GetComponent<Button>().onClick;
			object obj = <>c.<>9__8_0;
			if (obj == null)
			{
				UnityAction val = delegate
				{
					MainClass.showCosmetics = true;
					MainClass.SaveSettingsToFile();
				};
				<>c.<>9__8_0 = val;
				obj = (object)val;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
			GameObject gameObject2 = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("DisableButton")).gameObject;
			ButtonClickedEvent onClick2 = gameObject2.GetComponent<Button>().onClick;
			object obj2 = <>c.<>9__8_1;
			if (obj2 == null)
			{
				UnityAction val2 = delegate
				{
					MainClass.showCosmetics = false;
					MainClass.SaveSettingsToFile();
				};
				<>c.<>9__8_1 = val2;
				obj2 = (object)val2;
			}
			((UnityEvent)onClick2).AddListener((UnityAction)obj2);
			if (MainClass.showCosmetics)
			{
				gameObject.SetActive(false);
				gameObject2.SetActive(true);
			}
			else
			{
				gameObject.SetActive(true);
				gameObject2.SetActive(false);
			}
			PopulateCosmetics();
			UpdateCosmeticsOnDisplayGuy(startEnabled: false);
		}

		public static void PopulateCosmetics()
		{
			//IL_0106: 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_021e: Expected O, but got Unknown
			GameObject gameObject = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("CosmeticsHolder")
				.Find("Content")).gameObject;
			List<Transform> list = new List<Transform>();
			for (int i = 0; i < gameObject.transform.childCount; i++)
			{
				list.Add(gameObject.transform.GetChild(i));
			}
			foreach (Transform item in list)
			{
				Object.Destroy((Object)(object)((Component)item).gameObject);
			}
			foreach (KeyValuePair<string, CosmeticInstance> cosmeticInstance in cosmeticInstances)
			{
				GameObject val = Object.Instantiate<GameObject>(MainClass.cosmeticButton, gameObject.transform);
				val.transform.localScale = Vector3.one;
				GameObject disabledOverlay = ((Component)val.transform.Find("Deselected")).gameObject;
				disabledOverlay.SetActive(true);
				GameObject enabledOverlay = ((Component)val.transform.Find("Selected")).gameObject;
				enabledOverlay.SetActive(true);
				if (IsEquipped(cosmeticInstance.Value.cosmeticId))
				{
					enabledOverlay.SetActive(true);
					disabledOverlay.SetActive(false);
				}
				else
				{
					enabledOverlay.SetActive(false);
					disabledOverlay.SetActive(true);
				}
				RawImage component = ((Component)val.transform.Find("Icon")).GetComponent<RawImage>();
				component.texture = (Texture)(object)cosmeticInstance.Value.icon;
				Button component2 = val.GetComponent<Button>();
				((UnityEvent)component2.onClick).AddListener((UnityAction)delegate
				{
					ToggleCosmetic(cosmeticInstance.Value.cosmeticId);
					if (IsEquipped(cosmeticInstance.Value.cosmeticId))
					{
						enabledOverlay.SetActive(true);
						disabledOverlay.SetActive(false);
					}
					else
					{
						enabledOverlay.SetActive(false);
						disabledOverlay.SetActive(true);
					}
					MainClass.WriteCosmeticsToFile();
					UpdateCosmeticsOnDisplayGuy(startEnabled: true);
				});
			}
		}

		private static Color HexToColor(string hex)
		{
			//IL_0003: 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_0016: Unknown result type (might be due to invalid IL or missing references)
			Color result = default(Color);
			ColorUtility.TryParseHtmlString(hex, ref result);
			return result;
		}

		public static void UpdateCosmeticsOnDisplayGuy(bool startEnabled)
		{
			cosmeticApplication.ClearCosmetics();
			foreach (string locallySelectedCosmetic in locallySelectedCosmetics)
			{
				cosmeticApplication.ApplyCosmetic(locallySelectedCosmetic, startEnabled);
			}
			foreach (CosmeticInstance spawnedCosmetic in cosmeticApplication.spawnedCosmetics)
			{
				RecursiveLayerChange(((Component)spawnedCosmetic).transform, 5);
			}
		}

		private static void RecursiveLayerChange(Transform transform, int layer)
		{
			((Component)transform).gameObject.layer = layer;
			for (int i = 0; i < transform.childCount; i++)
			{
				RecursiveLayerChange(transform.GetChild(i), layer);
			}
		}

		public static bool IsEquipped(string cosmeticId)
		{
			return locallySelectedCosmetics.Contains(cosmeticId);
		}

		public static void ToggleCosmetic(string cosmeticId)
		{
			if (locallySelectedCosmetics.Contains(cosmeticId))
			{
				locallySelectedCosmetics.Remove(cosmeticId);
			}
			else
			{
				locallySelectedCosmetics.Add(cosmeticId);
			}
		}
	}
}
namespace MoreCompany.Behaviors
{
	public class SpinDragger : MonoBehaviour, IPointerDownHandler, IEventSystemHandler, IPointerUpHandler
	{
		public float speed = 1f;

		private Vector2 lastMousePosition;

		private bool dragging = false;

		private Vector3 rotationalVelocity = Vector3.zero;

		public float dragSpeed = 1f;

		public float airDrag = 0.99f;

		public GameObject target;

		private void Update()
		{
			//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_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_00a1: 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_0016: 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_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: 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_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_0054: 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_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)
			if (dragging)
			{
				Vector3 val = Vector2.op_Implicit(((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue() - lastMousePosition);
				rotationalVelocity += new Vector3(0f, 0f - val.x, 0f) * dragSpeed;
				lastMousePosition = ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue();
			}
			rotationalVelocity *= airDrag;
			target.transform.Rotate(rotationalVelocity * Time.deltaTime * speed, (Space)0);
		}

		public void OnPointerDown(PointerEventData eventData)
		{
			//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)
			lastMousePosition = ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue();
			dragging = true;
		}

		public void OnPointerUp(PointerEventData eventData)
		{
			dragging = false;
		}
	}
}

BepInEx/plugins/RugbugRedfern-Skinwalkers/SkinwalkerMod.dll

Decompiled 10 months 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.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Dissonance.Config;
using HarmonyLib;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("SkinwalkerMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SkinwalkerMod")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("fd4979a2-cef0-46af-8bf8-97e630b11475")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
internal class <Module>
{
	static <Module>()
	{
		NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>();
		NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>();
		NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>();
		NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>();
	}
}
namespace SkinwalkerMod;

[BepInPlugin("RugbugRedfern.SkinwalkerMod", "Skinwalker Mod", "1.0.8")]
internal class PluginLoader : BaseUnityPlugin
{
	private readonly Harmony harmony = new Harmony("RugbugRedfern.SkinwalkerMod");

	private const string modGUID = "RugbugRedfern.SkinwalkerMod";

	private const string modVersion = "1.0.8";

	private static bool initialized;

	public static PluginLoader Instance { get; private set; }

	private void Awake()
	{
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Expected O, but got Unknown
		if (initialized)
		{
			return;
		}
		initialized = true;
		Instance = this;
		harmony.PatchAll(Assembly.GetExecutingAssembly());
		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);
				}
			}
		}
		SkinwalkerLogger.Initialize("RugbugRedfern.SkinwalkerMod");
		SkinwalkerLogger.Log("SKINWALKER MOD STARTING UP 1.0.8");
		SkinwalkerConfig.InitConfig();
		SceneManager.sceneLoaded += SkinwalkerNetworkManagerHandler.ClientConnectInitializer;
		GameObject val = new GameObject("Skinwalker Mod");
		val.AddComponent<SkinwalkerModPersistent>();
		((Object)val).hideFlags = (HideFlags)61;
		Object.DontDestroyOnLoad((Object)(object)val);
	}

	public void BindConfig<T>(ref ConfigEntry<T> config, string section, string key, T defaultValue, string description = "")
	{
		config = ((BaseUnityPlugin)this).Config.Bind<T>(section, key, defaultValue, description);
	}
}
internal class SkinwalkerBehaviour : MonoBehaviour
{
	private AudioSource audioSource;

	public const float PLAY_INTERVAL_MIN = 15f;

	public const float PLAY_INTERVAL_MAX = 40f;

	private const float MAX_DIST = 100f;

	private float nextTimeToPlayAudio;

	private EnemyAI ai;

	public void Initialize(EnemyAI ai)
	{
		this.ai = ai;
		audioSource = ai.creatureVoice;
		SetNextTime();
	}

	private void Update()
	{
		//IL_0077: 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)
		if (!(Time.time > nextTimeToPlayAudio))
		{
			return;
		}
		SetNextTime();
		float num = -1f;
		if (Object.op_Implicit((Object)(object)ai) && !ai.isEnemyDead)
		{
			if ((Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null || (num = Vector3.Distance(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, ((Component)this).transform.position)) < 100f)
			{
				AudioClip sample = SkinwalkerModPersistent.Instance.GetSample();
				if (Object.op_Implicit((Object)(object)sample))
				{
					SkinwalkerLogger.Log(((Object)this).name + " played voice line 1");
					audioSource.PlayOneShot(sample);
				}
				else
				{
					SkinwalkerLogger.Log(((Object)this).name + " played voice line 0");
				}
			}
			else
			{
				SkinwalkerLogger.Log(((Object)this).name + " played voice line no (too far away) " + num);
			}
		}
		else
		{
			SkinwalkerLogger.Log(((Object)this).name + " played voice line no (dead) EnemyAI: " + (object)ai);
		}
	}

	private void SetNextTime()
	{
		if (SkinwalkerNetworkManager.Instance.VoiceLineFrequency.Value <= 0f)
		{
			nextTimeToPlayAudio = Time.time + 100000000f;
		}
		else
		{
			nextTimeToPlayAudio = Time.time + Random.Range(15f, 40f) / SkinwalkerNetworkManager.Instance.VoiceLineFrequency.Value;
		}
	}

	private T CopyComponent<T>(T original, GameObject destination) where T : Component
	{
		Type type = ((object)original).GetType();
		Component val = destination.AddComponent(type);
		FieldInfo[] fields = type.GetFields();
		FieldInfo[] array = fields;
		foreach (FieldInfo fieldInfo in array)
		{
			fieldInfo.SetValue(val, fieldInfo.GetValue(original));
		}
		return (T)(object)((val is T) ? val : null);
	}
}
internal class SkinwalkerConfig
{
	public static ConfigEntry<bool> VoiceEnabled_BaboonHawk;

	public static ConfigEntry<bool> VoiceEnabled_Bracken;

	public static ConfigEntry<bool> VoiceEnabled_BunkerSpider;

	public static ConfigEntry<bool> VoiceEnabled_Centipede;

	public static ConfigEntry<bool> VoiceEnabled_CoilHead;

	public static ConfigEntry<bool> VoiceEnabled_EyelessDog;

	public static ConfigEntry<bool> VoiceEnabled_ForestGiant;

	public static ConfigEntry<bool> VoiceEnabled_GhostGirl;

	public static ConfigEntry<bool> VoiceEnabled_GiantWorm;

	public static ConfigEntry<bool> VoiceEnabled_HoardingBug;

	public static ConfigEntry<bool> VoiceEnabled_Hygrodere;

	public static ConfigEntry<bool> VoiceEnabled_Jester;

	public static ConfigEntry<bool> VoiceEnabled_Masked;

	public static ConfigEntry<bool> VoiceEnabled_Nutcracker;

	public static ConfigEntry<bool> VoiceEnabled_SporeLizard;

	public static ConfigEntry<bool> VoiceEnabled_Thumper;

	public static ConfigEntry<float> VoiceLineFrequency;

	public static void InitConfig()
	{
		PluginLoader.Instance.BindConfig(ref VoiceLineFrequency, "Voice Settings", "VoiceLineFrequency", 1f, "1 is the default, and voice lines will occur every " + 15f.ToString("0") + " to " + 40f.ToString("0") + " seconds per enemy. Setting this to 2 means they will occur twice as often, 0.5 means half as often, etc.");
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_BaboonHawk, "Monster Voices", "Baboon Hawk", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_Bracken, "Monster Voices", "Bracken", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_BunkerSpider, "Monster Voices", "Bunker Spider", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_Centipede, "Monster Voices", "Centipede", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_CoilHead, "Monster Voices", "Coil Head", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_EyelessDog, "Monster Voices", "Eyeless Dog", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_ForestGiant, "Monster Voices", "Forest Giant", defaultValue: false);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_GhostGirl, "Monster Voices", "Ghost Girl", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_GiantWorm, "Monster Voices", "Giant Worm", defaultValue: false);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_HoardingBug, "Monster Voices", "Hoarding Bug", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_Hygrodere, "Monster Voices", "Hygrodere", defaultValue: false);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_Jester, "Monster Voices", "Jester", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_Masked, "Monster Voices", "Masked", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_Nutcracker, "Monster Voices", "Nutcracker", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_SporeLizard, "Monster Voices", "Spore Lizard", defaultValue: true);
		PluginLoader.Instance.BindConfig(ref VoiceEnabled_Thumper, "Monster Voices", "Thumper", defaultValue: true);
		SkinwalkerLogger.Log("VoiceEnabled_BaboonHawk" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_BaboonHawk.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_Bracken" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Bracken.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_BunkerSpider" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_BunkerSpider.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_Centipede" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Centipede.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_CoilHead" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_CoilHead.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_EyelessDog" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_EyelessDog.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_ForestGiant" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_ForestGiant.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_GhostGirl" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_GhostGirl.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_GiantWorm" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_GiantWorm.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_HoardingBug" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_HoardingBug.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_Hygrodere" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Hygrodere.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_Jester" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Jester.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_Masked" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Masked.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_Nutcracker" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Nutcracker.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_SporeLizard" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_SporeLizard.Value}]");
		SkinwalkerLogger.Log("VoiceEnabled_Thumper" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Thumper.Value}]");
		SkinwalkerLogger.Log("VoiceLineFrequency" + $" VALUE LOADED FROM CONFIG: [{VoiceLineFrequency.Value}]");
	}
}
internal static class SkinwalkerLogger
{
	internal static ManualLogSource logSource;

	public static void Initialize(string modGUID)
	{
		logSource = Logger.CreateLogSource(modGUID);
	}

	public static void Log(object message)
	{
		logSource.LogInfo(message);
	}

	public static void LogError(object message)
	{
		logSource.LogError(message);
	}

	public static void LogWarning(object message)
	{
		logSource.LogWarning(message);
	}
}
public class SkinwalkerModPersistent : MonoBehaviour
{
	private string audioFolder;

	private List<AudioClip> cachedAudio = new List<AudioClip>();

	private float nextTimeToCheckFolder = 30f;

	private float nextTimeToCheckEnemies = 30f;

	private const float folderScanInterval = 8f;

	private const float enemyScanInterval = 5f;

	public static SkinwalkerModPersistent Instance { get; private set; }

	private void Awake()
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		Instance = this;
		((Component)this).transform.position = Vector3.zero;
		SkinwalkerLogger.Log("Skinwalker Mod Object Initialized");
		audioFolder = Path.Combine(Application.dataPath, "..", "Dissonance_Diagnostics");
		EnableRecording();
		if (!Directory.Exists(audioFolder))
		{
			Directory.CreateDirectory(audioFolder);
		}
	}

	private void Start()
	{
		try
		{
			if (Directory.Exists(audioFolder))
			{
				Directory.Delete(audioFolder, recursive: true);
			}
		}
		catch (Exception message)
		{
			SkinwalkerLogger.Log(message);
		}
	}

	private void OnApplicationQuit()
	{
		DisableRecording();
	}

	private void EnableRecording()
	{
		DebugSettings.Instance.EnablePlaybackDiagnostics = true;
		DebugSettings.Instance.RecordFinalAudio = true;
	}

	private void Update()
	{
		if (Time.realtimeSinceStartup > nextTimeToCheckFolder)
		{
			nextTimeToCheckFolder = Time.realtimeSinceStartup + 8f;
			if (!Directory.Exists(audioFolder))
			{
				SkinwalkerLogger.Log("Audio folder not present. Don't worry about it, it will be created automatically when you play with friends. (" + audioFolder + ")");
				return;
			}
			string[] files = Directory.GetFiles(audioFolder);
			SkinwalkerLogger.Log($"Got audio file paths ({files.Length})");
			string[] array = files;
			foreach (string path in array)
			{
				((MonoBehaviour)this).StartCoroutine(LoadWavFile(path, delegate(AudioClip audioClip)
				{
					cachedAudio.Add(audioClip);
				}));
			}
		}
		if (!(Time.realtimeSinceStartup > nextTimeToCheckEnemies))
		{
			return;
		}
		nextTimeToCheckEnemies = Time.realtimeSinceStartup + 5f;
		EnemyAI[] array2 = Object.FindObjectsOfType<EnemyAI>(true);
		EnemyAI[] array3 = array2;
		SkinwalkerBehaviour skinwalkerBehaviour = default(SkinwalkerBehaviour);
		foreach (EnemyAI val in array3)
		{
			SkinwalkerLogger.Log("IsEnemyEnabled " + ((Object)val).name + " " + IsEnemyEnabled(val));
			if (IsEnemyEnabled(val) && !((Component)val).TryGetComponent<SkinwalkerBehaviour>(ref skinwalkerBehaviour))
			{
				((Component)val).gameObject.AddComponent<SkinwalkerBehaviour>().Initialize(val);
			}
		}
	}

	private bool IsEnemyEnabled(EnemyAI enemy)
	{
		if ((Object)(object)enemy == (Object)null)
		{
			return false;
		}
		return ((Object)((Component)enemy).gameObject).name switch
		{
			"MaskedPlayerEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Masked.Value, 
			"NutcrackerEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Nutcracker.Value, 
			"BaboonHawkEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_BaboonHawk.Value, 
			"Flowerman(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Bracken.Value, 
			"SandSpider(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_BunkerSpider.Value, 
			"RedLocustBees(Clone)" => false, 
			"Centipede(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Centipede.Value, 
			"SpringMan(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_CoilHead.Value, 
			"MouthDog(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_EyelessDog.Value, 
			"ForestGiant(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_ForestGiant.Value, 
			"DressGirl(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_GhostGirl.Value, 
			"SandWorm(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_GiantWorm.Value, 
			"HoarderBug(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_HoardingBug.Value, 
			"Blob(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Hygrodere.Value, 
			"JesterEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Jester.Value, 
			"PufferEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_SporeLizard.Value, 
			"Crawler(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Thumper.Value, 
			"DocileLocustBees(Clone)" => false, 
			"DoublewingedBird(Clone)" => false, 
			_ => true, 
		};
	}

	internal IEnumerator LoadWavFile(string path, Action<AudioClip> callback)
	{
		UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)20);
		try
		{
			yield return www.SendWebRequest();
			if ((int)www.result == 1)
			{
				SkinwalkerLogger.Log("Loaded clip from path " + path);
				AudioClip audioClip = DownloadHandlerAudioClip.GetContent(www);
				if (audioClip.length > 0.9f)
				{
					callback(audioClip);
				}
				try
				{
					File.Delete(path);
				}
				catch (Exception e)
				{
					SkinwalkerLogger.LogWarning(e);
				}
			}
		}
		finally
		{
			((IDisposable)www)?.Dispose();
		}
	}

	private void DisableRecording()
	{
		DebugSettings.Instance.EnablePlaybackDiagnostics = false;
		DebugSettings.Instance.RecordFinalAudio = false;
		if (Directory.Exists(audioFolder))
		{
			Directory.Delete(audioFolder, recursive: true);
		}
	}

	public AudioClip GetSample()
	{
		if (cachedAudio.Count > 0)
		{
			int index = Random.Range(0, cachedAudio.Count - 1);
			AudioClip result = cachedAudio[index];
			cachedAudio.RemoveAt(index);
			return result;
		}
		while (cachedAudio.Count > 200)
		{
			cachedAudio.RemoveAt(0);
		}
		return null;
	}

	public void ClearCache()
	{
		cachedAudio.Clear();
	}
}
internal static class SkinwalkerNetworkManagerHandler
{
	internal static void ClientConnectInitializer(Scene sceneName, LoadSceneMode sceneEnum)
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Expected O, but got Unknown
		if (((Scene)(ref sceneName)).name == "SampleSceneRelay")
		{
			GameObject val = new GameObject("SkinwalkerNetworkManager");
			val.AddComponent<NetworkObject>();
			val.AddComponent<SkinwalkerNetworkManager>();
			Debug.Log((object)"Initialized SkinwalkerNetworkManager");
		}
	}
}
internal class SkinwalkerNetworkManager : NetworkBehaviour
{
	public NetworkVariable<bool> VoiceEnabled_BaboonHawk = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_Bracken = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_BunkerSpider = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_Centipede = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_CoilHead = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_EyelessDog = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_ForestGiant = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_GhostGirl = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_GiantWorm = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_HoardingBug = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_Hygrodere = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_Jester = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_Masked = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_Nutcracker = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_SporeLizard = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<bool> VoiceEnabled_Thumper = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public NetworkVariable<float> VoiceLineFrequency = new NetworkVariable<float>(1f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

	public static SkinwalkerNetworkManager Instance { get; private set; }

	private void Awake()
	{
		Instance = this;
		if (GameNetworkManager.Instance.isHostingGame)
		{
			VoiceEnabled_BaboonHawk.Value = SkinwalkerConfig.VoiceEnabled_BaboonHawk.Value;
			VoiceEnabled_Bracken.Value = SkinwalkerConfig.VoiceEnabled_Bracken.Value;
			VoiceEnabled_BunkerSpider.Value = SkinwalkerConfig.VoiceEnabled_BunkerSpider.Value;
			VoiceEnabled_Centipede.Value = SkinwalkerConfig.VoiceEnabled_Centipede.Value;
			VoiceEnabled_CoilHead.Value = SkinwalkerConfig.VoiceEnabled_CoilHead.Value;
			VoiceEnabled_EyelessDog.Value = SkinwalkerConfig.VoiceEnabled_EyelessDog.Value;
			VoiceEnabled_ForestGiant.Value = SkinwalkerConfig.VoiceEnabled_ForestGiant.Value;
			VoiceEnabled_GhostGirl.Value = SkinwalkerConfig.VoiceEnabled_GhostGirl.Value;
			VoiceEnabled_GiantWorm.Value = SkinwalkerConfig.VoiceEnabled_GiantWorm.Value;
			VoiceEnabled_HoardingBug.Value = SkinwalkerConfig.VoiceEnabled_HoardingBug.Value;
			VoiceEnabled_Hygrodere.Value = SkinwalkerConfig.VoiceEnabled_Hygrodere.Value;
			VoiceEnabled_Jester.Value = SkinwalkerConfig.VoiceEnabled_Jester.Value;
			VoiceEnabled_Masked.Value = SkinwalkerConfig.VoiceEnabled_Masked.Value;
			VoiceEnabled_Nutcracker.Value = SkinwalkerConfig.VoiceEnabled_Nutcracker.Value;
			VoiceEnabled_SporeLizard.Value = SkinwalkerConfig.VoiceEnabled_SporeLizard.Value;
			VoiceEnabled_Thumper.Value = SkinwalkerConfig.VoiceEnabled_Thumper.Value;
			VoiceLineFrequency.Value = SkinwalkerConfig.VoiceLineFrequency.Value;
			SkinwalkerLogger.Log("HOST SENDING CONFIG TO CLIENTS");
		}
		SkinwalkerLogger.Log("SkinwalkerNetworkManager Awake");
	}

	public override void OnDestroy()
	{
		((NetworkBehaviour)this).OnDestroy();
		SkinwalkerLogger.Log("SkinwalkerNetworkManager OnDestroy");
		SkinwalkerModPersistent.Instance?.ClearCache();
	}

	protected override void __initializeVariables()
	{
		if (VoiceEnabled_BaboonHawk == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BaboonHawk cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_BaboonHawk).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk, "VoiceEnabled_BaboonHawk");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk);
		if (VoiceEnabled_Bracken == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Bracken cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_Bracken).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Bracken, "VoiceEnabled_Bracken");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Bracken);
		if (VoiceEnabled_BunkerSpider == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BunkerSpider cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_BunkerSpider).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider, "VoiceEnabled_BunkerSpider");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider);
		if (VoiceEnabled_Centipede == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Centipede cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_Centipede).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Centipede, "VoiceEnabled_Centipede");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Centipede);
		if (VoiceEnabled_CoilHead == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_CoilHead cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_CoilHead).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_CoilHead, "VoiceEnabled_CoilHead");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_CoilHead);
		if (VoiceEnabled_EyelessDog == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_EyelessDog cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_EyelessDog).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_EyelessDog, "VoiceEnabled_EyelessDog");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_EyelessDog);
		if (VoiceEnabled_ForestGiant == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_ForestGiant cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_ForestGiant).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_ForestGiant, "VoiceEnabled_ForestGiant");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_ForestGiant);
		if (VoiceEnabled_GhostGirl == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GhostGirl cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_GhostGirl).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GhostGirl, "VoiceEnabled_GhostGirl");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GhostGirl);
		if (VoiceEnabled_GiantWorm == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GiantWorm cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_GiantWorm).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GiantWorm, "VoiceEnabled_GiantWorm");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GiantWorm);
		if (VoiceEnabled_HoardingBug == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_HoardingBug cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_HoardingBug).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_HoardingBug, "VoiceEnabled_HoardingBug");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_HoardingBug);
		if (VoiceEnabled_Hygrodere == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Hygrodere cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_Hygrodere).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Hygrodere, "VoiceEnabled_Hygrodere");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Hygrodere);
		if (VoiceEnabled_Jester == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Jester cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_Jester).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Jester, "VoiceEnabled_Jester");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Jester);
		if (VoiceEnabled_Masked == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Masked cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_Masked).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Masked, "VoiceEnabled_Masked");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Masked);
		if (VoiceEnabled_Nutcracker == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Nutcracker cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_Nutcracker).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Nutcracker, "VoiceEnabled_Nutcracker");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Nutcracker);
		if (VoiceEnabled_SporeLizard == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_SporeLizard cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_SporeLizard).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_SporeLizard, "VoiceEnabled_SporeLizard");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_SporeLizard);
		if (VoiceEnabled_Thumper == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Thumper cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceEnabled_Thumper).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Thumper, "VoiceEnabled_Thumper");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Thumper);
		if (VoiceLineFrequency == null)
		{
			throw new Exception("SkinwalkerNetworkManager.VoiceLineFrequency cannot be null. All NetworkVariableBase instances must be initialized.");
		}
		((NetworkVariableBase)VoiceLineFrequency).Initialize((NetworkBehaviour)(object)this);
		((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceLineFrequency, "VoiceLineFrequency");
		base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceLineFrequency);
		((NetworkBehaviour)this).__initializeVariables();
	}

	protected internal override string __getTypeName()
	{
		return "SkinwalkerNetworkManager";
	}
}

BepInEx/plugins/Sligili-More_Emotes/MoreEmotes1.2.2.dll

Decompiled 10 months 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.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using MoreEmotes.Patch;
using Tools;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
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: AssemblyTitle("FuckYouMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FuckYouMod")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5ecc2bf2-af12-4e83-a6f1-cf2eacbf3060")]
[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 Tools
{
	public class Reflection
	{
		public static object GetInstanceField(Type type, object instance, string fieldName)
		{
			BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
			FieldInfo field = type.GetField(fieldName, bindingAttr);
			return field.GetValue(instance);
		}

		public static object CallMethod(object instance, string methodName, params object[] args)
		{
			MethodInfo method = instance.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
			if (method != null)
			{
				return method.Invoke(instance, args);
			}
			return null;
		}
	}
}
namespace MoreEmotes
{
	[BepInPlugin("MoreEmotes", "MoreEmotes-Sligili", "1.2.2")]
	public class FuckYouModInitialization : BaseUnityPlugin
	{
		private Harmony _harmony;

		private ConfigEntry<string> config_KeyWheel;

		private ConfigEntry<bool> config_InventoryCheck;

		private ConfigEntry<string> config_KeyEmote3;

		private ConfigEntry<string> config_KeyEmote4;

		private ConfigEntry<string> config_KeyEmote5;

		private ConfigEntry<string> config_KeyEmote6;

		private ConfigEntry<string> config_KeyEmote7;

		private ConfigEntry<string> config_KeyEmote8;

		private void Awake()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"MoreEmotes loaded");
			EmotePatch.animationsBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animationsbundle"));
			EmotePatch.animatorBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animatorbundle"));
			EmotePatch.local = EmotePatch.animatorBundle.LoadAsset<RuntimeAnimatorController>("Assets/MoreEmotes/NEWmetarig.controller");
			EmotePatch.others = EmotePatch.animatorBundle.LoadAsset<RuntimeAnimatorController>("Assets/MoreEmotes/NEWmetarigOtherPlayers.controller");
			CustomAudioAnimationEvent.claps[0] = EmotePatch.animationsBundle.LoadAsset<AudioClip>("Assets/MoreEmotes/SingleClapEmote1.wav");
			CustomAudioAnimationEvent.claps[1] = EmotePatch.animationsBundle.LoadAsset<AudioClip>("Assets/MoreEmotes/SingleClapEmote2.wav");
			ConfigFile();
			IncompatibilityAids();
			_harmony = new Harmony("MoreEmotes");
			_harmony.PatchAll(typeof(EmotePatch));
		}

		private void IncompatibilityAids()
		{
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				BepInPlugin metadata = pluginInfo.Value.Metadata;
				if (metadata.GUID.Equals("com.malco.lethalcompany.moreshipupgrades") || metadata.GUID.Equals("Stoneman.LethalProgression"))
				{
					EmotePatch.IncompatibleStuff = true;
					break;
				}
			}
		}

		private void ConfigFile()
		{
			EmotePatch.keybinds = new string[9];
			config_KeyWheel = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL", "Key", "v", (ConfigDescription)null);
			EmotePatch.wheelKeybind = config_KeyWheel.Value;
			config_InventoryCheck = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "InventoryCheck", true, "Prevents some emotes from performing while holding any item/scrap");
			EmotePatch.InvCheck = config_InventoryCheck.Value;
			config_KeyEmote3 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Middle Finger", "3", (ConfigDescription)null);
			EmotePatch.keybinds[2] = config_KeyEmote3.Value.Replace(" ", "");
			config_KeyEmote4 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "The Griddy", "6", (ConfigDescription)null);
			EmotePatch.keybinds[5] = config_KeyEmote4.Value.Replace(" ", "");
			config_KeyEmote5 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Shy", "5", (ConfigDescription)null);
			EmotePatch.keybinds[4] = config_KeyEmote5.Value.Replace(" ", "");
			config_KeyEmote6 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Clap", "4", (ConfigDescription)null);
			EmotePatch.keybinds[3] = config_KeyEmote6.Value.Replace(" ", "");
			config_KeyEmote7 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Twerk", "7", (ConfigDescription)null);
			EmotePatch.keybinds[6] = config_KeyEmote7.Value.Replace(" ", "");
			config_KeyEmote8 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Salute", "8", (ConfigDescription)null);
			EmotePatch.keybinds[7] = config_KeyEmote8.Value.Replace(" ", "");
		}
	}
	public static class PluginInfo
	{
		public const string Guid = "MoreEmotes";

		public const string Name = "MoreEmotes-Sligili";

		public const string Ver = "1.2.2";
	}
}
namespace MoreEmotes.Patch
{
	internal class EmotePatch
	{
		public static AssetBundle animationsBundle;

		public static AssetBundle animatorBundle;

		public static string[] keybinds;

		public static string wheelKeybind;

		private static CallbackContext context;

		public static RuntimeAnimatorController local;

		public static RuntimeAnimatorController others;

		private static int currentEmoteID;

		private static float svMovSpeed;

		public static bool IncompatibleStuff;

		public static bool InvCheck;

		public static bool emoteWheelIsOpened;

		public static GameObject wheel;

		public static GameObject rebindmenu;

		public static GameObject btn;

		private static SelectionWheel selectionWheel;

		[HarmonyPatch(typeof(MenuManager), "Start")]
		[HarmonyPostfix]
		private static void MenuStart(MenuManager __instance)
		{
			GameObject val = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesPanel.prefab");
			GameObject val2 = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesButton.prefab");
			GameObject gameObject = ((Component)((Component)__instance).transform.parent).gameObject;
			GameObject gameObject2 = ((Component)((Component)gameObject.transform.Find("MenuContainer")).transform.Find("SettingsPanel")).gameObject;
			if ((Object)(object)btn != (Object)null)
			{
				Object.Destroy((Object)(object)btn.gameObject);
			}
			btn = Object.Instantiate<GameObject>(val2, gameObject2.transform);
			btn.transform.SetSiblingIndex(7);
			if ((Object)(object)rebindmenu != (Object)null)
			{
				Object.Destroy((Object)(object)rebindmenu.gameObject);
			}
			rebindmenu = Object.Instantiate<GameObject>(val, gameObject2.transform);
			RebindBtn.defaultKeys = keybinds;
			BasicToggle.configValueInv = InvCheck;
			if ((Object)(object)gameObject2.GetComponent<SetupEverything>() == (Object)null)
			{
				gameObject2.AddComponent<SetupEverything>();
			}
			SetupEverything.configValue = InvCheck;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPostfix]
		private static void StartPostfix(PlayerControllerB __instance)
		{
			GameObject gameObject = ((Component)((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel")).transform.Find("metarig")).gameObject;
			CustomAudioAnimationEvent customAudioAnimationEvent = gameObject.AddComponent<CustomAudioAnimationEvent>();
			svMovSpeed = __instance.movementSpeed;
			customAudioAnimationEvent.player = __instance;
			if (Object.FindObjectsOfType(typeof(SelectionWheel)).Length == 0)
			{
				GameObject val = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesMenu.prefab");
				GameObject gameObject2 = ((Component)((Component)GameObject.Find("Systems").gameObject.transform.Find("UI")).gameObject.transform.Find("Canvas")).gameObject;
				GameObject val2 = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesPanel.prefab");
				GameObject val3 = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesButton.prefab");
				GameObject gameObject3 = ((Component)((Component)gameObject2.transform.Find("QuickMenu")).transform.Find("SettingsPanel")).gameObject;
				if ((Object)(object)btn != (Object)null)
				{
					Object.Destroy((Object)(object)btn.gameObject);
				}
				btn = Object.Instantiate<GameObject>(val3, gameObject3.transform);
				btn.transform.SetSiblingIndex(7);
				if ((Object)(object)rebindmenu != (Object)null)
				{
					Object.Destroy((Object)(object)rebindmenu.gameObject);
				}
				rebindmenu = Object.Instantiate<GameObject>(val2, gameObject3.transform);
				RebindBtn.defaultKeys = keybinds;
				BasicToggle.configValueInv = InvCheck;
				if ((Object)(object)wheel != (Object)null)
				{
					Object.Destroy((Object)(object)wheel.gameObject);
				}
				wheel = Object.Instantiate<GameObject>(val, gameObject2.transform);
				selectionWheel = wheel.AddComponent<SelectionWheel>();
				SelectionWheel.emotes_Keybinds = new string[keybinds.Length + 1];
				SelectionWheel.emotes_Keybinds = keybinds;
				if ((Object)(object)gameObject3.GetComponent<SetupEverything>() == (Object)null)
				{
					gameObject3.AddComponent<SetupEverything>();
				}
				SetupEverything.configValue = InvCheck;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(PlayerControllerB __instance)
		{
			//IL_0231: 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)
			if (!__instance.isPlayerControlled || !((NetworkBehaviour)__instance).IsOwner)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = others;
				return;
			}
			if ((Object)(object)__instance.playerBodyAnimator != (Object)(object)local)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = local;
			}
			if (__instance.performingEmote)
			{
				currentEmoteID = __instance.playerBodyAnimator.GetInteger("emoteNumber");
			}
			if (!IncompatibleStuff)
			{
				bool flag = (bool)Reflection.CallMethod(__instance, "CheckConditionsForEmote") && currentEmoteID == 6 && __instance.performingEmote;
				__instance.movementSpeed = (flag ? (svMovSpeed / 2f) : svMovSpeed);
			}
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", InvCheck ? 1 : 0);
			}
			else
			{
				InvCheck = PlayerPrefs.GetInt("InvCheck") == 1;
			}
			if (!PlayerPrefs.HasKey("Emote_Wheel"))
			{
				PlayerPrefs.SetString("Emote_Wheel", wheelKeybind);
			}
			if (InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[PlayerPrefs.GetString("Emote_Wheel")], 0f) && !emoteWheelIsOpened && !__instance.isPlayerDead && !__instance.inTerminalMenu && !__instance.quickMenuManager.isMenuOpen)
			{
				emoteWheelIsOpened = true;
				Cursor.visible = true;
				Cursor.lockState = (CursorLockMode)2;
				wheel.SetActive(emoteWheelIsOpened);
				__instance.disableLookInput = true;
			}
			else if ((!InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[PlayerPrefs.GetString("Emote_Wheel")], 0f) && emoteWheelIsOpened) || __instance.quickMenuManager.isMenuOpen)
			{
				if (!__instance.quickMenuManager.isMenuOpen || __instance.isPlayerDead)
				{
					int selectedEmoteID = selectionWheel.selectedEmoteID;
					if (selectedEmoteID <= 3 || selectedEmoteID == 6 || !InvCheck)
					{
						__instance.PerformEmote(context, selectedEmoteID);
					}
					else if (!__instance.isHoldingObject)
					{
						__instance.PerformEmote(context, selectedEmoteID);
					}
					Cursor.visible = false;
					Cursor.lockState = (CursorLockMode)1;
				}
				if (__instance.isPlayerDead && !__instance.quickMenuManager.isMenuOpen)
				{
					Cursor.visible = false;
					Cursor.lockState = (CursorLockMode)1;
				}
				__instance.disableLookInput = false;
				emoteWheelIsOpened = false;
				wheel.SetActive(emoteWheelIsOpened);
			}
			if (!emoteWheelIsOpened && !__instance.quickMenuManager.isMenuOpen)
			{
				EmoteInput(keybinds[2], needsEmptyHands: false, 3, __instance);
				EmoteInput(keybinds[3], needsEmptyHands: true, 4, __instance);
				EmoteInput(keybinds[4], needsEmptyHands: true, 5, __instance);
				EmoteInput(keybinds[5], needsEmptyHands: false, 6, __instance);
				EmoteInput(keybinds[6], needsEmptyHands: true, 7, __instance);
				EmoteInput(keybinds[7], needsEmptyHands: true, 8, __instance);
			}
		}

		private static void EmoteInput(string keyBind, bool needsEmptyHands, int emoteID, PlayerControllerB player)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			bool flag = PlayerPrefs.GetInt("InvCheck") == 1;
			Emotes emotes = (Emotes)emoteID;
			string text = emotes.ToString();
			if (PlayerPrefs.HasKey(text))
			{
				keyBind = PlayerPrefs.GetString(text);
			}
			else
			{
				PlayerPrefs.SetString(text, keyBind);
			}
			if (!keyBind.Equals(string.Empty) && InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keyBind], 0f) && (!player.isHoldingObject || !needsEmptyHands || !flag) && (!player.performingEmote || currentEmoteID != emoteID))
			{
				Debug.Log((object)text);
				player.PerformEmote(context, emoteID);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "CheckConditionsForEmote")]
		[HarmonyPrefix]
		private static bool prefixCheckConditions(ref bool __result, PlayerControllerB __instance)
		{
			bool flag = (bool)Reflection.GetInstanceField(typeof(PlayerControllerB), __instance, "isJumping");
			if (currentEmoteID == 6)
			{
				__result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && __instance.moveInputVector.x == 0f && !__instance.isSprinting && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu && !__instance.isTypingChat;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "PerformEmote")]
		[HarmonyPrefix]
		private static void PerformEmotePrefix(CallbackContext context, int emoteID, PlayerControllerB __instance)
		{
			if ((emoteID >= 3 || emoteWheelIsOpened || ((CallbackContext)(ref context)).performed) && ((((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject)) || __instance.isTestingPlayer) && (bool)Reflection.CallMethod(__instance, "CheckConditionsForEmote") && !(__instance.timeSinceStartingEmote < 0.5f))
			{
				__instance.timeSinceStartingEmote = 0f;
				__instance.performingEmote = true;
				__instance.playerBodyAnimator.SetInteger("emoteNumber", emoteID);
				__instance.StartPerformingEmoteServerRpc();
			}
		}
	}
	public class CustomAudioAnimationEvent : MonoBehaviour
	{
		private Animator animator;

		private AudioSource SoundsSource;

		public static AudioClip[] claps = (AudioClip[])(object)new AudioClip[2];

		public PlayerControllerB player;

		private void Start()
		{
			animator = ((Component)this).GetComponent<Animator>();
			SoundsSource = player.movementAudio;
		}

		public void PlayClapSound()
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			if (player.performingEmote && (!((NetworkBehaviour)player).IsOwner || !player.isPlayerControlled || animator.GetInteger("emoteNumber") == 4))
			{
				bool flag = player.isInHangarShipRoom && player.playersManager.hangarDoorsClosed;
				RoundManager.Instance.PlayAudibleNoise(((Component)player).transform.position, 22f, 0.6f, 0, flag, 6);
				SoundsSource.pitch = Random.Range(0.59f, 0.79f);
				SoundsSource.PlayOneShot(claps[Random.Range(0, claps.Length)]);
			}
		}

		public void PlayFootstepSound()
		{
			if (player.performingEmote && (!((NetworkBehaviour)player).IsOwner || !player.isPlayerControlled || animator.GetInteger("emoteNumber") == 6 || animator.GetInteger("emoteNumber") == 8) && ((Vector2)(ref player.moveInputVector)).sqrMagnitude == 0f)
			{
				player.PlayFootstepLocal();
				player.PlayFootstepServer();
			}
		}
	}
	public enum Emotes
	{
		Dance = 1,
		Point,
		Middle_Finger,
		Clap,
		Shy,
		The_Griddy,
		Twerk,
		Salute
	}
	public class SelectionWheel : MonoBehaviour
	{
		public RectTransform selectionBlock;

		public Text emoteInformation;

		public Text pageInformation;

		private int blocksNumber = 8;

		private int currentBlock = 1;

		public int pageNumber;

		public int selectedEmoteID;

		private float angle;

		private float pageCooldown = 0.1f;

		public GameObject[] Pages;

		private int cuadrante = 0;

		public string selectedEmoteName;

		public float wheelMovementOffset = 3.3f;

		public static string[] emotes_Keybinds;

		private Vector2 center;

		private void OnEnable()
		{
			//IL_0012: 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_01a7: Unknown result type (might be due to invalid IL or missing references)
			center = new Vector2((float)(Screen.width / 2), (float)(Screen.height / 2));
			PlayerInput component = GameObject.Find("PlayerSettingsObject").GetComponent<PlayerInput>();
			emotes_Keybinds[0] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote1", false), 0, (DisplayStringOptions)0);
			emotes_Keybinds[1] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote2", false), 0, (DisplayStringOptions)0);
			Cursor.visible = true;
			selectionBlock = ((Component)((Component)this).gameObject.transform.Find("SelectedEmote")).gameObject.GetComponent<RectTransform>();
			GameObject gameObject = ((Component)((Component)this).gameObject.transform.Find("FunctionalContent")).gameObject;
			emoteInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("EmoteInfo")).GetComponent<Text>();
			Pages = (GameObject[])(object)new GameObject[gameObject.transform.childCount];
			pageInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("PageNumber")).GetComponent<Text>();
			pageInformation.text = "Page " + Pages.Length + "/" + (pageNumber + 1);
			for (int i = 0; i < gameObject.transform.childCount; i++)
			{
				Pages[i] = ((Component)gameObject.transform.GetChild(i)).gameObject;
			}
			Mouse.current.WarpCursorPosition(center);
		}

		private void Update()
		{
			wheelSelection();
			pageSelection();
			selectedEmoteID = currentBlock + Mathf.RoundToInt((float)(blocksNumber / 4)) + blocksNumber * pageNumber;
			displayEmoteInfo();
		}

		private void wheelSelection()
		{
			//IL_0002: 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_0173: 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_0197: Unknown result type (might be due to invalid IL or missing references)
			if (!(Vector2.Distance(center, ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue()) < wheelMovementOffset))
			{
				bool flag = ((InputControl<float>)(object)((Pointer)Mouse.current).position.x).ReadValue() > center.x;
				bool flag2 = ((InputControl<float>)(object)((Pointer)Mouse.current).position.y).ReadValue() > center.y;
				cuadrante = ((!flag) ? (flag2 ? 2 : 3) : (flag2 ? 1 : 4));
				float num = (((InputControl<float>)(object)((Pointer)Mouse.current).position.y).ReadValue() - center.y) / (((InputControl<float>)(object)((Pointer)Mouse.current).position.x).ReadValue() - center.x);
				float num2 = 180 * (cuadrante - ((cuadrante <= 2) ? 1 : 2));
				angle = Mathf.Atan(num) * (180f / (float)Math.PI) + num2;
				if (angle == 90f)
				{
					angle = 270f;
				}
				else if (angle == 270f)
				{
					angle = 90f;
				}
				float num3 = 360 / blocksNumber;
				currentBlock = Mathf.RoundToInt((angle - num3 * 1.5f) / num3);
				((Transform)selectionBlock).localRotation = Quaternion.Euler(((Component)this).transform.rotation.z, ((Component)this).transform.rotation.y, num3 * (float)currentBlock);
			}
		}

		private void pageSelection()
		{
			pageInformation.text = "Page " + Pages.Length + "/" + (pageNumber + 1);
			if (pageCooldown > 0f)
			{
				pageCooldown -= Time.deltaTime;
			}
			else if (((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() != 0f)
			{
				GameObject[] pages = Pages;
				foreach (GameObject val in pages)
				{
					val.SetActive(false);
				}
				int num = ((((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() > 0f) ? 1 : (-1));
				if (pageNumber + 1 > Pages.Length - 1 && num > 0)
				{
					pageNumber = 0;
				}
				else if (pageNumber - 1 < 0 && num < 0)
				{
					pageNumber = Pages.Length - 1;
				}
				else
				{
					pageNumber += num;
				}
				Pages[pageNumber].SetActive(true);
				pageCooldown = 0.1f;
			}
		}

		private void displayEmoteInfo()
		{
			string text = ((selectedEmoteID > emotes_Keybinds.Length) ? "" : emotes_Keybinds[selectedEmoteID - 1]);
			object obj;
			if (selectedEmoteID <= Enum.GetValues(typeof(Emotes)).Length)
			{
				Emotes emotes = (Emotes)selectedEmoteID;
				obj = emotes.ToString().Replace("_", " ");
			}
			else
			{
				obj = "EMPTY";
			}
			string text2 = (string)obj;
			if (!PlayerPrefs.HasKey(text2.Replace(" ", "_")))
			{
				PlayerPrefs.SetString(text2.Replace(" ", "_"), (selectedEmoteID > emotes_Keybinds.Length) ? "" : emotes_Keybinds[selectedEmoteID - 1]);
			}
			else
			{
				text = PlayerPrefs.GetString(text2.Replace(" ", "_"));
			}
			emoteInformation.text = text2 + "\n[" + text.ToUpper() + "]";
		}
	}
	public class RebindBtn : MonoBehaviour
	{
		public string defaultKey;

		public static string[] defaultKeys;

		public string playerPrefs;

		public GameObject waitingForInput;

		public Text keyInfo;

		public Text description;

		private void Start()
		{
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			string text = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text;
			try
			{
				int num = (int)(Emotes)Enum.Parse(typeof(Emotes), text.Replace(" ", "_"));
				defaultKey = defaultKeys[num - 1];
			}
			catch
			{
				defaultKey = "V";
			}
			playerPrefs = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text.Replace(" ", "_");
			((Component)((Component)((Component)this).transform.parent).transform.Find("Delete")).gameObject.AddComponent<DeleteBtn>();
			keyInfo = ((Component)((Component)this).transform.Find("InputText")).GetComponent<Text>();
			waitingForInput = ((Component)((Component)this).transform.Find("wait")).gameObject;
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener(new UnityAction(GetKey));
			if (!PlayerPrefs.HasKey(playerPrefs))
			{
				PlayerPrefs.SetString(playerPrefs, defaultKey);
			}
			SetKeybind(PlayerPrefs.GetString(playerPrefs));
		}

		public void SetKeybind(string key)
		{
			PlayerPrefs.SetString(playerPrefs, key);
			keyInfo.text = key;
			((MonoBehaviour)this).StopAllCoroutines();
			waitingForInput.SetActive(false);
		}

		public void GetKey()
		{
			waitingForInput.SetActive(true);
			((MonoBehaviour)this).StartCoroutine(WaitForKey(delegate(string key)
			{
				SetKeybind(key);
			}));
		}

		private IEnumerator WaitForKey(Action<string> callback)
		{
			while (!((ButtonControl)Keyboard.current.anyKey).wasPressedThisFrame)
			{
				yield return (object)new WaitForEndOfFrame();
				Observable.CallOnce<InputControl>(InputSystem.onAnyButtonPress, (Action<InputControl>)delegate(InputControl ctrl)
				{
					callback((ctrl.device == Keyboard.current) ? ctrl.name : defaultKey);
				});
			}
		}
	}
	public class DeleteBtn : MonoBehaviour
	{
		private RebindBtn rebindBtn;

		private void Start()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			rebindBtn = ((Component)((Component)((Component)this).transform.parent).transform.Find("Button")).GetComponent<RebindBtn>();
			Button component = ((Component)this).GetComponent<Button>();
			((UnityEvent)component.onClick).AddListener(new UnityAction(deleteKey));
		}

		public void deleteKey()
		{
			rebindBtn.SetKeybind(string.Empty);
		}
	}
	public class BasicToggle : MonoBehaviour
	{
		private Toggle tog;

		public static bool configValueInv;

		public string playerPrefs;

		private void Start()
		{
			tog = ((Component)this).GetComponent<Toggle>();
			((UnityEvent<bool>)(object)tog.onValueChanged).AddListener((UnityAction<bool>)SetNewValue);
			if (!PlayerPrefs.HasKey(playerPrefs))
			{
				PlayerPrefs.SetInt(playerPrefs, configValueInv ? 1 : 0);
			}
		}

		public void SetNewValue(bool arg)
		{
			PlayerPrefs.SetInt(playerPrefs, tog.isOn ? 1 : 0);
		}
	}
	public class ButtonBasic : MonoBehaviour
	{
		public GameObject[] alternateActive = (GameObject[])(object)new GameObject[1];

		private void Start()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener(new UnityAction(onButtonTrigger));
			if (((Object)((Component)this).gameObject).name.Equals("BackButton"))
			{
				alternateActive[0] = ((Component)((Component)this).transform.parent).gameObject;
			}
			if (((Object)((Component)this).gameObject).name.Equals("MoreEmotesButton(Clone)"))
			{
				alternateActive[0] = ((Component)((Component)((Component)this).transform.parent).gameObject.transform.Find("MoreEmotesPanel(Clone)")).gameObject;
			}
		}

		public void onButtonTrigger()
		{
			GameObject[] array = alternateActive;
			foreach (GameObject val in array)
			{
				val.SetActive((!val.activeInHierarchy) ? true : false);
			}
		}
	}
	public class SetupEverything : MonoBehaviour
	{
		private GameObject panel;

		public static bool configValue;

		private void Start()
		{
			panel = ((Component)((Component)this).transform.Find("MoreEmotesPanel(Clone)")).gameObject;
			((Component)panel.transform.Find("Version")).GetComponent<Text>().text = "Sligili - 1.2.2";
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", configValue ? 1 : 0);
			}
			SetupMenuButton();
			BackButton();
			KeybindButtons();
			Others();
		}

		private void SetupMenuButton()
		{
			GameObject gameObject = ((Component)((Component)this).transform.Find("MoreEmotesButton(Clone)")).gameObject;
			gameObject.AddComponent<ButtonBasic>();
		}

		private void BackButton()
		{
			GameObject gameObject = ((Component)panel.transform.Find("BackButton")).gameObject;
			gameObject.AddComponent<ButtonBasic>();
		}

		private void KeybindButtons()
		{
			GameObject gameObject = ((Component)panel.transform.Find("KeybindButtons")).gameObject;
			GameObject[] array = (GameObject[])(object)new GameObject[gameObject.transform.childCount];
			for (int i = 0; i < gameObject.transform.childCount; i++)
			{
				array[i] = ((Component)gameObject.transform.GetChild(i)).gameObject;
			}
			GameObject[] array2 = array;
			foreach (GameObject val in array2)
			{
				((Component)val.transform.Find("Button")).gameObject.AddComponent<RebindBtn>();
			}
		}

		private void Others()
		{
			GameObject gameObject = ((Component)panel.transform.Find("Inv")).gameObject;
			gameObject.AddComponent<BasicToggle>();
			BasicToggle basicToggle = gameObject.AddComponent<BasicToggle>();
			basicToggle.playerPrefs = "InvCheck";
		}
	}
}

BepInEx/plugins/steven4547466-YoutubeBoombox/YoutubeBoombox.dll

Decompiled 10 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.ClientAPI;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using YoutubeBoombox.Providers;
using YoutubeDLSharp;
using YoutubeDLSharp.Converters;
using YoutubeDLSharp.Helpers;
using YoutubeDLSharp.Metadata;
using YoutubeDLSharp.Options;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("YoutubeBoombox")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("YoutubeBoombox")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("50a0e49b-1441-46da-9fbf-11bd9a8df0fd")]
[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]
internal class <Module>
{
	static <Module>()
	{
	}
}
public sealed class HttpUtility
{
	private sealed class HttpQSCollection : NameValueCollection
	{
		public override string ToString()
		{
			int count = Count;
			if (count == 0)
			{
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder();
			string[] allKeys = AllKeys;
			for (int i = 0; i < count; i++)
			{
				stringBuilder.AppendFormat("{0}={1}&", allKeys[i], UrlEncode(base[allKeys[i]]));
			}
			if (stringBuilder.Length > 0)
			{
				stringBuilder.Length--;
			}
			return stringBuilder.ToString();
		}
	}

	public class HttpEncoder
	{
		private static char[] hexChars;

		private static object entitiesLock;

		private static SortedDictionary<string, char> entities;

		private static Lazy<HttpEncoder> defaultEncoder;

		private static Lazy<HttpEncoder> currentEncoderLazy;

		private static HttpEncoder currentEncoder;

		private static IDictionary<string, char> Entities
		{
			get
			{
				lock (entitiesLock)
				{
					if (entities == null)
					{
						InitEntities();
					}
					return entities;
				}
			}
		}

		public static HttpEncoder Current
		{
			get
			{
				if (currentEncoder == null)
				{
					currentEncoder = currentEncoderLazy.Value;
				}
				return currentEncoder;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value");
				}
				currentEncoder = value;
			}
		}

		public static HttpEncoder Default => defaultEncoder.Value;

		static HttpEncoder()
		{
			hexChars = "0123456789abcdef".ToCharArray();
			entitiesLock = new object();
			defaultEncoder = new Lazy<HttpEncoder>(() => new HttpEncoder());
			currentEncoderLazy = new Lazy<HttpEncoder>(GetCustomEncoderFromConfig);
		}

		protected internal virtual void HeaderNameValueEncode(string headerName, string headerValue, out string encodedHeaderName, out string encodedHeaderValue)
		{
			if (string.IsNullOrEmpty(headerName))
			{
				encodedHeaderName = headerName;
			}
			else
			{
				encodedHeaderName = EncodeHeaderString(headerName);
			}
			if (string.IsNullOrEmpty(headerValue))
			{
				encodedHeaderValue = headerValue;
			}
			else
			{
				encodedHeaderValue = EncodeHeaderString(headerValue);
			}
		}

		private static void StringBuilderAppend(string s, ref StringBuilder sb)
		{
			if (sb == null)
			{
				sb = new StringBuilder(s);
			}
			else
			{
				sb.Append(s);
			}
		}

		private static string EncodeHeaderString(string input)
		{
			StringBuilder sb = null;
			foreach (char c in input)
			{
				if ((c < ' ' && c != '\t') || c == '\u007f')
				{
					StringBuilderAppend($"%{(int)c:x2}", ref sb);
				}
			}
			if (sb != null)
			{
				return sb.ToString();
			}
			return input;
		}

		protected internal virtual void HtmlAttributeEncode(string value, TextWriter output)
		{
			if (output == null)
			{
				throw new ArgumentNullException("output");
			}
			if (!string.IsNullOrEmpty(value))
			{
				output.Write(HtmlAttributeEncode(value));
			}
		}

		protected internal virtual void HtmlDecode(string value, TextWriter output)
		{
			if (output == null)
			{
				throw new ArgumentNullException("output");
			}
			output.Write(HtmlDecode(value));
		}

		protected internal virtual void HtmlEncode(string value, TextWriter output)
		{
			if (output == null)
			{
				throw new ArgumentNullException("output");
			}
			output.Write(HtmlEncode(value));
		}

		protected internal virtual byte[] UrlEncode(byte[] bytes, int offset, int count)
		{
			return UrlEncodeToBytes(bytes, offset, count);
		}

		private static HttpEncoder GetCustomEncoderFromConfig()
		{
			return defaultEncoder.Value;
		}

		protected internal virtual string UrlPathEncode(string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				return value;
			}
			MemoryStream memoryStream = new MemoryStream();
			int length = value.Length;
			for (int i = 0; i < length; i++)
			{
				UrlPathEncodeChar(value[i], memoryStream);
			}
			return Encoding.ASCII.GetString(memoryStream.ToArray());
		}

		internal static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count)
		{
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			int num = bytes.Length;
			if (num == 0)
			{
				return new byte[0];
			}
			if (offset < 0 || offset >= num)
			{
				throw new ArgumentOutOfRangeException("offset");
			}
			if (count < 0 || count > num - offset)
			{
				throw new ArgumentOutOfRangeException("count");
			}
			MemoryStream memoryStream = new MemoryStream(count);
			int num2 = offset + count;
			for (int i = offset; i < num2; i++)
			{
				UrlEncodeChar((char)bytes[i], memoryStream, isUnicode: false);
			}
			return memoryStream.ToArray();
		}

		internal static string HtmlEncode(string s)
		{
			if (s == null)
			{
				return null;
			}
			if (s.Length == 0)
			{
				return string.Empty;
			}
			bool flag = false;
			foreach (char c in s)
			{
				if (c == '&' || c == '"' || c == '<' || c == '>' || c > '\u009f' || c == '\'')
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				return s;
			}
			StringBuilder stringBuilder = new StringBuilder();
			int length = s.Length;
			for (int j = 0; j < length; j++)
			{
				char c2 = s[j];
				switch (c2)
				{
				case '&':
					stringBuilder.Append("&amp;");
					continue;
				case '>':
					stringBuilder.Append("&gt;");
					continue;
				case '<':
					stringBuilder.Append("&lt;");
					continue;
				case '"':
					stringBuilder.Append("&quot;");
					continue;
				case '\'':
					stringBuilder.Append("&#39;");
					continue;
				case '<':
					stringBuilder.Append("&#65308;");
					continue;
				case '>':
					stringBuilder.Append("&#65310;");
					continue;
				}
				if (c2 > '\u009f' && c2 < 'Ā')
				{
					stringBuilder.Append("&#");
					int num = c2;
					stringBuilder.Append(num.ToString(Helpers.InvariantCulture));
					stringBuilder.Append(";");
				}
				else
				{
					stringBuilder.Append(c2);
				}
			}
			return stringBuilder.ToString();
		}

		internal static string HtmlAttributeEncode(string s)
		{
			if (string.IsNullOrEmpty(s))
			{
				return string.Empty;
			}
			bool flag = false;
			foreach (char c in s)
			{
				if (c == '&' || c == '"' || c == '<' || c == '\'')
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				return s;
			}
			StringBuilder stringBuilder = new StringBuilder();
			int length = s.Length;
			for (int j = 0; j < length; j++)
			{
				char c2 = s[j];
				switch (c2)
				{
				case '&':
					stringBuilder.Append("&amp;");
					break;
				case '"':
					stringBuilder.Append("&quot;");
					break;
				case '<':
					stringBuilder.Append("&lt;");
					break;
				case '\'':
					stringBuilder.Append("&#39;");
					break;
				default:
					stringBuilder.Append(c2);
					break;
				}
			}
			return stringBuilder.ToString();
		}

		internal static string HtmlDecode(string s)
		{
			if (s == null)
			{
				return null;
			}
			if (s.Length == 0)
			{
				return string.Empty;
			}
			if (s.IndexOf('&') == -1)
			{
				return s;
			}
			StringBuilder stringBuilder = new StringBuilder();
			StringBuilder stringBuilder2 = new StringBuilder();
			StringBuilder stringBuilder3 = new StringBuilder();
			int length = s.Length;
			int num = 0;
			int num2 = 0;
			bool flag = false;
			bool flag2 = false;
			for (int i = 0; i < length; i++)
			{
				char c = s[i];
				if (num == 0)
				{
					if (c == '&')
					{
						stringBuilder2.Append(c);
						stringBuilder.Append(c);
						num = 1;
					}
					else
					{
						stringBuilder3.Append(c);
					}
					continue;
				}
				if (c == '&')
				{
					num = 1;
					if (flag2)
					{
						stringBuilder2.Append(num2.ToString(Helpers.InvariantCulture));
						flag2 = false;
					}
					stringBuilder3.Append(stringBuilder2.ToString());
					stringBuilder2.Length = 0;
					stringBuilder2.Append('&');
					continue;
				}
				switch (num)
				{
				case 1:
					if (c == ';')
					{
						num = 0;
						stringBuilder3.Append(stringBuilder2.ToString());
						stringBuilder3.Append(c);
						stringBuilder2.Length = 0;
					}
					else
					{
						num2 = 0;
						flag = false;
						num = ((c == '#') ? 3 : 2);
						stringBuilder2.Append(c);
						stringBuilder.Append(c);
					}
					break;
				case 2:
					stringBuilder2.Append(c);
					if (c == ';')
					{
						string text = stringBuilder2.ToString();
						if (text.Length > 1 && Entities.ContainsKey(text.Substring(1, text.Length - 2)))
						{
							text = Entities[text.Substring(1, text.Length - 2)].ToString();
						}
						stringBuilder3.Append(text);
						num = 0;
						stringBuilder2.Length = 0;
						stringBuilder.Length = 0;
					}
					break;
				case 3:
					if (c == ';')
					{
						if (num2 == 0)
						{
							stringBuilder3.Append(stringBuilder.ToString() + ";");
						}
						else if (num2 > 65535)
						{
							stringBuilder3.Append("&#");
							stringBuilder3.Append(num2.ToString(Helpers.InvariantCulture));
							stringBuilder3.Append(";");
						}
						else
						{
							stringBuilder3.Append((char)num2);
						}
						num = 0;
						stringBuilder2.Length = 0;
						stringBuilder.Length = 0;
						flag2 = false;
					}
					else if (flag && Uri.IsHexDigit(c))
					{
						num2 = num2 * 16 + Uri.FromHex(c);
						flag2 = true;
						stringBuilder.Append(c);
					}
					else if (char.IsDigit(c))
					{
						num2 = num2 * 10 + (c - 48);
						flag2 = true;
						stringBuilder.Append(c);
					}
					else if (num2 == 0 && (c == 'x' || c == 'X'))
					{
						flag = true;
						stringBuilder.Append(c);
					}
					else
					{
						num = 2;
						if (flag2)
						{
							stringBuilder2.Append(num2.ToString(Helpers.InvariantCulture));
							flag2 = false;
						}
						stringBuilder2.Append(c);
					}
					break;
				}
			}
			if (stringBuilder2.Length > 0)
			{
				stringBuilder3.Append(stringBuilder2.ToString());
			}
			else if (flag2)
			{
				stringBuilder3.Append(num2.ToString(Helpers.InvariantCulture));
			}
			return stringBuilder3.ToString();
		}

		internal static bool NotEncoded(char c)
		{
			if (c != '!' && c != '(' && c != ')' && c != '*' && c != '-' && c != '.')
			{
				return c == '_';
			}
			return true;
		}

		internal static void UrlEncodeChar(char c, Stream result, bool isUnicode)
		{
			if (c > 'ÿ')
			{
				result.WriteByte(37);
				result.WriteByte(117);
				int num = (int)c >> 12;
				result.WriteByte((byte)hexChars[num]);
				num = ((int)c >> 8) & 0xF;
				result.WriteByte((byte)hexChars[num]);
				num = ((int)c >> 4) & 0xF;
				result.WriteByte((byte)hexChars[num]);
				num = c & 0xF;
				result.WriteByte((byte)hexChars[num]);
			}
			else if (c > ' ' && NotEncoded(c))
			{
				result.WriteByte((byte)c);
			}
			else if (c == ' ')
			{
				result.WriteByte(43);
			}
			else if (c < '0' || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || c > 'z')
			{
				if (isUnicode && c > '\u007f')
				{
					result.WriteByte(37);
					result.WriteByte(117);
					result.WriteByte(48);
					result.WriteByte(48);
				}
				else
				{
					result.WriteByte(37);
				}
				int num2 = (int)c >> 4;
				result.WriteByte((byte)hexChars[num2]);
				num2 = c & 0xF;
				result.WriteByte((byte)hexChars[num2]);
			}
			else
			{
				result.WriteByte((byte)c);
			}
		}

		internal static void UrlPathEncodeChar(char c, Stream result)
		{
			if (c < '!' || c > '~')
			{
				byte[] bytes = Encoding.UTF8.GetBytes(c.ToString());
				for (int i = 0; i < bytes.Length; i++)
				{
					result.WriteByte(37);
					int num = bytes[i] >> 4;
					result.WriteByte((byte)hexChars[num]);
					num = bytes[i] & 0xF;
					result.WriteByte((byte)hexChars[num]);
				}
			}
			else if (c == ' ')
			{
				result.WriteByte(37);
				result.WriteByte(50);
				result.WriteByte(48);
			}
			else
			{
				result.WriteByte((byte)c);
			}
		}

		private static void InitEntities()
		{
			entities = new SortedDictionary<string, char>(StringComparer.Ordinal);
			entities.Add("nbsp", '\u00a0');
			entities.Add("iexcl", '¡');
			entities.Add("cent", '¢');
			entities.Add("pound", '£');
			entities.Add("curren", '¤');
			entities.Add("yen", '¥');
			entities.Add("brvbar", '¦');
			entities.Add("sect", '§');
			entities.Add("uml", '\u00a8');
			entities.Add("copy", '©');
			entities.Add("ordf", 'ª');
			entities.Add("laquo", '«');
			entities.Add("not", '¬');
			entities.Add("shy", '\u00ad');
			entities.Add("reg", '®');
			entities.Add("macr", '\u00af');
			entities.Add("deg", '°');
			entities.Add("plusmn", '±');
			entities.Add("sup2", '²');
			entities.Add("sup3", '³');
			entities.Add("acute", '\u00b4');
			entities.Add("micro", 'µ');
			entities.Add("para", '¶');
			entities.Add("middot", '·');
			entities.Add("cedil", '\u00b8');
			entities.Add("sup1", '¹');
			entities.Add("ordm", 'º');
			entities.Add("raquo", '»');
			entities.Add("frac14", '¼');
			entities.Add("frac12", '½');
			entities.Add("frac34", '¾');
			entities.Add("iquest", '¿');
			entities.Add("Agrave", 'À');
			entities.Add("Aacute", 'Á');
			entities.Add("Acirc", 'Â');
			entities.Add("Atilde", 'Ã');
			entities.Add("Auml", 'Ä');
			entities.Add("Aring", 'Å');
			entities.Add("AElig", 'Æ');
			entities.Add("Ccedil", 'Ç');
			entities.Add("Egrave", 'È');
			entities.Add("Eacute", 'É');
			entities.Add("Ecirc", 'Ê');
			entities.Add("Euml", 'Ë');
			entities.Add("Igrave", 'Ì');
			entities.Add("Iacute", 'Í');
			entities.Add("Icirc", 'Î');
			entities.Add("Iuml", 'Ï');
			entities.Add("ETH", 'Ð');
			entities.Add("Ntilde", 'Ñ');
			entities.Add("Ograve", 'Ò');
			entities.Add("Oacute", 'Ó');
			entities.Add("Ocirc", 'Ô');
			entities.Add("Otilde", 'Õ');
			entities.Add("Ouml", 'Ö');
			entities.Add("times", '×');
			entities.Add("Oslash", 'Ø');
			entities.Add("Ugrave", 'Ù');
			entities.Add("Uacute", 'Ú');
			entities.Add("Ucirc", 'Û');
			entities.Add("Uuml", 'Ü');
			entities.Add("Yacute", 'Ý');
			entities.Add("THORN", 'Þ');
			entities.Add("szlig", 'ß');
			entities.Add("agrave", 'à');
			entities.Add("aacute", 'á');
			entities.Add("acirc", 'â');
			entities.Add("atilde", 'ã');
			entities.Add("auml", 'ä');
			entities.Add("aring", 'å');
			entities.Add("aelig", 'æ');
			entities.Add("ccedil", 'ç');
			entities.Add("egrave", 'è');
			entities.Add("eacute", 'é');
			entities.Add("ecirc", 'ê');
			entities.Add("euml", 'ë');
			entities.Add("igrave", 'ì');
			entities.Add("iacute", 'í');
			entities.Add("icirc", 'î');
			entities.Add("iuml", 'ï');
			entities.Add("eth", 'ð');
			entities.Add("ntilde", 'ñ');
			entities.Add("ograve", 'ò');
			entities.Add("oacute", 'ó');
			entities.Add("ocirc", 'ô');
			entities.Add("otilde", 'õ');
			entities.Add("ouml", 'ö');
			entities.Add("divide", '÷');
			entities.Add("oslash", 'ø');
			entities.Add("ugrave", 'ù');
			entities.Add("uacute", 'ú');
			entities.Add("ucirc", 'û');
			entities.Add("uuml", 'ü');
			entities.Add("yacute", 'ý');
			entities.Add("thorn", 'þ');
			entities.Add("yuml", 'ÿ');
			entities.Add("fnof", 'ƒ');
			entities.Add("Alpha", 'Α');
			entities.Add("Beta", 'Β');
			entities.Add("Gamma", 'Γ');
			entities.Add("Delta", 'Δ');
			entities.Add("Epsilon", 'Ε');
			entities.Add("Zeta", 'Ζ');
			entities.Add("Eta", 'Η');
			entities.Add("Theta", 'Θ');
			entities.Add("Iota", 'Ι');
			entities.Add("Kappa", 'Κ');
			entities.Add("Lambda", 'Λ');
			entities.Add("Mu", 'Μ');
			entities.Add("Nu", 'Ν');
			entities.Add("Xi", 'Ξ');
			entities.Add("Omicron", 'Ο');
			entities.Add("Pi", 'Π');
			entities.Add("Rho", 'Ρ');
			entities.Add("Sigma", 'Σ');
			entities.Add("Tau", 'Τ');
			entities.Add("Upsilon", 'Υ');
			entities.Add("Phi", 'Φ');
			entities.Add("Chi", 'Χ');
			entities.Add("Psi", 'Ψ');
			entities.Add("Omega", 'Ω');
			entities.Add("alpha", 'α');
			entities.Add("beta", 'β');
			entities.Add("gamma", 'γ');
			entities.Add("delta", 'δ');
			entities.Add("epsilon", 'ε');
			entities.Add("zeta", 'ζ');
			entities.Add("eta", 'η');
			entities.Add("theta", 'θ');
			entities.Add("iota", 'ι');
			entities.Add("kappa", 'κ');
			entities.Add("lambda", 'λ');
			entities.Add("mu", 'μ');
			entities.Add("nu", 'ν');
			entities.Add("xi", 'ξ');
			entities.Add("omicron", 'ο');
			entities.Add("pi", 'π');
			entities.Add("rho", 'ρ');
			entities.Add("sigmaf", 'ς');
			entities.Add("sigma", 'σ');
			entities.Add("tau", 'τ');
			entities.Add("upsilon", 'υ');
			entities.Add("phi", 'φ');
			entities.Add("chi", 'χ');
			entities.Add("psi", 'ψ');
			entities.Add("omega", 'ω');
			entities.Add("thetasym", 'ϑ');
			entities.Add("upsih", 'ϒ');
			entities.Add("piv", 'ϖ');
			entities.Add("bull", '•');
			entities.Add("hellip", '…');
			entities.Add("prime", '′');
			entities.Add("Prime", '″');
			entities.Add("oline", '‾');
			entities.Add("frasl", '⁄');
			entities.Add("weierp", '℘');
			entities.Add("image", 'ℑ');
			entities.Add("real", 'ℜ');
			entities.Add("trade", '™');
			entities.Add("alefsym", 'ℵ');
			entities.Add("larr", '←');
			entities.Add("uarr", '↑');
			entities.Add("rarr", '→');
			entities.Add("darr", '↓');
			entities.Add("harr", '↔');
			entities.Add("crarr", '↵');
			entities.Add("lArr", '⇐');
			entities.Add("uArr", '⇑');
			entities.Add("rArr", '⇒');
			entities.Add("dArr", '⇓');
			entities.Add("hArr", '⇔');
			entities.Add("forall", '∀');
			entities.Add("part", '∂');
			entities.Add("exist", '∃');
			entities.Add("empty", '∅');
			entities.Add("nabla", '∇');
			entities.Add("isin", '∈');
			entities.Add("notin", '∉');
			entities.Add("ni", '∋');
			entities.Add("prod", '∏');
			entities.Add("sum", '∑');
			entities.Add("minus", '−');
			entities.Add("lowast", '∗');
			entities.Add("radic", '√');
			entities.Add("prop", '∝');
			entities.Add("infin", '∞');
			entities.Add("ang", '∠');
			entities.Add("and", '∧');
			entities.Add("or", '∨');
			entities.Add("cap", '∩');
			entities.Add("cup", '∪');
			entities.Add("int", '∫');
			entities.Add("there4", '∴');
			entities.Add("sim", '∼');
			entities.Add("cong", '≅');
			entities.Add("asymp", '≈');
			entities.Add("ne", '≠');
			entities.Add("equiv", '≡');
			entities.Add("le", '≤');
			entities.Add("ge", '≥');
			entities.Add("sub", '⊂');
			entities.Add("sup", '⊃');
			entities.Add("nsub", '⊄');
			entities.Add("sube", '⊆');
			entities.Add("supe", '⊇');
			entities.Add("oplus", '⊕');
			entities.Add("otimes", '⊗');
			entities.Add("perp", '⊥');
			entities.Add("sdot", '⋅');
			entities.Add("lceil", '⌈');
			entities.Add("rceil", '⌉');
			entities.Add("lfloor", '⌊');
			entities.Add("rfloor", '⌋');
			entities.Add("lang", '〈');
			entities.Add("rang", '〉');
			entities.Add("loz", '◊');
			entities.Add("spades", '♠');
			entities.Add("clubs", '♣');
			entities.Add("hearts", '♥');
			entities.Add("diams", '♦');
			entities.Add("quot", '"');
			entities.Add("amp", '&');
			entities.Add("lt", '<');
			entities.Add("gt", '>');
			entities.Add("OElig", 'Œ');
			entities.Add("oelig", 'œ');
			entities.Add("Scaron", 'Š');
			entities.Add("scaron", 'š');
			entities.Add("Yuml", 'Ÿ');
			entities.Add("circ", 'ˆ');
			entities.Add("tilde", '\u02dc');
			entities.Add("ensp", '\u2002');
			entities.Add("emsp", '\u2003');
			entities.Add("thinsp", '\u2009');
			entities.Add("zwnj", '\u200c');
			entities.Add("zwj", '\u200d');
			entities.Add("lrm", '\u200e');
			entities.Add("rlm", '\u200f');
			entities.Add("ndash", '–');
			entities.Add("mdash", '—');
			entities.Add("lsquo", '‘');
			entities.Add("rsquo", '’');
			entities.Add("sbquo", '‚');
			entities.Add("ldquo", '“');
			entities.Add("rdquo", '”');
			entities.Add("bdquo", '„');
			entities.Add("dagger", '†');
			entities.Add("Dagger", '‡');
			entities.Add("permil", '‰');
			entities.Add("lsaquo", '‹');
			entities.Add("rsaquo", '›');
			entities.Add("euro", '€');
		}
	}

	private class Helpers
	{
		public static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture;
	}

	public interface IHtmlString
	{
		string ToHtmlString();
	}

	public static void HtmlAttributeEncode(string s, TextWriter output)
	{
		if (output == null)
		{
			throw new ArgumentNullException("output");
		}
		HttpEncoder.Current.HtmlAttributeEncode(s, output);
	}

	public static string HtmlAttributeEncode(string s)
	{
		if (s == null)
		{
			return null;
		}
		using StringWriter stringWriter = new StringWriter();
		HttpEncoder.Current.HtmlAttributeEncode(s, stringWriter);
		return stringWriter.ToString();
	}

	public static string UrlDecode(string str)
	{
		return UrlDecode(str, Encoding.UTF8);
	}

	private static char[] GetChars(MemoryStream b, Encoding e)
	{
		return e.GetChars(b.GetBuffer(), 0, (int)b.Length);
	}

	private static void WriteCharBytes(IList buf, char ch, Encoding e)
	{
		if (ch > 'ÿ')
		{
			byte[] bytes = e.GetBytes(new char[1] { ch });
			foreach (byte b in bytes)
			{
				buf.Add(b);
			}
		}
		else
		{
			buf.Add((byte)ch);
		}
	}

	public static string UrlDecode(string s, Encoding e)
	{
		if (s == null)
		{
			return null;
		}
		if (s.IndexOf('%') == -1 && s.IndexOf('+') == -1)
		{
			return s;
		}
		if (e == null)
		{
			e = Encoding.UTF8;
		}
		long num = s.Length;
		List<byte> list = new List<byte>();
		for (int i = 0; i < num; i++)
		{
			char c = s[i];
			if (c == '%' && i + 2 < num && s[i + 1] != '%')
			{
				int @char;
				if (s[i + 1] == 'u' && i + 5 < num)
				{
					@char = GetChar(s, i + 2, 4);
					if (@char != -1)
					{
						WriteCharBytes(list, (char)@char, e);
						i += 5;
					}
					else
					{
						WriteCharBytes(list, '%', e);
					}
				}
				else if ((@char = GetChar(s, i + 1, 2)) != -1)
				{
					WriteCharBytes(list, (char)@char, e);
					i += 2;
				}
				else
				{
					WriteCharBytes(list, '%', e);
				}
			}
			else if (c == '+')
			{
				WriteCharBytes(list, ' ', e);
			}
			else
			{
				WriteCharBytes(list, c, e);
			}
		}
		byte[] bytes = list.ToArray();
		list = null;
		return e.GetString(bytes);
	}

	public static string UrlDecode(byte[] bytes, Encoding e)
	{
		if (bytes == null)
		{
			return null;
		}
		return UrlDecode(bytes, 0, bytes.Length, e);
	}

	private static int GetInt(byte b)
	{
		char c = (char)b;
		if (c >= '0' && c <= '9')
		{
			return c - 48;
		}
		if (c >= 'a' && c <= 'f')
		{
			return c - 97 + 10;
		}
		if (c >= 'A' && c <= 'F')
		{
			return c - 65 + 10;
		}
		return -1;
	}

	private static int GetChar(byte[] bytes, int offset, int length)
	{
		int num = 0;
		int num2 = length + offset;
		for (int i = offset; i < num2; i++)
		{
			int @int = GetInt(bytes[i]);
			if (@int == -1)
			{
				return -1;
			}
			num = (num << 4) + @int;
		}
		return num;
	}

	private static int GetChar(string str, int offset, int length)
	{
		int num = 0;
		int num2 = length + offset;
		for (int i = offset; i < num2; i++)
		{
			char c = str[i];
			if (c > '\u007f')
			{
				return -1;
			}
			int @int = GetInt((byte)c);
			if (@int == -1)
			{
				return -1;
			}
			num = (num << 4) + @int;
		}
		return num;
	}

	public static string UrlDecode(byte[] bytes, int offset, int count, Encoding e)
	{
		if (bytes == null)
		{
			return null;
		}
		if (count == 0)
		{
			return string.Empty;
		}
		if (bytes == null)
		{
			throw new ArgumentNullException("bytes");
		}
		if (offset < 0 || offset > bytes.Length)
		{
			throw new ArgumentOutOfRangeException("offset");
		}
		if (count < 0 || offset + count > bytes.Length)
		{
			throw new ArgumentOutOfRangeException("count");
		}
		StringBuilder stringBuilder = new StringBuilder();
		MemoryStream memoryStream = new MemoryStream();
		int num = count + offset;
		for (int i = offset; i < num; i++)
		{
			if (bytes[i] == 37 && i + 2 < count && bytes[i + 1] != 37)
			{
				int @char;
				if (bytes[i + 1] == 117 && i + 5 < num)
				{
					if (memoryStream.Length > 0)
					{
						stringBuilder.Append(GetChars(memoryStream, e));
						memoryStream.SetLength(0L);
					}
					@char = GetChar(bytes, i + 2, 4);
					if (@char != -1)
					{
						stringBuilder.Append((char)@char);
						i += 5;
						continue;
					}
				}
				else if ((@char = GetChar(bytes, i + 1, 2)) != -1)
				{
					memoryStream.WriteByte((byte)@char);
					i += 2;
					continue;
				}
			}
			if (memoryStream.Length > 0)
			{
				stringBuilder.Append(GetChars(memoryStream, e));
				memoryStream.SetLength(0L);
			}
			if (bytes[i] == 43)
			{
				stringBuilder.Append(' ');
			}
			else
			{
				stringBuilder.Append((char)bytes[i]);
			}
		}
		if (memoryStream.Length > 0)
		{
			stringBuilder.Append(GetChars(memoryStream, e));
		}
		memoryStream = null;
		return stringBuilder.ToString();
	}

	public static byte[] UrlDecodeToBytes(byte[] bytes)
	{
		if (bytes == null)
		{
			return null;
		}
		return UrlDecodeToBytes(bytes, 0, bytes.Length);
	}

	public static byte[] UrlDecodeToBytes(string str)
	{
		return UrlDecodeToBytes(str, Encoding.UTF8);
	}

	public static byte[] UrlDecodeToBytes(string str, Encoding e)
	{
		if (str == null)
		{
			return null;
		}
		if (e == null)
		{
			throw new ArgumentNullException("e");
		}
		return UrlDecodeToBytes(e.GetBytes(str));
	}

	public static byte[] UrlDecodeToBytes(byte[] bytes, int offset, int count)
	{
		if (bytes == null)
		{
			return null;
		}
		if (count == 0)
		{
			return new byte[0];
		}
		int num = bytes.Length;
		if (offset < 0 || offset >= num)
		{
			throw new ArgumentOutOfRangeException("offset");
		}
		if (count < 0 || offset > num - count)
		{
			throw new ArgumentOutOfRangeException("count");
		}
		MemoryStream memoryStream = new MemoryStream();
		int num2 = offset + count;
		for (int i = offset; i < num2; i++)
		{
			char c = (char)bytes[i];
			switch (c)
			{
			case '+':
				c = ' ';
				break;
			case '%':
				if (i < num2 - 2)
				{
					int @char = GetChar(bytes, i + 1, 2);
					if (@char != -1)
					{
						c = (char)@char;
						i += 2;
					}
				}
				break;
			}
			memoryStream.WriteByte((byte)c);
		}
		return memoryStream.ToArray();
	}

	public static string UrlEncode(string str)
	{
		return UrlEncode(str, Encoding.UTF8);
	}

	public static string UrlEncode(string s, Encoding Enc)
	{
		if (s == null)
		{
			return null;
		}
		if (s == string.Empty)
		{
			return string.Empty;
		}
		bool flag = false;
		int length = s.Length;
		for (int i = 0; i < length; i++)
		{
			char c = s[i];
			if ((c < '0' || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || c > 'z') && !HttpEncoder.NotEncoded(c))
			{
				flag = true;
				break;
			}
		}
		if (!flag)
		{
			return s;
		}
		byte[] bytes = new byte[Enc.GetMaxByteCount(s.Length)];
		int bytes2 = Enc.GetBytes(s, 0, s.Length, bytes, 0);
		return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, 0, bytes2));
	}

	public static string UrlEncode(byte[] bytes)
	{
		if (bytes == null)
		{
			return null;
		}
		if (bytes.Length == 0)
		{
			return string.Empty;
		}
		return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, 0, bytes.Length));
	}

	public static string UrlEncode(byte[] bytes, int offset, int count)
	{
		if (bytes == null)
		{
			return null;
		}
		if (bytes.Length == 0)
		{
			return string.Empty;
		}
		return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, offset, count));
	}

	public static byte[] UrlEncodeToBytes(string str)
	{
		return UrlEncodeToBytes(str, Encoding.UTF8);
	}

	public static byte[] UrlEncodeToBytes(string str, Encoding e)
	{
		if (str == null)
		{
			return null;
		}
		if (str.Length == 0)
		{
			return new byte[0];
		}
		byte[] bytes = e.GetBytes(str);
		return UrlEncodeToBytes(bytes, 0, bytes.Length);
	}

	public static byte[] UrlEncodeToBytes(byte[] bytes)
	{
		if (bytes == null)
		{
			return null;
		}
		if (bytes.Length == 0)
		{
			return new byte[0];
		}
		return UrlEncodeToBytes(bytes, 0, bytes.Length);
	}

	public static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count)
	{
		if (bytes == null)
		{
			return null;
		}
		return HttpEncoder.Current.UrlEncode(bytes, offset, count);
	}

	public static string UrlEncodeUnicode(string str)
	{
		if (str == null)
		{
			return null;
		}
		return Encoding.ASCII.GetString(UrlEncodeUnicodeToBytes(str));
	}

	public static byte[] UrlEncodeUnicodeToBytes(string str)
	{
		if (str == null)
		{
			return null;
		}
		if (str.Length == 0)
		{
			return new byte[0];
		}
		MemoryStream memoryStream = new MemoryStream(str.Length);
		foreach (char c in str)
		{
			HttpEncoder.UrlEncodeChar(c, memoryStream, isUnicode: true);
		}
		return memoryStream.ToArray();
	}

	public static string HtmlDecode(string s)
	{
		if (s == null)
		{
			return null;
		}
		using StringWriter stringWriter = new StringWriter();
		HttpEncoder.Current.HtmlDecode(s, stringWriter);
		return stringWriter.ToString();
	}

	public static void HtmlDecode(string s, TextWriter output)
	{
		if (output == null)
		{
			throw new ArgumentNullException("output");
		}
		if (!string.IsNullOrEmpty(s))
		{
			HttpEncoder.Current.HtmlDecode(s, output);
		}
	}

	public static string HtmlEncode(string s)
	{
		if (s == null)
		{
			return null;
		}
		using StringWriter stringWriter = new StringWriter();
		HttpEncoder.Current.HtmlEncode(s, stringWriter);
		return stringWriter.ToString();
	}

	public static void HtmlEncode(string s, TextWriter output)
	{
		if (output == null)
		{
			throw new ArgumentNullException("output");
		}
		if (!string.IsNullOrEmpty(s))
		{
			HttpEncoder.Current.HtmlEncode(s, output);
		}
	}

	public static string HtmlEncode(object value)
	{
		if (value == null)
		{
			return null;
		}
		if (value is IHtmlString htmlString)
		{
			return htmlString.ToHtmlString();
		}
		return HtmlEncode(value.ToString());
	}

	public static string JavaScriptStringEncode(string value)
	{
		return JavaScriptStringEncode(value, addDoubleQuotes: false);
	}

	public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
	{
		if (string.IsNullOrEmpty(value))
		{
			if (!addDoubleQuotes)
			{
				return string.Empty;
			}
			return "\"\"";
		}
		int length = value.Length;
		bool flag = false;
		for (int i = 0; i < length; i++)
		{
			char c = value[i];
			if ((c >= '\0' && c <= '\u001f') || c == '"' || c == '\'' || c == '<' || c == '>' || c == '\\')
			{
				flag = true;
				break;
			}
		}
		if (!flag)
		{
			if (!addDoubleQuotes)
			{
				return value;
			}
			return "\"" + value + "\"";
		}
		StringBuilder stringBuilder = new StringBuilder();
		if (addDoubleQuotes)
		{
			stringBuilder.Append('"');
		}
		for (int j = 0; j < length; j++)
		{
			char c = value[j];
			if (c < '\0' || c > '\a')
			{
				switch (c)
				{
				default:
					if (c != '\'' && c != '<' && c != '>')
					{
						switch (c)
						{
						case '\b':
							stringBuilder.Append("\\b");
							break;
						case '\t':
							stringBuilder.Append("\\t");
							break;
						case '\n':
							stringBuilder.Append("\\n");
							break;
						case '\f':
							stringBuilder.Append("\\f");
							break;
						case '\r':
							stringBuilder.Append("\\r");
							break;
						case '"':
							stringBuilder.Append("\\\"");
							break;
						case '\\':
							stringBuilder.Append("\\\\");
							break;
						default:
							stringBuilder.Append(c);
							break;
						}
						continue;
					}
					break;
				case '\v':
				case '\u000e':
				case '\u000f':
				case '\u0010':
				case '\u0011':
				case '\u0012':
				case '\u0013':
				case '\u0014':
				case '\u0015':
				case '\u0016':
				case '\u0017':
				case '\u0018':
				case '\u0019':
				case '\u001a':
				case '\u001b':
				case '\u001c':
				case '\u001d':
				case '\u001e':
				case '\u001f':
					break;
				}
			}
			stringBuilder.AppendFormat("\\u{0:x4}", (int)c);
		}
		if (addDoubleQuotes)
		{
			stringBuilder.Append('"');
		}
		return stringBuilder.ToString();
	}

	public static string UrlPathEncode(string s)
	{
		return HttpEncoder.Current.UrlPathEncode(s);
	}

	public static NameValueCollection ParseQueryString(string query)
	{
		return ParseQueryString(query, Encoding.UTF8);
	}

	public static NameValueCollection ParseQueryString(string query, Encoding encoding)
	{
		if (query == null)
		{
			throw new ArgumentNullException("query");
		}
		if (encoding == null)
		{
			throw new ArgumentNullException("encoding");
		}
		if (query.Length == 0 || (query.Length == 1 && query[0] == '?'))
		{
			return new HttpQSCollection();
		}
		if (query[0] == '?')
		{
			query = query.Substring(1);
		}
		NameValueCollection result = new HttpQSCollection();
		ParseQueryString(query, encoding, result);
		return result;
	}

	internal static void ParseQueryString(string query, Encoding encoding, NameValueCollection result)
	{
		if (query.Length == 0)
		{
			return;
		}
		string text = HtmlDecode(query);
		int length = text.Length;
		int num = 0;
		bool flag = true;
		while (num <= length)
		{
			int num2 = -1;
			int num3 = -1;
			for (int i = num; i < length; i++)
			{
				if (num2 == -1 && text[i] == '=')
				{
					num2 = i + 1;
				}
				else if (text[i] == '&')
				{
					num3 = i;
					break;
				}
			}
			if (flag)
			{
				flag = false;
				if (text[num] == '?')
				{
					num++;
				}
			}
			string name;
			if (num2 == -1)
			{
				name = null;
				num2 = num;
			}
			else
			{
				name = UrlDecode(text.Substring(num, num2 - num - 1), encoding);
			}
			if (num3 < 0)
			{
				num = -1;
				num3 = text.Length;
			}
			else
			{
				num = num3 + 1;
			}
			string value = UrlDecode(text.Substring(num2, num3 - num2), encoding);
			result.Add(name, value);
			if (num == -1)
			{
				break;
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace YoutubeDLSharp
{
	public enum DownloadState
	{
		None,
		PreProcessing,
		Downloading,
		PostProcessing,
		Error,
		Success
	}
	public class DownloadProgress
	{
		public DownloadState State { get; }

		public float Progress { get; }

		public string TotalDownloadSize { get; }

		public string DownloadSpeed { get; }

		public string ETA { get; }

		public int VideoIndex { get; }

		public string Data { get; }

		public DownloadProgress(DownloadState status, float progress = 0f, string totalDownloadSize = null, string downloadSpeed = null, string eta = null, int index = 1, string data = null)
		{
			State = status;
			Progress = progress;
			TotalDownloadSize = totalDownloadSize;
			DownloadSpeed = downloadSpeed;
			ETA = eta;
			VideoIndex = index;
			Data = data;
		}
	}
	public class RunResult<T>
	{
		public bool Success { get; }

		public string[] ErrorOutput { get; }

		public T Data { get; }

		public RunResult(bool success, string[] error, T result)
		{
			Success = success;
			ErrorOutput = error;
			Data = result;
		}
	}
	public static class Utils
	{
		internal class FFmpegApi
		{
			public class Root
			{
				[JsonProperty("version")]
				public string Version { get; set; }

				[JsonProperty("permalink")]
				public string Permalink { get; set; }

				[JsonProperty("bin")]
				public Bin Bin { get; set; }
			}

			public class Bin
			{
				[JsonProperty("windows-64")]
				public OsBinVersion Windows64 { get; set; }

				[JsonProperty("linux-64")]
				public OsBinVersion Linux64 { get; set; }

				[JsonProperty("osx-64")]
				public OsBinVersion Osx64 { get; set; }
			}

			public class OsBinVersion
			{
				[JsonProperty("ffmpeg")]
				public string Ffmpeg { get; set; }

				[JsonProperty("ffprobe")]
				public string Ffprobe { get; set; }
			}

			public enum BinaryType
			{
				[EnumMember(Value = "ffmpeg")]
				FFmpeg,
				[EnumMember(Value = "ffprobe")]
				FFprobe
			}
		}

		private static readonly HttpClient _client = new HttpClient();

		private static readonly Regex rgxTimestamp = new Regex("[0-9]+(?::[0-9]+)+", RegexOptions.Compiled);

		private static readonly Dictionary<char, string> accentChars = "ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ".Zip(new string[68]
		{
			"A", "A", "A", "A", "A", "A", "AE", "C", "E", "E",
			"E", "E", "I", "I", "I", "I", "D", "N", "O", "O",
			"O", "O", "O", "O", "O", "OE", "U", "U", "U", "U",
			"U", "Y", "P", "ss", "a", "a", "a", "a", "a", "a",
			"ae", "c", "e", "e", "e", "e", "i", "i", "i", "i",
			"o", "n", "o", "o", "o", "o", "o", "o", "o", "oe",
			"u", "u", "u", "u", "u", "y", "p", "y"
		}, (char c, string s) => new
		{
			Key = c,
			Val = s
		}).ToDictionary(o => o.Key, o => o.Val);

		public static string YtDlpBinaryName => GetYtDlpBinaryName();

		public static string FfmpegBinaryName => GetFfmpegBinaryName();

		public static string FfprobeBinaryName => GetFfprobeBinaryName();

		public static string Sanitize(string s, bool restricted = false)
		{
			rgxTimestamp.Replace(s, (Match m) => m.Groups[0].Value.Replace(':', '_'));
			string text = string.Join("", s.Select((char c) => sanitizeChar(c, restricted)));
			text = text.Replace("__", "_").Trim(new char[1] { '_' });
			if (restricted && text.StartsWith("-_"))
			{
				text = text.Substring(2);
			}
			if (text.StartsWith("-"))
			{
				text = "_" + text.Substring(1);
			}
			text = text.TrimStart(new char[1] { '.' });
			if (string.IsNullOrWhiteSpace(text))
			{
				text = "_";
			}
			return text;
		}

		private static string sanitizeChar(char c, bool restricted)
		{
			if (restricted && accentChars.ContainsKey(c))
			{
				return accentChars[c];
			}
			if (c != '?' && c >= ' ')
			{
				switch (c)
				{
				case '\u007f':
					break;
				case '"':
					if (!restricted)
					{
						return "'";
					}
					return "";
				case ':':
					if (!restricted)
					{
						return " -";
					}
					return "_-";
				default:
					if (Enumerable.Contains("\\/|*<>", c))
					{
						return "_";
					}
					if (restricted && Enumerable.Contains("!&'()[]{}$;`^,# ", c))
					{
						return "_";
					}
					if (restricted && c > '\u007f')
					{
						return "_";
					}
					return c.ToString();
				}
			}
			return "";
		}

		public static string GetFullPath(string fileName)
		{
			if (File.Exists(fileName))
			{
				return Path.GetFullPath(fileName);
			}
			string environmentVariable = Environment.GetEnvironmentVariable("PATH");
			string[] array = environmentVariable.Split(new char[1] { Path.PathSeparator });
			foreach (string path in array)
			{
				string text = Path.Combine(path, fileName);
				if (File.Exists(text))
				{
					return text;
				}
			}
			return null;
		}

		public static async Task DownloadBinaries(bool skipExisting = true, string directoryPath = "")
		{
			if (skipExisting)
			{
				if (!File.Exists(Path.Combine(directoryPath, GetYtDlpBinaryName())))
				{
					await DownloadYtDlp(directoryPath);
				}
				if (!File.Exists(Path.Combine(directoryPath, GetFfmpegBinaryName())))
				{
					await DownloadFFmpeg(directoryPath);
				}
				if (!File.Exists(Path.Combine(directoryPath, GetFfprobeBinaryName())))
				{
					await DownloadFFprobe(directoryPath);
				}
			}
			else
			{
				await DownloadYtDlp(directoryPath);
				await DownloadFFmpeg(directoryPath);
				await DownloadFFprobe(directoryPath);
			}
		}

		private static string GetYtDlpDownloadUrl()
		{
			return OSHelper.GetOSVersion() switch
			{
				OSVersion.Windows => "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe", 
				OSVersion.OSX => "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos", 
				OSVersion.Linux => "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp", 
				_ => throw new Exception("Your OS isn't supported"), 
			};
		}

		private static string GetYtDlpBinaryName()
		{
			string ytDlpDownloadUrl = GetYtDlpDownloadUrl();
			return Path.GetFileName(ytDlpDownloadUrl);
		}

		private static string GetFfmpegBinaryName()
		{
			switch (OSHelper.GetOSVersion())
			{
			case OSVersion.Windows:
				return "ffmpeg.exe";
			case OSVersion.OSX:
			case OSVersion.Linux:
				return "ffmpeg";
			default:
				throw new Exception("Your OS isn't supported");
			}
		}

		private static string GetFfprobeBinaryName()
		{
			switch (OSHelper.GetOSVersion())
			{
			case OSVersion.Windows:
				return "ffprobe.exe";
			case OSVersion.OSX:
			case OSVersion.Linux:
				return "ffprobe";
			default:
				throw new Exception("Your OS isn't supported");
			}
		}

		public static async Task DownloadYtDlp(string directoryPath = "")
		{
			string ytDlpDownloadUrl = GetYtDlpDownloadUrl();
			if (string.IsNullOrEmpty(directoryPath))
			{
				directoryPath = Directory.GetCurrentDirectory();
			}
			string downloadLocation = Path.Combine(directoryPath, Path.GetFileName(ytDlpDownloadUrl));
			File.WriteAllBytes(downloadLocation, await DownloadFileBytesAsync(ytDlpDownloadUrl));
		}

		public static async Task DownloadFFmpeg(string directoryPath = "")
		{
			await FFDownloader(directoryPath);
		}

		public static async Task DownloadFFprobe(string directoryPath = "")
		{
			await FFDownloader(directoryPath, FFmpegApi.BinaryType.FFprobe);
		}

		private static async Task FFDownloader(string directoryPath = "", FFmpegApi.BinaryType binary = FFmpegApi.BinaryType.FFmpeg)
		{
			if (string.IsNullOrEmpty(directoryPath))
			{
				directoryPath = Directory.GetCurrentDirectory();
			}
			FFmpegApi.Root root = JsonConvert.DeserializeObject<FFmpegApi.Root>(await (await _client.GetAsync("https://ffbinaries.com/api/v1/version/latest")).Content.ReadAsStringAsync());
			FFmpegApi.OsBinVersion osBinVersion = OSHelper.GetOSVersion() switch
			{
				OSVersion.Windows => root?.Bin.Windows64, 
				OSVersion.OSX => root?.Bin.Osx64, 
				OSVersion.Linux => root?.Bin.Linux64, 
				_ => throw new NotImplementedException("Your OS isn't supported"), 
			};
			string uri = ((binary == FFmpegApi.BinaryType.FFmpeg) ? osBinVersion.Ffmpeg : osBinVersion.Ffprobe);
			using MemoryStream stream = new MemoryStream(await DownloadFileBytesAsync(uri));
			using ZipArchive zipArchive = new ZipArchive(stream, ZipArchiveMode.Read);
			if (zipArchive.Entries.Count > 0)
			{
				zipArchive.Entries[0].ExtractToFile(Path.Combine(directoryPath, zipArchive.Entries[0].FullName), overwrite: true);
			}
		}

		private static async Task<byte[]> DownloadFileBytesAsync(string uri)
		{
			if (!Uri.TryCreate(uri, UriKind.Absolute, out Uri _))
			{
				throw new InvalidOperationException("URI is invalid.");
			}
			return await _client.GetByteArrayAsync(uri);
		}
	}
	public class YoutubeDL
	{
		private static readonly Regex rgxFile = new Regex("^outfile:\\s\\\"?(.*)\\\"?", RegexOptions.Compiled);

		private static Regex rgxFilePostProc = new Regex("\\[download\\] Destination: [a-zA-Z]:\\\\\\S+\\.\\S{3,}", RegexOptions.Compiled);

		protected ProcessRunner runner;

		public string YoutubeDLPath { get; set; } = Utils.YtDlpBinaryName;


		public string FFmpegPath { get; set; } = Utils.FfmpegBinaryName;


		public string OutputFolder { get; set; } = Environment.CurrentDirectory;


		public string OutputFileTemplate { get; set; } = "%(title)s [%(id)s].%(ext)s";


		public bool RestrictFilenames { get; set; }

		public bool OverwriteFiles { get; set; } = true;


		public bool IgnoreDownloadErrors { get; set; } = true;


		public string Version => FileVersionInfo.GetVersionInfo(Utils.GetFullPath(YoutubeDLPath)).FileVersion;

		public YoutubeDL(byte maxNumberOfProcesses = 4)
		{
			runner = new ProcessRunner(maxNumberOfProcesses);
		}

		public async Task SetMaxNumberOfProcesses(byte count)
		{
			await runner.SetTotalCount(count);
		}

		public async Task<RunResult<string[]>> RunWithOptions(string[] urls, OptionSet options, CancellationToken ct)
		{
			List<string> output = new List<string>();
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				output.Add(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, urls, options, ct);
			return new RunResult<string[]>(num == 0, error, output.ToArray());
		}

		public async Task<RunResult<string>> RunWithOptions(string url, OptionSet options, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, bool showArgs = true)
		{
			string outFile = string.Empty;
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			if (showArgs)
			{
				output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, options) + "\n");
			}
			else
			{
				output?.Report("Starting Download: " + url);
			}
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				Match match = rgxFilePostProc.Match(e.Data);
				if (match.Success)
				{
					outFile = match.Groups[0].ToString().Replace("[download] Destination:", "").Replace(" ", "");
					progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outFile));
				}
				output?.Report(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, options, ct, progress);
			return new RunResult<string>(num == 0, error, outFile);
		}

		public async Task<string> RunUpdate()
		{
			string output = string.Empty;
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				output = e.Data;
			};
			await youtubeDLProcess.RunAsync(null, new OptionSet
			{
				Update = true
			});
			return output;
		}

		public async Task<RunResult<VideoData>> RunVideoDataFetch(string url, CancellationToken ct = default(CancellationToken), bool flat = true, bool fetchComments = false, OptionSet overrideOptions = null)
		{
			OptionSet optionSet = GetDownloadOptions();
			optionSet.DumpSingleJson = true;
			optionSet.FlatPlaylist = flat;
			optionSet.WriteComments = fetchComments;
			if (overrideOptions != null)
			{
				optionSet = optionSet.OverrideOptions(overrideOptions);
			}
			VideoData videoData = null;
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				videoData = JsonConvert.DeserializeObject<VideoData>(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct);
			return new RunResult<VideoData>(num == 0, error, videoData);
		}

		public async Task<RunResult<string>> RunVideoDownload(string url, string format = "bestvideo+bestaudio/best", DownloadMergeFormat mergeFormat = DownloadMergeFormat.Unspecified, VideoRecodeFormat recodeFormat = VideoRecodeFormat.None, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null)
		{
			OptionSet optionSet = GetDownloadOptions();
			optionSet.Format = format;
			optionSet.MergeOutputFormat = mergeFormat;
			optionSet.RecodeVideo = recodeFormat;
			if (overrideOptions != null)
			{
				optionSet = optionSet.OverrideOptions(overrideOptions);
			}
			string outputFile = string.Empty;
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n");
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				Match match = rgxFile.Match(e.Data);
				if (match.Success)
				{
					outputFile = match.Groups[1].ToString().Trim(new char[1] { '"' });
					progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outputFile));
				}
				output?.Report(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress);
			return new RunResult<string>(num == 0, error, outputFile);
		}

		public async Task<RunResult<string[]>> RunVideoPlaylistDownload(string url, int? start = 1, int? end = null, int[] items = null, string format = "bestvideo+bestaudio/best", VideoRecodeFormat recodeFormat = VideoRecodeFormat.None, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null)
		{
			OptionSet optionSet = GetDownloadOptions();
			optionSet.NoPlaylist = false;
			optionSet.PlaylistStart = start;
			optionSet.PlaylistEnd = end;
			if (items != null)
			{
				optionSet.PlaylistItems = string.Join(",", items);
			}
			optionSet.Format = format;
			optionSet.RecodeVideo = recodeFormat;
			if (overrideOptions != null)
			{
				optionSet = optionSet.OverrideOptions(overrideOptions);
			}
			List<string> outputFiles = new List<string>();
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n");
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				Match match = rgxFile.Match(e.Data);
				if (match.Success)
				{
					string text = match.Groups[1].ToString().Trim(new char[1] { '"' });
					outputFiles.Add(text);
					progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, text));
				}
				output?.Report(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress);
			return new RunResult<string[]>(num == 0, error, outputFiles.ToArray());
		}

		public async Task<RunResult<string>> RunAudioDownload(string url, AudioConversionFormat format = AudioConversionFormat.Best, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null)
		{
			OptionSet optionSet = GetDownloadOptions();
			optionSet.Format = "bestaudio/best";
			optionSet.ExtractAudio = true;
			optionSet.AudioFormat = format;
			if (overrideOptions != null)
			{
				optionSet = optionSet.OverrideOptions(overrideOptions);
			}
			string outputFile = string.Empty;
			new List<string>();
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n");
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				Match match = rgxFile.Match(e.Data);
				if (match.Success)
				{
					outputFile = match.Groups[1].ToString().Trim(new char[1] { '"' });
					progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outputFile));
				}
				output?.Report(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress);
			return new RunResult<string>(num == 0, error, outputFile);
		}

		public async Task<RunResult<string[]>> RunAudioPlaylistDownload(string url, int? start = 1, int? end = null, int[] items = null, AudioConversionFormat format = AudioConversionFormat.Best, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null)
		{
			List<string> outputFiles = new List<string>();
			OptionSet optionSet = GetDownloadOptions();
			optionSet.NoPlaylist = false;
			optionSet.PlaylistStart = start;
			optionSet.PlaylistEnd = end;
			if (items != null)
			{
				optionSet.PlaylistItems = string.Join(",", items);
			}
			optionSet.Format = "bestaudio/best";
			optionSet.ExtractAudio = true;
			optionSet.AudioFormat = format;
			if (overrideOptions != null)
			{
				optionSet = optionSet.OverrideOptions(overrideOptions);
			}
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n");
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				Match match = rgxFile.Match(e.Data);
				if (match.Success)
				{
					string text = match.Groups[1].ToString().Trim(new char[1] { '"' });
					outputFiles.Add(text);
					progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, text));
				}
				output?.Report(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress);
			return new RunResult<string[]>(num == 0, error, outputFiles.ToArray());
		}

		protected virtual OptionSet GetDownloadOptions()
		{
			return new OptionSet
			{
				IgnoreErrors = IgnoreDownloadErrors,
				IgnoreConfig = true,
				NoPlaylist = true,
				Downloader = "m3u8:native",
				DownloaderArgs = "ffmpeg:-nostats -loglevel 0",
				Output = Path.Combine(OutputFolder, OutputFileTemplate),
				RestrictFilenames = RestrictFilenames,
				ForceOverwrites = OverwriteFiles,
				NoOverwrites = !OverwriteFiles,
				NoPart = true,
				FfmpegLocation = Utils.GetFullPath(FFmpegPath),
				Exec = "echo outfile: {}"
			};
		}
	}
	public class YoutubeDLProcess
	{
		private static readonly Regex rgxPlaylist = new Regex("Downloading video (\\d+) of (\\d+)", RegexOptions.Compiled);

		private static readonly Regex rgxProgress = new Regex("\\[download\\]\\s+(?:(?<percent>[\\d\\.]+)%(?:\\s+of\\s+\\~?\\s*(?<total>[\\d\\.\\w]+))?\\s+at\\s+(?:(?<speed>[\\d\\.\\w]+\\/s)|[\\w\\s]+)\\s+ETA\\s(?<eta>[\\d\\:]+))?", RegexOptions.Compiled);

		private static readonly Regex rgxPost = new Regex("\\[(\\w+)\\]\\s+", RegexOptions.Compiled);

		public string PythonPath { get; set; }

		public string ExecutablePath { get; set; }

		public bool UseWindowsEncodingWorkaround { get; set; } = true;


		public event EventHandler<DataReceivedEventArgs> OutputReceived;

		public event EventHandler<DataReceivedEventArgs> ErrorReceived;

		public YoutubeDLProcess(string executablePath = "yt-dlp.exe")
		{
			ExecutablePath = executablePath;
		}

		internal string ConvertToArgs(string[] urls, OptionSet options)
		{
			return ((urls != null) ? string.Join(" ", urls.Select((string s) => "\"" + s + "\"")) : string.Empty) + options.ToString();
		}

		public async Task<int> RunAsync(string[] urls, OptionSet options)
		{
			return await RunAsync(urls, options, CancellationToken.None);
		}

		public async Task<int> RunAsync(string[] urls, OptionSet options, CancellationToken ct, IProgress<DownloadProgress> progress = null)
		{
			TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
			Process process = new Process();
			ProcessStartInfo processStartInfo = new ProcessStartInfo
			{
				CreateNoWindow = true,
				UseShellExecute = false,
				RedirectStandardOutput = true,
				RedirectStandardError = true,
				StandardOutputEncoding = Encoding.UTF8,
				StandardErrorEncoding = Encoding.UTF8
			};
			if (OSHelper.IsWindows && UseWindowsEncodingWorkaround)
			{
				processStartInfo.FileName = "cmd.exe";
				string text = (string.IsNullOrEmpty(PythonPath) ? ("\"" + ExecutablePath + "\" " + ConvertToArgs(urls, options)) : (PythonPath + " \"" + ExecutablePath + "\" " + ConvertToArgs(urls, options)));
				processStartInfo.Arguments = "/C chcp 65001 >nul 2>&1 && " + text;
			}
			else if (!string.IsNullOrEmpty(PythonPath))
			{
				processStartInfo.FileName = PythonPath;
				processStartInfo.Arguments = "\"" + ExecutablePath + "\" " + ConvertToArgs(urls, options);
			}
			else
			{
				processStartInfo.FileName = ExecutablePath;
				processStartInfo.Arguments = ConvertToArgs(urls, options);
			}
			process.EnableRaisingEvents = true;
			process.StartInfo = processStartInfo;
			TaskCompletionSource<bool> tcsOut = new TaskCompletionSource<bool>();
			bool isDownloading = false;
			process.OutputDataReceived += delegate(object o, DataReceivedEventArgs e)
			{
				if (e.Data == null)
				{
					tcsOut.SetResult(result: true);
				}
				else
				{
					Match match;
					if ((match = rgxProgress.Match(e.Data)).Success)
					{
						if (match.Groups.Count > 1 && match.Groups[1].Length > 0)
						{
							float progress2 = float.Parse(match.Groups[1].ToString(), CultureInfo.InvariantCulture) / 100f;
							Group group = match.Groups["total"];
							string totalDownloadSize = (group.Success ? group.Value : null);
							Group group2 = match.Groups["speed"];
							string downloadSpeed = (group2.Success ? group2.Value : null);
							Group group3 = match.Groups["eta"];
							string eta = (group3.Success ? group3.Value : null);
							progress?.Report(new DownloadProgress(DownloadState.Downloading, progress2, totalDownloadSize, downloadSpeed, eta));
						}
						else
						{
							progress?.Report(new DownloadProgress(DownloadState.Downloading));
						}
						isDownloading = true;
					}
					else if ((match = rgxPlaylist.Match(e.Data)).Success)
					{
						int index = int.Parse(match.Groups[1].Value);
						progress?.Report(new DownloadProgress(DownloadState.PreProcessing, 0f, null, null, null, index));
						isDownloading = false;
					}
					else if (isDownloading && (match = rgxPost.Match(e.Data)).Success)
					{
						progress?.Report(new DownloadProgress(DownloadState.PostProcessing, 1f));
						isDownloading = false;
					}
					this.OutputReceived?.Invoke(this, e);
				}
			};
			TaskCompletionSource<bool> tcsError = new TaskCompletionSource<bool>();
			process.ErrorDataReceived += delegate(object o, DataReceivedEventArgs e)
			{
				if (e.Data == null)
				{
					tcsError.SetResult(result: true);
				}
				else
				{
					progress?.Report(new DownloadProgress(DownloadState.Error, 0f, null, null, null, 1, e.Data));
					this.ErrorReceived?.Invoke(this, e);
				}
			};
			process.Exited += async delegate
			{
				await tcsOut.Task;
				await tcsError.Task;
				tcs.TrySetResult(process.ExitCode);
				process.Dispose();
			};
			ct.Register(delegate
			{
				if (!tcs.Task.IsCompleted)
				{
					tcs.TrySetCanceled();
				}
				try
				{
					if (!process.HasExited)
					{
						process.KillTree();
					}
				}
				catch
				{
				}
			});
			if (!(await Task.Run(() => process.Start())))
			{
				tcs.TrySetException(new InvalidOperationException("Failed to start yt-dlp process."));
			}
			process.BeginOutputReadLine();
			process.BeginErrorReadLine();
			progress?.Report(new DownloadProgress(DownloadState.PreProcessing));
			return await tcs.Task;
		}
	}
}
namespace YoutubeDLSharp.Options
{
	public enum DownloadMergeFormat
	{
		Unspecified,
		Mp4,
		Mkv,
		Ogg,
		Webm,
		Flv
	}
	public enum AudioConversionFormat
	{
		Best,
		Aac,
		Flac,
		Mp3,
		M4a,
		Opus,
		Vorbis,
		Wav
	}
	public enum VideoRecodeFormat
	{
		None,
		Mp4,
		Mkv,
		Ogg,
		Webm,
		Flv,
		Avi
	}
	public interface IOption
	{
		string DefaultOptionString { get; }

		string[] OptionStrings { get; }

		bool IsSet { get; }

		bool IsCustom { get; }

		void SetFromString(string s);

		IEnumerable<string> ToStringCollection();
	}
	public class MultiOption<T> : IOption
	{
		private MultiValue<T> value;

		public string DefaultOptionString => OptionStrings.Last();

		public string[] OptionStrings { get; }

		public bool IsSet { get; private set; }

		public bool IsCustom { get; }

		public MultiValue<T> Value
		{
			get
			{
				return value;
			}
			set
			{
				IsSet = !object.Equals(value, default(T));
				this.value = value;
			}
		}

		public MultiOption(params string[] optionStrings)
		{
			OptionStrings = optionStrings;
			IsSet = false;
		}

		public MultiOption(bool isCustom, params string[] optionStrings)
		{
			OptionStrings = optionStrings;
			IsSet = false;
			IsCustom = isCustom;
		}

		public void SetFromString(string s)
		{
			string[] array = s.Split(new char[1] { ' ' });
			string stringValue = s.Substring(array[0].Length).Trim().Trim(new char[1] { '"' });
			if (!OptionStrings.Contains(array[0]))
			{
				throw new ArgumentException("Given string does not match required format.");
			}
			T val = Utils.OptionValueFromString<T>(stringValue);
			if (!IsSet)
			{
				Value = val;
			}
			else
			{
				Value.Values.Add(val);
			}
		}

		public override string ToString()
		{
			return string.Join(" ", ToStringCollection());
		}

		public IEnumerable<string> ToStringCollection()
		{
			if (!IsSet)
			{
				return new string[1] { "" };
			}
			List<string> list = new List<string>();
			foreach (T value in Value.Values)
			{
				list.Add(DefaultOptionString + Utils.OptionValueToString(value));
			}
			return list;
		}
	}
	public class MultiValue<T>
	{
		private readonly List<T> values;

		public List<T> Values => values;

		public MultiValue(params T[] values)
		{
			this.values = values.ToList();
		}

		public static implicit operator MultiValue<T>(T value)
		{
			return new MultiValue<T>(value);
		}

		public static implicit operator MultiValue<T>(T[] values)
		{
			return new MultiValue<T>(values);
		}

		public static explicit operator T(MultiValue<T> value)
		{
			if (value.Values.Count == 1)
			{
				return value.Values[0];
			}
			throw new InvalidCastException($"Cannot cast sequence of values to {typeof(T)}.");
		}

		public static explicit operator T[](MultiValue<T> value)
		{
			return value.Values.ToArray();
		}
	}
	public class Option<T> : IOption
	{
		private T value;

		public string DefaultOptionString => OptionStrings.Last();

		public string[] OptionStrings { get; }

		public bool IsSet { get; private set; }

		public T Value
		{
			get
			{
				return value;
			}
			set
			{
				IsSet = !object.Equals(value, default(T));
				this.value = value;
			}
		}

		public bool IsCustom { get; }

		public Option(params string[] optionStrings)
		{
			OptionStrings = optionStrings;
			IsSet = false;
		}

		public Option(bool isCustom, params string[] optionStrings)
		{
			OptionStrings = optionStrings;
			IsSet = false;
			IsCustom = isCustom;
		}

		public void SetFromString(string s)
		{
			string[] array = s.Split(new char[1] { ' ' });
			string stringValue = s.Substring(array[0].Length).Trim().Trim(new char[1] { '"' });
			if (!OptionStrings.Contains(array[0]))
			{
				throw new ArgumentException("Given string does not match required format.");
			}
			Value = Utils.OptionValueFromString<T>(stringValue);
		}

		public override string ToString()
		{
			if (!IsSet)
			{
				return string.Empty;
			}
			string text = Utils.OptionValueToString(Value);
			return DefaultOptionString + text;
		}

		public IEnumerable<string> ToStringCollection()
		{
			return new string[1] { ToString() };
		}
	}
	internal class OptionComparer : IEqualityComparer<IOption>
	{
		public bool Equals(IOption x, IOption y)
		{
			if (x != null)
			{
				if (y != null)
				{
					return x.ToString().Equals(y.ToString());
				}
				return false;
			}
			return y == null;
		}

		public int GetHashCode(IOption obj)
		{
			return obj.ToString().GetHashCode();
		}
	}
	public class OptionSet : ICloneable
	{
		private Option<string> username = new Option<string>("-u", "--username");

		private Option<string> password = new Option<string>("-p", "--password");

		private Option<string> twoFactor = new Option<string>("-2", "--twofactor");

		private Option<bool> netrc = new Option<bool>("-n", "--netrc");

		private Option<string> netrcLocation = new Option<string>("--netrc-location");

		private Option<string> videoPassword = new Option<string>("--video-password");

		private Option<string> apMso = new Option<string>("--ap-mso");

		private Option<string> apUsername = new Option<string>("--ap-username");

		private Option<string> apPassword = new Option<string>("--ap-password");

		private Option<bool> apListMso = new Option<bool>("--ap-list-mso");

		private Option<string> clientCertificate = new Option<string>("--client-certificate");

		private Option<string> clientCertificateKey = new Option<string>("--client-certificate-key");

		private Option<string> clientCertificatePassword = new Option<string>("--client-certificate-password");

		private static readonly OptionComparer Comparer = new OptionComparer();

		public static readonly OptionSet Default = new OptionSet();

		private Option<bool> getDescription = new Option<bool>("--get-description");

		private Option<bool> getDuration = new Option<bool>("--get-duration");

		private Option<bool> getFilename = new Option<bool>("--get-filename");

		private Option<bool> getFormat = new Option<bool>("--get-format");

		private Option<bool> getId = new Option<bool>("--get-id");

		private Option<bool> getThumbnail = new Option<bool>("--get-thumbnail");

		private Option<bool> getTitle = new Option<bool>("-e", "--get-title");

		private Option<bool> getUrl = new Option<bool>("-g", "--get-url");

		private Option<string> matchTitle = new Option<string>("--match-title");

		private Option<string> rejectTitle = new Option<string>("--reject-title");

		private Option<long?> minViews = new Option<long?>("--min-views");

		private Option<long?> maxViews = new Option<long?>("--max-views");

		private Option<string> userAgent = new Option<string>("--user-agent");

		private Option<string> referer = new Option<string>("--referer");

		private Option<int?> playlistStart = new Option<int?>("--playlist-start");

		private Option<int?> playlistEnd = new Option<int?>("--playlist-end");

		private Option<bool> playlistReverse = new Option<bool>("--playlist-reverse");

		private Option<bool> forceGenericExtractor = new Option<bool>("--force-generic-extractor");

		private Option<string> execBeforeDownload = new Option<string>("--exec-before-download");

		private Option<bool> noExecBeforeDownload = new Option<bool>("--no-exec-before-download");

		private Option<bool> allFormats = new Option<bool>("--all-formats");

		private Option<bool> allSubs = new Option<bool>("--all-subs");

		private Option<bool> printJson = new Option<bool>("--print-json");

		private Option<string> autonumberSize = new Option<string>("--autonumber-size");

		private Option<int?> autonumberStart = new Option<int?>("--autonumber-start");

		private Option<bool> id = new Option<bool>("--id");

		private Option<string> metadataFromTitle = new Option<string>("--metadata-from-title");

		private Option<bool> hlsPreferNative = new Option<bool>("--hls-prefer-native");

		private Option<bool> hlsPreferFfmpeg = new Option<bool>("--hls-prefer-ffmpeg");

		private Option<bool> listFormatsOld = new Option<bool>("--list-formats-old");

		private Option<bool> listFormatsAsTable = new Option<bool>("--list-formats-as-table");

		private Option<bool> youtubeSkipDashManifest = new Option<bool>("--youtube-skip-dash-manifest");

		private Option<bool> youtubeSkipHlsManifest = new Option<bool>("--youtube-skip-hls-manifest");

		private Option<int?> concurrentFragments = new Option<int?>("-N", "--concurrent-fragments");

		private Option<long?> limitRate = new Option<long?>("-r", "--limit-rate");

		private Option<long?> throttledRate = new Option<long?>("--throttled-rate");

		private Option<int?> retries = new Option<int?>("-R", "--retries");

		private Option<int?> fileAccessRetries = new Option<int?>("--file-access-retries");

		private Option<int?> fragmentRetries = new Option<int?>("--fragment-retries");

		private MultiOption<string> retrySleep = new MultiOption<string>("--retry-sleep");

		private Option<bool> skipUnavailableFragments = new Option<bool>("--skip-unavailable-fragments");

		private Option<bool> abortOnUnavailableFragment = new Option<bool>("--abort-on-unavailable-fragment");

		private Option<bool> keepFragments = new Option<bool>("--keep-fragments");

		private Option<bool> noKeepFragments = new Option<bool>("--no-keep-fragments");

		private Option<long?> bufferSize = new Option<long?>("--buffer-size");

		private Option<bool> resizeBuffer = new Option<bool>("--resize-buffer");

		private Option<bool> noResizeBuffer = new Option<bool>("--no-resize-buffer");

		private Option<long?> httpChunkSize = new Option<long?>("--http-chunk-size");

		private Option<bool> playlistRandom = new Option<bool>("--playlist-random");

		private Option<bool> lazyPlaylist = new Option<bool>("--lazy-playlist");

		private Option<bool> noLazyPlaylist = new Option<bool>("--no-lazy-playlist");

		private Option<bool> xattrSetFilesize = new Option<bool>("--xattr-set-filesize");

		private Option<bool> hlsUseMpegts = new Option<bool>("--hls-use-mpegts");

		private Option<bool> noHlsUseMpegts = new Option<bool>("--no-hls-use-mpegts");

		private MultiOption<string> downloadSections = new MultiOption<string>("--download-sections");

		private MultiOption<string> downloader = new MultiOption<string>("--downloader", "--external-downloader");

		private MultiOption<string> downloaderArgs = new MultiOption<string>("--downloader-args", "--external-downloader-args");

		private Option<int?> extractorRetries = new Option<int?>("--extractor-retries");

		private Option<bool> allowDynamicMpd = new Option<bool>("--allow-dynamic-mpd");

		private Option<bool> ignoreDynamicMpd = new Option<bool>("--ignore-dynamic-mpd");

		private Option<bool> hlsSplitDiscontinuity = new Option<bool>("--hls-split-discontinuity");

		private Option<bool> noHlsSplitDiscontinuity = new Option<bool>("--no-hls-split-discontinuity");

		private MultiOption<string> extractorArgs = new MultiOption<string>("--extractor-args");

		private Option<string> batchFile = new Option<string>("-a", "--batch-file");

		private Option<bool> noBatchFile = new Option<bool>("--no-batch-file");

		private Option<string> paths = new Option<string>("-P", "--paths");

		private Option<string> output = new Option<string>("-o", "--output");

		private Option<string> outputNaPlaceholder = new Option<string>("--output-na-placeholder");

		private Option<bool> restrictFilenames = new Option<bool>("--restrict-filenames");

		private Option<bool> noRestrictFilenames = new Option<bool>("--no-restrict-filenames");

		private Option<bool> windowsFilenames = new Option<bool>("--windows-filenames");

		private Option<bool> noWindowsFilenames = new Option<bool>("--no-windows-filenames");

		private Option<int?> trimFilenames = new Option<int?>("--trim-filenames");

		private Option<bool> noOverwrites = new Option<bool>("-w", "--no-overwrites");

		private Option<bool> forceOverwrites = new Option<bool>("--force-overwrites");

		private Option<bool> noForceOverwrites = new Option<bool>("--no-force-overwrites");

		private Option<bool> doContinue = new Option<bool>("-c", "--continue");

		private Option<bool> noContinue = new Option<bool>("--no-continue");

		private Option<bool> part = new Option<bool>("--part");

		private Option<bool> noPart = new Option<bool>("--no-part");

		private Option<bool> mtime = new Option<bool>("--mtime");

		private Option<bool> noMtime = new Option<bool>("--no-mtime");

		private Option<bool> writeDescription = new Option<bool>("--write-description");

		private Option<bool> noWriteDescription = new Option<bool>("--no-write-description");

		private Option<bool> writeInfoJson = new Option<bool>("--write-info-json");

		private Option<bool> noWriteInfoJson = new Option<bool>("--no-write-info-json");

		private Option<bool> writePlaylistMetafiles = new Option<bool>("--write-playlist-metafiles");

		private Option<bool> noWritePlaylistMetafiles = new Option<bool>("--no-write-playlist-metafiles");

		private Option<bool> cleanInfoJson = new Option<bool>("--clean-info-json");

		private Option<bool> noCleanInfoJson = new Option<bool>("--no-clean-info-json");

		private Option<bool> writeComments = new Option<bool>("--write-comments");

		private Option<bool> noWriteComments = new Option<bool>("--no-write-comments");

		private Option<string> loadInfoJson = new Option<string>("--load-info-json");

		private Option<string> cookies = new Option<string>("--cookies");

		private Option<bool> noCookies = new Option<bool>("--no-cookies");

		private Option<string> cookiesFromBrowser = new Option<string>("--cookies-from-browser");

		private Option<bool> noCookiesFromBrowser = new Option<bool>("--no-cookies-from-browser");

		private Option<string> cacheDir = new Option<string>("--cache-dir");

		private Option<bool> noCacheDir = new Option<bool>("--no-cache-dir");

		private Option<bool> removeCacheDir = new Option<bool>("--rm-cache-dir");

		private Option<bool> help = new Option<bool>("-h", "--help");

		private Option<bool> version = new Option<bool>("--version");

		private Option<bool> update = new Option<bool>("-U", "--update");

		private Option<bool> noUpdate = new Option<bool>("--no-update");

		private Option<bool> ignoreErrors = new Option<bool>("-i", "--ignore-errors");

		private Option<bool> noAbortOnError = new Option<bool>("--no-abort-on-error");

		private Option<bool> abortOnError = new Option<bool>("--abort-on-error");

		private Option<bool> dumpUserAgent = new Option<bool>("--dump-user-agent");

		private Option<bool> listExtractors = new Option<bool>("--list-extractors");

		private Option<bool> extractorDescriptions = new Option<bool>("--extractor-descriptions");

		private Option<string> useExtractors = new Option<string>("--use-extractors");

		private Option<string> defaultSearch = new Option<string>("--default-search");

		private Option<bool> ignoreConfig = new Option<bool>("--ignore-config");

		private Option<bool> noConfigLocations = new Option<bool>("--no-config-locations");

		private MultiOption<string> configLocations = new MultiOption<string>("--config-locations");

		private Option<bool> flatPlaylist = new Option<bool>("--flat-playlist");

		private Option<bool> noFlatPlaylist = new Option<bool>("--no-flat-playlist");

		private Option<bool> liveFromStart = new Option<bool>("--live-from-start");

		private Option<bool> noLiveFromStart = new Option<bool>("--no-live-from-start");

		private Option<string> waitForVideo = new Option<string>("--wait-for-video");

		private Option<bool> noWaitForVideo = new Option<bool>("--no-wait-for-video");

		private Option<bool> markWatched = new Option<bool>("--mark-watched");

		private Option<bool> noMarkWatched = new Option<bool>("--no-mark-watched");

		private Option<bool> noColors = new Option<bool>("--no-colors");

		private Option<string> compatOptions = new Option<string>("--compat-options");

		private Option<string> alias = new Option<string>("--alias");

		private Option<string> geoVerificationProxy = new Option<string>("--geo-verification-proxy");

		private Option<bool> geoBypass = new Option<bool>("--geo-bypass");

		private Option<bool> noGeoBypass = new Option<bool>("--no-geo-bypass");

		private Option<string> geoBypassCountry = new Option<string>("--geo-bypass-country");

		private Option<string> geoBypassIpBlock = new Option<string>("--geo-bypass-ip-block");

		private Option<bool> writeLink = new Option<bool>("--write-link");

		private Option<bool> writeUrlLink = new Option<bool>("--write-url-link");

		private Option<bool> writeWeblocLink = new Option<bool>("--write-webloc-link");

		private Option<bool> writeDesktopLink = new Option<bool>("--write-desktop-link");

		private Option<string> proxy = new Option<string>("--proxy");

		private Option<int?> socketTimeout = new Option<int?>("--socket-timeout");

		private Option<string> sourceAddress = new Option<string>("--source-address");

		private Option<bool> forceIPv4 = new Option<bool>("-4", "--force-ipv4");

		private Option<bool> forceIPv6 = new Option<bool>("-6", "--force-ipv6");

		private Option<bool> extractAudio = new Option<bool>("-x", "--extract-audio");

		private Option<AudioConversionFormat> audioFormat = new Option<AudioConversionFormat>("--audio-format");

		private Option<byte?> audioQuality = new Option<byte?>("--audio-quality");

		private Option<string> remuxVideo = new Option<string>("--remux-video");

		private Option<VideoRecodeFormat> recodeVideo = new Option<VideoRecodeFormat>("--recode-video");

		private MultiOption<string> postprocessorArgs = new MultiOption<string>("--postprocessor-args");

		private Option<bool> keepVideo = new Option<bool>("-k", "--keep-video");

		private Option<bool> noKeepVideo = new Option<bool>("--no-keep-video");

		private Option<bool> postOverwrites = new Option<bool>("--post-overwrites");

		private Option<bool> noPostOverwrites = new Option<bool>("--no-post-overwrites");

		private Option<bool> embedSubs = new Option<bool>("--embed-subs");

		private Option<bool> noEmbedSubs = new Option<bool>("--no-embed-subs");

		private Option<bool> embedThumbnail = new Option<bool>("--embed-thumbnail");

		private Option<bool> noEmbedThumbnail = new Option<bool>("--no-embed-thumbnail");

		private Option<bool> embedMetadata = new Option<bool>("--embed-metadata");

		private Option<bool> noEmbedMetadata = new Option<bool>("--no-embed-metadata");

		private Option<bool> embedChapters = new Option<bool>("--embed-chapters");

		private Option<bool> noEmbedChapters = new Option<bool>("--no-embed-chapters");

		private Option<bool> embedInfoJson = new Option<bool>("--embed-info-json");

		private Option<bool> noEmbedInfoJson = new Option<bool>("--no-embed-info-json");

		private Option<string> parseMetadata = new Option<string>("--parse-metadata");

		private MultiOption<string> replaceInMetadata = new MultiOption<string>("--replace-in-metadata");

		private Option<bool> xattrs = new Option<bool>("--xattrs");

		private Option<string> concatPlaylist = new Option<string>("--concat-playlist");

		private Option<string> fixup = new Option<string>("--fixup");

		private Option<string> ffmpegLocation = new Option<string>("--ffmpeg-location");

		private MultiOption<string> exec = new MultiOption<string>("--exec");

		private Option<bool> noExec = new Option<bool>("--no-exec");

		private Option<string> convertSubs = new Option<string>("--convert-subs");

		private Option<string> convertThumbnails = new Option<string>("--convert-thumbnails");

		private Option<bool> splitChapters = new Option<bool>("--split-chapters");

		private Option<bool> noSplitChapters = new Option<bool>("--no-split-chapters");

		private MultiOption<string> removeChapters = new MultiOption<string>("--remove-chapters");

		private Option<bool> noRemoveChapters = new Option<bool>("--no-remove-chapters");

		private Option<bool> forceKeyframesAtCuts = new Option<bool>("--force-keyframes-at-cuts");

		private Option<bool> noForceKeyframesAtCuts = new Option<bool>("--no-force-keyframes-at-cuts");

		private MultiOption<string> usePostprocessor = new MultiOption<string>("--use-postprocessor");

		private Option<string> sponsorblockMark = new Option<string>("--sponsorblock-mark");

		private Option<string> sponsorblockRemove = new Option<string>("--sponsorblock-remove");

		private Option<string> sponsorblockChapterTitle = new Option<string>("--sponsorblock-chapter-title");

		private Option<bool> noSponsorblock = new Option<bool>("--no-sponsorblock");

		private Option<string> sponsorblockApi = new Option<string>("--sponsorblock-api");

		private Option<bool> writeSubs = new Option<bool>("--write-subs");

		private Option<bool> noWriteSubs = new Option<bool>("--no-write-subs");

		private Option<bool> writeAutoSubs = new Option<bool>("--write-auto-subs");

		private Option<bool> noWriteAutoSubs = new Option<bool>("--no-write-auto-subs");

		private Option<bool> listSubs = new Option<bool>("--list-subs");

		private Option<string> subFormat = new Option<string>("--sub-format");

		private Option<string> subLangs = new Option<string>("--sub-langs");

		private Option<bool> writeThumbnail = new Option<bool>("--write-thumbnail");

		private Option<bool> noWriteThumbnail = new Option<bool>("--no-write-thumbnail");

		private Option<bool> writeAllThumbnails = new Option<bool>("--write-all-thumbnails");

		private Option<bool> listThumbnails = new Option<bool>("--list-thumbnails");

		private Option<bool> quiet = new Option<bool>("-q", "--quiet");

		private Option<bool> noWarnings = new Option<bool>("--no-warnings");

		private Option<bool> simulate = new Option<bool>("-s", "--simulate");

		private Option<bool> noSimulate = new Option<bool>("--no-simulate");

		private Option<bool> ignoreNoFormatsError = new Option<bool>("--ignore-no-formats-error");

		private Option<bool> noIgnoreNoFormatsError = new Option<bool>("--no-ignore-no-formats-error");

		private Option<bool> skipDownload = new Option<bool>("--skip-download");

		private MultiOption<string> print = new MultiOption<string>("-O", "--print");

		private MultiOption<string> printToFile = new MultiOption<string>("--print-to-file");

		private Option<bool> dumpJson = new Option<bool>("-j", "--dump-json");

		private Option<bool> dumpSingleJson = new Option<bool>("-J", "--dump-single-json");

		private Option<bool> forceWriteArchive = new Option<bool>("--force-write-archive");

		private Option<bool> newline = new Option<bool>("--newline");

		private Option<bool> noProgress = new Option<bool>("--no-progress");

		private Option<bool> progress = new Option<bool>("--progress");

		private Option<bool> consoleTitle = new Option<bool>("--console-title");

		private Option<string> progressTemplate = new Option<string>("--progress-template");

		private Option<bool> verbose = new Option<bool>("-v", "--verbose");

		private Option<bool> dumpPages = new Option<bool>("--dump-pages");

		private Option<bool> writePages = new Option<bool>("--write-pages");

		private Option<bool> printTraffic = new Option<bool>("--print-traffic");

		private Option<string> format = new Option<string>("-f", "--format");

		private Option<string> formatSort = new Option<string>("-S", "--format-sort");

		private Option<bool> formatSortForce = new Option<bool>("--format-sort-force");

		private Option<bool> noFormatSortForce = new Option<bool>("--no-format-sort-force");

		private Option<bool> videoMultistreams = new Option<bool>("--video-multistreams");

		private Option<bool> noVideoMultistreams = new Option<bool>("--no-video-multistreams");

		private Option<bool> audioMultistreams = new Option<bool>("--audio-multistreams");

		private Option<bool> noAudioMultistreams = new Option<bool>("--no-audio-multistreams");

		private Option<bool> preferFreeFormats = new Option<bool>("--prefer-free-formats");

		private Option<bool> noPreferFreeFormats = new Option<bool>("--no-prefer-free-formats");

		private Option<bool> checkFormats = new Option<bool>("--check-formats");

		private Option<bool> checkAllFormats = new Option<bool>("--check-all-formats");

		private Option<bool> noCheckFormats = new Option<bool>("--no-check-formats");

		private Option<bool> listFormats = new Option<bool>("-F", "--list-formats");

		private Option<DownloadMergeFormat> mergeOutputFormat = new Option<DownloadMergeFormat>("--merge-output-format");

		private Option<string> playlistItems = new Option<string>("-I", "--playlist-items");

		private Option<string> minFilesize = new Option<string>("--min-filesize");

		private Option<string> maxFilesize = new Option<string>("--max-filesize");

		private Option<DateTime> date = new Option<DateTime>("--date");

		private Option<DateTime> dateBefore = new Option<DateTime>("--datebefore");

		private Option<DateTime> dateAfter = new Option<DateTime>("--dateafter");

		private MultiOption<string> matchFilters = new MultiOption<string>("--match-filters");

		private Option<bool> noMatchFilter = new Option<bool>("--no-match-filter");

		private Option<bool> noPlaylist = new Option<bool>("--no-playlist");

		private Option<bool> yesPlaylist = new Option<bool>("--yes-playlist");

		private Option<byte?> ageLimit = new Option<byte?>("--age-limit");

		private Option<string> downloadArchive = new Option<string>("--download-archive");

		private Option<bool> noDownloadArchive = new Option<bool>("--no-download-archive");

		private Option<int?> maxDownloads = new Option<int?>("--max-downloads");

		private Option<bool> breakOnExisting = new Option<bool>("--break-on-existing");

		private Option<bool> breakOnReject = new Option<bool>("--break-on-reject");

		private Option<bool> breakPerInput = new Option<bool>("--break-per-input");

		private Option<bool> noBreakPerInput = new Option<bool>("--no-break-per-input");

		private Option<int?> skipPlaylistAfterErrors = new Option<int?>("--skip-playlist-after-errors");

		private Option<string> encoding = new Option<string>("--encoding");

		private Option<bool> legacyServerConnect = new Option<bool>("--legacy-server-connect");

		private Option<bool> noCheckCertificates = new Option<bool>("--no-check-certificates");

		private Option<bool> preferInsecure = new Option<bool>("--prefer-insecure");

		private MultiOption<string> addHeader = new MultiOption<string>("--add-header");

		private Option<bool> bidiWorkaround = new Option<bool>("--bidi-workaround");

		private Option<int?> sleepRequests = new Option<int?>("--sleep-requests");

		private Option<int?> sleepInterval = new Option<int?>("--sleep-interval");

		private Option<int?> maxSleepInterval = new Option<int?>("--max-sleep-interval");

		private Option<int?> sleepSubtitles = new Option<int?>("--sleep-subtitles");

		public string Username
		{
			get
			{
				return username.Value;
			}
			set
			{
				username.Value = value;
			}
		}

		public string Password
		{
			get
			{
				return password.Value;
			}
			set
			{
				password.Value = value;
			}
		}

		public string TwoFactor
		{
			get
			{
				return twoFactor.Value;
			}
			set
			{
				twoFactor.Value = value;
			}
		}

		public bool Netrc
		{
			get
			{
				return netrc.Value;
			}
			set
			{
				netrc.Value = value;
			}
		}

		public string NetrcLocation
		{
			get
			{
				return netrcLocation.Value;
			}
			set
			{
				netrcLocation.Value = value;
			}
		}

		public string VideoPassword
		{
			get
			{
				return videoPassword.Value;
			}
			set
			{
				videoPassword.Value = value;
			}
		}

		public string ApMso
		{
			get
			{
				return apMso.Value;
			}
			set
			{
				apMso.Value = value;
			}
		}

		public string ApUsername
		{
			get
			{
				return apUsername.Value;
			}
			set
			{
				apUsername.Value = value;
			}
		}

		public string ApPassword
		{
			get
			{
				return apPassword.Value;
			}
			set
			{
				apPassword.Value = value;
			}
		}

		public bool ApListMso
		{
			get
			{
				return apListMso.Value;
			}
			set
			{
				apListMso.Value = value;
			}
		}

		public string ClientCertificate
		{
			get
			{
				return clientCertificate.Value;
			}
			set
			{
				clientCertificate.Value = value;
			}
		}

		public string ClientCertificateKey
		{
			get
			{
				return clientCertificateKey.Value;
			}
			set
			{
				clientCertificateKey.Value = value;
			}
		}

		public string ClientCertificatePassword
		{
			get
			{
				return clientCertificatePassword.Value;
			}
			set
			{
				clientCertificatePassword.Value = value;
			}
		}

		public IOption[] CustomOptions { get; set; } = new IOption[0];


		[Obsolete("Deprecated in favor of: --print description.")]
		public bool GetDescription
		{
			get
			{
				return getDescription.Value;
			}
			set
			{
				getDescription.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print duration_string.")]
		public bool GetDuration
		{
			get
			{
				return getDuration.Value;
			}
			set
			{
				getDuration.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print filename.")]
		public bool GetFilename
		{
			get
			{
				return getFilename.Value;
			}
			set
			{
				getFilename.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print format.")]
		public bool GetFormat
		{
			get
			{
				return getFormat.Value;
			}
			set
			{
				getFormat.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print id.")]
		public bool GetId
		{
			get
			{
				return getId.Value;
			}
			set
			{
				getId.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print thumbnail.")]
		public bool GetThumbnail
		{
			get
			{
				return getThumbnail.Value;
			}
			set
			{
				getThumbnail.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print title.")]
		public bool GetTitle
		{
			get
			{
				return getTitle.Value;
			}
			set
			{
				getTitle.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print urls.")]
		public bool GetUrl
		{
			get
			{
				return getUrl.Value;
			}
			set
			{
				getUrl.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --match-filter \"title ~= (?i)REGEX\".")]
		public string MatchTitle
		{
			get
			{
				return matchTitle.Value;
			}
			set
			{
				matchTitle.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --match-filter \"title !~= (?i)REGEX\".")]
		public string RejectTitle
		{
			get
			{
				return rejectTitle.Value;
			}
			set
			{
				rejectTitle.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --match-filter \"view_count >=? COUNT\".")]
		public long? MinViews
		{
			get
			{
				return minViews.Value;
			}
			set
			{
				minViews.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --match-filter \"view_count <=? COUNT\".")]
		public long? MaxViews
		{
			get
			{
				return maxViews.Value;
			}
			set
			{
				maxViews.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --add-header \"User-Agent:UA\".")]
		public string UserAgent
		{
			get
			{
				return userAgent.Value;
			}
			set
			{
				userAgent.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --add-header \"Referer:URL\".")]
		public string Referer
		{
			get
			{
				return referer.Value;
			}
			set
			{
				referer.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -I NUMBER:.")]
		public int? PlaylistStart
		{
			get
			{
				return playlistStart.Value;
			}
			set
			{
				playlistStart.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -I :NUMBER.")]
		public int? PlaylistEnd
		{
			get
			{
				return playlistEnd.Value;
			}
			set
			{
				playlistEnd.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -I ::-1.")]
		public bool PlaylistReverse
		{
			get
			{
				return playlistReverse.Value;
			}
			set
			{
				playlistReverse.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --ies generic,default.")]
		public bool ForceGenericExtractor
		{
			get
			{
				return forceGenericExtractor.Value;
			}
			set
			{
				forceGenericExtractor.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --exec \"before_dl:CMD\".")]
		public string ExecBeforeDownload
		{
			get
			{
				return execBeforeDownload.Value;
			}
			set
			{
				execBeforeDownload.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --no-exec.")]
		public bool NoExecBeforeDownload
		{
			get
			{
				return noExecBeforeDownload.Value;
			}
			set
			{
				noExecBeforeDownload.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -f all.")]
		public bool AllFormats
		{
			get
			{
				return allFormats.Value;
			}
			set
			{
				allFormats.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --sub-langs all --write-subs.")]
		public bool AllSubs
		{
			get
			{
				return allSubs.Value;
			}
			set
			{
				allSubs.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -j --no-simulate.")]
		public bool PrintJson
		{
			get
			{
				return printJson.Value;
			}
			set
			{
				printJson.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: Use string formatting, e.g. %(autonumber)03d.")]
		public string AutonumberSize
		{
			get
			{
				return autonumberSize.Value;
			}
			set
			{
				autonumberSize.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: Use internal field formatting like %(autonumber+NUMBER)s.")]
		public int? AutonumberStart
		{
			get
			{
				return autonumberStart.Value;
			}
			set
			{
				autonumberStart.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -o \"%(id)s.%(ext)s\".")]
		public bool Id
		{
			get
			{
				return id.Value;
			}
			set
			{
				id.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --parse-metadata \"%(title)s:FORMAT\".")]
		public string MetadataFromTitle
		{
			get
			{
				return metadataFromTitle.Value;
			}
			set
			{
				metadataFromTitle.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --downloader \"m3u8:native\".")]
		public bool HlsPreferNative
		{
			get
			{
				return hlsPreferNative.Value;
			}
			set
			{
				hlsPreferNative.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --downloader \"m3u8:ffmpeg\".")]
		public bool HlsPreferFfmpeg
		{
			get
			{
				return hlsPreferFfmpeg.Value;
			}
			set
			{
				hlsPreferFfmpeg.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --compat-options list-formats (Alias: --no-list-formats-as-table).")]
		public bool ListFormatsOld
		{
			get
			{
				return listFormatsOld.Value;
			}
			set
			{
				listFormatsOld.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --compat-options -list-formats [Default] (Alias: --no-list-formats-old).")]
		public bool ListFormatsAsTable
		{
			get
			{
				return listFormatsAsTable.Value;
			}
			set
			{
				listFormatsAsTable.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --extractor-args \"youtube:skip=dash\" (Alias: --no-youtube-include-dash-manifest).")]
		public bool YoutubeSkipDashManifest
		{
			get
			{
				return youtubeSkipDashManifest.Value;
			}
			set
			{
				youtubeSkipDashManifest.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --extractor-args \"youtube:skip=hls\" (Alias: --no-youtube-include-hls-manifest).")]
		public bool YoutubeSkipHlsManifest
		{
			get
			{
				return youtubeSkipHlsManifest.Value;
			}
			set
			{
				youtubeSkipHlsManifest.Value = value;
			}
		}

		public int? ConcurrentFragments
		{
			get
			{
				return concurrentFragments.Value;
			}
			set
			{
				concurrentFragments.Value = value;
			}
		}

		public long? LimitRate
		{
			get
			{
				return limitRate.Value;
			}
			set
			{
				limitRate.Value = value;
			}
		}

		public long? ThrottledRate
		{
			get
			{
				return throttledRate.Value;
			}
			set
			{
				throttledRate.Value = value;
			}
		}

		public int? Retries
		{
			get
			{
				return retries.Value;
			}
			set
			{
				retries.Value = value;
			}
		}

		public int? FileAccessRetries
		{
			get
			{
				return fileAccessRetries.Value;
			}
			set
			{
				fileAccessRetries.Value = value;
			}
		}

		public int? FragmentRetries
		{
			get
			{
				return fragmentRetries.Value;
			}
			set
			{
				fragmentRetries.Value = value;
			}
		}

		public MultiValue<string> RetrySleep
		{
			get
			{
				return retrySleep.Value;
			}
			set
			{
				retrySleep.Value = value;
			}
		}

		public bool SkipUnavailableFragments
		{
			get
			{
				return skipUnavailableFragments.Value;
			}
			set
			{
				skipUnavailableFragments.Value = value;
			}
		}

		public bool AbortOnUnavailableFragment
		{
			get
			{
				return abortOnUnavailableFragment.Value;
			}
			set
			{
				abortOnUnavailableFragment.Value = value;
			}
		}

		public bool KeepFragments
		{
			get
			{
				return keepFragments.Value;
			}
			set
			{
				keepFragments.Value = value;
			}
		}

		public bool NoKeepFragments
		{
			get
			{
				return noKeepFragments.Value;
			}
			set
			{
				noKeepFragments.Value = value;
			}
		}

		public long? BufferSize
		{
			get
			{
				return bufferSize.Value;
			}
			set
			{
				bufferSize.Value = value;
			}
		}

		public bool ResizeBuffer
		{
			get
			{
				return resizeBuffer.Value;
			}
			set
			{
				resizeBuffer.Value = value;
			}
		}

		public bool NoResizeBuffer
		{
			get
			{
				return noResizeBuffer.Value;
			}
			set
			{
				noResizeBuffer.Value = value;
			}
		}

		public long? HttpChunkSize
		{
			get
			{
				return httpChunkSize.Value;
			}
			set
			{
				httpChunkSize.Value = value;
			}
		}

		public bool PlaylistRandom
		{
			get
			{
				return playlistRandom.Value;
			}
			set
			{
				playlistRandom.Value = value;
			}
		}

		public bool LazyPlaylist
		{
			get
			{
				return lazyPlaylist.Value;
			}
			set
			{
				lazyPlaylist.Value = value;
			}
		}

		public bool NoLazyPlaylist
		{
			get
			{
				return noLazyPlaylist.Value;
			}
			set
			{
				noLazyPlaylist.Value = value;
			}
		}

		public bool XattrSetFilesize
		{
			get
			{
				return xattrSetFilesize.Value;
			}
			set
			{
				xattrSetFilesize.Value = value;
			}
		}

		public bool HlsUseMpegts
		{
			get
			{
				return hlsUseMpegts.Value;
			}
			set
			{
				hlsUseMpegts.Value = value;
			}
		}

		public bool NoHlsUseMpegts
		{
			get
			{
				return noHlsUseMpegts.Value;
			}
			set
			{
				noHlsUseMpegts.Value = value;
			}
		}

		public MultiValue<string> DownloadSections
		{
			get
			{
				return downloadSections.Value;
			}
			set
			{
				downloadSections.Value = value;
			}
		}

		public MultiValue<string> Downloader
		{
			get
			{
				return downloader.Value;
			}
			set
			{
				downloader.Value = value;
			}
		}

		public MultiValue<string> DownloaderArgs
		{
			get
			{
				return downloaderArgs.Value;
			}
			set
			{
				downloaderArgs.Value = value;
			}
		}

		public int? ExtractorRetries
		{
			get
			{
				return extractorRetries.Value;
			}
			set
			{
				extractorRetries.Value = value;
			}
		}

		public bool AllowDynamicMpd
		{
			get
			{
				return allowDynamicMpd.Value;
			}
			set
			{
				allowDynamicMpd.Value = value;
			}
		}

		public bool IgnoreDynamicMpd
		{
			get
			{
				return ignoreDynamicMpd.Value;
			}
			set
			{
				ignoreDynamicMpd.Value = value;
			}
		}

		public bool HlsSplitDiscontinuity
		{
			get
			{
				return hlsSplitDiscontinuity.Value;
			}
			set
			{
				hlsSplitDiscontinuity.Value = value;
			}
		}

		public bool NoHlsSplitDiscontinuity
		{
			get
			{
				return noHlsSplitDiscontinuity.Value;
			}
			set
			{
				noHlsSplitDiscontinuity.Value = value;
			}
		}

		public MultiValue<string> ExtractorArgs
		{
			get
			{
				return extractorArgs.Value;
			}
			set
			{
				extractorArgs.Value = value;
			}
		}

		public string BatchFile
		{
			get
			{
				return batchFile.Value;
			}
			set
			{
				batchFile.Value = value;
			}
		}

		public bool NoBatchFile
		{
			get
			{
				return noBatchFile.Value;
			}
			set
			{
				noBatchFile.Value = value;
			}
		}

		public string Paths
		{
			get
			{
				return paths.Value;
			}
			set
			{
				paths.Value = value;
			}
		}

		public string Output
		{
			get
			{
				return output.Value;
			}
			set
			{
				output.Value = value;
			}
		}

		public string OutputNaPlaceholder
		{
			get
			{
				return outputNaPlaceholder.Value;
			}
			set
			{
				outputNaPlaceholder.Value = value;
			}
		}

		public bool RestrictFilenames
		{
			get
			{
				return restrictFilenames.Value;
			}
			set
			{
				restrictFilenames.Value = value;
			}
		}

		public bool NoRestrictFilenames
		{
			get
			{
				return noRestrictFilenames.Value;
			}
			set
			{
				noRestrictFilenames.Value = value;
			}
		}

		public bool WindowsFilenames
		{
			get
			{
				return windowsFilenames.Value;
			}
			set
			{
				windowsFilenames.Value = value;
			}
		}

		public bool NoWindowsFilenames
		{
			get
			{
				return noWindowsFilenames.Value;
			}
			set
			{
				noWindowsFilenames.Value = value;
			}
		}

		public int? TrimFilenames
		{
			get
			{
				return trimFilenames.Value;
			}
			set
			{
				trimFilenames.Value = value;
			}
		}

		public bool NoOverwrites
		{
			get
			{
				return noOverwrites.Value;
			}
			set
			{
				noOverwrites.Value = value;
			}
		}

		public bool ForceOverwrites
		{
			get
			{
				return forceOverwrites.Value;
			}
			set
			{
				forceOverwrites.Value = value;
			}
		}

		public bool NoForceOverwrites
		{
			get
			{
				return noForceOverwrites.Value;
			}
			set
			{
				noForceOverwrites.Value = value;
			}
		}

		public bool Continue
		{
			get
			{
				return doContinue.Value;
			}
			set
			{
				doContinue.Value = value;
			}
		}

		public bool NoContinue
		{
			get
			{
				return noContinue.Value;
			}
			set
			{
				noContinue.Value = value;
			}
		}

		public bool Part
		{
			get
			{
				return part.Value;
			}
			set
			{
				part.Value = value;
			}
		}

		public bool NoPart
		{
			get
			{
				return noPart.Value;
			}
			set
			{
				noPart.Value = value;
			}
		}

		public bool Mtime
		{
			get
			{
				return mtime.Value;
			}
			set
			{
				mtime.Value = value;
			}
		}

	

BepInEx/plugins/tinyhoot-ShipLoot/ShipLoot/ShipLoot.dll

Decompiled 10 months 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 BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("ShipLoot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("ShipLoot")]
[assembly: AssemblyCopyright("Copyright © tinyhoot 2023")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("1.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace ShipLoot
{
	[BepInPlugin("com.github.tinyhoot.ShipLoot", "ShipLoot", "1.0")]
	internal class ShipLoot : BaseUnityPlugin
	{
		public const string GUID = "com.github.tinyhoot.ShipLoot";

		public const string NAME = "ShipLoot";

		public const string VERSION = "1.0";

		internal static ManualLogSource Log;

		private void Awake()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			new Harmony("com.github.tinyhoot.ShipLoot").PatchAll(Assembly.GetExecutingAssembly());
		}
	}
}
namespace ShipLoot.Patches
{
	[HarmonyPatch]
	internal class HudManagerPatcher
	{
		private static GameObject _totalCounter;

		private static TextMeshProUGUI _textMesh;

		private static float _displayTimeLeft;

		private const float DisplayTime = 5f;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HUDManager), "PingScan_performed")]
		private static void OnScan(HUDManager __instance, CallbackContext context)
		{
			if (!((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && __instance.CanPlayerScan() && !(__instance.playerPingingScan > -0.5f) && (StartOfRound.Instance.inShipPhase || GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom))
			{
				if (!Object.op_Implicit((Object)(object)_totalCounter))
				{
					CopyValueCounter();
				}
				float num = CalculateLootValue();
				((TMP_Text)_textMesh).text = $"SHIP: ${num:F0}";
				_displayTimeLeft = 5f;
				if (!_totalCounter.activeSelf)
				{
					((MonoBehaviour)GameNetworkManager.Instance).StartCoroutine(ShipLootCoroutine());
				}
			}
		}

		private static IEnumerator ShipLootCoroutine()
		{
			_totalCounter.SetActive(true);
			while (_displayTimeLeft > 0f)
			{
				float displayTimeLeft = _displayTimeLeft;
				_displayTimeLeft = 0f;
				yield return (object)new WaitForSeconds(displayTimeLeft);
			}
			_totalCounter.SetActive(false);
		}

		private static float CalculateLootValue()
		{
			List<GrabbableObject> list = (from obj in GameObject.Find("/Environment/HangarShip").GetComponentsInChildren<GrabbableObject>()
				where ((Object)obj).name != "ClipboardManual" && ((Object)obj).name != "StickyNoteItem"
				select obj).ToList();
			ShipLoot.Log.LogDebug((object)"Calculating total ship scrap value.");
			CollectionExtensions.Do<GrabbableObject>((IEnumerable<GrabbableObject>)list, (Action<GrabbableObject>)delegate(GrabbableObject scrap)
			{
				ShipLoot.Log.LogDebug((object)$"{((Object)scrap).name} - ${scrap.scrapValue}");
			});
			return list.Sum((GrabbableObject scrap) => scrap.scrapValue);
		}

		private static void CopyValueCounter()
		{
			//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_0076: 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_008d: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GameObject.Find("/Systems/UI/Canvas/IngamePlayerHUD/BottomMiddle/ValueCounter");
			if (!Object.op_Implicit((Object)(object)val))
			{
				ShipLoot.Log.LogError((object)"Failed to find ValueCounter object to copy!");
			}
			_totalCounter = Object.Instantiate<GameObject>(val.gameObject, val.transform.parent, false);
			_totalCounter.transform.Translate(0f, 1f, 0f);
			Vector3 localPosition = _totalCounter.transform.localPosition;
			_totalCounter.transform.localPosition = new Vector3(localPosition.x + 50f, -50f, localPosition.z);
			_textMesh = _totalCounter.GetComponentInChildren<TextMeshProUGUI>();
		}
	}
}

BepInEx/plugins/Verity-TooManySuits/TooManySuits.dll

Decompiled 10 months ago
using System;
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 Microsoft.CodeAnalysis;
using MoreSuits;
using TMPro;
using TooManySuits.Helper;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[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("TooManySuits")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("TooManySuits")]
[assembly: AssemblyTitle("TooManySuits")]
[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 TooManySuits
{
	[BepInPlugin("verity.TooManySuits", "Too Many Suits", "1.0.4")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static ManualLogSource LogSource;

		public static ConfigEntry<string> NextButton;

		public static ConfigEntry<string> BackButton;

		public static ConfigEntry<float> TextScale;

		private void Awake()
		{
			//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_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			LogSource = ((BaseUnityPlugin)this).Logger;
			NextButton = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Next-Page-Keybind", "<Keyboard>/n", "Next page button.");
			BackButton = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Back-Page-Keybind", "<Keyboard>/b", "Back page button.");
			TextScale = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Text-Scale", 0.003f, "Size of the text above the suit rack.");
			GameObject val = new GameObject("TooManySuits");
			val.AddComponent<PluginLoader>();
			((Object)val).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)val);
		}
	}
	public class PluginLoader : MonoBehaviour
	{
		private class Hooks
		{
			public static bool SetUI;

			public static GameObject SuitPanel;

			public static void HookStartGame()
			{
				Plugin.LogSource.LogInfo((object)"StartOfRound!");
				Object.Instantiate<GameObject>(suitSelectBundle.LoadAsset<GameObject>("SuitSelect"));
				SuitPanel = GameObject.Find("SuitPanel");
				SuitPanel.SetActive(false);
				SetUI = true;
			}
		}

		private readonly Harmony Harmony = new Harmony("TooManySuits");

		private InputAction moveRightAction;

		private InputAction moveLeftAction;

		private int currentPage;

		private int suitsPerPage = 13;

		private int suitsLength;

		private UnlockableSuit[] allSuits;

		private static AssetBundle suitSelectBundle;

		private void Awake()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected O, but got Unknown
			Plugin.LogSource.LogInfo((object)"TooManySuits Mod Loaded.");
			moveRightAction = new InputAction((string)null, (InputActionType)0, Plugin.NextButton.Value, (string)null, (string)null, (string)null);
			moveRightAction.performed += MoveRightAction;
			moveRightAction.Enable();
			moveLeftAction = new InputAction((string)null, (InputActionType)0, Plugin.BackButton.Value, (string)null, (string)null, (string)null);
			moveLeftAction.performed += MoveLeftAction;
			moveLeftAction.Enable();
			MethodInfo method = typeof(StartOfRound).GetMethod("Start", BindingFlags.Instance | BindingFlags.NonPublic);
			MethodInfo method2 = typeof(Hooks).GetMethod("HookStartGame");
			Harmony.Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo method3 = typeof(PlayerControllerB).GetMethod("Start", BindingFlags.Instance | BindingFlags.NonPublic);
			MethodInfo method4 = typeof(LocalPlayer).GetMethod("PlayerControllerStart");
			Harmony.Patch((MethodBase)method3, (HarmonyMethod)null, new HarmonyMethod(method4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			suitSelectBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "suitselect"));
			if (MoreSuitsMod.MakeSuitsFitOnRack)
			{
				suitsPerPage = 20;
			}
		}

		private void Update()
		{
			if (!((Object)(object)StartOfRound.Instance == (Object)null))
			{
				allSuits = (from suit in Resources.FindObjectsOfTypeAll<UnlockableSuit>()
					orderby suit.syncedSuitID.Value
					select suit).ToArray();
				DisplaySuits();
			}
		}

		private void DisplaySuits()
		{
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: 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_0258: 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_0280: 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_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: 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_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_015d: 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_00cb: 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_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: 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)
			if (allSuits.Length == 0)
			{
				return;
			}
			int num = currentPage * suitsPerPage;
			int num2 = Mathf.Min(num + suitsPerPage, allSuits.Length);
			int num3 = 0;
			for (int i = 0; i < allSuits.Length; i++)
			{
				UnlockableSuit val = allSuits[i];
				AutoParentToShip component = ((Component)val).gameObject.GetComponent<AutoParentToShip>();
				if ((Object)(object)component == (Object)null)
				{
					continue;
				}
				bool flag = i >= num && i < num2;
				((Component)val).gameObject.SetActive(flag);
				if (flag)
				{
					component.overrideOffset = true;
					if (MoreSuitsMod.MakeSuitsFitOnRack && suitsLength > 13)
					{
						float num4 = 0.18f;
						num4 /= (float)Math.Min(suitsLength, 20) / 12f;
						component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + StartOfRound.Instance.rightmostSuitPosition.forward * (num4 * (float)num3);
						component.rotationOffset = new Vector3(0f, 90f, 0f);
					}
					else
					{
						component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + StartOfRound.Instance.rightmostSuitPosition.forward * (0.18f * (float)num3);
						component.rotationOffset = new Vector3(0f, 90f, 0f);
					}
					num3++;
				}
			}
			suitsLength = allSuits.Length;
			if (!LocalPlayer.isActive())
			{
				return;
			}
			if (LocalPlayer.localPlayer.isInHangarShipRoom)
			{
				((TMP_Text)Hooks.SuitPanel.GetComponentInChildren<TextMeshProUGUI>()).text = $"Page {currentPage + 1}/{suitsLength / suitsPerPage + 1}";
				Hooks.SuitPanel.SetActive(true);
				return;
			}
			Hooks.SuitPanel.SetActive(false);
			if (Hooks.SetUI)
			{
				Hooks.SetUI = false;
				Hooks.SuitPanel.GetComponentInParent<Canvas>().renderMode = (RenderMode)2;
				Hooks.SuitPanel.GetComponentInParent<Canvas>().worldCamera = LocalPlayer.localPlayer.gameplayCamera;
				Transform transform = Hooks.SuitPanel.transform;
				Bounds bounds = StartOfRound.Instance.shipBounds.bounds;
				transform.position = ((Bounds)(ref bounds)).center - new Vector3(2.8992f, 0.7998f, 2f);
				Hooks.SuitPanel.transform.rotation = Quaternion.Euler(0f, 180f, 0f);
				Hooks.SuitPanel.transform.localScale = new Vector3(Plugin.TextScale.Value, Plugin.TextScale.Value, Plugin.TextScale.Value);
				Hooks.SuitPanel.SetActive(true);
			}
		}

		private void MoveRightAction(CallbackContext obj)
		{
			currentPage = Mathf.Min(currentPage + 1, Mathf.CeilToInt((float)suitsLength / (float)suitsPerPage) - 1);
		}

		private void MoveLeftAction(CallbackContext obj)
		{
			currentPage = Mathf.Max(currentPage - 1, 0);
		}
	}
}
namespace TooManySuits.Helper
{
	public class LocalPlayer
	{
		public static PlayerControllerB localPlayer;

		public static bool isActive()
		{
			return (Object)(object)localPlayer != (Object)null;
		}

		public static void PlayerControllerStart(PlayerControllerB __instance)
		{
			if (NetworkManager.Singleton.LocalClientId == __instance.playerClientId)
			{
				localPlayer = __instance;
			}
		}
	}
}

BepInEx/plugins/x753-More_Suits/MoreSuits.dll

Decompiled 10 months 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.Permissions;
using BepInEx;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("MoreSuits")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A mod that adds more suit options to Lethal Company")]
[assembly: AssemblyFileVersion("1.4.1.0")]
[assembly: AssemblyInformationalVersion("1.4.1")]
[assembly: AssemblyProduct("MoreSuits")]
[assembly: AssemblyTitle("MoreSuits")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.1.0")]
[module: UnverifiableCode]
namespace MoreSuits;

[BepInPlugin("x753.More_Suits", "More Suits", "1.4.1")]
public class MoreSuitsMod : BaseUnityPlugin
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void StartPatch(ref StartOfRound __instance)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_067c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0681: Unknown result type (might be due to invalid IL or missing references)
			//IL_0687: Unknown result type (might be due to invalid IL or missing references)
			//IL_068c: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0400: Expected O, but got Unknown
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Expected O, but got Unknown
			//IL_0598: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Expected O, but got Unknown
			try
			{
				if (SuitsAdded)
				{
					return;
				}
				int count = __instance.unlockablesList.unlockables.Count;
				UnlockableItem val = new UnlockableItem();
				int num = 0;
				for (int i = 0; i < __instance.unlockablesList.unlockables.Count; i++)
				{
					UnlockableItem val2 = __instance.unlockablesList.unlockables[i];
					if (!((Object)(object)val2.suitMaterial != (Object)null) || !val2.alreadyUnlocked)
					{
						continue;
					}
					val = val2;
					List<string> list = Directory.GetDirectories(Paths.PluginPath, "moresuits", SearchOption.AllDirectories).ToList();
					List<string> list2 = new List<string>();
					List<string> list3 = new List<string>();
					List<string> list4 = DisabledSuits.ToLower().Replace(".png", "").Split(',')
						.ToList();
					List<string> list5 = new List<string>();
					if (!LoadAllSuits)
					{
						foreach (string item2 in list)
						{
							if (File.Exists(Path.Combine(item2, "!less-suits.txt")))
							{
								string[] collection = new string[9] { "glow", "kirby", "knuckles", "luigi", "mario", "minion", "skeleton", "slayer", "smile" };
								list5.AddRange(collection);
								break;
							}
						}
					}
					foreach (string item3 in list)
					{
						if (item3 != "")
						{
							string[] files = Directory.GetFiles(item3, "*.png");
							string[] files2 = Directory.GetFiles(item3, "*.matbundle");
							list2.AddRange(files);
							list3.AddRange(files2);
						}
					}
					list3.Sort();
					list2.Sort();
					try
					{
						foreach (string item4 in list3)
						{
							Object[] array = AssetBundle.LoadFromFile(item4).LoadAllAssets();
							foreach (Object val3 in array)
							{
								if (val3 is Material)
								{
									Material item = (Material)val3;
									customMaterials.Add(item);
								}
							}
						}
					}
					catch (Exception ex)
					{
						Debug.Log((object)("Something went wrong with More Suits! Could not load materials from asset bundle(s). Error: " + ex));
					}
					foreach (string item5 in list2)
					{
						if (list4.Contains(Path.GetFileNameWithoutExtension(item5).ToLower()))
						{
							continue;
						}
						string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
						if (list5.Contains(Path.GetFileNameWithoutExtension(item5).ToLower()) && item5.Contains(directoryName))
						{
							continue;
						}
						UnlockableItem val4;
						Material val5;
						if (Path.GetFileNameWithoutExtension(item5).ToLower() == "default")
						{
							val4 = val;
							val5 = val4.suitMaterial;
						}
						else
						{
							val4 = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)val));
							val5 = Object.Instantiate<Material>(val4.suitMaterial);
						}
						byte[] array2 = File.ReadAllBytes(item5);
						Texture2D val6 = new Texture2D(2, 2);
						ImageConversion.LoadImage(val6, array2);
						val5.mainTexture = (Texture)(object)val6;
						val4.unlockableName = Path.GetFileNameWithoutExtension(item5);
						try
						{
							string path = Path.Combine(Path.GetDirectoryName(item5), "advanced", val4.unlockableName + ".json");
							if (File.Exists(path))
							{
								string[] array3 = File.ReadAllLines(path);
								for (int j = 0; j < array3.Length; j++)
								{
									string[] array4 = array3[j].Trim().Split(':');
									if (array4.Length != 2)
									{
										continue;
									}
									string text = array4[0].Trim('"', ' ', ',');
									string text2 = array4[1].Trim('"', ' ', ',');
									if (text2.Contains(".png"))
									{
										byte[] array5 = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(item5), "advanced", text2));
										Texture2D val7 = new Texture2D(2, 2);
										ImageConversion.LoadImage(val7, array5);
										val5.SetTexture(text, (Texture)(object)val7);
										continue;
									}
									if (text == "PRICE" && int.TryParse(text2, out var result))
									{
										try
										{
											val4 = AddToRotatingShop(val4, result, __instance.unlockablesList.unlockables.Count);
										}
										catch (Exception ex2)
										{
											Debug.Log((object)("Something went wrong with More Suits! Could not add a suit to the rotating shop. Error: " + ex2));
										}
										continue;
									}
									switch (text2)
									{
									case "KEYWORD":
										val5.EnableKeyword(text);
										continue;
									case "DISABLEKEYWORD":
										val5.DisableKeyword(text);
										continue;
									case "SHADERPASS":
										val5.SetShaderPassEnabled(text, true);
										continue;
									case "DISABLESHADERPASS":
										val5.SetShaderPassEnabled(text, false);
										continue;
									}
									float result2;
									Vector4 vector;
									if (text == "SHADER")
									{
										Shader shader = Shader.Find(text2);
										val5.shader = shader;
									}
									else if (text == "MATERIAL")
									{
										foreach (Material customMaterial in customMaterials)
										{
											if (((Object)customMaterial).name == text2)
											{
												val5 = Object.Instantiate<Material>(customMaterial);
												val5.mainTexture = (Texture)(object)val6;
												break;
											}
										}
									}
									else if (float.TryParse(text2, out result2))
									{
										val5.SetFloat(text, result2);
									}
									else if (TryParseVector4(text2, out vector))
									{
										val5.SetVector(text, vector);
									}
								}
							}
						}
						catch (Exception ex3)
						{
							Debug.Log((object)("Something went wrong with More Suits! Error: " + ex3));
						}
						val4.suitMaterial = val5;
						if (val4.unlockableName.ToLower() != "default")
						{
							if (num == MaxSuits)
							{
								Debug.Log((object)"Attempted to add a suit, but you've already reached the max number of suits! Modify the config if you want more.");
								continue;
							}
							__instance.unlockablesList.unlockables.Add(val4);
							num++;
						}
					}
					SuitsAdded = true;
					break;
				}
				UnlockableItem val8 = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)val));
				val8.alreadyUnlocked = false;
				val8.hasBeenMoved = false;
				val8.placedPosition = Vector3.zero;
				val8.placedRotation = Vector3.zero;
				val8.unlockableType = 753;
				while (__instance.unlockablesList.unlockables.Count < count + MaxSuits)
				{
					__instance.unlockablesList.unlockables.Add(val8);
				}
			}
			catch (Exception ex4)
			{
				Debug.Log((object)("Something went wrong with More Suits! Error: " + ex4));
			}
		}

		[HarmonyPatch("PositionSuitsOnRack")]
		[HarmonyPrefix]
		private static bool PositionSuitsOnRackPatch(ref StartOfRound __instance)
		{
			//IL_009a: 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_00ac: 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_00b8: 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_00d1: 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)
			List<UnlockableSuit> source = Object.FindObjectsOfType<UnlockableSuit>().ToList();
			source = source.OrderBy((UnlockableSuit suit) => suit.syncedSuitID.Value).ToList();
			int num = 0;
			foreach (UnlockableSuit item in source)
			{
				AutoParentToShip component = ((Component)item).gameObject.GetComponent<AutoParentToShip>();
				component.overrideOffset = true;
				float num2 = 0.18f;
				if (MakeSuitsFitOnRack && source.Count > 13)
				{
					num2 /= (float)Math.Min(source.Count, 20) / 12f;
				}
				component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + __instance.rightmostSuitPosition.forward * num2 * (float)num;
				component.rotationOffset = new Vector3(0f, 90f, 0f);
				num++;
			}
			return false;
		}
	}

	private const string modGUID = "x753.More_Suits";

	private const string modName = "More Suits";

	private const string modVersion = "1.4.1";

	private readonly Harmony harmony = new Harmony("x753.More_Suits");

	private static MoreSuitsMod Instance;

	public static bool SuitsAdded = false;

	public static string DisabledSuits;

	public static bool LoadAllSuits;

	public static bool MakeSuitsFitOnRack;

	public static int MaxSuits;

	public static List<Material> customMaterials = new List<Material>();

	private static TerminalNode cancelPurchase;

	private static TerminalKeyword buyKeyword;

	private void Awake()
	{
		if ((Object)(object)Instance == (Object)null)
		{
			Instance = this;
		}
		DisabledSuits = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Disabled Suit List", "UglySuit751.png,UglySuit752.png,UglySuit753.png", "Comma-separated list of suits that shouldn't be loaded").Value;
		LoadAllSuits = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Ignore !less-suits.txt", false, "If true, ignores the !less-suits.txt file and will attempt to load every suit, except those in the disabled list. This should be true if you're not worried about having too many suits.").Value;
		MakeSuitsFitOnRack = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Make Suits Fit on Rack", true, "If true, squishes the suits together so more can fit on the rack.").Value;
		MaxSuits = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Max Suits", 100, "The maximum number of suits to load. If you have more, some will be ignored.").Value;
		harmony.PatchAll();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin More Suits is loaded!");
	}

	private static UnlockableItem AddToRotatingShop(UnlockableItem newSuit, int price, int unlockableID)
	{
		//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)
		//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_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Expected O, but got Unknown
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d4: Expected O, but got Unknown
		//IL_0298: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Expected O, but got Unknown
		Terminal val = Object.FindObjectOfType<Terminal>();
		for (int i = 0; i < val.terminalNodes.allKeywords.Length; i++)
		{
			if (((Object)val.terminalNodes.allKeywords[i]).name == "Buy")
			{
				buyKeyword = val.terminalNodes.allKeywords[i];
				break;
			}
		}
		newSuit.alreadyUnlocked = false;
		newSuit.hasBeenMoved = false;
		newSuit.placedPosition = Vector3.zero;
		newSuit.placedRotation = Vector3.zero;
		newSuit.shopSelectionNode = ScriptableObject.CreateInstance<TerminalNode>();
		((Object)newSuit.shopSelectionNode).name = newSuit.unlockableName + "SuitBuy1";
		newSuit.shopSelectionNode.creatureName = newSuit.unlockableName + " suit";
		newSuit.shopSelectionNode.displayText = "You have requested to order " + newSuit.unlockableName + " suits.\nTotal cost of item: [totalCost].\n\nPlease CONFIRM or DENY.\n\n";
		newSuit.shopSelectionNode.clearPreviousText = true;
		newSuit.shopSelectionNode.shipUnlockableID = unlockableID;
		newSuit.shopSelectionNode.itemCost = price;
		newSuit.shopSelectionNode.overrideOptions = true;
		CompatibleNoun val2 = new CompatibleNoun();
		val2.noun = ScriptableObject.CreateInstance<TerminalKeyword>();
		val2.noun.word = "confirm";
		val2.noun.isVerb = true;
		val2.result = ScriptableObject.CreateInstance<TerminalNode>();
		((Object)val2.result).name = newSuit.unlockableName + "SuitBuyConfirm";
		val2.result.creatureName = "";
		val2.result.displayText = "Ordered " + newSuit.unlockableName + " suits! Your new balance is [playerCredits].\n\n";
		val2.result.clearPreviousText = true;
		val2.result.shipUnlockableID = unlockableID;
		val2.result.buyUnlockable = true;
		val2.result.itemCost = price;
		val2.result.terminalEvent = "";
		CompatibleNoun val3 = new CompatibleNoun();
		val3.noun = ScriptableObject.CreateInstance<TerminalKeyword>();
		val3.noun.word = "deny";
		val3.noun.isVerb = true;
		if ((Object)(object)cancelPurchase == (Object)null)
		{
			cancelPurchase = ScriptableObject.CreateInstance<TerminalNode>();
		}
		val3.result = cancelPurchase;
		((Object)val3.result).name = "MoreSuitsCancelPurchase";
		val3.result.displayText = "Cancelled order.\n";
		newSuit.shopSelectionNode.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { val2, val3 };
		TerminalKeyword val4 = ScriptableObject.CreateInstance<TerminalKeyword>();
		((Object)val4).name = newSuit.unlockableName + "Suit";
		val4.word = newSuit.unlockableName.ToLower() + " suit";
		val4.defaultVerb = buyKeyword;
		CompatibleNoun val5 = new CompatibleNoun();
		val5.noun = val4;
		val5.result = newSuit.shopSelectionNode;
		List<CompatibleNoun> list = buyKeyword.compatibleNouns.ToList();
		list.Add(val5);
		buyKeyword.compatibleNouns = list.ToArray();
		List<TerminalKeyword> list2 = val.terminalNodes.allKeywords.ToList();
		list2.Add(val4);
		list2.Add(val2.noun);
		list2.Add(val3.noun);
		val.terminalNodes.allKeywords = list2.ToArray();
		return newSuit;
	}

	public static bool TryParseVector4(string input, out Vector4 vector)
	{
		//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_0051: 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)
		vector = Vector4.zero;
		string[] array = input.Split(',');
		if (array.Length == 4 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3) && float.TryParse(array[3], out var result4))
		{
			vector = new Vector4(result, result2, result3, result4);
			return true;
		}
		return false;
	}
}