Decompiled source of The Barn modpack v1.0.1

AlexCodesGames-AdditionalSuits/AdditionalSuits.dll

Decompiled 6 months ago
using System;
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.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("AdditionalSuits")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdditionalSuits")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("0c25b026-8574-4dd2-9af2-4265f618ef8a")]
[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 AdditionalSuits;

[Serializable]
public class UnlockableSuitDef
{
	public string suitID;

	public string suitName;

	public string suitTexture;
}
public class UnlockableSuitDefListing
{
	public List<UnlockableSuitDef> unlockableSuits = new List<UnlockableSuitDef>();
}
[BepInPlugin("ACS.AdditionalSuits", "AdditionalSuits", "1.1.1")]
public class AdditionalSuitsBase : BaseUnityPlugin
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void StartPatch(ref StartOfRound __instance)
		{
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Expected O, but got Unknown
			try
			{
				if (SuitsLoaded)
				{
					return;
				}
				UnlockableItem val = null;
				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)
					{
						val = val2;
						break;
					}
				}
				string text = Path.Combine(ModResourceFolder, "suit-defs.json");
				mls.LogInfo((object)("AdditionalSuits - attempting to parse json file: " + text));
				string text2 = File.ReadAllText(text);
				if (text2 == null)
				{
					mls.LogInfo((object)"AdditionalSuits - ERROR: json file was not found");
					return;
				}
				mls.LogInfo((object)"AdditionalSuits - converting json file to manifest...");
				string[] array = text2.Split(new char[1] { '[' });
				array = array[1].Split(new char[1] { ']' });
				array = array[0].Split(new char[1] { '{' });
				SuitDefManifest = new UnlockableSuitDefListing();
				for (int j = 1; j < array.Length; j++)
				{
					string text3 = "{" + array[j].Trim();
					if (j != array.Length - 1)
					{
						text3 = text3.Substring(0, text3.Length - 1);
					}
					UnlockableSuitDef item = JsonUtility.FromJson<UnlockableSuitDef>(text3);
					SuitDefManifest.unlockableSuits.Add(item);
				}
				mls.LogInfo((object)("AdditionalSuits - loading item defs from manifest, " + SuitDefManifest.unlockableSuits.Count + " items were found..."));
				foreach (UnlockableSuitDef unlockableSuit in SuitDefManifest.unlockableSuits)
				{
					mls.LogInfo((object)("AdditionalSuits - processing custom suit {id=" + unlockableSuit.suitID + ", name=" + unlockableSuit.suitName + "}..."));
					UnlockableItem val3 = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)val));
					Texture2D val4 = new Texture2D(2, 2);
					ImageConversion.LoadImage(val4, File.ReadAllBytes(Path.Combine(ModResourceFolder, unlockableSuit.suitTexture)));
					Material val5 = Object.Instantiate<Material>(val3.suitMaterial);
					val5.mainTexture = (Texture)(object)val4;
					val3.suitMaterial = val5;
					val3.unlockableName = unlockableSuit.suitName;
					__instance.unlockablesList.unlockables.Add(val3);
					mls.LogInfo((object)("AdditionalSuits - added custom suit {id=" + unlockableSuit.suitID + ", name=" + unlockableSuit.suitName + "}!"));
				}
				mls.LogInfo((object)"AdditionalSuits - loaded item defs from json file!");
				SuitsLoaded = true;
			}
			catch (Exception ex)
			{
				mls.LogInfo((object)("AdditionalSuits - initialization failed!\nERROR: " + ex));
			}
		}
	}

	private static AdditionalSuitsBase Instance;

	private const string modGUID = "ACS.AdditionalSuits";

	private const string modName = "AdditionalSuits";

	private const string modVersion = "1.1.1";

	private readonly Harmony harmony = new Harmony("ACS.AdditionalSuits");

	public static ManualLogSource mls;

	public static bool SuitsLoaded;

	public static string ModResourceFolder;

	public static UnlockableSuitDefListing SuitDefManifest;

	private void Awake()
	{
		if ((Object)(object)Instance == (Object)null)
		{
			Instance = this;
		}
		mls = Logger.CreateLogSource("ACS.AdditionalSuits");
		mls.LogInfo((object)"AdditionalSuits - initializing...");
		ModResourceFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "resAdditionalSuits");
		harmony.PatchAll();
		mls.LogInfo((object)"AdditionalSuits - initialized!");
	}
}

anormaltwig-LateCompany/LateCompanyV1.0.6.dll

Decompiled 6 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+31dbb98cfa5670c23f3ffb21c05582c54159b82d")]
[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.6";
	}
	[BepInPlugin("twig.latecompany", "Late Company", "1.0.6")]
	internal class Plugin : BaseUnityPlugin
	{
		private ConfigEntry<bool> configLateJoinOrbitOnly;

		public static bool OnlyLateJoinInOrbit = 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", "Late join orbit only", true, "Don't allow joining while the ship is not in orbit.");
			OnlyLateJoinInOrbit = 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")]
	[HarmonyWrapSafe]
	internal static class DisableInviteFriendsButton_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "InviteFriendsButton")]
	[HarmonyWrapSafe]
	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_0009: 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_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)
			NetworkManager networkManager = target.NetworkManager;
			try
			{
				int num = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref num);
				int num2 = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref num2);
				int num3 = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref num3);
				WeatherSync.DoOverride = true;
				WeatherSync.CurrentWeather = (LevelWeatherType)num3;
				RPCExecStage.SetValue(target, RpcEnum.Client);
				((RoundManager)((target is RoundManager) ? target : null)).GenerateNewLevelClientRpc(num, num2);
				RPCExecStage.SetValue(target, RpcEnum.None);
			}
			catch
			{
				((FastBufferReader)(ref reader)).Seek(0);
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(RoundManager), "SetToCurrentLevelWeather")]
	[HarmonyWrapSafe]
	internal static class SetToCurrentLevelWeather_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			//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)
			if (!WeatherSync.DoOverride)
			{
				return true;
			}
			WeatherSync.DoOverride = false;
			TimeOfDay.Instance.currentLevelWeather = WeatherSync.CurrentWeather;
			return false;
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnPlayerConnectedClientRpc")]
	[HarmonyWrapSafe]
	internal 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_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			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, (short)instance2.currentLevel.currentWeather);
				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 class OnPlayerDC_Patch
	{
		[HarmonyPostfix]
		public static void Postfix()
		{
			if (StartOfRound.Instance.inShipPhase || !Plugin.OnlyLateJoinInOrbit)
			{
				Plugin.SetLobbyJoinable(joinable: true);
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "StartGame")]
	[HarmonyWrapSafe]
	internal class StartGame_Patch
	{
		[HarmonyPrefix]
		public static void Prefix()
		{
			if (Plugin.OnlyLateJoinInOrbit)
			{
				Plugin.SetLobbyJoinable(joinable: false);
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "SetShipReadyToLand")]
	[HarmonyWrapSafe]
	internal class SetShipReadyToLand_Patch
	{
		[HarmonyPrefix]
		public static void Postfix()
		{
			if (Plugin.OnlyLateJoinInOrbit && StartOfRound.Instance.connectedPlayersAmount + 1 < StartOfRound.Instance.allPlayerScripts.Length)
			{
				Plugin.SetLobbyJoinable(joinable: true);
			}
		}
	}
}

Clementinise-CustomSounds/CustomSounds.dll

Decompiled 6 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.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CustomSounds.Networking;
using CustomSounds.Patches;
using HarmonyLib;
using LCSoundTool;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("CustomSounds")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomSounds")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9e086160-a7fd-4721-ba09-3e8534cb7011")]
[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")]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace CustomSounds
{
	[BepInPlugin("CustomSounds", "Custom Sounds", "2.1.2")]
	public class Plugin : BaseUnityPlugin
	{
		private const string PLUGIN_GUID = "CustomSounds";

		private const string PLUGIN_NAME = "Custom Sounds";

		private const string PLUGIN_VERSION = "2.1.2";

		public static Plugin Instance;

		internal ManualLogSource logger;

		private Harmony harmony;

		public HashSet<string> currentSounds = new HashSet<string>();

		public HashSet<string> oldSounds = new HashSet<string>();

		public HashSet<string> modifiedSounds = new HashSet<string>();

		public Dictionary<string, string> soundHashes = new Dictionary<string, string>();

		public Dictionary<string, string> soundPacks = new Dictionary<string, string>();

		public static ConfigEntry<KeyboardShortcut> AcceptSyncKey;

		public ConfigEntry<bool> configUseNetworking;

		private Dictionary<string, string> customSoundNames = new Dictionary<string, string>();

		public static bool Initialized { get; private set; }

		private void Awake()
		{
			//IL_0076: 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_009a: Expected O, but got Unknown
			if (!((Object)(object)Instance == (Object)null))
			{
				return;
			}
			Instance = this;
			logger = Logger.CreateLogSource("CustomSounds");
			logger.LogInfo((object)"Plugin CustomSounds is loaded!");
			configUseNetworking = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "EnableNetworking", true, "Whether or not to use the networking built into this plugin. If set to true everyone in the lobby needs CustomSounds to join and also \"EnableNetworking\" set to true.");
			AcceptSyncKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Experimental", "AcceptSyncKey", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Key to accept audio sync.");
			harmony = new Harmony("CustomSounds");
			harmony.PatchAll(typeof(TerminalParsePlayerSentencePatch));
			if (configUseNetworking.Value)
			{
				harmony.PatchAll(typeof(NetworkObjectManager));
			}
			modifiedSounds = new HashSet<string>();
			string customSoundsFolderPath = GetCustomSoundsFolderPath();
			if (!Directory.Exists(customSoundsFolderPath))
			{
				logger.LogInfo((object)"\"CustomSounds\" folder not found. Creating it now.");
				Directory.CreateDirectory(customSoundsFolderPath);
			}
			string path = Path.Combine(Paths.BepInExConfigPath);
			try
			{
				List<string> list = File.ReadAllLines(path).ToList();
				int num = list.FindIndex((string line) => line.StartsWith("HideManagerGameObject"));
				if (num != -1)
				{
					logger.LogInfo((object)"\"hideManagerGameObject\" value not correctly set. Fixing it now.");
					list[num] = "HideManagerGameObject = true";
				}
				File.WriteAllLines(path, list);
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Error modifying config file: " + ex.Message));
			}
			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);
					}
				}
			}
		}

		internal void Start()
		{
			Initialize();
		}

		internal void OnDestroy()
		{
			Initialize();
		}

		internal void Initialize()
		{
			if (!Initialized)
			{
				Initialized = true;
				DeleteTempFolder();
				ReloadSounds(serverSync: false, isTemporarySync: false);
			}
		}

		private void OnApplicationQuit()
		{
			DeleteTempFolder();
		}

		public GameObject LoadNetworkPrefabFromEmbeddedResource()
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string name = "CustomSounds.Bundle.audionetworkhandler";
			using Stream stream = executingAssembly.GetManifestResourceStream(name);
			if (stream == null)
			{
				Debug.LogError((object)"Asset bundle not found in embedded resources.");
				return null;
			}
			byte[] array = new byte[stream.Length];
			stream.Read(array, 0, array.Length);
			AssetBundle val = AssetBundle.LoadFromMemory(array);
			if ((Object)(object)val == (Object)null)
			{
				Debug.LogError((object)"Failed to load AssetBundle from memory.");
				return null;
			}
			return val.LoadAsset<GameObject>("audionetworkhandler");
		}

		public void DeleteTempFolder()
		{
			string customSoundsTempFolderPath = GetCustomSoundsTempFolderPath();
			if (Directory.Exists(customSoundsTempFolderPath))
			{
				try
				{
					Directory.Delete(customSoundsTempFolderPath, recursive: true);
					logger.LogInfo((object)"Temporary-Sync folder deleted successfully.");
				}
				catch (Exception ex)
				{
					logger.LogError((object)("Error deleting Temporary-Sync folder: " + ex.Message));
				}
			}
		}

		public string GetCustomSoundsFolderPath()
		{
			return Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)Instance).Info.Location), "CustomSounds");
		}

		public string GetCustomSoundsTempFolderPath()
		{
			return Path.Combine(GetCustomSoundsFolderPath(), "Temporary-Sync");
		}

		public static byte[] SerializeWavToBytes(string filePath)
		{
			try
			{
				return File.ReadAllBytes(filePath);
			}
			catch (Exception ex)
			{
				Console.WriteLine("An error occurred: " + ex.Message);
				return null;
			}
		}

		public static string SerializeWavToBase64(string filePath)
		{
			try
			{
				byte[] inArray = File.ReadAllBytes(filePath);
				return Convert.ToBase64String(inArray);
			}
			catch (Exception ex)
			{
				Console.WriteLine("An error occurred: " + ex.Message);
				return null;
			}
		}

		public static void DeserializeBytesToWav(byte[] byteArray, string audioFileName)
		{
			try
			{
				string customSoundsTempFolderPath = Instance.GetCustomSoundsTempFolderPath();
				if (!Directory.Exists(customSoundsTempFolderPath))
				{
					Instance.logger.LogInfo((object)"\"Temporary-Sync\" folder not found. Creating it now.");
					Directory.CreateDirectory(customSoundsTempFolderPath);
				}
				File.WriteAllBytes(Path.Combine(customSoundsTempFolderPath, audioFileName), byteArray);
				Console.WriteLine("WAV file \"" + audioFileName + "\" created!");
			}
			catch (Exception ex)
			{
				Console.WriteLine("An error occurred: " + ex.Message);
			}
		}

		public static List<byte[]> SplitAudioData(byte[] audioData, int maxSegmentSize = 62000)
		{
			List<byte[]> list = new List<byte[]>();
			for (int i = 0; i < audioData.Length; i += maxSegmentSize)
			{
				int num = Mathf.Min(maxSegmentSize, audioData.Length - i);
				byte[] array = new byte[num];
				Array.Copy(audioData, i, array, 0, num);
				list.Add(array);
			}
			return list;
		}

		public static byte[] CombineAudioSegments(List<byte[]> segments)
		{
			List<byte> list = new List<byte>();
			foreach (byte[] segment in segments)
			{
				list.AddRange(segment);
			}
			return list.ToArray();
		}

		public void ShowCustomTip(string header, string body, bool isWarning)
		{
			HUDManager.Instance.DisplayTip(header, body, isWarning, false, "LC_Tip1");
		}

		public void ForceUnsync()
		{
			DeleteTempFolder();
			ReloadSounds(serverSync: false, isTemporarySync: false);
		}

		public void RevertSounds()
		{
			HashSet<string> hashSet = new HashSet<string>();
			foreach (string currentSound in currentSounds)
			{
				string text = currentSound;
				if (currentSound.Contains("-"))
				{
					text = currentSound.Substring(0, currentSound.IndexOf("-"));
				}
				if (!hashSet.Contains(text))
				{
					logger.LogInfo((object)(text + " restored."));
					SoundTool.RestoreAudioClip(text);
					hashSet.Add(text);
				}
			}
			logger.LogInfo((object)"Original game sounds restored.");
		}

		public static string CalculateMD5(string filename)
		{
			using MD5 mD = MD5.Create();
			using FileStream inputStream = File.OpenRead(filename);
			byte[] array = mD.ComputeHash(inputStream);
			return BitConverter.ToString(array).Replace("-", "").ToLowerInvariant();
		}

		public void ReloadSounds(bool serverSync, bool isTemporarySync)
		{
			oldSounds = new HashSet<string>(currentSounds);
			modifiedSounds.Clear();
			string directoryName = Path.GetDirectoryName(Paths.PluginPath);
			currentSounds.Clear();
			customSoundNames.Clear();
			string customSoundsTempFolderPath = GetCustomSoundsTempFolderPath();
			logger.LogInfo((object)("Temporary folder: " + customSoundsTempFolderPath));
			if (Directory.Exists(customSoundsTempFolderPath) && isTemporarySync)
			{
				ProcessDirectory(customSoundsTempFolderPath, serverSync, isTemporarySync: true);
			}
			ProcessDirectory(directoryName, serverSync, isTemporarySync: false);
		}

		private void ProcessDirectory(string directoryPath, bool serverSync, bool isTemporarySync)
		{
			string[] directories = Directory.GetDirectories(directoryPath, "CustomSounds", SearchOption.AllDirectories);
			foreach (string text in directories)
			{
				string fileName = Path.GetFileName(Path.GetDirectoryName(text));
				ProcessSoundFiles(text, fileName, serverSync, isTemporarySync);
				string[] directories2 = Directory.GetDirectories(text);
				foreach (string text2 in directories2)
				{
					string fileName2 = Path.GetFileName(text2);
					ProcessSoundFiles(text2, fileName2, serverSync, isTemporarySync);
				}
			}
		}

		private (string soundName, int? percentage, string customName) ParseSoundFileName(string fullSoundName)
		{
			string[] array = fullSoundName.Split(new char[1] { '-' });
			string s = array[^1].Replace(".wav", "");
			if (int.TryParse(s, out var result))
			{
				string item = array[0];
				string item2 = string.Join(" ", array.Skip(1).Take(array.Length - 2));
				return (item, result, item2);
			}
			return (array[0], null, string.Join(" ", array.Skip(1)).Replace(".wav", ""));
		}

		private void ProcessSoundFiles(string directoryPath, string packName, bool serverSync, bool isTemporarySync)
		{
			string[] files = Directory.GetFiles(directoryPath, "*.wav");
			foreach (string text in files)
			{
				string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
				(string soundName, int? percentage, string customName) tuple = ParseSoundFileName(fileNameWithoutExtension);
				string item = tuple.soundName;
				int? item2 = tuple.percentage;
				string item3 = tuple.customName;
				string text2 = (item2.HasValue ? $"{item}-{item3}-{item2.Value}" : (item + "-" + item3));
				string text3 = CalculateMD5(text);
				if (isTemporarySync || !currentSounds.Contains(text2))
				{
					if (soundHashes.TryGetValue(text2, out var value) && value != text3)
					{
						modifiedSounds.Add(text2);
					}
					AudioClip audioClip = SoundTool.GetAudioClip(directoryPath, "", text);
					SoundTool.ReplaceAudioClip(item, audioClip);
					soundHashes[text2] = text3;
					currentSounds.Add(text2);
					soundPacks[item] = packName;
					string text4 = "[" + packName + "] " + item + " sound replaced!";
					if (item2 > 0)
					{
						text4 += $" (Random chance: {item2}%)";
					}
					logger.LogInfo((object)text4);
					string key = item + (item2.HasValue ? $"-{item2.Value}-{item3}" : ("-" + item3));
					if (!string.IsNullOrEmpty(item3))
					{
						customSoundNames[key] = item3;
					}
					if (serverSync)
					{
						string text5 = Path.Combine(directoryPath, fileNameWithoutExtension + ".wav");
						logger.LogInfo((object)("[" + text5 + "] " + fileNameWithoutExtension + ".wav!"));
						AudioNetworkHandler.Instance.QueueAudioData(SerializeWavToBytes(text5), fileNameWithoutExtension + ".wav");
					}
				}
			}
		}

		public string ListAllSounds(bool isListing)
		{
			StringBuilder stringBuilder = new StringBuilder(isListing ? "Listing all currently loaded custom sounds:\n\n" : "Customsounds reloaded.\n\n");
			Dictionary<string, List<string>> soundsByPack = new Dictionary<string, List<string>>();
			Action<HashSet<string>, string> action = delegate(HashSet<string> soundsSet, string status)
			{
				foreach (string item5 in soundsSet)
				{
					(string soundName, int? percentage, string customName) tuple = ParseSoundFileName(item5);
					string item = tuple.soundName;
					int? item2 = tuple.percentage;
					string item3 = tuple.customName;
					string text = (item2.HasValue ? $" (Random: {item2.Value}%)" : "");
					string text2 = "";
					string key = item + (item2.HasValue ? $"-{item2.Value}-{item3}" : ("-" + item3));
					if (customSoundNames.TryGetValue(key, out var value))
					{
						text2 = " [" + value + "]";
					}
					string key2 = (soundPacks.ContainsKey(item) ? soundPacks[item] : "Unknown");
					if (!soundsByPack.ContainsKey(key2))
					{
						soundsByPack[key2] = new List<string>();
					}
					string item4 = (isListing ? (item + text + text2) : (item + " (" + status + ")" + text + text2));
					soundsByPack[key2].Add(item4);
				}
			};
			if (!isListing)
			{
				action(new HashSet<string>(currentSounds.Except(oldSounds)), "N¹");
				action(new HashSet<string>(oldSounds.Except(currentSounds)), "D²");
				action(new HashSet<string>(oldSounds.Intersect(currentSounds).Except(modifiedSounds)), "A.E³");
				action(new HashSet<string>(modifiedSounds), "M⁴");
			}
			else
			{
				action(new HashSet<string>(currentSounds), "N¹");
			}
			foreach (string key3 in soundsByPack.Keys)
			{
				stringBuilder.AppendLine(key3 + " :");
				foreach (string item6 in soundsByPack[key3])
				{
					stringBuilder.AppendLine("- " + item6);
				}
				stringBuilder.AppendLine();
			}
			if (!isListing)
			{
				stringBuilder.AppendLine("Footnotes:");
				stringBuilder.AppendLine("¹ N = New");
				stringBuilder.AppendLine("² D = Deleted");
				stringBuilder.AppendLine("³ A.E = Already Existed");
				stringBuilder.AppendLine("⁴ M = Modified");
				stringBuilder.AppendLine();
			}
			return stringBuilder.ToString();
		}
	}
}
namespace CustomSounds.Patches
{
	[HarmonyPatch]
	public class NetworkObjectManager
	{
		private static GameObject networkPrefab;

		private static GameObject networkHandlerHost;

		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		[HarmonyPrefix]
		public static void Init()
		{
			if (!((Object)(object)networkPrefab != (Object)null))
			{
				networkPrefab = Plugin.Instance.LoadNetworkPrefabFromEmbeddedResource();
				networkPrefab.AddComponent<AudioNetworkHandler>();
				NetworkManager.Singleton.AddNetworkPrefab(networkPrefab);
				Plugin.Instance.logger.LogInfo((object)"Created AudioNetworkHandler prefab");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		private static void SpawnNetworkHandler()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					Plugin.Instance.logger.LogInfo((object)"Spawning network handler");
					networkHandlerHost = Object.Instantiate<GameObject>(networkPrefab, Vector3.zero, Quaternion.identity);
					if (networkHandlerHost.GetComponent<NetworkObject>().IsSpawned)
					{
						Debug.Log((object)"NetworkObject is spawned and active.");
					}
					else
					{
						Debug.Log((object)"Failed to spawn NetworkObject.");
					}
					networkHandlerHost.GetComponent<NetworkObject>().Spawn(true);
					if ((Object)(object)AudioNetworkHandler.Instance != (Object)null)
					{
						Debug.Log((object)"Successfully accessed AudioNetworkHandler instance.");
					}
					else
					{
						Debug.Log((object)"AudioNetworkHandler instance is null.");
					}
				}
			}
			catch
			{
				Plugin.Instance.logger.LogError((object)"Failed to spawned network handler");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		private static void DestroyNetworkHandler()
		{
			try
			{
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					Plugin.Instance.logger.LogInfo((object)"Destroying network handler");
					Object.Destroy((Object)(object)networkHandlerHost);
					networkHandlerHost = null;
				}
			}
			catch
			{
				Plugin.Instance.logger.LogError((object)"Failed to destroy network handler");
			}
		}
	}
	[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
	public static class TerminalParsePlayerSentencePatch
	{
		public static bool Prefix(Terminal __instance, ref TerminalNode __result)
		{
			string[] array = __instance.screenText.text.Split(new char[1] { '\n' });
			if (array.Length == 0)
			{
				return true;
			}
			string[] array2 = array.Last().Trim().ToLower()
				.Split(new char[1] { ' ' });
			if (array2.Length == 0 || (array2[0] != "customsounds" && array2[0] != "cs"))
			{
				return true;
			}
			Plugin.Instance.logger.LogInfo((object)("Received terminal command: " + string.Join(" ", array2)));
			if (array2.Length > 1 && (array2[0] == "customsounds" || array2[0] == "cs"))
			{
				switch (array2[1])
				{
				case "reload":
				case "rl":
					Plugin.Instance.RevertSounds();
					Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: false);
					__result = CreateTerminalNode(Plugin.Instance.ListAllSounds(isListing: false));
					return false;
				case "revert":
				case "rv":
					Plugin.Instance.RevertSounds();
					__result = CreateTerminalNode("Game sounds reverted to original.\n\n");
					return false;
				case "list":
				case "l":
					__result = CreateTerminalNode(Plugin.Instance.ListAllSounds(isListing: true));
					return false;
				case "help":
				case "h":
					if (NetworkManager.Singleton.IsHost)
					{
						__result = CreateTerminalNode("CustomSounds commands \n(Can also be used with 'CS' as an alias).\n\n>CUSTOMSOUNDS LIST/L\nTo display all currently loaded sounds\n\n>CUSTOMSOUNDS RELOAD/RL\nTo reload and apply sounds from the 'CustomSounds' folder and its subfolders.\n\n>CUSTOMSOUNDS REVERT/RV\nTo unload all custom sounds and restore original game sounds\n\n>CUSTOMSOUNDS SYNC/S\nTo start the sync of custom sounds with clients\n\n>CUSTOMSOUNDS FORCE-UNSYNC/FU\nTo force the unsync process for all clients\n\n");
					}
					else
					{
						__result = CreateTerminalNode("CustomSounds commands \n(Can also be used with 'CS' as an alias).\n\n>CUSTOMSOUNDS LIST/L\nTo display all currently loaded sounds\n\n>CUSTOMSOUNDS RELOAD/RL\nTo reload and apply sounds from the 'CustomSounds' folder and its subfolders.\n\n>CUSTOMSOUNDS REVERT/RV\nTo unload all custom sounds and restore original game sounds\n\n>CUSTOMSOUNDS UNSYNC/U\nUnsyncs sounds sent by the host.\n\n");
					}
					return false;
				case "sync":
				case "s":
					if (NetworkManager.Singleton.IsHost)
					{
						if (Plugin.Instance.configUseNetworking.Value)
						{
							__result = CreateTerminalNode("Custom sound sync initiated. \nSyncing sounds with clients...\n\n");
							Plugin.Instance.ReloadSounds(serverSync: true, isTemporarySync: false);
						}
						else
						{
							__result = CreateTerminalNode("Custom sound sync is currently disabled. \nPlease enable network support in the plugin config to use this feature.\n\n");
						}
					}
					else
					{
						__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command can only be used by the host!\n\n");
					}
					return false;
				case "unsync":
				case "u":
					if (!NetworkManager.Singleton.IsHost)
					{
						__result = CreateTerminalNode("Unsyncing custom sounds. \nTemporary files deleted and original sounds reloaded.\n\n");
						Plugin.Instance.DeleteTempFolder();
						Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: false);
					}
					else
					{
						__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command cannot be used by the host!\n\n");
					}
					return false;
				case "fu":
				case "force-unsync":
					if (NetworkManager.Singleton.IsHost)
					{
						__result = CreateTerminalNode("Forcing unsync for all clients. \nAll client-side temporary synced files have been deleted, and original sounds reloaded.\n\n");
						AudioNetworkHandler.Instance.ForceUnsync();
					}
					else
					{
						__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command can only be used by the host!\n\n");
					}
					return false;
				default:
					__result = CreateTerminalNode("Unknown customsounds command.\n\n");
					return false;
				}
			}
			return true;
		}

		private static TerminalNode CreateTerminalNode(string message)
		{
			TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
			val.displayText = message;
			val.clearPreviousText = true;
			return val;
		}
	}
}
namespace CustomSounds.Networking
{
	public class AudioNetworkHandler : NetworkBehaviour
	{
		private struct AudioData
		{
			public List<byte[]> Segments;

			public string FileName;

			public AudioData(List<byte[]> segments, string fileName)
			{
				Segments = segments;
				FileName = fileName;
			}
		}

		private List<byte[]> receivedAudioSegments = new List<byte[]>();

		private string audioFileName;

		private int totalAudioFiles;

		private int processedAudioFiles;

		private int totalSegments;

		private int processedSegments;

		private bool isRequestingSync;

		private float[] progressThresholds = new float[4] { 0.25f, 0.5f, 0.75f, 1f };

		private int lastThresholdIndex = -1;

		private bool hasAcceptedSync = false;

		private Queue<AudioData> audioQueue = new Queue<AudioData>();

		private bool isSendingAudio = false;

		public static AudioNetworkHandler Instance { get; private set; }

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
				Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
				Debug.Log((object)"AudioNetworkHandler instance created.");
			}
			else
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
				Debug.Log((object)"Extra AudioNetworkHandler instance destroyed.");
			}
		}

		private void Update()
		{
			//IL_0011: 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 (isRequestingSync)
			{
				KeyboardShortcut value = Plugin.AcceptSyncKey.Value;
				if (((KeyboardShortcut)(ref value)).IsPressed())
				{
					Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Sync request accepted successfully!", isWarning: false);
					hasAcceptedSync = true;
					isRequestingSync = false;
				}
			}
		}

		public void QueueAudioData(byte[] audioData, string audioName)
		{
			List<byte[]> list = Plugin.SplitAudioData(audioData);
			totalSegments += list.Count;
			audioQueue.Enqueue(new AudioData(list, audioName));
			if (!isSendingAudio)
			{
				totalAudioFiles = audioQueue.Count;
				processedAudioFiles = 0;
				((MonoBehaviour)this).StartCoroutine(SendAudioDataQueue());
			}
		}

		private IEnumerator SendAudioDataQueue()
		{
			isSendingAudio = true;
			totalSegments = 0;
			processedSegments = 0;
			lastThresholdIndex = -1;
			RequestSyncWithClients();
			yield return (object)new WaitForSeconds(6f);
			isRequestingSync = false;
			DisplayStartingSyncMessageClientRpc();
			yield return (object)new WaitForSeconds(2f);
			while (audioQueue.Count > 0)
			{
				AudioData audioData = audioQueue.Dequeue();
				yield return ((MonoBehaviour)this).StartCoroutine(SendAudioDataCoroutine(audioData.Segments, audioData.FileName));
				processedAudioFiles++;
				UpdateProgress();
			}
			NotifyClientsQueueCompletedServerRpc();
			isSendingAudio = false;
		}

		private void RequestSyncWithClients()
		{
			foreach (NetworkClient connectedClients in NetworkManager.Singleton.ConnectedClientsList)
			{
				RequestSyncClientRpc(connectedClients.ClientId);
			}
		}

		[ClientRpc]
		private void RequestSyncClientRpc(ulong clientId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3186703908u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, clientId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3186703908u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((NetworkBehaviour)this).IsServer)
				{
					Plugin.Instance.ShowCustomTip("CustomSounds Sync", $"Press {Plugin.AcceptSyncKey.Value} to accept the audio sync request.", isWarning: false);
					isRequestingSync = true;
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void NotifyClientsQueueCompletedServerRpc(ServerRpcParams rpcParams = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(152710787u, rpcParams, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val, 152710787u, rpcParams, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					ProcessLastAudioFileClientRpc();
				}
			}
		}

		public void ForceUnsync()
		{
			ForceUnsyncClientsClientRpc();
		}

		[ClientRpc]
		private void ForceUnsyncClientsClientRpc()
		{
			//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(3960362720u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3960362720u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).IsServer)
				{
					Debug.Log((object)"Forcing all clients to delete Temporary-Sync folder.");
					return;
				}
				Plugin.Instance.ShowCustomTip("CustomSounds Sync", "The CustomSounds sync has been reset by the host.\nTemporary files deleted and original sounds reloaded", isWarning: false);
				Plugin.Instance.DeleteTempFolder();
				Plugin.Instance.RevertSounds();
				Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: false);
			}
		}

		[ClientRpc]
		private void ProcessLastAudioFileClientRpc()
		{
			//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(234624598u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 234624598u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && hasAcceptedSync)
				{
					hasAcceptedSync = false;
					ProcessLastAudioFile();
					Debug.Log((object)"Reverting all sounds.");
					Plugin.Instance.RevertSounds();
					Debug.Log((object)"All sounds reverted!");
					Debug.Log((object)"Reloading all sounds.");
					Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: true);
					Debug.Log((object)"All sounds reloaded!");
				}
			}
		}

		private void ProcessLastAudioFile()
		{
			if (receivedAudioSegments.Count > 0 && !string.IsNullOrEmpty(audioFileName))
			{
				byte[] byteArray = Plugin.CombineAudioSegments(receivedAudioSegments);
				Plugin.DeserializeBytesToWav(byteArray, audioFileName);
				receivedAudioSegments.Clear();
				audioFileName = null;
			}
		}

		public void SendAudioData(byte[] audioData, string audioName)
		{
			List<byte[]> list = Plugin.SplitAudioData(audioData);
			audioFileName = audioName;
			SendAudioMetaDataToClientsServerRpc(list.Count, audioName);
			((MonoBehaviour)this).StartCoroutine(SendAudioDataCoroutine(list, audioName));
		}

		[ServerRpc]
		public void SendAudioMetaDataToClientsServerRpc(int totalSegments, string fileName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Invalid comparison between Unknown and I4
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: 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_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			//IL_010d: 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 != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3991320206u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, totalSegments);
				bool flag = fileName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(fileName, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3991320206u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				Debug.Log((object)$"Sending metadata to clients: {totalSegments} segments, file name: {fileName}");
				ReceiveAudioMetaDataClientRpc(totalSegments, fileName);
			}
		}

		private IEnumerator SendAudioDataCoroutine(List<byte[]> audioSegments, string audioName)
		{
			foreach (byte[] segment in audioSegments)
			{
				SendBytesToServerRpc(segment, audioName);
				processedSegments++;
				UpdateProgress();
				yield return (object)new WaitForSeconds(0.2f);
			}
		}

		[ServerRpc]
		public void SendBytesToServerRpc(byte[] audioSegment, string audioName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Invalid comparison between Unknown and I4
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: 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_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			//IL_0119: 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_00f2: 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_014b: 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 != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3131260794u, val, (RpcDelivery)0);
				bool flag = audioSegment != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioSegment, default(ForPrimitives));
				}
				bool flag2 = audioName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(audioName, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3131260794u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				Debug.Log((object)("Sending segment to server: " + audioName));
				ReceiveBytesClientRpc(audioSegment, audioName);
			}
		}

		[ClientRpc]
		public void ReceiveAudioMetaDataClientRpc(int totalSegments, string fileName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: 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_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_00c7: 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(1027341762u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, totalSegments);
				bool flag = fileName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(fileName, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1027341762u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				Debug.Log((object)$"Received metadata on client: {totalSegments} segments expected, file name: {fileName}");
				audioFileName = fileName;
				receivedAudioSegments.Clear();
			}
		}

		[ClientRpc]
		public void ReceiveBytesClientRpc(byte[] audioSegment, string audioName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: 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_00d3: 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_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: 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(2945580654u, val, (RpcDelivery)0);
				bool flag = audioSegment != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioSegment, default(ForPrimitives));
				}
				bool flag2 = audioName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(audioName, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2945580654u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((NetworkBehaviour)this).IsServer && hasAcceptedSync)
			{
				if (!string.IsNullOrEmpty(audioName) && audioFileName != audioName)
				{
					ProcessLastAudioFile();
					audioFileName = audioName;
				}
				receivedAudioSegments.Add(audioSegment);
			}
		}

		[ClientRpc]
		private void DisplayStartingSyncMessageClientRpc()
		{
			//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(3964799390u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3964799390u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (hasAcceptedSync)
				{
					Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Starting audio synchronization. Please wait...", isWarning: false);
					Plugin.Instance.DeleteTempFolder();
				}
				else if (((NetworkBehaviour)this).IsServer)
				{
					Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Initiating audio synchronization. Sending files to clients...", isWarning: false);
				}
			}
		}

		private void UpdateProgress()
		{
			float progress = (float)processedSegments / (float)totalSegments;
			int currentThresholdIndex = GetCurrentThresholdIndex(progress);
			if (currentThresholdIndex > lastThresholdIndex)
			{
				lastThresholdIndex = currentThresholdIndex;
				UpdateProgressClientRpc(progress);
			}
		}

		private int GetCurrentThresholdIndex(float progress)
		{
			for (int num = progressThresholds.Length - 1; num >= 0; num--)
			{
				if (progress >= progressThresholds[num])
				{
					return num;
				}
			}
			return -1;
		}

		[ClientRpc]
		private void UpdateProgressClientRpc(float progress)
		{
			//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)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3902617409u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref progress, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3902617409u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost) || (!((NetworkBehaviour)this).IsServer && !hasAcceptedSync))
			{
				return;
			}
			string text = GenerateProgressBar(progress);
			if (progress < 1f)
			{
				if (!((NetworkBehaviour)this).IsServer)
				{
					Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Sounds transfer progression:\n" + text, isWarning: false);
				}
			}
			else if (((NetworkBehaviour)this).IsServer)
			{
				Plugin.Instance.ShowCustomTip("CustomSounds Sync", "All sounds have been successfully sent!", isWarning: false);
			}
			else
			{
				Plugin.Instance.ShowCustomTip("CustomSounds Sync", "All sounds have been successfully received!", isWarning: false);
			}
		}

		private string GenerateProgressBar(float progress)
		{
			int num = 26;
			progress = Mathf.Clamp(progress, 0f, 1f);
			int num2 = (int)(progress * (float)num);
			return "[" + new string('#', num2) + new string('-', num - num2) + "] " + (int)(progress * 100f) + "%";
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_AudioNetworkHandler()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(3186703908u, new RpcReceiveHandler(__rpc_handler_3186703908));
			NetworkManager.__rpc_func_table.Add(152710787u, new RpcReceiveHandler(__rpc_handler_152710787));
			NetworkManager.__rpc_func_table.Add(3960362720u, new RpcReceiveHandler(__rpc_handler_3960362720));
			NetworkManager.__rpc_func_table.Add(234624598u, new RpcReceiveHandler(__rpc_handler_234624598));
			NetworkManager.__rpc_func_table.Add(3991320206u, new RpcReceiveHandler(__rpc_handler_3991320206));
			NetworkManager.__rpc_func_table.Add(3131260794u, new RpcReceiveHandler(__rpc_handler_3131260794));
			NetworkManager.__rpc_func_table.Add(1027341762u, new RpcReceiveHandler(__rpc_handler_1027341762));
			NetworkManager.__rpc_func_table.Add(2945580654u, new RpcReceiveHandler(__rpc_handler_2945580654));
			NetworkManager.__rpc_func_table.Add(3964799390u, new RpcReceiveHandler(__rpc_handler_3964799390));
			NetworkManager.__rpc_func_table.Add(3902617409u, new RpcReceiveHandler(__rpc_handler_3902617409));
		}

		private static void __rpc_handler_3186703908(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ulong clientId = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref clientId);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((AudioNetworkHandler)(object)target).RequestSyncClientRpc(clientId);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_152710787(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ServerRpcParams server = rpcParams.Server;
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((AudioNetworkHandler)(object)target).NotifyClientsQueueCompletedServerRpc(server);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3960362720(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;
				((AudioNetworkHandler)(object)target).ForceUnsyncClientsClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_234624598(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;
				((AudioNetworkHandler)(object)target).ProcessLastAudioFileClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3991320206(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Invalid comparison between Unknown and I4
			//IL_00bb: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
				return;
			}
			int num = default(int);
			ByteUnpacker.ReadValueBitPacked(reader, ref num);
			bool flag = default(bool);
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
			string fileName = null;
			if (flag)
			{
				((FastBufferReader)(ref reader)).ReadValueSafe(ref fileName, false);
			}
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((AudioNetworkHandler)(object)target).SendAudioMetaDataToClientsServerRpc(num, fileName);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}

		private static void __rpc_handler_3131260794(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Invalid comparison between Unknown and I4
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
				return;
			}
			bool flag = default(bool);
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
			byte[] audioSegment = null;
			if (flag)
			{
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioSegment, default(ForPrimitives));
			}
			bool flag2 = default(bool);
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
			string audioName = null;
			if (flag2)
			{
				((FastBufferReader)(ref reader)).ReadValueSafe(ref audioName, false);
			}
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((AudioNetworkHandler)(object)target).SendBytesToServerRpc(audioSegment, audioName);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}

		private static void __rpc_handler_1027341762(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_006e: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int num = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref num);
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string fileName = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref fileName, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((AudioNetworkHandler)(object)target).ReceiveAudioMetaDataClientRpc(num, fileName);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2945580654(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_0074: 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_0058: 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_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				byte[] audioSegment = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioSegment, default(ForPrimitives));
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				string audioName = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref audioName, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((AudioNetworkHandler)(object)target).ReceiveBytesClientRpc(audioSegment, audioName);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3964799390(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;
				((AudioNetworkHandler)(object)target).DisplayStartingSyncMessageClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3902617409(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				float progress = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref progress, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((AudioNetworkHandler)(object)target).UpdateProgressClientRpc(progress);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

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

DaMinion-More_Emotes/MoreEmotes1.1.3.dll

Decompiled 6 months ago
using System;
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.InputSystem;

[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.1.3")]
	public class FuckYouModInitialization : BaseUnityPlugin
	{
		private Harmony _harmony;

		private ConfigEntry<string> config_KeyEmote3;

		private ConfigEntry<string> config_KeyEmote4;

		private ConfigEntry<string> config_KeyEmote5;

		private ConfigEntry<string> config_KeyEmote6;

		private ConfigEntry<bool> config_toggleEmote3;

		private ConfigEntry<bool> config_toggleEmote4;

		private ConfigEntry<bool> config_toggleEmote5;

		private ConfigEntry<bool> config_toggleEmote6;

		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()
		{
			config_KeyEmote3 = ((BaseUnityPlugin)this).Config.Bind<string>("MIDDLEFINGER", "EmoteKey", "3", "SUPPORTED KEYS A-Z | 0-9 | F1-F12 ");
			config_toggleEmote3 = ((BaseUnityPlugin)this).Config.Bind<bool>("MIDDLEFINGER", "Enable", true, "ENABLE MIDDLEFINGER EMOTE KEY");
			EmotePatch.keyBind_Emote3 = config_KeyEmote3.Value;
			EmotePatch.enable3 = config_toggleEmote3.Value;
			config_KeyEmote4 = ((BaseUnityPlugin)this).Config.Bind<string>("THE GRIDDY", "EmoteKey", "6", "SUPPORTED KEYS A-Z | 0-9 | F1-F12 ");
			config_toggleEmote4 = ((BaseUnityPlugin)this).Config.Bind<bool>("THE GRIDDY", "Enable", true, "ENABLE THE GRIDDY EMOTE KEY");
			EmotePatch.keyBind_Emote4 = config_KeyEmote4.Value;
			EmotePatch.enable4 = config_toggleEmote4.Value;
			config_KeyEmote5 = ((BaseUnityPlugin)this).Config.Bind<string>("SHY", "EmoteKey", "5", "SUPPORTED KEYS A-Z | 0-9 | F1-F12 ");
			config_toggleEmote5 = ((BaseUnityPlugin)this).Config.Bind<bool>("SHY", "Enable", true, "ENABLE SHY EMOTE KEY");
			EmotePatch.keyBind_Emote5 = config_KeyEmote5.Value;
			EmotePatch.enable5 = config_toggleEmote5.Value;
			config_KeyEmote6 = ((BaseUnityPlugin)this).Config.Bind<string>("CLAP", "EmoteKey", "4", "SUPPORTED KEYS A-Z | 0-9 | F1-F12 ");
			config_toggleEmote6 = ((BaseUnityPlugin)this).Config.Bind<bool>("CLAP", "Enable", true, "ENABLE CLAP EMOTE KEY");
			EmotePatch.keyBind_Emote6 = config_KeyEmote6.Value;
			EmotePatch.enable6 = config_toggleEmote6.Value;
		}
	}
	public static class PluginInfo
	{
		public const string Guid = "MoreEmotes";

		public const string Name = "MoreEmotes-Sligili";

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

		public static AssetBundle animatorBundle;

		public static bool enable3;

		public static bool enable4;

		public static bool enable5;

		public static bool enable6;

		public static string keyBind_Emote3;

		public static string keyBind_Emote4;

		public static string keyBind_Emote5;

		public static string keyBind_Emote6;

		private static CallbackContext context;

		public static RuntimeAnimatorController local;

		public static RuntimeAnimatorController others;

		private static int currentEmoteID;

		private static float svMovSpeed;

		public static bool IncompatibleStuff;

		[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;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(PlayerControllerB __instance)
		{
			if (!__instance.isPlayerControlled || !((NetworkBehaviour)__instance).IsOwner)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = others;
				return;
			}
			if ((Object)(object)__instance.playerBodyAnimator != (Object)(object)local)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = local;
			}
			currentEmoteID = __instance.playerBodyAnimator.GetInteger("emoteNumber");
			if (!IncompatibleStuff)
			{
				bool flag = (bool)Reflection.CallMethod(__instance, "CheckConditionsForEmote") && currentEmoteID == 4 && __instance.performingEmote;
				__instance.movementSpeed = (flag ? (svMovSpeed / 2f) : svMovSpeed);
			}
			CheckEmoteInput(keyBind_Emote3, enable3, needsEmptyHands: false, 3, __instance);
			CheckEmoteInput(keyBind_Emote4, enable4, needsEmptyHands: false, 4, __instance);
			CheckEmoteInput(keyBind_Emote5, enable5, needsEmptyHands: true, 5, __instance);
			CheckEmoteInput(keyBind_Emote6, enable6, needsEmptyHands: true, 6, __instance);
		}

		private static void CheckEmoteInput(string keyBind, bool enabled, bool needsEmptyHands, int emoteID, PlayerControllerB player)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if (InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keyBind], 0f) && enabled && (!player.isHoldingObject || !needsEmptyHands) && (!player.performingEmote || currentEmoteID != emoteID))
			{
				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 == 4)
			{
				__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 || ((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") == 6))
			{
				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") == 4) && ((Vector2)(ref player.moveInputVector)).sqrMagnitude == 0f)
			{
				player.PlayFootstepLocal();
				player.PlayFootstepServer();
			}
		}
	}
}

FlipMods-ReservedFlashlightSlot/ReservedFlashlightSlot.dll

Decompiled 6 months ago
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using ReservedFlashlightSlot.Patches;
using ReservedItemSlotCore;
using ReservedItemSlotCore.Networking;
using ReservedItemSlotCore.Patches;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ReservedFlashlightSlot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReservedFlashlightSlot")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5b7d6563-4e51-4a69-bcf9-fa1dea6eff75")]
[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 ReservedFlashlightSlot
{
	public static class ConfigSettings
	{
		public static ConfigEntry<string> activateFlashlightKey;

		public static ConfigEntry<bool> hideFlashlightMeshShoulder;

		public static string activateFlashlightDisplayName;

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			activateFlashlightKey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedItemSlotCore", "ActivateFlashlightKey", "<Keyboard>/f", "Activate flashlight keybind.");
			hideFlashlightMeshShoulder = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedItemSlotCore", "HideFlashlightOnShoulder", false, "Hides the flashlight mesh while on your shoulder.");
			activateFlashlightDisplayName = GetDisplayName(activateFlashlightKey.Value);
		}

		public static string GetDisplayName(string key)
		{
			key = key.Replace("<Keyboard>/", "");
			key = key.Replace("<Mouse>/", "");
			string text = key;
			text = text.Replace("leftAlt", "Alt");
			text = text.Replace("rightAlt", "Alt");
			text = text.Replace("leftCtrl", "Ctrl");
			text = text.Replace("rightCtrl", "Ctrl");
			text = text.Replace("leftShift", "Shift");
			text = text.Replace("rightShift", "Shift");
			text = text.Replace("leftButton", "LMB");
			text = text.Replace("rightButton", "RMB");
			return text.Replace("middleButton", "MMB");
		}
	}
	[HarmonyPatch]
	internal static class Keybinds
	{
		public static PlayerControllerB localPlayerController;

		private static InputAction activateFlashlightAction;

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void OnLocalPlayerConnect(PlayerControllerB __instance)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			localPlayerController = __instance;
			activateFlashlightAction = new InputAction((string)null, (InputActionType)0, ConfigSettings.activateFlashlightKey.Value, "Press", (string)null, (string)null);
			if (((Component)localPlayerController).gameObject.activeSelf)
			{
				SubscribeToEvents();
			}
		}

		private static void SubscribeToEvents()
		{
			if (activateFlashlightAction != null)
			{
				activateFlashlightAction.Enable();
				activateFlashlightAction.performed += OnActivateFlashlightPerformed;
			}
		}

		[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 (activateFlashlightAction != null && !((Object)(object)__instance != (Object)(object)localPlayerController))
			{
				activateFlashlightAction.performed -= OnActivateFlashlightPerformed;
				activateFlashlightAction.Disable();
			}
		}

		private static void OnActivateFlashlightPerformed(CallbackContext context)
		{
			if ((Object)(object)localPlayerController == (Object)null || !localPlayerController.isPlayerControlled || localPlayerController.inTerminalMenu || (((NetworkBehaviour)localPlayerController).IsServer && !localPlayerController.isHostPlayerObject))
			{
				return;
			}
			FlashlightItem mainFlashlight = ReservedFlashlightSlotPatcher.GetMainFlashlight(localPlayerController);
			if (((CallbackContext)(ref context)).performed && !((Object)(object)mainFlashlight == (Object)null))
			{
				float num = (float)Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").GetValue();
				if (!(num < 0.075f))
				{
					((GrabbableObject)mainFlashlight).UseItemOnClient(!((GrabbableObject)mainFlashlight).isBeingUsed);
					Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0);
				}
			}
		}
	}
	[BepInPlugin("FlipMods.ReservedFlashlightSlot", "ReservedFlashlightSlot", "1.4.5")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		private Harmony _harmony;

		public static ReservedItemInfo proFlashlightInfo = new ReservedItemInfo("Pro-flashlight", 120, true, true, true, true);

		public static ReservedItemInfo flashlightInfo = new ReservedItemInfo("Flashlight", 120, true, true, true, true);

		private void Awake()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			instance = this;
			ConfigSettings.BindConfigSettings();
			_harmony = new Harmony("ReservedFlashlightSlot");
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"ReservedFlashlightSlot loaded");
		}

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

		public const string PLUGIN_NAME = "ReservedFlashlightSlot";

		public const string PLUGIN_VERSION = "1.4.5";
	}
}
namespace ReservedFlashlightSlot.Patches
{
	[HarmonyPatch]
	internal static class ReservedFlashlightSlotPatcher
	{
		private static Vector3 playerShoulderPositionOffset = new Vector3(0.2f, 0f, 0f);

		private static Vector3 playerShoulderRotationOffset = new Vector3(90f, 0f, 0f);

		private static string originalControlTooltip = "";

		public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController;

		public static PlayerControllerB GetPreviousPlayerHeldBy(FlashlightItem flashlightItem)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			return (PlayerControllerB)Traverse.Create((object)flashlightItem).Field("previousPlayerHeldBy").GetValue();
		}

		public static FlashlightItem GetMainFlashlight(PlayerControllerB playerController)
		{
			return GetCurrentlySelectedFlashlight(playerController) ?? GetReservedFlashlight(playerController);
		}

		public static FlashlightItem GetReservedFlashlight(PlayerControllerB playerController)
		{
			GrabbableObject obj = ((playerController != null) ? playerController.ItemSlots[Plugin.flashlightInfo.indexInInventory] : null);
			return (FlashlightItem)(object)((obj is FlashlightItem) ? obj : null);
		}

		public static FlashlightItem GetCurrentlySelectedFlashlight(PlayerControllerB playerController)
		{
			GrabbableObject obj = ((playerController != null) ? playerController.ItemSlots[playerController.currentItemSlot] : null);
			return (FlashlightItem)(object)((obj is FlashlightItem) ? obj : null);
		}

		public static bool IsFlashlightOn(PlayerControllerB playerController)
		{
			return ((GrabbableObject)(GetMainFlashlight(playerController)?)).isBeingUsed ?? false;
		}

		[HarmonyPatch(typeof(FlashlightItem), "__initializeVariables")]
		[HarmonyPostfix]
		public static void EditTooltips(FlashlightItem __instance)
		{
			if (originalControlTooltip == "")
			{
				originalControlTooltip = ((GrabbableObject)__instance).itemProperties.toolTips[((GrabbableObject)__instance).itemProperties.toolTips.Length - 1];
			}
			((GrabbableObject)__instance).itemProperties.toolTips[((GrabbableObject)__instance).itemProperties.toolTips.Length - 1] = $"{originalControlTooltip}[{ConfigSettings.activateFlashlightDisplayName.ToUpper()}]";
		}

		[HarmonyPatch(typeof(MenuManager), "OnEnable")]
		[HarmonyPostfix]
		public static void ResetVariables()
		{
			Keybinds.localPlayerController = null;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_performed")]
		[HarmonyPrefix]
		public static bool PreventActivatingDuplicateItem(CallbackContext context, PlayerControllerB __instance)
		{
			FlashlightItem currentlySelectedFlashlight = GetCurrentlySelectedFlashlight(__instance);
			if ((Object)(object)__instance != (Object)(object)localPlayerController || (Object)(object)currentlySelectedFlashlight == (Object)null)
			{
				return true;
			}
			if (!((CallbackContext)(ref context)).performed)
			{
				return false;
			}
			FlashlightItem reservedFlashlight = GetReservedFlashlight(__instance);
			if ((Object)(object)currentlySelectedFlashlight != (Object)(object)reservedFlashlight && (!((GrabbableObject)reservedFlashlight).itemProperties.requiresBattery || !((GrabbableObject)reservedFlashlight).insertedBattery.empty))
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(FlashlightItem), "SwitchFlashlight")]
		[HarmonyPostfix]
		public static void OnSwitchOnOffFlashlight(bool on, FlashlightItem __instance)
		{
			if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null))
			{
				UpdateAllFlashlightStates(((GrabbableObject)__instance).playerHeldBy, on);
			}
		}

		[HarmonyPatch(typeof(FlashlightItem), "PocketItem")]
		[HarmonyPostfix]
		public static void OnPocketFlashlightLocal(FlashlightItem __instance)
		{
			OnPocketFlashlight(__instance, ((GrabbableObject)__instance).isBeingUsed);
		}

		[HarmonyPatch(typeof(FlashlightItem), "PocketFlashlightClientRpc")]
		[HarmonyPrefix]
		public static bool OnPocketFlashlightClientRpc(bool stillUsingFlashlight, FlashlightItem __instance)
		{
			if (!NetworkHelper.IsValidClientRpcExecStage((NetworkBehaviour)(object)__instance) || ((NetworkBehaviour)__instance).IsOwner || (Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null || (Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController || !NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance))
			{
				return false;
			}
			((MonoBehaviour)__instance).StartCoroutine(OnPocketFlashlightEndOfFrame(__instance, stillUsingFlashlight));
			return true;
		}

		private static IEnumerator OnPocketFlashlightEndOfFrame(FlashlightItem flashlightItem, bool stillUsingFlashlight)
		{
			yield return (object)new WaitForEndOfFrame();
			OnPocketFlashlight(flashlightItem, stillUsingFlashlight);
		}

		private static void OnPocketFlashlight(FlashlightItem flashlightItem, bool stillUsingFlashlight = false)
		{
			if (!((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)null))
			{
				((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)flashlightItem;
				((GrabbableObject)flashlightItem).parentObject = ((GrabbableObject)flashlightItem).playerHeldBy.playerGlobalHead;
				bool flag = (Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)(object)localPlayerController;
			}
		}

		[HarmonyPatch(typeof(FlashlightItem), "EquipItem")]
		[HarmonyPostfix]
		public static void OnEquipFlashlight(FlashlightItem __instance)
		{
			if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null))
			{
				if ((Object)(object)__instance == (Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight)
				{
					((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight = null;
				}
				((GrabbableObject)__instance).parentObject = (((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController) ? ((GrabbableObject)__instance).playerHeldBy.localItemHolder : ((GrabbableObject)__instance).playerHeldBy.serverItemHolder);
			}
		}

		[HarmonyPatch(typeof(GrabbableObject), "LateUpdate")]
		[HarmonyPostfix]
		public static void SetPositionOffset(GrabbableObject __instance)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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)
			if (__instance is FlashlightItem && (Object)(object)__instance.playerHeldBy != (Object)null && __instance.isPocketed && (Object)(object)__instance.parentObject != (Object)null && (Object)(object)__instance != (Object)(object)GetCurrentlySelectedFlashlight(__instance.playerHeldBy))
			{
				Transform transform = ((Component)__instance.parentObject).transform;
				((Component)__instance).transform.rotation = ((Component)__instance.parentObject).transform.rotation * Quaternion.Euler(playerShoulderRotationOffset);
				((Component)__instance).transform.position = transform.position + transform.rotation * playerShoulderPositionOffset;
			}
		}

		[HarmonyPatch(typeof(GrabbableObject), "EnableItemMeshes")]
		[HarmonyPrefix]
		public static void OnEnableItemMeshes(ref bool enable, GrabbableObject __instance)
		{
			if (__instance is FlashlightItem && (Object)(object)__instance.playerHeldBy != (Object)null && ((Object)(object)__instance == (Object)(object)GetCurrentlySelectedFlashlight(__instance.playerHeldBy) || ((Object)(object)__instance == (Object)(object)GetReservedFlashlight(__instance.playerHeldBy) && (Object)(object)__instance.playerHeldBy != (Object)(object)localPlayerController)))
			{
				enable = true;
			}
		}

		private static void UpdateAllFlashlightStates(PlayerControllerB playerController, bool mainFlashlightActive = true)
		{
			FlashlightItem mainFlashlight = GetMainFlashlight(playerController);
			if ((Object)(object)mainFlashlight == (Object)null)
			{
				((Behaviour)playerController.helmetLight).enabled = false;
				mainFlashlightActive = false;
			}
			else
			{
				playerController.ChangeHelmetLight(mainFlashlight.flashlightTypeID, mainFlashlightActive && (Object)(object)playerController == (Object)(object)localPlayerController && (Object)(object)playerController.ItemSlots[playerController.currentItemSlot] != (Object)(object)mainFlashlight);
			}
			for (int i = 0; i < PlayerPatcher.combinedHotbarSize; i++)
			{
				GrabbableObject obj = playerController.ItemSlots[i];
				FlashlightItem val = (FlashlightItem)(object)((obj is FlashlightItem) ? obj : null);
				if ((Object)(object)val != (Object)null)
				{
					UpdateFlashlightState(val, (Object)(object)val == (Object)(object)mainFlashlight && mainFlashlightActive);
				}
			}
		}

		private static void UpdateFlashlightState(FlashlightItem flashlightItem, bool active)
		{
			if (!((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)null))
			{
				PlayerControllerB playerHeldBy = ((GrabbableObject)flashlightItem).playerHeldBy;
				((GrabbableObject)flashlightItem).isBeingUsed = active;
				bool flag = (Object)(object)playerHeldBy != (Object)(object)localPlayerController || (Object)(object)playerHeldBy.ItemSlots[playerHeldBy.currentItemSlot] == (Object)(object)flashlightItem;
				((Behaviour)flashlightItem.flashlightBulb).enabled = active && flag;
				((Behaviour)flashlightItem.flashlightBulbGlow).enabled = active && flag;
				flashlightItem.usingPlayerHelmetLight = active && !flag;
			}
		}
	}
}

FlipMods-ReservedItemSlotCore/ReservedItemSlotCore.dll

Decompiled 6 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using ReservedItemSlotCore.Networking;
using ReservedItemSlotCore.Patches;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
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("ReservedItemSlotCore")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReservedItemSlotCore")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("238ce080-e339-46b6-9b08-992a950453a1")]
[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 ReservedItemSlotCore
{
	public static class ConfigSettings
	{
		public static ConfigEntry<string> focusReservedHotbarHotkey;

		public static ConfigEntry<string> specialReservedItemUseHotkey;

		public static string focusReservedHotbarHotkeyDisplayName;

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			focusReservedHotbarHotkey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedItemSlotCore", "FocusReservedItemSlotsHotkey", "<Keyboard>/leftAlt", "Which key will focus your reserved item slots hotbar to allow selcting, dropping, charging, etc.");
			specialReservedItemUseHotkey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedItemSlotCore", "SpecialReservedItemUseHotkey", "<Mouse>/middleButton", "[REMOVED] Which key will focus your reserved item slots hotbar to allow selcting, dropping, charging, etc.");
			focusReservedHotbarHotkeyDisplayName = GetDisplayName(focusReservedHotbarHotkey.Value);
		}

		public static string GetDisplayName(string key)
		{
			key = key.Replace("<Keyboard>/", "");
			key = key.Replace("<Mouse>/", "");
			string text = key;
			text = text.Replace("leftAlt", "Alt");
			text = text.Replace("rightAlt", "Alt");
			text = text.Replace("leftCtrl", "Ctrl");
			text = text.Replace("rightCtrl", "Ctrl");
			text = text.Replace("leftShift", "Shift");
			text = text.Replace("rightShift", "Shift");
			text = text.Replace("leftButton", "LMB");
			text = text.Replace("rightButton", "RMB");
			return text.Replace("middleButton", "MMB");
		}
	}
	[HarmonyPatch]
	internal static class HotbarSlotSync
	{
		public static PlayerControllerB localPlayerController;

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void Init(PlayerControllerB __instance)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			localPlayerController = __instance;
			NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("OnSwapHotbarClientRpc", new HandleNamedMessageDelegate(OnSwapHotbarClientRpc));
			if (NetworkManager.Singleton.IsServer)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("OnSwapHotbarServerRpc", new HandleNamedMessageDelegate(OnSwapHotbarServerRpc));
			}
		}

		private static void SendSwapHotbarUpdate(int hotbarSlot)
		{
			//IL_0038: 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_0056: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsClient)
			{
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1);
				try
				{
					Plugin.Log("Sending hotbar swap slot: " + hotbarSlot);
					((FastBufferWriter)(ref val)).WriteValue<int>(ref hotbarSlot, default(ForPrimitives));
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("OnSwapHotbarServerRpc", 0uL, val, (NetworkDelivery)3);
					return;
				}
				finally
				{
					((IDisposable)(FastBufferWriter)(ref val)).Dispose();
				}
			}
			Plugin.Log("Failed to send hotbar swap index.");
		}

		private static void OnSwapHotbarServerRpc(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_006f: 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_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)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer)
			{
				return;
			}
			if (((FastBufferReader)(ref reader)).TryBeginRead(4))
			{
				int num = default(int);
				((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives));
				Plugin.Log("Receiving request for hotbar swap. Slot: " + num + " ClientId: " + clientId);
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(12, (Allocator)2, -1);
				try
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref clientId, default(ForPrimitives));
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("OnSwapHotbarClientRpc", val, (NetworkDelivery)3);
					return;
				}
				finally
				{
					((IDisposable)(FastBufferWriter)(ref val)).Dispose();
				}
			}
			Plugin.Log("Failed to receive hotbar swap index from Client: " + clientId);
		}

		private static void OnSwapHotbarClientRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_002e: 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_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)
			{
				return;
			}
			if (((FastBufferReader)(ref reader)).TryBeginRead(12))
			{
				int hotbarSlot = default(int);
				((FastBufferReader)(ref reader)).ReadValue<int>(ref hotbarSlot, default(ForPrimitives));
				ulong num = default(ulong);
				((FastBufferReader)(ref reader)).ReadValue<ulong>(ref num, default(ForPrimitives));
				Plugin.Log("Receiving update for hotbar swap. Slot: " + hotbarSlot + " ClientId: " + num);
				if (num == localPlayerController.actualClientId || UpdateClientHotbarSlot(num, hotbarSlot))
				{
					return;
				}
				Plugin.Log("Failed to receive hotbar swap index from Client: " + num);
			}
			Plugin.Log("Failed to receive hotbar swap index from Client");
		}

		private static bool UpdateClientHotbarSlot(ulong clientId, int hotbarSlot)
		{
			Plugin.Log("Updating hotbar slot: " + hotbarSlot + " ClientId: " + clientId);
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				if (StartOfRound.Instance.allPlayerScripts[i].actualClientId == clientId)
				{
					CallSwitchToItemSlotMethod(StartOfRound.Instance.allPlayerScripts[i], hotbarSlot);
					return true;
				}
			}
			return false;
		}

		public static void SwapHotbarSlot(int hotbarIndex)
		{
			SendSwapHotbarUpdate(hotbarIndex);
			CallSwitchToItemSlotMethod(localPlayerController, hotbarIndex);
			Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0);
		}

		private static void CallSwitchToItemSlotMethod(PlayerControllerB playerController, int hotbarIndex)
		{
			ShipBuildModeManager.Instance.CancelBuildMode(true);
			MethodInfo method = ((object)playerController).GetType().GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic);
			method.Invoke(playerController, new object[2] { hotbarIndex, null });
			if ((Object)(object)playerController.currentlyHeldObjectServer != (Object)null)
			{
				((Component)playerController.currentlyHeldObjectServer).gameObject.GetComponent<AudioSource>().PlayOneShot(playerController.currentlyHeldObjectServer.itemProperties.grabSFX, 0.6f);
			}
		}
	}
	[HarmonyPatch]
	internal static class Keybinds
	{
		public static PlayerControllerB localPlayerController;

		public static InputAction focusReservedHotbarAction;

		public static bool holdingModifierKey;

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void OnLocalPlayerConnect(PlayerControllerB __instance)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			localPlayerController = __instance;
			focusReservedHotbarAction = new InputAction((string)null, (InputActionType)0, ConfigSettings.focusReservedHotbarHotkey.Value, (string)null, (string)null, (string)null);
			if (((Component)localPlayerController).gameObject.activeSelf)
			{
				SubscribeToEvents();
			}
		}

		private static void SubscribeToEvents()
		{
			if (focusReservedHotbarAction != null && Plugin.numReservedItemSlots > 0)
			{
				focusReservedHotbarAction.performed += FocusReservedHotbarSlotsAction;
				focusReservedHotbarAction.canceled += UnfocusReservedHotbarSlotsPerformed;
				focusReservedHotbarAction.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 (focusReservedHotbarAction != null && Plugin.numReservedItemSlots > 0 && !((Object)(object)__instance != (Object)(object)localPlayerController))
			{
				focusReservedHotbarAction.performed -= FocusReservedHotbarSlotsAction;
				focusReservedHotbarAction.canceled -= UnfocusReservedHotbarSlotsPerformed;
				focusReservedHotbarAction.Disable();
			}
		}

		private static void FocusReservedHotbarSlotsAction(CallbackContext context)
		{
			if (!((Object)(object)localPlayerController == (Object)null) && !((Object)(object)localPlayerController == (Object)null) && ((NetworkBehaviour)localPlayerController).IsOwner && localPlayerController.isPlayerControlled && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject))
			{
				holdingModifierKey = true;
				bool flag = (bool)Traverse.Create((object)localPlayerController).Field("throwingObject").GetValue();
				if (!(localPlayerController.inTerminalMenu || localPlayerController.isPlayerDead || localPlayerController.isGrabbingObjectAnimation || localPlayerController.inSpecialInteractAnimation || flag) && !localPlayerController.isTypingChat && !localPlayerController.twoHanded && !localPlayerController.activatingItem && ((CallbackContext)(ref context)).performed)
				{
					ReservedItemPatcher.SetFocusReservedHotbarSlots(active: true);
				}
			}
		}

		private static void UnfocusReservedHotbarSlotsPerformed(CallbackContext context)
		{
			if (!((Object)(object)localPlayerController == (Object)null) && ((NetworkBehaviour)localPlayerController).IsOwner && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject))
			{
				holdingModifierKey = false;
				if (ReservedItemPatcher.CanSwapToReservedHotbarSlot() && ((CallbackContext)(ref context)).canceled)
				{
					ReservedItemPatcher.SetFocusReservedHotbarSlots(active: false);
				}
			}
		}
	}
	[BepInPlugin("FlipMods.ReservedItemSlotCore", "ReservedItemSlotCore", "1.4.4")]
	public class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		public static Plugin instance;

		public static Dictionary<string, ReservedItemInfo> reservedItemsDict => ReservedItemInfo.reservedItemsDict;

		public static List<ReservedItemInfo> reservedItemsList => ReservedItemInfo.reservedItemsList;

		public static List<ReservedItemInfo> reservedItemSlotReps => ReservedItemInfo.reservedItemSlotReps;

		public static int numReservedItemSlots => ReservedItemInfo.numReservedItemSlots;

		private void Awake()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			instance = this;
			_harmony = new Harmony("ReservedItemSlotCore");
			ConfigSettings.BindConfigSettings();
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"ReservedItemSlotCore loaded");
		}

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

		public static bool IsReservedItem(string itemName)
		{
			return reservedItemsDict.ContainsKey(itemName);
		}

		public static ReservedItemInfo GetReservedItemInfo(string itemName)
		{
			return IsReservedItem(itemName) ? reservedItemsDict[itemName] : null;
		}

		public static ReservedItemInfo GetReservedItemInfo(GrabbableObject item)
		{
			return ((Object)(object)item != (Object)null) ? GetReservedItemInfo(item.itemProperties.itemName) : null;
		}

		public static int GetReservedItemHotbarIndex(string itemName)
		{
			return IsReservedItem(itemName) ? reservedItemsDict[itemName].indexInInventory : (-1);
		}
	}
	public class ReservedItemInfo
	{
		public static Dictionary<string, ReservedItemInfo> reservedItemsDict = new Dictionary<string, ReservedItemInfo>();

		public static List<ReservedItemInfo> reservedItemsList = new List<ReservedItemInfo>();

		public static List<ReservedItemInfo> reservedItemSlotReps = new List<ReservedItemInfo>();

		public static int defaultHotbarSlotPriority = 10;

		public static int currentUndefinedHotbarSlotPriority = 0;

		public string itemName;

		public int hotbarSlotPriority;

		private int undefinedHotbarSlotPriority = -1;

		public int reservedItemIndex;

		public bool forceUpdateCanBeGrabbedBeforeGameStart = false;

		public bool canBeGrabbedBeforeGameStart = false;

		public bool forceUpdateRequiresBattery = false;

		public bool requiresBattery = false;

		public static int numReservedItemSlots => reservedItemSlotReps.Count;

		public int indexInInventory => ((Object)(object)PlayerPatcher.localPlayerController != (Object)null) ? (PlayerPatcher.localPlayerController.ItemSlots.Length - (numReservedItemSlots - reservedItemIndex)) : (-1);

		public ReservedItemInfo(string itemName, int hotbarSlotPriority = -1, bool forceUpdateCanBeGrabbedBeforeGameStart = false, bool canBeGrabbedBeforeGameStart = false, bool forceUpdateRequiresBattery = false, bool requiresBattery = false)
		{
			this.itemName = itemName;
			this.forceUpdateCanBeGrabbedBeforeGameStart = forceUpdateCanBeGrabbedBeforeGameStart;
			this.canBeGrabbedBeforeGameStart = canBeGrabbedBeforeGameStart;
			this.forceUpdateRequiresBattery = forceUpdateRequiresBattery;
			this.requiresBattery = requiresBattery;
			if (hotbarSlotPriority != -1)
			{
				this.hotbarSlotPriority = hotbarSlotPriority;
			}
			else
			{
				this.hotbarSlotPriority = defaultHotbarSlotPriority;
				undefinedHotbarSlotPriority = ++currentUndefinedHotbarSlotPriority;
			}
			if (!reservedItemsDict.ContainsKey(this.itemName))
			{
				reservedItemsDict.Add(this.itemName, this);
				reservedItemsList.Add(this);
				int i;
				for (i = 0; i < reservedItemSlotReps.Count; i++)
				{
					ReservedItemInfo reservedItemInfo = reservedItemSlotReps[i];
					if (this.hotbarSlotPriority == reservedItemInfo.hotbarSlotPriority)
					{
						if (undefinedHotbarSlotPriority == reservedItemInfo.undefinedHotbarSlotPriority)
						{
							i = -1;
						}
						break;
					}
					if (this.hotbarSlotPriority > reservedItemInfo.hotbarSlotPriority)
					{
						break;
					}
				}
				if (i >= 0)
				{
					reservedItemIndex = i;
					reservedItemSlotReps.Insert(i, this);
					for (int j = i + 1; j < reservedItemSlotReps.Count; j++)
					{
						reservedItemSlotReps[j].reservedItemIndex = j;
					}
				}
			}
			else
			{
				Plugin.Log($"Tried to add duplicate item name to the ReservedItems list: {this.itemName}");
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FlipMods.ReservedItemSlotCore";

		public const string PLUGIN_NAME = "ReservedItemSlotCore";

		public const string PLUGIN_VERSION = "1.4.4";
	}
}
namespace ReservedItemSlotCore.Networking
{
	public static class NetworkHelper
	{
		private static int NONE_EXEC_STAGE = 0;

		private static int SERVER_EXEC_STAGE = 1;

		private static int CLIENT_EXEC_STAGE = 2;

		public static int GetExecStage(NetworkBehaviour __instance)
		{
			return (int)Traverse.Create((object)__instance).Field("__rpc_exec_stage").GetValue();
		}

		public static bool IsClientExecStage(NetworkBehaviour __instance)
		{
			return GetExecStage(__instance) == CLIENT_EXEC_STAGE;
		}

		public static bool IsServerExecStage(NetworkBehaviour __instance)
		{
			return GetExecStage(__instance) == SERVER_EXEC_STAGE;
		}

		public static bool IsValidClientRpcExecStage(NetworkBehaviour __instance)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
			{
				return false;
			}
			int num = (int)Traverse.Create((object)__instance).Field("__rpc_exec_stage").GetValue();
			if ((singleton.IsServer || singleton.IsHost) && num != 2)
			{
				return false;
			}
			return true;
		}
	}
}
namespace ReservedItemSlotCore.Patches
{
	[HarmonyPatch]
	public static class HUDPatcher
	{
		private static CanvasScaler canvasScaler;

		private static AspectRatioFitter aspectRatioFitter;

		private static float iconWidth;

		private static float xPos;

		[HarmonyPatch(typeof(HUDManager), "Awake")]
		[HarmonyPrefix]
		public static void Initialize(HUDManager __instance)
		{
			//IL_0032: 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)
			canvasScaler = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<CanvasScaler>();
			aspectRatioFitter = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<AspectRatioFitter>();
			iconWidth = ((Component)__instance.itemSlotIconFrames[0]).GetComponent<RectTransform>().sizeDelta.x;
			xPos = canvasScaler.referenceResolution.x / 2f / aspectRatioFitter.aspectRatio - iconWidth / 4f;
		}

		[HarmonyPatch(typeof(HUDManager), "Start")]
		[HarmonyPostfix]
		public static void AddNewHotbarSlotsHud(HUDManager __instance)
		{
			//IL_0040: 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_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: 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_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: 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)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			if (PlayerPatcher.reservedHotbarSize > 0)
			{
				List<Image> list = new List<Image>(__instance.itemSlotIconFrames);
				List<Image> list2 = new List<Image>(__instance.itemSlotIcons);
				float y = ((Component)HUDManager.Instance.itemSlotIconFrames[0]).GetComponent<RectTransform>().sizeDelta.y;
				Vector3 eulerAngles = ((Transform)((Component)HUDManager.Instance.itemSlotIconFrames[0]).GetComponent<RectTransform>()).eulerAngles;
				Vector3 eulerAngles2 = ((Transform)((Component)HUDManager.Instance.itemSlotIcons[0]).GetComponent<RectTransform>()).eulerAngles;
				Plugin.Log($"Adding {ReservedItemInfo.reservedItemsList.Count} Reserved Item slots to the inventory HUD. Previous inventory HUD size: {PlayerPatcher.unreservedHotbarSize}");
				for (int i = 0; i < Plugin.reservedItemSlotReps.Count; i++)
				{
					ReservedItemInfo reservedItemInfo = Plugin.reservedItemSlotReps[i];
					Plugin.Log($"Adding Reserved Item slot for item types [{reservedItemInfo.itemName}]. Inventory index: {list.Count}");
					float num = ((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.anchoredPosition.y + 1.125f * y * (float)i;
					Image val = Object.Instantiate<Image>(HUDManager.Instance.itemSlotIconFrames[PlayerPatcher.unreservedHotbarSize - 1], ((Component)HUDManager.Instance.itemSlotIconFrames[0]).transform.parent);
					((Object)val).name = $"ReservedItemSlot{i} [{reservedItemInfo.itemName}]";
					((Graphic)val).rectTransform.anchoredPosition = new Vector2(xPos, num);
					((Transform)((Graphic)val).rectTransform).eulerAngles = eulerAngles;
					CanvasGroup val2 = ((Component)val).gameObject.AddComponent<CanvasGroup>();
					val2.ignoreParentGroups = true;
					val2.alpha = 1f;
					Image component = ((Component)((Component)val).transform.GetChild(0)).GetComponent<Image>();
					((Object)component).name = "Icon";
					((Transform)((Graphic)component).rectTransform).eulerAngles = eulerAngles2;
					list.Add(val);
					list2.Add(component);
				}
				if (Plugin.numReservedItemSlots > 0)
				{
					TextMeshProUGUI component2 = new GameObject("ReservedItemSlotTooltip", new Type[2]
					{
						typeof(RectTransform),
						typeof(TextMeshProUGUI)
					}).GetComponent<TextMeshProUGUI>();
					RectTransform rectTransform = ((TMP_Text)component2).rectTransform;
					((Component)rectTransform).transform.parent = ((Component)list[PlayerPatcher.unreservedHotbarSize]).transform;
					((Transform)rectTransform).localScale = Vector3.one;
					rectTransform.sizeDelta = new Vector2(((Graphic)list[0]).rectTransform.sizeDelta.x * 2f, 10f);
					rectTransform.pivot = Vector2.one / 2f;
					rectTransform.anchoredPosition3D = new Vector3(0f, (0f - rectTransform.sizeDelta.x / 2f) * 1.2f, 0f);
					((TMP_Text)component2).font = ((TMP_Text)__instance.controlTipLines[0]).font;
					((TMP_Text)component2).fontSize = 7f;
					((TMP_Text)component2).alignment = (TextAlignmentOptions)514;
					((TMP_Text)component2).text = string.Format($"Hold: [{ConfigSettings.GetDisplayName(ConfigSettings.focusReservedHotbarHotkey.Value)}]");
				}
				__instance.itemSlotIconFrames = list.ToArray();
				__instance.itemSlotIcons = list2.ToArray();
				Plugin.Log($"Finished adding {PlayerPatcher.reservedHotbarSize} Reserved Item slots in the inventory HUD.");
			}
		}
	}
	[HarmonyPatch]
	public static class ReservedItemPatcher
	{
		public static bool isReservedHotbarFocused;

		public static int indexUnfocusedReservedHotbar;

		public static int indexFocusedReservedHotbar;

		public static Dictionary<PlayerControllerB, ReservedItemInfo> grabbingReservedItemInfoDict;

		private static GrabbableObject previouslyHeldObjectServer;

		public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController;

		public static int unreservedHotbarSize => PlayerPatcher.unreservedHotbarSize;

		public static int reservedHotbarSize => Plugin.numReservedItemSlots;

		public static int combinedHotbarSize => PlayerPatcher.combinedHotbarSize;

		public static ReservedItemInfo grabbingReservedItemInfoLocal
		{
			get
			{
				return ((Object)(object)localPlayerController != (Object)null) ? grabbingReservedItemInfoDict[localPlayerController] : null;
			}
			set
			{
				if (!((Object)(object)localPlayerController == (Object)null))
				{
					grabbingReservedItemInfoDict[localPlayerController] = value;
				}
			}
		}

		[HarmonyPatch(typeof(MenuManager), "OnEnable")]
		[HarmonyPrefix]
		public static void ResetVariables(MenuManager __instance)
		{
			if (grabbingReservedItemInfoDict == null)
			{
				grabbingReservedItemInfoDict = new Dictionary<PlayerControllerB, ReservedItemInfo>();
			}
			if (grabbingReservedItemInfoDict.Count > 0)
			{
				grabbingReservedItemInfoDict.Clear();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPrefix]
		public static void OnLocalPlayerConnect(PlayerControllerB __instance)
		{
			grabbingReservedItemInfoDict[__instance] = null;
		}

		private static GrabbableObject GetCurrentlyGrabbingObject(PlayerControllerB playerController)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			return (GrabbableObject)Traverse.Create((object)playerController).Field("currentlyGrabbingObject").GetValue();
		}

		private static void SetCurrentlyGrabbingObject(PlayerControllerB playerController, GrabbableObject grabbable)
		{
			Traverse.Create((object)playerController).Field("currentlyGrabbingObject").SetValue((object)grabbable);
		}

		[HarmonyPatch(typeof(PlayerControllerB), "BeginGrabObject")]
		[HarmonyPrefix]
		public static bool GrabReservedItemPrefix(PlayerControllerB __instance)
		{
			//IL_0021: 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_003b: 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_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Expected O, but got Unknown
			if (isReservedHotbarFocused)
			{
				return false;
			}
			Ray val = default(Ray);
			((Ray)(ref val))..ctor(((Component)__instance.gameplayCamera).transform.position, ((Component)__instance.gameplayCamera).transform.forward);
			RaycastHit val2 = default(RaycastHit);
			if (!Physics.Raycast(val, ref val2, __instance.grabDistance, PlayerPatcher.INTERACTABLE_OBJECT_MASK) || ((Component)((RaycastHit)(ref val2)).collider).gameObject.layer == 8 || !(((Component)((RaycastHit)(ref val2)).collider).tag == "PhysicsProp") || __instance.twoHanded || __instance.sinkingValue > 0.73f)
			{
				grabbingReservedItemInfoLocal = null;
				return true;
			}
			GrabbableObject component = ((Component)((Component)((RaycastHit)(ref val2)).collider).transform).gameObject.GetComponent<GrabbableObject>();
			grabbingReservedItemInfoLocal = Plugin.GetReservedItemInfo(component);
			if (grabbingReservedItemInfoLocal == null)
			{
				return true;
			}
			if (!GameNetworkManager.Instance.gameHasStarted && !component.itemProperties.canBeGrabbedBeforeGameStart && !StartOfRound.Instance.testRoom.activeSelf)
			{
				return false;
			}
			Traverse.Create((object)__instance).Field("grabInvalidated").SetValue((object)false);
			SetCurrentlyGrabbingObject(__instance, component);
			if (__instance.inSpecialInteractAnimation || component.isHeld || component.isPocketed)
			{
				return false;
			}
			NetworkObject networkObject = ((NetworkBehaviour)component).NetworkObject;
			if ((Object)(object)networkObject == (Object)null || !networkObject.IsSpawned)
			{
				return false;
			}
			if (grabbingReservedItemInfoLocal == null || !IsItemSlotEmpty(grabbingReservedItemInfoLocal))
			{
				return true;
			}
			((Behaviour)__instance.cursorIcon).enabled = false;
			((TMP_Text)__instance.cursorTip).text = "";
			__instance.twoHanded = component.itemProperties.twoHanded;
			__instance.carryWeight += Mathf.Clamp(component.itemProperties.weight - 1f, 0f, 10f);
			__instance.grabObjectAnimationTime = 0f;
			MethodInfo method = ((object)__instance).GetType().GetMethod("GrabObjectServerRpc", BindingFlags.Instance | BindingFlags.NonPublic);
			method.Invoke(__instance, new object[1] { NetworkObjectReference.op_Implicit(networkObject) });
			Coroutine val3 = (Coroutine)Traverse.Create((object)__instance).Field("grabObjectCoroutine").GetValue();
			if (val3 != null)
			{
				((MonoBehaviour)__instance).StopCoroutine(val3);
			}
			MethodInfo method2 = ((object)__instance).GetType().GetMethod("GrabObject", BindingFlags.Instance | BindingFlags.NonPublic);
			val3 = ((MonoBehaviour)__instance).StartCoroutine((IEnumerator)method2.Invoke(__instance, new object[0]));
			Traverse.Create((object)__instance).Field("grabObjectCoroutine").SetValue((object)val3);
			return false;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")]
		[HarmonyPrefix]
		public static bool GrabReservedItemClientRpcPrefix(bool grabValidated, NetworkObjectReference grabbedObject, PlayerControllerB __instance)
		{
			if (!NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance))
			{
				return true;
			}
			if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsListening)
			{
				if (grabValidated)
				{
					NetworkObject val = default(NetworkObject);
					if (((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null))
					{
						GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
						ReservedItemInfo reservedItemInfo = Plugin.GetReservedItemInfo(component);
						if (reservedItemInfo != null && IsItemSlotEmpty(reservedItemInfo, __instance))
						{
							__instance.ItemSlots[reservedItemInfo.indexInInventory] = component;
							component.playerHeldBy = __instance;
							component.isHeld = true;
							component.EnablePhysics(false);
							component.hasHitGround = false;
							component.isInFactory = __instance.isInsideFactory;
							component.EnableItemMeshes(false);
							Traverse.Create((object)component).Field("previousPlayerHeldBy").SetValue((object)__instance);
							component.PocketItem();
							if ((Object)(object)__instance != (Object)(object)localPlayerController)
							{
								Plugin.Log("Grab object completed on player: " + ((Object)__instance).name);
								if ((Object)(object)component.itemProperties.grabSFX != (Object)null)
								{
									__instance.itemAudio.PlayOneShot(component.itemProperties.grabSFX, 1f);
								}
								grabbingReservedItemInfoDict[__instance] = null;
							}
							else
							{
								HUDManager.Instance.itemSlotIcons[reservedItemInfo.indexInInventory].sprite = component.itemProperties.itemIcon;
								((Behaviour)HUDManager.Instance.itemSlotIcons[reservedItemInfo.indexInInventory]).enabled = true;
								HUDManager.Instance.PingHUDElement(HUDManager.Instance.Inventory, 1.5f, 1f, 0.13f);
								previouslyHeldObjectServer = localPlayerController.currentlyHeldObjectServer;
								localPlayerController.currentlyHeldObjectServer = component;
							}
							return false;
						}
					}
				}
				else if ((Object)(object)__instance == (Object)(object)localPlayerController)
				{
					Plugin.Log("Failed to validate ReservedItemGrab by the local player. Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + ".");
					Traverse.Create((object)localPlayerController).Field("grabInvalidated").SetValue((object)true);
				}
				else
				{
					Plugin.Log("Failed to validate ReservedItemGrab by player with id: " + ((Object)__instance).name + ". Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + ".");
				}
			}
			grabbingReservedItemInfoDict[__instance] = null;
			return true;
		}

		[HarmonyPatch(typeof(GrabbableObject), "GrabItemOnClient")]
		[HarmonyPrefix]
		public static void OnReservedItemGrabbed(GrabbableObject __instance)
		{
			if (grabbingReservedItemInfoLocal != null && !((Object)(object)__instance != (Object)(object)GetCurrentlyGrabbingObject(localPlayerController)))
			{
				OnLocalPlayerGrabbedReservedItem();
				__instance.PocketItem();
			}
		}

		private static void OnLocalPlayerGrabbedReservedItem()
		{
			localPlayerController.currentlyHeldObjectServer = previouslyHeldObjectServer;
			previouslyHeldObjectServer = null;
			grabbingReservedItemInfoLocal = null;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "FirstEmptyItemSlot")]
		[HarmonyPostfix]
		public static void GetReservedItemSlotPlacementIndex(ref int __result, PlayerControllerB __instance)
		{
			ReservedItemInfo reservedItemInfo = grabbingReservedItemInfoDict[__instance];
			if (reservedItemInfo != null)
			{
				if (__result == reservedItemInfo.indexInInventory && IsItemSlotEmpty(reservedItemInfo, __instance))
				{
					return;
				}
				grabbingReservedItemInfoDict[__instance] = null;
			}
			if (__result < unreservedHotbarSize)
			{
				return;
			}
			__result = -1;
			for (int i = 0; i < unreservedHotbarSize; i++)
			{
				if ((Object)(object)__instance.ItemSlots[i] == (Object)null)
				{
					__result = i;
					break;
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "NextItemSlot")]
		[HarmonyPrefix]
		public static bool PreventScrollingOtherHotbar(ref int __result, bool forward, PlayerControllerB __instance)
		{
			__result = __instance.currentItemSlot;
			bool flag = __instance.currentItemSlot >= unreservedHotbarSize;
			int num = (forward ? 1 : (-1));
			if (!flag)
			{
				__result = Mathf.Clamp(__result, 0, unreservedHotbarSize - 1) + num;
				if (__result < 0)
				{
					__result = unreservedHotbarSize - 1;
				}
				else if (__result >= unreservedHotbarSize)
				{
					__result = 0;
				}
			}
			else
			{
				__result = Mathf.Clamp(__result, unreservedHotbarSize, combinedHotbarSize - 1) + num;
				if (__result < unreservedHotbarSize)
				{
					__result = combinedHotbarSize - 1;
				}
				else if (__result >= combinedHotbarSize)
				{
					__result = unreservedHotbarSize;
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")]
		[HarmonyPrefix]
		public static void RefocusReservedHotbarAfterAnimation(PlayerControllerB __instance)
		{
			if (!((Object)(object)__instance != (Object)(object)localPlayerController) && Keybinds.holdingModifierKey != isReservedHotbarFocused && CanSwapToReservedHotbarSlot())
			{
				SetFocusReservedHotbarSlots(Keybinds.holdingModifierKey);
			}
		}

		public static bool CanSwapToReservedHotbarSlot()
		{
			bool flag = (bool)Traverse.Create((object)localPlayerController).Field("throwingObject").GetValue();
			return !(localPlayerController.inTerminalMenu || localPlayerController.isPlayerDead || localPlayerController.isGrabbingObjectAnimation || localPlayerController.inSpecialInteractAnimation || flag) && !localPlayerController.isTypingChat && !localPlayerController.twoHanded && !localPlayerController.activatingItem;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "UpdateSpecialAnimationValue")]
		[HarmonyPostfix]
		public static void OnSpecialAnimationUpdate(bool specialAnimation, PlayerControllerB __instance, short yVal = 0, float timed = 0f, bool climbingLadder = false)
		{
			if (!((Object)(object)__instance != (Object)(object)localPlayerController))
			{
				if (specialAnimation && isReservedHotbarFocused)
				{
					SetFocusReservedHotbarSlots(active: false);
				}
				if (!specialAnimation && isReservedHotbarFocused != Keybinds.holdingModifierKey)
				{
					SetFocusReservedHotbarSlots(Keybinds.holdingModifierKey);
				}
			}
		}

		public static void SetFocusReservedHotbarSlots(bool active)
		{
			if (reservedHotbarSize <= 0 || isReservedHotbarFocused == active)
			{
				return;
			}
			Plugin.Log("SettingFocusReservedHotbar to: " + active);
			isReservedHotbarFocused = active;
			int num = localPlayerController.currentItemSlot;
			if (isReservedHotbarFocused && num < unreservedHotbarSize)
			{
				if (indexFocusedReservedHotbar == -1)
				{
					indexFocusedReservedHotbar = unreservedHotbarSize;
				}
				indexUnfocusedReservedHotbar = num;
				num = Mathf.Max(indexFocusedReservedHotbar, unreservedHotbarSize);
				if ((Object)(object)localPlayerController.ItemSlots[num] == (Object)null)
				{
					for (int i = 0; i < reservedHotbarSize; i++)
					{
						int num2 = unreservedHotbarSize + i;
						if ((Object)(object)localPlayerController.ItemSlots[num2] != (Object)null)
						{
							num = num2;
							break;
						}
					}
				}
			}
			else if (!isReservedHotbarFocused && num >= unreservedHotbarSize)
			{
				indexFocusedReservedHotbar = num;
				num = Mathf.Min(indexUnfocusedReservedHotbar, unreservedHotbarSize - 1);
			}
			HotbarSlotSync.SwapHotbarSlot(num);
		}

		public static bool IsItemSlotEmpty(string itemName, PlayerControllerB player = null)
		{
			return IsItemSlotEmpty(Plugin.GetReservedItemInfo(itemName), player);
		}

		public static bool IsItemSlotEmpty(ReservedItemInfo itemInfo, PlayerControllerB player = null)
		{
			if ((Object)(object)player == (Object)null)
			{
				player = localPlayerController;
			}
			if ((Object)(object)player == (Object)null)
			{
				return false;
			}
			return itemInfo != null && itemInfo.indexInInventory < player.ItemSlots.Length && (Object)(object)player.ItemSlots[itemInfo.indexInInventory] == (Object)null;
		}

		public static GrabbableObject GetHeldReservedObject(string itemName, PlayerControllerB player = null)
		{
			if ((Object)(object)player == (Object)null)
			{
				player = localPlayerController;
			}
			if ((Object)(object)player == (Object)null)
			{
				return null;
			}
			int reservedItemHotbarIndex = Plugin.GetReservedItemHotbarIndex(itemName);
			return (reservedItemHotbarIndex >= 0 && reservedItemHotbarIndex < player.ItemSlots.Length && (Object)(object)player.ItemSlots[reservedItemHotbarIndex] != (Object)null) ? player.ItemSlots[reservedItemHotbarIndex] : null;
		}

		[HarmonyPatch(typeof(GrabbableObject), "Start")]
		[HarmonyPostfix]
		public static void InitializeReservedItemProperties(GrabbableObject __instance)
		{
			ReservedItemInfo reservedItemInfo = Plugin.GetReservedItemInfo(__instance.itemProperties.itemName);
			if (reservedItemInfo != null)
			{
				if (reservedItemInfo.forceUpdateCanBeGrabbedBeforeGameStart)
				{
					__instance.itemProperties.canBeGrabbedBeforeGameStart = reservedItemInfo.canBeGrabbedBeforeGameStart;
				}
				if (reservedItemInfo.forceUpdateRequiresBattery)
				{
					__instance.itemProperties.requiresBattery = reservedItemInfo.requiresBattery;
				}
			}
		}
	}
	[HarmonyPatch]
	public static class PlayerPatcher
	{
		public static PlayerControllerB localPlayerController;

		public static int vanillaHotbarSize = -1;

		public static int INTERACTABLE_OBJECT_MASK { get; private set; }

		public static int unreservedHotbarSize => ((Object)(object)localPlayerController != (Object)null) ? (localPlayerController.ItemSlots.Length - reservedHotbarSize) : vanillaHotbarSize;

		public static int reservedHotbarSize => Plugin.numReservedItemSlots;

		public static int combinedHotbarSize => unreservedHotbarSize + reservedHotbarSize;

		[HarmonyPatch(typeof(MenuManager), "OnEnable")]
		[HarmonyPrefix]
		public static void ResetVariables(MenuManager __instance)
		{
			localPlayerController = null;
			vanillaHotbarSize = -1;
			ReservedItemPatcher.isReservedHotbarFocused = false;
			ReservedItemPatcher.indexUnfocusedReservedHotbar = 0;
			ReservedItemPatcher.indexFocusedReservedHotbar = -1;
			Keybinds.localPlayerController = null;
			Keybinds.focusReservedHotbarAction = null;
			Keybinds.holdingModifierKey = false;
			HotbarSlotSync.localPlayerController = null;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Awake")]
		[HarmonyPostfix]
		public static void InitializePlayerController(PlayerControllerB __instance)
		{
			if (vanillaHotbarSize == -1)
			{
				vanillaHotbarSize = __instance.ItemSlots.Length;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPostfix]
		public static void InitializePlayerControllerLate(PlayerControllerB __instance)
		{
			__instance.ItemSlots = (GrabbableObject[])(object)new GrabbableObject[__instance.ItemSlots.Length + reservedHotbarSize];
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPrefix]
		public static void OnLocalPlayerConnect(PlayerControllerB __instance)
		{
			localPlayerController = __instance;
			INTERACTABLE_OBJECT_MASK = (int)Traverse.Create((object)__instance).Field("interactableObjectsMask").GetValue();
		}
	}
}

larryr1-LukesAdditionalSuits/AdditionalSuits.dll

Decompiled 6 months ago
using System;
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.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("AdditionalSuits")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdditionalSuits")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("0c25b026-8574-4dd2-9af2-4265f618ef8a")]
[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 AdditionalSuits;

[BepInPlugin("ACS.AdditionalSuits", "AdditionalSuits", "1.0.2")]
public class AdditionalSuitsBase : BaseUnityPlugin
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void StartPatch(ref StartOfRound __instance)
		{
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			try
			{
				if (SuitsLoaded)
				{
					return;
				}
				for (int i = 0; i < __instance.unlockablesList.unlockables.Count; i++)
				{
					UnlockableItem val = __instance.unlockablesList.unlockables[i];
					mls.LogInfo((object)("AdditionalSuits - processing unlockable {index=" + i + ", name=" + val.unlockableName + "}"));
					if (!((Object)(object)val.suitMaterial == (Object)null) && val.alreadyUnlocked)
					{
						string[] files = Directory.GetFiles(SuitTextureFolder, "*.png");
						string[] array = files;
						foreach (string text in array)
						{
							mls.LogInfo((object)("AdditionalSuits - adding suit {file=" + text + "}"));
							UnlockableItem val2 = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)val));
							Material val3 = Object.Instantiate<Material>(val2.suitMaterial);
							Texture2D val4 = new Texture2D(2, 2);
							ImageConversion.LoadImage(val4, File.ReadAllBytes(Path.Combine(SuitTextureFolder, text)));
							val3.mainTexture = (Texture)(object)val4;
							val2.suitMaterial = val3;
							string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
							val2.unlockableName = fileNameWithoutExtension.Replace("_", " ").Substring(2);
							__instance.unlockablesList.unlockables.Add(val2);
						}
						SuitsLoaded = true;
						break;
					}
				}
			}
			catch (Exception ex)
			{
				mls.LogInfo((object)("AdditionalSuits - initialization failed!\nERROR: " + ex));
			}
		}
	}

	private static AdditionalSuitsBase Instance;

	private const string modGUID = "ACS.AdditionalSuits";

	private const string modName = "AdditionalSuits";

	private const string modVersion = "1.0.2";

	private readonly Harmony harmony = new Harmony("ACS.AdditionalSuits");

	public static ManualLogSource mls;

	public static bool SuitsLoaded;

	public static string SuitTextureFolder;

	private void Awake()
	{
		if ((Object)(object)Instance == (Object)null)
		{
			Instance = this;
		}
		mls = Logger.CreateLogSource("ACS.AdditionalSuits");
		mls.LogInfo((object)"AdditionalSuits - initializing...");
		SuitTextureFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "resAdditionalSuits");
		harmony.PatchAll();
		mls.LogInfo((object)"AdditionalSuits - initialized!");
	}
}

NiceHairs-Symbiosis/Symbiosis.dll

Decompiled 6 months ago
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Symbiosis.Extensions;
using Symbiosis.Patches;
using Symbiosis.Utils;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Symbiosis")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Symbiosis")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("97f95e36-1154-479c-be65-4ef35b78018f")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Symbiosis
{
	[BepInPlugin("niceh.Symbiosis", "Symbiosis", "1.0.2")]
	public class Plugin : BaseUnityPlugin
	{
		public const string GUID = "niceh.Symbiosis";

		public const string Name = "Symbiosis";

		public static Plugin Instance { get; private set; }

		public static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//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_002b: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			Harmony val = new Harmony("niceh.Symbiosis");
			val.PatchAll(typeof(Patch_HoarderBugAI));
			val.PatchAll(typeof(Patch_ExtensionLadderItem));
			val.PatchAll(typeof(Patch_StunGrenadeItem));
		}
	}
}
namespace Symbiosis.Utils
{
	public static class Util_GrabbableObject
	{
		public static HoarderBugAI FindHoarderBug(this GrabbableObject item)
		{
			if ((Object)(object)item.playerHeldBy != (Object)null)
			{
				return null;
			}
			HoarderBugAI[] array = Object.FindObjectsByType<HoarderBugAI>((FindObjectsSortMode)0);
			foreach (HoarderBugAI val in array)
			{
				if (val != null && val.heldItem != null && !((Object)(object)val.heldItem.itemGrabbableObject != (Object)(object)item))
				{
					return val;
				}
			}
			return null;
		}
	}
}
namespace Symbiosis.Extensions
{
	public static class Extension_HoarderBugAI
	{
		private static readonly MethodInfo info_DropItem = typeof(HoarderBugAI).GetMethod("DropItem", BindingFlags.Instance | BindingFlags.NonPublic);

		public static void DropItem(this HoarderBugAI bug, NetworkObject item, Vector3 targetFloorPosition, bool droppingInNest = true)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			info_DropItem?.Invoke(bug, new object[3] { item, targetFloorPosition, droppingInNest });
		}
	}
	public static class Extension_StunGrenadeItem
	{
		public static readonly FieldInfo info_pullPinCoroutine = typeof(StunGrenadeItem).GetField("pullPinCoroutine", BindingFlags.Instance | BindingFlags.NonPublic);

		public static void SetPullPinCoroutine(this StunGrenadeItem item, Coroutine coroutine)
		{
			info_pullPinCoroutine?.SetValue(item, coroutine);
		}

		public static Coroutine GetPullPinCoroutine(this StunGrenadeItem item)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return (Coroutine)(info_pullPinCoroutine?.GetValue(item));
		}

		public static IEnumerator NoPlayerPullPinAnimation(this StunGrenadeItem item)
		{
			item.inPullingPinAnimation = true;
			item.itemAnimator.SetTrigger("pullPin");
			item.itemAudio.PlayOneShot(item.pullPinSFX);
			WalkieTalkie.TransmitOneShotAudio(item.itemAudio, item.pullPinSFX, 0.8f);
			yield return (object)new WaitForSeconds(1f);
			item.inPullingPinAnimation = false;
			item.pinPulled = true;
			((GrabbableObject)item).itemUsedUp = true;
		}
	}
}
namespace Symbiosis.Patches
{
	internal static class Patch_ExtensionLadderItem
	{
		[HarmonyPatch(typeof(ExtensionLadderItem), "ItemActivate")]
		[HarmonyPrefix]
		private static bool ItemActivate(ExtensionLadderItem __instance)
		{
			//IL_006c: 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)
			if ((Object)(object)((GrabbableObject)__instance).playerHeldBy != (Object)null)
			{
				return true;
			}
			Plugin.Log.LogInfo((object)"ITEM IS NOT HELD BY PLAYER");
			if (!((NetworkBehaviour)__instance).IsOwner)
			{
				return true;
			}
			Plugin.Log.LogInfo((object)"ITEM IS OWNER");
			HoarderBugAI val = ((GrabbableObject)(object)__instance).FindHoarderBug();
			if (val == null)
			{
				Plugin.Log.LogInfo((object)"NO BUG FOUND");
				return false;
			}
			Plugin.Log.LogInfo((object)"DROPPING LADDER");
			val.DropItem(((Component)__instance).GetComponent<NetworkObject>(), ((GrabbableObject)__instance).GetItemFloorPosition(default(Vector3)), droppingInNest: false);
			return false;
		}
	}
	internal static class Patch_HoarderBugAI
	{
		private static readonly Random _rand = new Random();

		[HarmonyPatch(typeof(HoarderBugAI), "Start")]
		[HarmonyPrefix]
		private static void Start(HoarderBugAI __instance)
		{
			((MonoBehaviour)__instance).StartCoroutine(HoarderBugUseItem(__instance));
		}

		private static IEnumerator HoarderBugUseItem(HoarderBugAI bug)
		{
			while (((Behaviour)bug).isActiveAndEnabled)
			{
				try
				{
					if (!((EnemyAI)bug).inSpecialAnimation && !((EnemyAI)bug).isEnemyDead && !StartOfRound.Instance.allPlayersDead && bug.heldItem != null && (Object)(object)bug.heldItem.itemGrabbableObject != (Object)null)
					{
						ManualLogSource log = Plugin.Log;
						HoarderBugItem heldItem = bug.heldItem;
						log.LogInfo((object)("USING " + ((heldItem != null) ? ((Object)heldItem.itemGrabbableObject.itemProperties).name : null)));
						bug.heldItem.itemGrabbableObject.UseItemOnClient(_rand.Next(3) != 0);
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)ex);
				}
				yield return (object)new WaitForSeconds((float)_rand.Next(20));
			}
		}
	}
	internal static class Patch_StunGrenadeItem
	{
		[HarmonyPatch(typeof(StunGrenadeItem), "ItemActivate")]
		[HarmonyPrefix]
		private static bool ItemActivate(StunGrenadeItem __instance)
		{
			if ((Object)(object)((GrabbableObject)__instance).playerHeldBy != (Object)null)
			{
				return true;
			}
			Plugin.Log.LogInfo((object)"ITEM IS NOT HELD BY PLAYER");
			if (__instance.inPullingPinAnimation)
			{
				return true;
			}
			Plugin.Log.LogInfo((object)"ITEM IS IN PULLING ANIMATION");
			if (__instance.GetPullPinCoroutine() != null)
			{
				return true;
			}
			Plugin.Log.LogInfo((object)"ITEM HAS NO COROUTINE: STARTING NO PLAYER PULLING PIN ANIMATION");
			__instance.SetPullPinCoroutine(((MonoBehaviour)__instance).StartCoroutine(__instance.NoPlayerPullPinAnimation()));
			return false;
		}
	}
}

no00ob-LCSoundTool/LC_SoundTool.dll

Decompiled 6 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LCSoundTool.Networking;
using LCSoundTool.Patches;
using LCSoundTool.Resources;
using LCSoundTool.Utilities;
using LCSoundToolMod.Properties;
using Microsoft.CodeAnalysis;
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: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LC_SoundTool")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Various audio related functions. Mainly logs all sounds that are playing and what type of playback they're into the BepInEx console.")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.0")]
[assembly: AssemblyProduct("LC_SoundTool")]
[assembly: AssemblyTitle("LC_SoundTool")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/no00ob/LCSoundTool")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.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 LCSoundToolMod
{
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LC_SoundTool";

		public const string PLUGIN_NAME = "LC_SoundTool";

		public const string PLUGIN_VERSION = "1.4.0";
	}
}
namespace LCSoundToolMod.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					ResourceManager resourceManager = new ResourceManager("LCSoundToolMod.Properties.Resources", typeof(Resources).Assembly);
					resourceMan = resourceManager;
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal static byte[] soundtool
		{
			get
			{
				object @object = ResourceManager.GetObject("soundtool", resourceCulture);
				return (byte[])@object;
			}
		}

		internal Resources()
		{
		}
	}
}
namespace LCSoundTool
{
	public class AudioSourceExtension : MonoBehaviour
	{
		public AudioSource audioSource;

		public bool playOnAwake = false;

		public bool loop = false;

		private bool updateHasBeenLogged = false;

		private bool hasPlayed = false;

		private void OnEnable()
		{
			if (!((Object)(object)audioSource == (Object)null) && !audioSource.isPlaying)
			{
				if (playOnAwake)
				{
					audioSource.Play();
				}
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Started playback of {audioSource} with clip {audioSource.clip} in OnEnable function!");
				}
				updateHasBeenLogged = false;
				hasPlayed = false;
			}
		}

		private void OnDisable()
		{
			if (!((Object)(object)audioSource == (Object)null) && audioSource.isPlaying)
			{
				if (playOnAwake)
				{
					audioSource.Stop();
				}
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Stopped playback of {audioSource} with clip {audioSource.clip} in OnDisable function!");
				}
				updateHasBeenLogged = false;
				hasPlayed = false;
			}
		}

		private void Update()
		{
			if ((Object)(object)audioSource == (Object)null)
			{
				return;
			}
			if ((Object)(object)audioSource.clip == (Object)null)
			{
				hasPlayed = false;
			}
			if (audioSource.isPlaying)
			{
				updateHasBeenLogged = false;
			}
			else if (!((Behaviour)audioSource).isActiveAndEnabled)
			{
				hasPlayed = false;
			}
			else
			{
				if (!playOnAwake)
				{
					return;
				}
				if ((Object)(object)audioSource.clip != (Object)null && !hasPlayed)
				{
					audioSource.Play();
					if (SoundTool.infoDebugging)
					{
						SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Started playback of {audioSource} with clip {audioSource.clip} in Update function!");
					}
					updateHasBeenLogged = false;
					hasPlayed = true;
				}
				else if (!updateHasBeenLogged)
				{
					updateHasBeenLogged = true;
					if (SoundTool.infoDebugging)
					{
						SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Can not start playback of {audioSource} with missing clip in Update function!");
					}
				}
			}
		}
	}
	public class RandomAudioClip
	{
		public AudioClip clip;

		[Range(0f, 1f)]
		public float chance = 1f;

		public RandomAudioClip(AudioClip clip, float chance)
		{
			this.clip = clip;
			this.chance = chance;
		}
	}
	[BepInPlugin("LCSoundTool", "LC Sound Tool", "1.4.0")]
	public class SoundTool : BaseUnityPlugin
	{
		public enum AudioType
		{
			wav,
			ogg,
			mp3
		}

		private const string PLUGIN_GUID = "LCSoundTool";

		private const string PLUGIN_NAME = "LC Sound Tool";

		private ConfigEntry<bool> configUseNetworking;

		private ConfigEntry<bool> configSyncRandomSeed;

		private ConfigEntry<float> configPlayOnAwakePatchRepeatDelay;

		private readonly Harmony harmony = new Harmony("LCSoundTool");

		public static SoundTool Instance;

		internal ManualLogSource logger;

		public KeyboardShortcut toggleAudioSourceDebugLog;

		public KeyboardShortcut toggleIndepthDebugLog;

		public KeyboardShortcut toggleInformationalDebugLog;

		public bool wasKeyDown;

		public bool wasKeyDown2;

		public bool wasKeyDown3;

		public static bool debugAudioSources;

		public static bool indepthDebugging;

		public static bool infoDebugging;

		public static bool networkingInitialized { get; private set; }

		public static bool networkingAvailable { get; private set; }

		public static Dictionary<string, List<RandomAudioClip>> replacedClips { get; private set; }

		public static Dictionary<string, AudioClip> networkedClips => NetworkHandler.networkedAudioClips;

		public static Dictionary<string, AudioType> clipTypes { get; private set; }

		public static event Action ClientNetworkedAudioChanged
		{
			add
			{
				NetworkHandler.ClientNetworkedAudioChanged += value;
			}
			remove
			{
				NetworkHandler.ClientNetworkedAudioChanged -= value;
			}
		}

		public static event Action HostNetworkedAudioChanged
		{
			add
			{
				NetworkHandler.HostNetworkedAudioChanged += value;
			}
			remove
			{
				NetworkHandler.HostNetworkedAudioChanged -= value;
			}
		}

		public static bool IsDebuggingOn()
		{
			if (debugAudioSources || indepthDebugging || infoDebugging)
			{
				return true;
			}
			return false;
		}

		private void Awake()
		{
			//IL_012e: 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_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			networkingAvailable = true;
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			configUseNetworking = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "EnableNetworking", false, "Whether or not to use the networking built into this plugin. If set to true everyone in the lobby needs LCSoundTool installed and networking enabled to join.");
			configSyncRandomSeed = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "SyncUnityRandomSeed", false, "Whether or not to sync the default Unity randomization seed with all clients. For this feature, networking has to be set to true. Will send the UnityEngine.Random.seed from the host to all clients automatically upon loading a networked scene.");
			configPlayOnAwakePatchRepeatDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Experimental", "NewPlayOnAwakePatchRepeatDelay", 90f, "How long to wait between checks for new playOnAwake AudioSources. Runs the same patching that is done when each scene is loaded with this delay between each run. DO NOT set too low or high. Anything below 10 or above 600 can cause issues. This time is in seconds. Set to 0 to disable rerunning the patch, but be warned that this might break runtime initialized playOnAwake AudioSources.");
			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);
					}
				}
			}
			logger = Logger.CreateLogSource("LCSoundTool");
			logger.LogInfo((object)"Plugin LCSoundTool is loaded!");
			toggleAudioSourceDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[0]);
			toggleIndepthDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 });
			toggleInformationalDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 });
			debugAudioSources = false;
			indepthDebugging = false;
			infoDebugging = false;
			replacedClips = new Dictionary<string, List<RandomAudioClip>>();
			clipTypes = new Dictionary<string, AudioType>();
		}

		private void Start()
		{
			if (!configUseNetworking.Value)
			{
				networkingAvailable = false;
				Instance.logger.LogWarning((object)"Networking disabled. Mod in fully client side mode, but no networked actions can take place! You can safely ignore this if you want the mod to run fully client side.");
			}
			else
			{
				networkingAvailable = true;
			}
			if (configUseNetworking.Value)
			{
				logger.LogDebug((object)"Loading SoundTool AssetBundle...");
				Assets.bundle = AssetBundle.LoadFromMemory(LCSoundToolMod.Properties.Resources.soundtool);
				if ((Object)(object)Assets.bundle == (Object)null)
				{
					logger.LogError((object)"Failed to load SoundTool AssetBundle!");
				}
				else
				{
					logger.LogDebug((object)"Finished loading SoundTool AssetBundle!");
				}
			}
			harmony.PatchAll(typeof(AudioSourcePatch));
			if (configUseNetworking.Value)
			{
				harmony.PatchAll(typeof(GameNetworkManagerPatch));
				harmony.PatchAll(typeof(StartOfRoundPatch));
			}
			SceneManager.sceneLoaded += OnSceneLoaded;
		}

		private void Update()
		{
			if (configUseNetworking.Value)
			{
				if (!networkingInitialized)
				{
					if ((Object)(object)NetworkHandler.Instance != (Object)null)
					{
						networkingInitialized = true;
					}
				}
				else if ((Object)(object)NetworkHandler.Instance == (Object)null)
				{
					networkingInitialized = false;
				}
			}
			else
			{
				networkingInitialized = false;
			}
			if (((KeyboardShortcut)(ref toggleInformationalDebugLog)).IsDown() && !wasKeyDown3)
			{
				wasKeyDown3 = true;
				wasKeyDown2 = false;
				wasKeyDown = false;
			}
			if (((KeyboardShortcut)(ref toggleInformationalDebugLog)).IsUp() && wasKeyDown3)
			{
				wasKeyDown3 = false;
				wasKeyDown2 = false;
				wasKeyDown = false;
				infoDebugging = !infoDebugging;
				Instance.logger.LogDebug((object)$"Toggling informational debug logs {infoDebugging}!");
				return;
			}
			if (((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsDown() && !wasKeyDown2)
			{
				wasKeyDown2 = true;
				wasKeyDown = false;
			}
			if (((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsUp() && wasKeyDown2)
			{
				wasKeyDown2 = false;
				wasKeyDown = false;
				debugAudioSources = !debugAudioSources;
				indepthDebugging = debugAudioSources;
				infoDebugging = debugAudioSources;
				Instance.logger.LogDebug((object)$"Toggling in-depth AudioSource debug logs {debugAudioSources}!");
				return;
			}
			if (!wasKeyDown2 && !((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsDown() && ((KeyboardShortcut)(ref toggleAudioSourceDebugLog)).IsDown() && !wasKeyDown)
			{
				wasKeyDown = true;
				wasKeyDown2 = false;
			}
			if (((KeyboardShortcut)(ref toggleAudioSourceDebugLog)).IsUp() && wasKeyDown)
			{
				wasKeyDown = false;
				wasKeyDown2 = false;
				debugAudioSources = !debugAudioSources;
				if (indepthDebugging && !debugAudioSources)
				{
					indepthDebugging = false;
				}
				Instance.logger.LogDebug((object)$"Toggling AudioSource debug logs {debugAudioSources}!");
			}
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_0013: 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)
			if (!((Object)(object)Instance == (Object)null))
			{
				PatchPlayOnAwakeAudio(scene);
				OnSceneLoadedNetworking();
				if (((Scene)(ref scene)).name.ToLower().Contains("level"))
				{
					((MonoBehaviour)this).StopAllCoroutines();
					((MonoBehaviour)this).StartCoroutine(PatchPlayOnAwakeDelayed(scene, 1f));
				}
			}
		}

		private IEnumerator PatchPlayOnAwakeDelayed(Scene scene, float wait)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (infoDebugging)
			{
				logger.LogDebug((object)$"Started playOnAwake patch coroutine with delay of {wait} seconds");
			}
			yield return (object)new WaitForSecondsRealtime(wait);
			if (infoDebugging)
			{
				logger.LogDebug((object)"Running playOnAwake patch coroutine!");
			}
			PatchPlayOnAwakeAudio(scene);
			float repeatWait = configPlayOnAwakePatchRepeatDelay.Value;
			if (repeatWait != 0f)
			{
				if (repeatWait < 10f)
				{
					repeatWait = 10f;
				}
				if (repeatWait > 600f)
				{
					repeatWait = 600f;
				}
				((MonoBehaviour)this).StartCoroutine(PatchPlayOnAwakeDelayed(scene, repeatWait));
			}
		}

		private void PatchPlayOnAwakeAudio(Scene scene)
		{
			if (infoDebugging)
			{
				Instance.logger.LogDebug((object)("Grabbing all playOnAwake AudioSources for loaded scene " + ((Scene)(ref scene)).name));
			}
			AudioSource[] allPlayOnAwakeAudioSources = GetAllPlayOnAwakeAudioSources();
			if (infoDebugging)
			{
				Instance.logger.LogDebug((object)$"Found a total of {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSource(s)!");
				Instance.logger.LogDebug((object)$"Starting setup on {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSource(s)...");
			}
			AudioSource[] array = allPlayOnAwakeAudioSources;
			AudioSourceExtension audioSourceExtension = default(AudioSourceExtension);
			foreach (AudioSource val in array)
			{
				val.Stop();
				if (((Component)((Component)val).transform).TryGetComponent<AudioSourceExtension>(ref audioSourceExtension))
				{
					audioSourceExtension.audioSource = val;
					audioSourceExtension.playOnAwake = true;
					audioSourceExtension.loop = val.loop;
					val.playOnAwake = false;
					if (infoDebugging)
					{
						Instance.logger.LogDebug((object)$"-Set- {Array.IndexOf(allPlayOnAwakeAudioSources, val) + 1} {val} done!");
					}
					continue;
				}
				AudioSourceExtension audioSourceExtension2 = ((Component)val).gameObject.AddComponent<AudioSourceExtension>();
				audioSourceExtension2.audioSource = val;
				audioSourceExtension2.playOnAwake = true;
				audioSourceExtension2.loop = val.loop;
				val.playOnAwake = false;
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)$"-Add- {Array.IndexOf(allPlayOnAwakeAudioSources, val) + 1} {val} done!");
				}
			}
			if (infoDebugging)
			{
				Instance.logger.LogDebug((object)$"Done setting up {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSources!");
			}
		}

		private void OnSceneLoadedNetworking()
		{
			if (networkingAvailable && networkingInitialized && configSyncRandomSeed.Value)
			{
				int num = (int)DateTime.Now.Ticks;
				Random.InitState(num);
				SendUnityRandomSeed(num);
			}
		}

		public AudioSource[] GetAllPlayOnAwakeAudioSources()
		{
			AudioSource[] array = Object.FindObjectsOfType<AudioSource>(true);
			List<AudioSource> list = new List<AudioSource>();
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i].playOnAwake)
				{
					list.Add(array[i]);
				}
			}
			return list.ToArray();
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			string name = newClip.GetName();
			float num = 100f;
			if (name.Contains("-"))
			{
				string[] array = name.Split('-');
				if (array.Length > 1)
				{
					string s = array[^1];
					if (int.TryParse(s, out var result))
					{
						num = (float)result * 0.01f;
						name = string.Join("-", array, 0, array.Length - 1);
					}
				}
			}
			if (replacedClips.ContainsKey(originalName) && num >= 100f)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with 100% chance of playback! This is not allowed.");
				return;
			}
			num = Mathf.Clamp01(num);
			if (replacedClips.ContainsKey(originalName))
			{
				replacedClips[originalName].Add(new RandomAudioClip(newClip, num));
			}
			else
			{
				replacedClips[originalName] = new List<RandomAudioClip>
				{
					new RandomAudioClip(newClip, num)
				};
			}
			float num2 = 0f;
			for (int i = 0; i < replacedClips[originalName].Count(); i++)
			{
				num2 += replacedClips[originalName][i].chance;
			}
			if ((num2 < 1f || num2 > 1f) && replacedClips[originalName].Count() > 1)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} does not equal 100% (at least yet?)");
			}
			else if (num2 == 1f && replacedClips[originalName].Count() > 1)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} is equal to 100%");
			}
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip)
		{
			if ((Object)(object)originalClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
			}
			else
			{
				ReplaceAudioClip(originalClip.GetName(), newClip);
			}
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip, float chance)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			string name = newClip.GetName();
			if (replacedClips.ContainsKey(originalName) && chance >= 100f)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with 100% chance of playback! This is not allowed.");
				return;
			}
			chance = Mathf.Clamp01(chance);
			if (replacedClips.ContainsKey(originalName))
			{
				replacedClips[originalName].Add(new RandomAudioClip(newClip, chance));
			}
			else
			{
				replacedClips[originalName] = new List<RandomAudioClip>
				{
					new RandomAudioClip(newClip, chance)
				};
			}
			float num = 0f;
			for (int i = 0; i < replacedClips[originalName].Count(); i++)
			{
				num += replacedClips[originalName][i].chance;
			}
			if ((num < 1f || num > 1f) && replacedClips[originalName].Count() > 1)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} does not equal 100% (at least yet?)");
			}
			else if (num == 1f && replacedClips[originalName].Count() > 1)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} is equal to 100%");
			}
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, float chance)
		{
			if ((Object)(object)originalClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
			}
			else
			{
				ReplaceAudioClip(originalClip.GetName(), newClip, chance);
			}
		}

		public static void RemoveRandomAudioClip(string name, float chance)
		{
			if (string.IsNullOrEmpty(name))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed.");
			}
			else if (!replacedClips.ContainsKey(name))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed.");
			}
			else
			{
				if (!(chance > 0f))
				{
					return;
				}
				for (int i = 0; i < replacedClips[name].Count(); i++)
				{
					if (replacedClips[name][i].chance == chance)
					{
						replacedClips[name].RemoveAt(i);
						break;
					}
				}
			}
		}

		public static void RestoreAudioClip(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed.");
			}
			else if (!replacedClips.ContainsKey(name))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed.");
			}
			else
			{
				replacedClips.Remove(name);
			}
		}

		public static void RestoreAudioClip(AudioClip clip)
		{
			if ((Object)(object)clip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed.");
			}
			else
			{
				RestoreAudioClip(clip.GetName());
			}
		}

		public static AudioClip GetAudioClip(string modFolder, string soundName)
		{
			return GetAudioClip(modFolder, string.Empty, soundName);
		}

		public static AudioClip GetAudioClip(string modFolder, string subFolder, string soundName)
		{
			AudioType audioType = AudioType.wav;
			bool flag = true;
			string text = " ";
			string text2 = Path.Combine(Paths.PluginPath, modFolder, subFolder, soundName);
			string text3 = Path.Combine(Paths.PluginPath, modFolder, soundName);
			string path = Path.Combine(Paths.PluginPath, modFolder, subFolder);
			string text4 = Path.Combine(Paths.PluginPath, subFolder, soundName);
			string path2 = Path.Combine(Paths.PluginPath, subFolder);
			if (!Directory.Exists(path))
			{
				if (!string.IsNullOrEmpty(subFolder))
				{
					Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + "/" + subFolder + " does not exist!"));
				}
				else
				{
					Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + " does not exist!"));
					if (!modFolder.Contains("-"))
					{
						Instance.logger.LogWarning((object)"This sound mod might not be compatable with mod managers. You should contact the sound mod's author.");
					}
				}
				flag = false;
			}
			if (!File.Exists(text2))
			{
				Instance.logger.LogWarning((object)("Requested audio file does not exist at path " + text2 + "!"));
				flag = false;
				Instance.logger.LogDebug((object)("Looking for audio file from mod root instead at " + text3 + "..."));
				if (File.Exists(text3))
				{
					Instance.logger.LogDebug((object)("Found audio file at path " + text3 + "!"));
					text2 = text3;
					flag = true;
				}
				else
				{
					Instance.logger.LogWarning((object)("Requested audio file does not exist at mod root path " + text3 + "!"));
				}
			}
			if (Directory.Exists(path2))
			{
				if (!string.IsNullOrEmpty(subFolder))
				{
					Instance.logger.LogWarning((object)("Legacy directory location at BepInEx/Plugins/" + subFolder + " found!"));
				}
				else if (!modFolder.Contains("-"))
				{
					Instance.logger.LogWarning((object)"Legacy directory location at BepInEx/Plugins found!");
				}
			}
			if (File.Exists(text4))
			{
				Instance.logger.LogWarning((object)("Legacy path contains the requested audio file at path " + text4 + "!"));
				text = " legacy ";
				text2 = text4;
				flag = true;
			}
			string[] array = soundName.Split('.');
			if (array[^1].ToLower().Contains("ogg"))
			{
				audioType = AudioType.ogg;
				Instance.logger.LogDebug((object)"File detected as an Ogg Vorbis file!");
			}
			else if (array[^1].ToLower().Contains("mp3"))
			{
				audioType = AudioType.mp3;
				Instance.logger.LogDebug((object)"File detected as a MPEG MP3 file!");
			}
			AudioClip val = null;
			if (flag)
			{
				Instance.logger.LogDebug((object)("Loading AudioClip " + soundName + " from" + text + "path: " + text2));
				switch (audioType)
				{
				case AudioType.wav:
					val = WavUtility.LoadFromDiskToAudioClip(text2);
					break;
				case AudioType.ogg:
					val = OggUtility.LoadFromDiskToAudioClip(text2);
					break;
				case AudioType.mp3:
					val = Mp3Utility.LoadFromDiskToAudioClip(text2);
					break;
				}
				Instance.logger.LogDebug((object)$"Finished loading AudioClip {soundName} with length of {val.length}!");
			}
			else
			{
				Instance.logger.LogWarning((object)("Failed to load AudioClip " + soundName + " from invalid" + text + "path at " + text2 + "!"));
			}
			if (string.IsNullOrEmpty(val.GetName()))
			{
				string empty = string.Empty;
				string[] array2 = new string[0];
				switch (audioType)
				{
				case AudioType.wav:
					empty = soundName.Replace(".wav", "");
					array2 = empty.Split('/');
					if (array2.Length <= 1)
					{
						array2 = empty.Split('\\');
					}
					empty = array2[^1];
					((Object)val).name = empty;
					break;
				case AudioType.ogg:
					empty = soundName.Replace(".ogg", "");
					array2 = empty.Split('/');
					if (array2.Length <= 1)
					{
						array2 = empty.Split('\\');
					}
					empty = array2[^1];
					((Object)val).name = empty;
					break;
				case AudioType.mp3:
					empty = soundName.Replace(".mp3", "");
					array2 = empty.Split('/');
					if (array2.Length <= 1)
					{
						array2 = empty.Split('\\');
					}
					empty = array2[^1];
					((Object)val).name = empty;
					break;
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				clipTypes.Add(val.GetName(), audioType);
			}
			return val;
		}

		public static AudioClip GetAudioClip(string modFolder, string soundName, AudioType audioType)
		{
			return GetAudioClip(modFolder, string.Empty, soundName, audioType);
		}

		public static AudioClip GetAudioClip(string modFolder, string subFolder, string soundName, AudioType audioType)
		{
			bool flag = true;
			string text = " ";
			string text2 = Path.Combine(Paths.PluginPath, modFolder, subFolder, soundName);
			string text3 = Path.Combine(Paths.PluginPath, modFolder, soundName);
			string path = Path.Combine(Paths.PluginPath, modFolder, subFolder);
			string text4 = Path.Combine(Paths.PluginPath, subFolder, soundName);
			string path2 = Path.Combine(Paths.PluginPath, subFolder);
			if (!Directory.Exists(path))
			{
				if (!string.IsNullOrEmpty(subFolder))
				{
					Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + "/" + subFolder + " does not exist!"));
				}
				else
				{
					Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + " does not exist!"));
					if (!modFolder.Contains("-"))
					{
						Instance.logger.LogWarning((object)"This sound mod might not be compatable with mod managers. You should contact the sound mod's author.");
					}
				}
				flag = false;
			}
			if (!File.Exists(text2))
			{
				Instance.logger.LogWarning((object)("Requested audio file does not exist at path " + text2 + "!"));
				flag = false;
				Instance.logger.LogDebug((object)("Looking for audio file from mod root instead at " + text3 + "..."));
				if (File.Exists(text3))
				{
					Instance.logger.LogDebug((object)("Found audio file at path " + text3 + "!"));
					text2 = text3;
					flag = true;
				}
				else
				{
					Instance.logger.LogWarning((object)("Requested audio file does not exist at mod root path " + text3 + "!"));
				}
			}
			if (Directory.Exists(path2))
			{
				if (!string.IsNullOrEmpty(subFolder))
				{
					Instance.logger.LogWarning((object)("Legacy directory location at BepInEx/Plugins/" + subFolder + " found!"));
				}
				else if (!modFolder.Contains("-"))
				{
					Instance.logger.LogWarning((object)"Legacy directory location at BepInEx/Plugins found!");
				}
			}
			if (File.Exists(text4))
			{
				Instance.logger.LogWarning((object)("Legacy path contains the requested audio file at path " + text4 + "!"));
				text = " legacy ";
				text2 = text4;
				flag = true;
			}
			switch (audioType)
			{
			case AudioType.wav:
				Instance.logger.LogDebug((object)"File defined as a WAV file!");
				break;
			case AudioType.ogg:
				Instance.logger.LogDebug((object)"File defined as an Ogg Vorbis file!");
				break;
			case AudioType.mp3:
				Instance.logger.LogDebug((object)"File defined as a MPEG MP3 file!");
				break;
			}
			AudioClip val = null;
			if (flag)
			{
				Instance.logger.LogDebug((object)("Loading AudioClip " + soundName + " from" + text + "path: " + text2));
				switch (audioType)
				{
				case AudioType.wav:
					val = WavUtility.LoadFromDiskToAudioClip(text2);
					break;
				case AudioType.ogg:
					val = OggUtility.LoadFromDiskToAudioClip(text2);
					break;
				case AudioType.mp3:
					val = Mp3Utility.LoadFromDiskToAudioClip(text2);
					break;
				}
				Instance.logger.LogDebug((object)$"Finished loading AudioClip {soundName} with length of {val.length}!");
			}
			else
			{
				Instance.logger.LogWarning((object)("Failed to load AudioClip " + soundName + " from invalid" + text + "path at " + text2 + "!"));
			}
			if (string.IsNullOrEmpty(val.GetName()))
			{
				string empty = string.Empty;
				string[] array = new string[0];
				switch (audioType)
				{
				case AudioType.wav:
					empty = soundName.Replace(".wav", "");
					array = empty.Split('/');
					if (array.Length <= 1)
					{
						array = empty.Split('\\');
					}
					empty = array[^1];
					((Object)val).name = empty;
					break;
				case AudioType.ogg:
					empty = soundName.Replace(".ogg", "");
					array = empty.Split('/');
					if (array.Length <= 1)
					{
						array = empty.Split('\\');
					}
					empty = array[^1];
					((Object)val).name = empty;
					break;
				case AudioType.mp3:
					empty = soundName.Replace(".mp3", "");
					array = empty.Split('/');
					if (array.Length <= 1)
					{
						array = empty.Split('\\');
					}
					empty = array[^1];
					((Object)val).name = empty;
					break;
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				clipTypes.Add(val.GetName(), audioType);
			}
			return val;
		}

		public static void SendNetworkedAudioClip(AudioClip audioClip)
		{
			if (!Instance.configUseNetworking.Value)
			{
				Instance.logger.LogWarning((object)$"Networking disabled! Failed to send {audioClip}!");
				return;
			}
			if ((Object)(object)audioClip == (Object)null)
			{
				Instance.logger.LogWarning((object)$"audioClip variable of SendAudioClip not assigned! Failed to send {audioClip}!");
				return;
			}
			if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null)
			{
				Instance.logger.LogWarning((object)$"Instance of SoundTool not found or networking has not finished initializing. Failed to send {audioClip}! If you're sending things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!");
				return;
			}
			string name = audioClip.GetName();
			if (clipTypes.ContainsKey(name))
			{
				if (clipTypes[name] == AudioType.ogg)
				{
					NetworkHandler.Instance.SendAudioClipServerRpc(name, OggUtility.AudioClipToByteArray(audioClip, out var _));
					return;
				}
				if (clipTypes[name] == AudioType.mp3)
				{
					NetworkHandler.Instance.SendAudioClipServerRpc(name, Mp3Utility.AudioClipToByteArray(audioClip, out var _));
					return;
				}
			}
			NetworkHandler.Instance.SendAudioClipServerRpc(name, WavUtility.AudioClipToByteArray(audioClip, out var _));
		}

		public static void RemoveNetworkedAudioClip(AudioClip audioClip)
		{
			RemoveNetworkedAudioClip(audioClip.GetName());
		}

		public static void RemoveNetworkedAudioClip(string audioClip)
		{
			if (!Instance.configUseNetworking.Value)
			{
				Instance.logger.LogWarning((object)("Networking disabled! Failed to remove " + audioClip + "!"));
			}
			else if (string.IsNullOrEmpty(audioClip))
			{
				Instance.logger.LogWarning((object)("audioClip variable of RemoveAudioClip not assigned! Failed to remove " + audioClip + "!"));
			}
			else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null)
			{
				Instance.logger.LogWarning((object)("Instance of SoundTool not found or networking has not finished initializing. Failed to remove " + audioClip + "! If you're removing things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!"));
			}
			else
			{
				NetworkHandler.Instance.RemoveAudioClipServerRpc(audioClip);
			}
		}

		public static void SyncNetworkedAudioClips()
		{
			if (!Instance.configUseNetworking.Value)
			{
				Instance.logger.LogWarning((object)"Networking disabled! Failed to sync audio clips!");
			}
			else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null)
			{
				Instance.logger.LogWarning((object)"Instance of SoundTool not found or networking has not finished initializing. Failed to sync networked audio! If you're syncing things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!");
			}
			else
			{
				NetworkHandler.Instance.SyncAudioClipsServerRpc();
			}
		}

		public static void SendUnityRandomSeed(int seed)
		{
			if (!Instance.configUseNetworking.Value)
			{
				Instance.logger.LogWarning((object)"Networking disabled! Failed to send Unity random seed!");
			}
			else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null)
			{
				Instance.logger.LogWarning((object)"Instance of SoundTool not found or networking has not finished initializing. Failed to send Unity Random seed! If you're sending the seed in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked methods run only after the player setups a networked connection!");
			}
			else
			{
				NetworkHandler.Instance.SendSeedToClientsServerRpc(seed);
			}
		}
	}
}
namespace LCSoundTool.Utilities
{
	public static class Mp3Utility
	{
		public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples)
		{
			samples = new float[audioClip.samples * audioClip.channels];
			audioClip.GetData(samples, 0);
			byte[] array = new byte[samples.Length * 2];
			int num = 32767;
			for (int i = 0; i < samples.Length; i++)
			{
				short value = (short)(samples[i] * (float)num);
				BitConverter.GetBytes(value).CopyTo(array, i * 2);
			}
			return array;
		}

		public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName)
		{
			int num = 16;
			int num2 = num / 8;
			AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false);
			val.SetData(ConvertByteArrayToFloatArray(byteArray), 0);
			return val;
		}

		private static float[] ConvertByteArrayToFloatArray(byte[] byteArray)
		{
			float[] array = new float[byteArray.Length / 2];
			int num = 32767;
			for (int i = 0; i < array.Length; i++)
			{
				short num2 = BitConverter.ToInt16(byteArray, i * 2);
				array[i] = (float)num2 / (float)num;
			}
			return array;
		}

		public static AudioClip LoadFromDiskToAudioClip(string path)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			AudioClip result = null;
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)13);
			try
			{
				audioClip.SendWebRequest();
				try
				{
					while (!audioClip.isDone)
					{
					}
					if ((int)audioClip.result != 1)
					{
						SoundTool.Instance.logger.LogError((object)("Failed to load MP3 AudioClip from path: " + path + " Full error: " + audioClip.error));
					}
					else
					{
						result = DownloadHandlerAudioClip.GetContent(audioClip);
					}
				}
				catch (Exception ex)
				{
					SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace));
				}
			}
			finally
			{
				((IDisposable)audioClip)?.Dispose();
			}
			return result;
		}
	}
	public static class OggUtility
	{
		public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples)
		{
			samples = new float[audioClip.samples * audioClip.channels];
			audioClip.GetData(samples, 0);
			byte[] array = new byte[samples.Length * 2];
			int num = 32767;
			for (int i = 0; i < samples.Length; i++)
			{
				short value = (short)(samples[i] * (float)num);
				BitConverter.GetBytes(value).CopyTo(array, i * 2);
			}
			return array;
		}

		public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName)
		{
			int num = 16;
			int num2 = num / 8;
			AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false);
			val.SetData(ConvertByteArrayToFloatArray(byteArray), 0);
			return val;
		}

		private static float[] ConvertByteArrayToFloatArray(byte[] byteArray)
		{
			float[] array = new float[byteArray.Length / 2];
			int num = 32767;
			for (int i = 0; i < array.Length; i++)
			{
				short num2 = BitConverter.ToInt16(byteArray, i * 2);
				array[i] = (float)num2 / (float)num;
			}
			return array;
		}

		public static AudioClip LoadFromDiskToAudioClip(string path)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			AudioClip result = null;
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)14);
			try
			{
				audioClip.SendWebRequest();
				try
				{
					while (!audioClip.isDone)
					{
					}
					if ((int)audioClip.result != 1)
					{
						SoundTool.Instance.logger.LogError((object)("Failed to load OGGVORBIS AudioClip from path: " + path + " Full error: " + audioClip.error));
					}
					else
					{
						result = DownloadHandlerAudioClip.GetContent(audioClip);
					}
				}
				catch (Exception ex)
				{
					SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace));
				}
			}
			finally
			{
				((IDisposable)audioClip)?.Dispose();
			}
			return result;
		}
	}
	public static class WavUtility
	{
		public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples)
		{
			samples = new float[audioClip.samples * audioClip.channels];
			audioClip.GetData(samples, 0);
			byte[] array = new byte[samples.Length * 2];
			int num = 32767;
			for (int i = 0; i < samples.Length; i++)
			{
				short value = (short)(samples[i] * (float)num);
				BitConverter.GetBytes(value).CopyTo(array, i * 2);
			}
			return array;
		}

		public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName)
		{
			int num = 16;
			int num2 = num / 8;
			AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false);
			val.SetData(ConvertByteArrayToFloatArray(byteArray), 0);
			return val;
		}

		private static float[] ConvertByteArrayToFloatArray(byte[] byteArray)
		{
			float[] array = new float[byteArray.Length / 2];
			int num = 32767;
			for (int i = 0; i < array.Length; i++)
			{
				short num2 = BitConverter.ToInt16(byteArray, i * 2);
				array[i] = (float)num2 / (float)num;
			}
			return array;
		}

		public static AudioClip LoadFromDiskToAudioClip(string path)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			AudioClip result = null;
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)20);
			try
			{
				audioClip.SendWebRequest();
				try
				{
					while (!audioClip.isDone)
					{
					}
					if ((int)audioClip.result != 1)
					{
						SoundTool.Instance.logger.LogError((object)("Failed to load WAV AudioClip from path: " + path + " Full error: " + audioClip.error));
					}
					else
					{
						result = DownloadHandlerAudioClip.GetContent(audioClip);
					}
				}
				catch (Exception ex)
				{
					SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace));
				}
			}
			finally
			{
				((IDisposable)audioClip)?.Dispose();
			}
			return result;
		}
	}
}
namespace LCSoundTool.Patches
{
	[HarmonyPatch(typeof(AudioSource))]
	internal class AudioSourcePatch
	{
		private static Dictionary<string, AudioClip> originalClips = new Dictionary<string, AudioClip>();

		[HarmonyPatch("Play", new Type[] { })]
		[HarmonyPrefix]
		public static void Play_Patch(AudioSource __instance)
		{
			RunDynamicClipReplacement(__instance);
			DebugPlayMethod(__instance);
		}

		[HarmonyPatch("Play", new Type[] { typeof(ulong) })]
		[HarmonyPrefix]
		public static void Play_UlongPatch(AudioSource __instance)
		{
			RunDynamicClipReplacement(__instance);
			DebugPlayMethod(__instance);
		}

		[HarmonyPatch("Play", new Type[] { typeof(double) })]
		[HarmonyPrefix]
		public static void Play_DoublePatch(AudioSource __instance)
		{
			RunDynamicClipReplacement(__instance);
			DebugPlayMethod(__instance);
		}

		[HarmonyPatch("PlayDelayed", new Type[] { typeof(float) })]
		[HarmonyPrefix]
		public static void PlayDelayed_Patch(AudioSource __instance)
		{
			RunDynamicClipReplacement(__instance);
			DebugPlayDelayedMethod(__instance);
		}

		[HarmonyPatch("PlayClipAtPoint", new Type[]
		{
			typeof(AudioClip),
			typeof(Vector3),
			typeof(float)
		})]
		[HarmonyPrefix]
		public static bool PlayClipAtPoint_Patch(AudioClip clip, Vector3 position, float volume)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0012: 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)
			GameObject val = new GameObject("One shot audio");
			val.transform.position = position;
			AudioSource val2 = val.AddComponent<AudioSource>();
			val2.clip = clip;
			val2.spatialBlend = 1f;
			val2.volume = volume;
			RunDynamicClipReplacement(val2);
			val2.Play();
			DebugPlayClipAtPointMethod(val2, position);
			Object.Destroy((Object)(object)val, clip.length * ((Time.timeScale < 0.01f) ? 0.01f : Time.timeScale));
			return false;
		}

		[HarmonyPatch("PlayOneShotHelper", new Type[]
		{
			typeof(AudioSource),
			typeof(AudioClip),
			typeof(float)
		})]
		[HarmonyPrefix]
		public static void PlayOneShotHelper_Patch(AudioSource source, ref AudioClip clip, float volumeScale)
		{
			clip = ReplaceClipWithNew(clip);
			DebugPlayOneShotMethod(source, clip);
		}

		private static void DebugPlayMethod(AudioSource instance)
		{
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)instance != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{instance} at {((Component)instance).transform.root} is playing {((Object)instance.clip).name}");
			}
			else if (SoundTool.indepthDebugging && (Object)(object)instance != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{instance} is playing {((Object)instance.clip).name} at");
				Transform val = ((Component)instance).transform;
				while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)instance).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}");
					val = val.parent;
				}
				if ((Object)(object)val == (Object)(object)((Component)instance).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)instance).transform.root}");
				}
			}
		}

		private static void DebugPlayDelayedMethod(AudioSource instance)
		{
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)instance != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{instance} at {((Component)instance).transform.root} is playing {((Object)instance.clip).name} with delay");
			}
			else if (SoundTool.indepthDebugging && (Object)(object)instance != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{instance} is playing {((Object)instance.clip).name} with delay at");
				Transform val = ((Component)instance).transform;
				while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)instance).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}");
					val = val.parent;
				}
				if ((Object)(object)val == (Object)(object)((Component)instance).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)instance).transform.root}");
				}
			}
		}

		private static void DebugPlayClipAtPointMethod(AudioSource audioSource, Vector3 position)
		{
			//IL_0065: 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)
			if ((Object)(object)audioSource == (Object)null)
			{
				return;
			}
			if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{audioSource} at {((Component)audioSource).transform.root} is playing {((Object)audioSource.clip).name} at point {position}");
			}
			else if (SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{audioSource} is playing {((Object)audioSource.clip).name} located at point {position} within ");
				Transform val = ((Component)audioSource).transform;
				while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)audioSource).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}");
					val = val.parent;
				}
				if ((Object)(object)val == (Object)(object)((Component)audioSource).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)audioSource).transform.root}");
				}
			}
		}

		private static void DebugPlayOneShotMethod(AudioSource source, AudioClip clip)
		{
			if ((Object)(object)source == (Object)null || (Object)(object)clip == (Object)null)
			{
				return;
			}
			if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)source != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{source} at {((Component)source).transform.root} is playing one shot {((Object)clip).name}");
			}
			else if (SoundTool.indepthDebugging && (Object)(object)source != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{source} is playing one shot {((Object)clip).name} at");
				Transform val = ((Component)source).transform;
				while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)source).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}");
					val = val.parent;
				}
				if ((Object)(object)val == (Object)(object)((Component)source).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)source).transform.root}");
				}
			}
		}

		private static void RunDynamicClipReplacement(AudioSource instance)
		{
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.clip == (Object)null)
			{
				return;
			}
			string name = instance.clip.GetName();
			if (SoundTool.replacedClips.ContainsKey(name))
			{
				if (!originalClips.ContainsKey(name))
				{
					originalClips.Add(name, instance.clip);
				}
				List<RandomAudioClip> list = SoundTool.replacedClips[name];
				float num = 0f;
				foreach (RandomAudioClip item in list)
				{
					num += item.chance;
				}
				float num2 = Random.Range(0f, num);
				{
					foreach (RandomAudioClip item2 in list)
					{
						if (num2 <= item2.chance)
						{
							instance.clip = item2.clip;
							break;
						}
						num2 -= item2.chance;
					}
					return;
				}
			}
			if (originalClips.ContainsKey(name))
			{
				instance.clip = originalClips[name];
				originalClips.Remove(name);
			}
		}

		private static AudioClip ReplaceClipWithNew(AudioClip original)
		{
			if ((Object)(object)original == (Object)null)
			{
				return original;
			}
			string name = original.GetName();
			if (SoundTool.replacedClips.ContainsKey(name))
			{
				if (!originalClips.ContainsKey(name))
				{
					originalClips.Add(name, original);
				}
				List<RandomAudioClip> list = SoundTool.replacedClips[name];
				float num = 0f;
				foreach (RandomAudioClip item in list)
				{
					num += item.chance;
				}
				float num2 = Random.Range(0f, num);
				foreach (RandomAudioClip item2 in list)
				{
					if (num2 <= item2.chance)
					{
						return item2.clip;
					}
					num2 -= item2.chance;
				}
			}
			else if (originalClips.ContainsKey(name))
			{
				AudioClip result = originalClips[name];
				originalClips.Remove(name);
				return result;
			}
			return original;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		public static GameObject networkPrefab;

		public static GameObject networkHandlerHost;

		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		public static void Start_Patch()
		{
			if (!((Object)(object)networkPrefab != (Object)null))
			{
				SoundTool.Instance.logger.LogDebug((object)"Loading NetworkHandler prefab...");
				networkPrefab = Assets.bundle.LoadAsset<GameObject>("SoundToolNetworkHandler.prefab");
				if ((Object)(object)networkPrefab == (Object)null)
				{
					SoundTool.Instance.logger.LogError((object)"Failed to load NetworkHandler prefab!");
				}
				if ((Object)(object)networkPrefab != (Object)null)
				{
					NetworkManager.Singleton.AddNetworkPrefab(networkPrefab);
					SoundTool.Instance.logger.LogDebug((object)"Registered NetworkHandler prefab!");
				}
				else
				{
					SoundTool.Instance.logger.LogWarning((object)"Failed to registered NetworkHandler prefab! No networking can take place.");
				}
			}
		}

		[HarmonyPatch("StartDisconnect")]
		[HarmonyPostfix]
		private static void StartDisconnect_Patch()
		{
			try
			{
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					SoundTool.Instance.logger.LogDebug((object)"Destroying NetworkHandler prefab!");
					Object.Destroy((Object)(object)networkHandlerHost);
					networkHandlerHost = null;
				}
			}
			catch
			{
				SoundTool.Instance.logger.LogError((object)"Failed to destroy NetworkHandler prefab!");
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void SpawnNetworkHandler()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					SoundTool.Instance.logger.LogDebug((object)"Spawning NetworkHandler prefab!");
					GameNetworkManagerPatch.networkHandlerHost = Object.Instantiate<GameObject>(GameNetworkManagerPatch.networkPrefab, Vector3.zero, Quaternion.identity);
					GameNetworkManagerPatch.networkHandlerHost.GetComponent<NetworkObject>().Spawn(true);
				}
			}
			catch
			{
				SoundTool.Instance.logger.LogError((object)"Failed to spawn NetworkHandler prefab!");
			}
		}
	}
}
namespace LCSoundTool.Networking
{
	public class NetworkHandler : NetworkBehaviour
	{
		public static NetworkHandler Instance { get; private set; }

		public static Dictionary<string, AudioClip> networkedAudioClips { get; private set; }

		public static event Action ClientNetworkedAudioChanged;

		public static event Action HostNetworkedAudioChanged;

		public override void OnNetworkSpawn()
		{
			Debug.Log((object)"LCSoundTool - NetworkHandler created!");
			NetworkHandler.ClientNetworkedAudioChanged = null;
			NetworkHandler.HostNetworkedAudioChanged = null;
			networkedAudioClips = new Dictionary<string, AudioClip>();
			Instance = this;
		}

		[ClientRpc]
		public void ReceiveAudioClipClientRpc(string clipName, byte[] audioData)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: 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_00c6: 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_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			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(2736638642u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				bool flag2 = audioData != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioData, default(ForPrimitives));
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2736638642u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			if (!networkedAudioClips.ContainsKey(clipName))
			{
				AudioClip val3 = null;
				if (SoundTool.clipTypes.ContainsKey(clipName))
				{
					if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.ogg)
					{
						val3 = OggUtility.ByteArrayToAudioClip(audioData, clipName);
					}
					else if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.mp3)
					{
						val3 = Mp3Utility.ByteArrayToAudioClip(audioData, clipName);
					}
				}
				if ((Object)(object)val3 == (Object)null)
				{
					val3 = WavUtility.ByteArrayToAudioClip(audioData, clipName);
				}
				networkedAudioClips.Add(clipName, val3);
				NetworkHandler.ClientNetworkedAudioChanged?.Invoke();
			}
			else
			{
				SoundTool.Instance.logger.LogDebug((object)("Sound " + clipName + " already exists for this client! Skipping addition of this sound for this client."));
			}
		}

		[ClientRpc]
		public void RemoveAudioClipClientRpc(string clipName)
		{
			//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(1355469546u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1355469546u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && networkedAudioClips.ContainsKey(clipName))
			{
				networkedAudioClips.Remove(clipName);
				NetworkHandler.ClientNetworkedAudioChanged?.Invoke();
			}
		}

		[ClientRpc]
		public void SyncAudioClipsClientRpc(Strings clipNames)
		{
			//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)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3300200130u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<Strings>(ref clipNames, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3300200130u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			string[] myStrings = clipNames.MyStrings;
			for (int i = 0; i < myStrings.Length; i++)
			{
				if (!networkedAudioClips.ContainsKey(myStrings[i]))
				{
					SendExistingAudioClipServerRpc(myStrings[i]);
				}
			}
		}

		[ClientRpc]
		public void ReceiveSeedClientRpc(int seed)
		{
			//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(1556253924u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, seed);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1556253924u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Random.InitState(seed);
					SoundTool.Instance.logger.LogDebug((object)$"Client received a new Unity Random seed of {seed}!");
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SendAudioClipServerRpc(string clipName, byte[] audioData)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: 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_00c6: 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_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(867452943u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				bool flag2 = audioData != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioData, default(ForPrimitives));
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 867452943u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ReceiveAudioClipClientRpc(clipName, audioData);
				NetworkHandler.HostNetworkedAudioChanged?.Invoke();
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void RemoveAudioClipServerRpc(string clipName)
		{
			//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 != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3103497155u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3103497155u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				RemoveAudioClipClientRpc(clipName);
				NetworkHandler.HostNetworkedAudioChanged?.Invoke();
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SyncAudioClipsServerRpc()
		{
			//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 != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(178607916u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 178607916u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				Strings clipNames = new Strings(networkedAudioClips.Keys.ToArray());
				if (clipNames.MyStrings.Length < 1)
				{
					SoundTool.Instance.logger.LogDebug((object)"No sounds found in networkedClips. Syncing process cancelled!");
				}
				else
				{
					SyncAudioClipsClientRpc(clipNames);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SendExistingAudioClipServerRpc(string clipName)
		{
			//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 != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(4006259189u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 4006259189u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			if (networkedAudioClips.ContainsKey(clipName))
			{
				byte[] array = null;
				if (SoundTool.clipTypes.ContainsKey(clipName))
				{
					if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.ogg)
					{
						array = OggUtility.AudioClipToByteArray(networkedAudioClips[clipName], out var _);
					}
					else if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.mp3)
					{
						array = Mp3Utility.AudioClipToByteArray(networkedAudioClips[clipName], out var _);
					}
				}
				if (array == null)
				{
					array = WavUtility.AudioClipToByteArray(networkedAudioClips[clipName], out var _);
				}
				ReceiveAudioClipClientRpc(clipName, array);
			}
			else
			{
				SoundTool.Instance.logger.LogWarning((object)"Trying to obtain and sync a sound from the host that does not exist in the host's game!");
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SendSeedToClientsServerRpc(int seed)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(4286510828u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, seed);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 4286510828u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && ((NetworkBehaviour)this).IsHost)
				{
					ReceiveSeedClientRpc(seed);
					SoundTool.Instance.logger.LogDebug((object)$"Sending a new Unity random seed of {seed} to all clients...");
				}
			}
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_NetworkHandler()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(2736638642u, new RpcReceiveHandler(__rpc_handler_2736638642));
			NetworkManager.__rpc_func_table.Add(1355469546u, new RpcReceiveHandler(__rpc_handler_1355469546));
			NetworkManager.__rpc_func_table.Add(3300200130u, new RpcReceiveHandler(__rpc_handler_3300200130));
			NetworkManager.__rpc_func_table.Add(1556253924u, new RpcReceiveHandler(__rpc_handler_1556253924));
			NetworkManager.__rpc_func_table.Add(867452943u, new RpcReceiveHandler(__rpc_handler_867452943));
			NetworkManager.__rpc_func_table.Add(3103497155u, new RpcReceiveHandler(__rpc_handler_3103497155));
			NetworkManager.__rpc_func_table.Add(178607916u, new RpcReceiveHandler(__rpc_handler_178607916));
			NetworkManager.__rpc_func_table.Add(4006259189u, new RpcReceiveHandler(__rpc_handler_4006259189));
			NetworkManager.__rpc_func_table.Add(4286510828u, new RpcReceiveHandler(__rpc_handler_4286510828));
		}

		private static void __rpc_handler_2736638642(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_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string clipName = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false);
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				byte[] audioData = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioData, default(ForPrimitives));
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).ReceiveAudioClipClientRpc(clipName, audioData);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1355469546(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 clipName = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).RemoveAudioClipClientRpc(clipName);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3300200130(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)
			{
				Strings clipNames = default(Strings);
				((FastBufferReader)(ref reader)).ReadValueSafe<Strings>(ref clipNames, default(ForNetworkSerializable));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).SyncAudioClipsClientRpc(clipNames);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1556253924(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 seed = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref seed);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).ReceiveSeedClientRpc(seed);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_867452943(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_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string clipName = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false);
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				byte[] audioData = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioData, default(ForPrimitives));
				}
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).SendAudioClipServerRpc(clipName, audioData);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3103497155(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 clipName = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).RemoveAudioClipServerRpc(clipName);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_178607916(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).SyncAudioClipsServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_4006259189(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 clipName = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).SendExistingAudioClipServerRpc(clipName);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_4286510828(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 seed = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref seed);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).SendSeedToClientsServerRpc(seed);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "NetworkHandler";
		}
	}
	public struct Strings : INetworkSerializable
	{
		private string[] myStrings;

		public string[] MyStrings
		{
			get
			{
				return myStrings;
			}
			set
			{
				myStrings = value;
			}
		}

		public Strings(string[] myStrings)
		{
			this.myStrings = myStrings;
		}

		public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
		{
			//IL_000f: 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_0024: 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_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			if (serializer.IsWriter)
			{
				FastBufferWriter fastBufferWriter = serializer.GetFastBufferWriter();
				int num = myStrings.Length;
				((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				for (int i = 0; i < myStrings.Length; i++)
				{
					((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe(myStrings[i], false);
				}
			}
			if (serializer.IsReader)
			{
				FastBufferReader fastBufferReader = serializer.GetFastBufferReader();
				int num2 = default(int);
				((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num2, default(ForPrimitives));
				myStrings = new string[num2];
				for (int j = 0; j < num2; j++)
				{
					((FastBufferReader)(ref fastBufferReader)).ReadValueSafe(ref myStrings[j], false);
				}
			}
		}
	}
}
namespace LCSoundTool.Resources
{
	public static class Assets
	{
		internal static AssetBundle bundle;
	}
}

notnotnotswipez-MoreCompany/MoreCompany.dll

Decompiled 6 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;
		}
	}
}

RickArg-Helmet_Cameras/HelmetCamera.dll

Decompiled 6 months ago
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;
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("HelmetCamera")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HelmetCamera")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("b99c4d46-5f13-47b3-a5af-5e3f37772e77")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HelmetCamera
{
	[BepInPlugin("RickArg.lethalcompany.helmetcameras", "Helmet_Cameras", "2.1.5")]
	public class PluginInit : BaseUnityPlugin
	{
		public static Harmony _harmony;

		public static ConfigEntry<int> config_isHighQuality;

		public static ConfigEntry<int> config_renderDistance;

		public static ConfigEntry<int> config_cameraFps;

		private void Awake()
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			config_isHighQuality = ((BaseUnityPlugin)this).Config.Bind<int>("MONITOR QUALITY", "monitorResolution", 0, "Low FPS affection. High Quality mode. 0 - vanilla (48x48), 1 - vanilla+ (128x128), 2 - mid quality (256x256), 3 - high quality (512x512), 4 - Very High Quality (1024x1024)");
			config_renderDistance = ((BaseUnityPlugin)this).Config.Bind<int>("MONITOR QUALITY", "renderDistance", 20, "Low FPS affection. Render distance for helmet camera.");
			config_cameraFps = ((BaseUnityPlugin)this).Config.Bind<int>("MONITOR QUALITY", "cameraFps", 30, "Very high FPS affection. FPS for helmet camera. To increase YOUR fps, you should low cameraFps value.");
			_harmony = new Harmony("HelmetCamera");
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Helmet_Cameras is loaded with version 2.1.5!");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"--------Helmet camera patch done.---------");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "RickArg.lethalcompany.helmetcameras";

		public const string PLUGIN_NAME = "Helmet_Cameras";

		public const string PLUGIN_VERSION = "2.1.5";
	}
	public class Plugin : MonoBehaviour
	{
		private RenderTexture renderTexture;

		private bool isMonitorChanged = false;

		private GameObject helmetCameraNew;

		private bool isSceneLoaded = false;

		private bool isCoroutineStarted = false;

		private int currentTransformIndex;

		private int resolution = 0;

		private int renderDistance = 50;

		private float cameraFps = 30f;

		private float elapsed;

		private void Awake()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Expected O, but got Unknown
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			resolution = PluginInit.config_isHighQuality.Value;
			renderDistance = PluginInit.config_renderDistance.Value;
			cameraFps = PluginInit.config_cameraFps.Value;
			switch (resolution)
			{
			case 0:
				renderTexture = new RenderTexture(48, 48, 24);
				break;
			case 1:
				renderTexture = new RenderTexture(128, 128, 24);
				break;
			case 2:
				renderTexture = new RenderTexture(256, 256, 24);
				break;
			case 3:
				renderTexture = new RenderTexture(512, 512, 24);
				break;
			case 4:
				renderTexture = new RenderTexture(1024, 1024, 24);
				break;
			}
		}

		public void Start()
		{
			//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_0031: 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_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)
			isCoroutineStarted = false;
			while ((Object)(object)helmetCameraNew == (Object)null)
			{
				helmetCameraNew = new GameObject("HelmetCamera");
			}
			Scene activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).name != "MainMenu")
			{
				activeScene = SceneManager.GetActiveScene();
				if (((Scene)(ref activeScene)).name != "InitScene")
				{
					activeScene = SceneManager.GetActiveScene();
					if (((Scene)(ref activeScene)).name != "InitSceneLaunchOptions")
					{
						isSceneLoaded = true;
						Debug.Log((object)"[HELMET_CAMERAS] Starting coroutine...");
						((MonoBehaviour)this).StartCoroutine(LoadSceneEnter());
						return;
					}
				}
			}
			isSceneLoaded = false;
			isMonitorChanged = false;
		}

		private IEnumerator LoadSceneEnter()
		{
			Debug.Log((object)"[HELMET_CAMERAS] 5 seconds for init mode... Please wait...");
			yield return (object)new WaitForSeconds(5f);
			isCoroutineStarted = true;
			if ((Object)(object)GameObject.Find("Environment/HangarShip/Cameras/ShipCamera") != (Object)null)
			{
				Debug.Log((object)"[HELMET_CAMERAS] Ship camera founded...");
				if (!isMonitorChanged)
				{
					((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube").GetComponent<MeshRenderer>()).materials[2].mainTexture = ((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001").GetComponent<MeshRenderer>()).materials[2].mainTexture;
					((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001").GetComponent<MeshRenderer>()).materials[2].mainTexture = (Texture)(object)renderTexture;
					helmetCameraNew.AddComponent<Camera>();
					((Behaviour)helmetCameraNew.GetComponent<Camera>()).enabled = false;
					helmetCameraNew.GetComponent<Camera>().targetTexture = renderTexture;
					helmetCameraNew.GetComponent<Camera>().cullingMask = 20649983;
					helmetCameraNew.GetComponent<Camera>().farClipPlane = renderDistance;
					helmetCameraNew.GetComponent<Camera>().nearClipPlane = 0.55f;
					isMonitorChanged = true;
					Debug.Log((object)"[HELMET_CAMERAS] Monitors were changed...");
					Debug.Log((object)"[HELMET_CAMERAS] Turning off vanilla internal ship camera");
					((Behaviour)GameObject.Find("Environment/HangarShip/Cameras/ShipCamera").GetComponent<Camera>()).enabled = false;
				}
			}
		}

		public void Update()
		{
			//IL_022b: 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_0244: 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)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_012e: 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_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			bool flag = isSceneLoaded && isCoroutineStarted;
			if (flag && StartOfRound.Instance.localPlayerController.isInHangarShipRoom)
			{
				helmetCameraNew.SetActive(true);
				elapsed += Time.deltaTime;
				if (elapsed > 1f / cameraFps)
				{
					elapsed = 0f;
					((Behaviour)helmetCameraNew.GetComponent<Camera>()).enabled = true;
				}
				else
				{
					((Behaviour)helmetCameraNew.GetComponent<Camera>()).enabled = false;
				}
				GameObject val = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001/CameraMonitorScript");
				currentTransformIndex = val.GetComponent<ManualCameraRenderer>().targetTransformIndex;
				TransformAndName val2 = val.GetComponent<ManualCameraRenderer>().radarTargets[currentTransformIndex];
				if (!val2.isNonPlayer)
				{
					try
					{
						helmetCameraNew.transform.SetPositionAndRotation(val2.transform.Find("ScavengerModel/metarig/CameraContainer/MainCamera/HelmetLights").position + new Vector3(0f, 0f, 0f), val2.transform.Find("ScavengerModel/metarig/CameraContainer/MainCamera/HelmetLights").rotation * Quaternion.Euler(0f, 0f, 0f));
						DeadBodyInfo[] array = Object.FindObjectsOfType<DeadBodyInfo>();
						for (int i = 0; i < array.Length; i++)
						{
							if (array[i].playerScript.playerUsername == val2.name)
							{
								helmetCameraNew.transform.SetPositionAndRotation(((Component)array[i]).gameObject.transform.Find("spine.001/spine.002/spine.003").position, ((Component)array[i]).gameObject.transform.Find("spine.001/spine.002/spine.003").rotation * Quaternion.Euler(0f, 0f, 0f));
							}
						}
						return;
					}
					catch (NullReferenceException)
					{
						Debug.Log((object)"[HELMET_CAMERAS] ERROR NULL REFERENCE");
						return;
					}
				}
				helmetCameraNew.transform.SetPositionAndRotation(val2.transform.position + new Vector3(0f, 1.6f, 0f), val2.transform.rotation * Quaternion.Euler(0f, -90f, 0f));
			}
			else if (flag && !StartOfRound.Instance.localPlayerController.isInHangarShipRoom)
			{
				helmetCameraNew.SetActive(false);
			}
		}
	}
}
namespace HelmetCamera.Patches
{
	[HarmonyPatch]
	internal class HelmetCamera
	{
		public static void InitCameras()
		{
			GameObject val = GameObject.Find("Environment/HangarShip/Cameras/ShipCamera");
			val.AddComponent<Plugin>();
		}

		[HarmonyPatch(typeof(StartOfRound), "Start")]
		[HarmonyPostfix]
		public static void InitCamera(ref ManualCameraRenderer __instance)
		{
			InitCameras();
		}
	}
}

RugbugRedfern-Skinwalkers/SkinwalkerMod.dll

Decompiled 6 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";
	}
}

x753-More_Suits/MoreSuits.dll

Decompiled 6 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;
	}
}