Decompiled source of Halalos Vallalat Modpack v1.1.1

BepInEx/plugins/CustomBoomboxFix.dll

Decompiled 7 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 Microsoft.CodeAnalysis;

[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("CustomBoomboxFix")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("CustomBoomboxFix")]
[assembly: AssemblyTitle("CustomBoomboxFix")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CustomBoomboxFix
{
	[BepInPlugin("CustomBoomboxFix", "CustomBoomboxFix", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private string CustomSongsPluginPath => Path.Combine(Paths.PluginPath, "Custom Songs");

		private string TargetPath => Path.Combine(Paths.BepInExRootPath, "Custom Songs", "Boombox Music");

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin CustomBoomboxFix is loaded!");
			CreatePluginCustomSongsFolder();
			DeleteAllFilesInTargetPath();
			SearchAndCopyCustomSongs();
			CopyMusicFiles();
		}

		private void CreatePluginCustomSongsFolder()
		{
			if (!Directory.Exists(CustomSongsPluginPath))
			{
				Directory.CreateDirectory(CustomSongsPluginPath);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Created 'Custom Songs' folder in plugin directory.");
			}
		}

		private void CopyMusicFiles()
		{
			if (!Directory.Exists(TargetPath))
			{
				Directory.CreateDirectory(TargetPath);
			}
			IEnumerable<string> enumerable = Directory.GetFiles(CustomSongsPluginPath, "*.mp3").Concat(Directory.GetFiles(CustomSongsPluginPath, "*.wav"));
			foreach (string item in enumerable)
			{
				string fileName = Path.GetFileName(item);
				string text = Path.Combine(TargetPath, fileName);
				if (!File.Exists(text))
				{
					File.Copy(item, text);
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Copied " + fileName + " to Boombox Music folder."));
				}
			}
		}

		private void DeleteAllFilesInTargetPath()
		{
			try
			{
				if (Directory.Exists(TargetPath))
				{
					string[] files = Directory.GetFiles(TargetPath);
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Deleting files in '" + TargetPath + "'..."));
					string[] array = files;
					foreach (string path in array)
					{
						File.Delete(path);
					}
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Deleted files in '" + TargetPath + "'"));
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Target path '" + TargetPath + "' does not exist."));
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("An error occurred while trying to delete files: " + ex.Message));
			}
		}

		private void SearchAndCopyCustomSongs()
		{
			string[] directories = Directory.GetDirectories(Paths.PluginPath);
			string[] array = directories;
			foreach (string path in array)
			{
				string text = Path.Combine(path, "Custom Songs");
				if (!Directory.Exists(text))
				{
					continue;
				}
				IEnumerable<string> enumerable = Directory.GetFiles(text, "*.mp3").Concat(Directory.GetFiles(text, "*.wav"));
				foreach (string item in enumerable)
				{
					string fileName = Path.GetFileName(item);
					string text2 = Path.Combine(TargetPath, fileName);
					if (!File.Exists(text2))
					{
						File.Copy(item, text2);
						((BaseUnityPlugin)this).Logger.LogInfo((object)("Copied " + fileName + " from " + text + " to Boombox Music folder."));
					}
				}
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "CustomBoomboxFix";

		public const string PLUGIN_NAME = "CustomBoomboxFix";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

BepInEx/plugins/CustomBoomboxTracks.dll

Decompiled 7 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.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CustomBoomboxTracks.Configuration;
using CustomBoomboxTracks.Managers;
using CustomBoomboxTracks.Utilities;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CustomBoomboxTracks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.0")]
[assembly: AssemblyProduct("CustomBoomboxTracks")]
[assembly: AssemblyTitle("CustomBoomboxTracks")]
[assembly: AssemblyVersion("1.4.0.0")]
namespace CustomBoomboxTracks
{
	[BepInPlugin("com.steven.lethalcompany.boomboxmusic", "Custom Boombox Music", "1.4.0")]
	public class BoomboxPlugin : BaseUnityPlugin
	{
		private const string GUID = "com.steven.lethalcompany.boomboxmusic";

		private const string NAME = "Custom Boombox Music";

		private const string VERSION = "1.4.0";

		private static BoomboxPlugin Instance;

		private void Awake()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			LogInfo("Loading...");
			AudioManager.GenerateFolders();
			Config.Init();
			new Harmony("com.steven.lethalcompany.boomboxmusic").PatchAll();
			LogInfo("Loading Complete!");
		}

		internal static void LogDebug(string message)
		{
			Instance.Log(message, (LogLevel)32);
		}

		internal static void LogInfo(string message)
		{
			Instance.Log(message, (LogLevel)16);
		}

		internal static void LogWarning(string message)
		{
			Instance.Log(message, (LogLevel)4);
		}

		internal static void LogError(string message)
		{
			Instance.Log(message, (LogLevel)2);
		}

		internal static void LogError(Exception ex)
		{
			Instance.Log(ex.Message + "\n" + ex.StackTrace, (LogLevel)2);
		}

		private void Log(string message, LogLevel logLevel)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			((BaseUnityPlugin)this).Logger.Log(logLevel, (object)message);
		}
	}
}
namespace CustomBoomboxTracks.Utilities
{
	public class SharedCoroutineStarter : MonoBehaviour
	{
		private static SharedCoroutineStarter _instance;

		public static Coroutine StartCoroutine(IEnumerator routine)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_instance == (Object)null)
			{
				_instance = new GameObject("Shared Coroutine Starter").AddComponent<SharedCoroutineStarter>();
				Object.DontDestroyOnLoad((Object)(object)_instance);
			}
			return ((MonoBehaviour)_instance).StartCoroutine(routine);
		}
	}
}
namespace CustomBoomboxTracks.Patches
{
	[HarmonyPatch(typeof(BoomboxItem), "PocketItem")]
	internal class BoomboxItem_PocketItem
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			bool flag = false;
			for (int i = 0; i < list.Count; i++)
			{
				if (!flag)
				{
					if (list[i].opcode == OpCodes.Call)
					{
						flag = true;
					}
					continue;
				}
				if (list[i].opcode == OpCodes.Ret)
				{
					break;
				}
				list[i].opcode = OpCodes.Nop;
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(BoomboxItem), "Start")]
	internal class BoomboxItem_Start
	{
		private static void Postfix(BoomboxItem __instance)
		{
			if (AudioManager.FinishedLoading)
			{
				AudioManager.ApplyClips(__instance);
				return;
			}
			AudioManager.OnAllSongsLoaded += delegate
			{
				AudioManager.ApplyClips(__instance);
			};
		}
	}
	[HarmonyPatch(typeof(BoomboxItem), "StartMusic")]
	internal class BoomboxItem_StartMusic
	{
		private static void Postfix(BoomboxItem __instance, bool startMusic)
		{
			if (startMusic)
			{
				BoomboxPlugin.LogInfo("Playing " + ((Object)__instance.boomboxAudio.clip).name);
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "Awake")]
	internal class StartOfRound_Awake
	{
		private static void Prefix()
		{
			AudioManager.Load();
		}
	}
}
namespace CustomBoomboxTracks.Managers
{
	internal static class AudioManager
	{
		private static string[] allSongPaths;

		private static List<AudioClip> clips = new List<AudioClip>();

		private static bool firstRun = true;

		private static bool finishedLoading = false;

		private static readonly string directory = Path.Combine(Paths.BepInExRootPath, "Custom Songs", "Boombox Music");

		public static bool FinishedLoading => finishedLoading;

		public static bool HasNoSongs => allSongPaths.Length == 0;

		public static event Action OnAllSongsLoaded;

		public static void GenerateFolders()
		{
			Directory.CreateDirectory(directory);
			BoomboxPlugin.LogInfo("Created directory at " + directory);
		}

		public static void Load()
		{
			if (!firstRun)
			{
				return;
			}
			firstRun = false;
			allSongPaths = Directory.GetFiles(directory);
			if (allSongPaths.Length == 0)
			{
				BoomboxPlugin.LogWarning("No songs found!");
				return;
			}
			BoomboxPlugin.LogInfo("Preparing to load AudioClips...");
			List<Coroutine> list = new List<Coroutine>();
			string[] array = allSongPaths;
			for (int i = 0; i < array.Length; i++)
			{
				Coroutine item = SharedCoroutineStarter.StartCoroutine(LoadAudioClip(array[i]));
				list.Add(item);
			}
			SharedCoroutineStarter.StartCoroutine(WaitForAllClips(list));
		}

		private static IEnumerator LoadAudioClip(string filePath)
		{
			BoomboxPlugin.LogInfo("Loading " + filePath + "!");
			if ((int)GetAudioType(filePath) == 0)
			{
				BoomboxPlugin.LogError("Failed to load AudioClip from " + filePath + "\nUnsupported file extension!");
				yield break;
			}
			UnityWebRequest loader = UnityWebRequestMultimedia.GetAudioClip(filePath, GetAudioType(filePath));
			if (Config.StreamFromDisk)
			{
				DownloadHandler downloadHandler = loader.downloadHandler;
				((DownloadHandlerAudioClip)((downloadHandler is DownloadHandlerAudioClip) ? downloadHandler : null)).streamAudio = true;
			}
			loader.SendWebRequest();
			while (!loader.isDone)
			{
				yield return null;
			}
			if (loader.error != null)
			{
				BoomboxPlugin.LogError("Error loading clip from path: " + filePath + "\n" + loader.error);
				BoomboxPlugin.LogError(loader.error);
				yield break;
			}
			AudioClip content = DownloadHandlerAudioClip.GetContent(loader);
			if (Object.op_Implicit((Object)(object)content) && (int)content.loadState == 2)
			{
				BoomboxPlugin.LogInfo("Loaded " + filePath);
				((Object)content).name = Path.GetFileName(filePath);
				clips.Add(content);
			}
			else
			{
				BoomboxPlugin.LogError("Failed to load clip at: " + filePath + "\nThis might be due to an mismatch between the audio codec and the file extension!");
			}
		}

		private static IEnumerator WaitForAllClips(List<Coroutine> coroutines)
		{
			foreach (Coroutine coroutine in coroutines)
			{
				yield return coroutine;
			}
			clips.Sort((AudioClip first, AudioClip second) => ((Object)first).name.CompareTo(((Object)second).name));
			finishedLoading = true;
			AudioManager.OnAllSongsLoaded?.Invoke();
			AudioManager.OnAllSongsLoaded = null;
		}

		public static void ApplyClips(BoomboxItem __instance)
		{
			BoomboxPlugin.LogInfo("Applying clips!");
			if (Config.UseDefaultSongs)
			{
				__instance.musicAudios = __instance.musicAudios.Concat(clips).ToArray();
			}
			else
			{
				__instance.musicAudios = clips.ToArray();
			}
			BoomboxPlugin.LogInfo($"Total Clip Count: {__instance.musicAudios.Length}");
		}

		private static AudioType GetAudioType(string path)
		{
			string text = Path.GetExtension(path).ToLower();
			switch (text)
			{
			case ".wav":
				return (AudioType)20;
			case ".ogg":
				return (AudioType)14;
			case ".mp3":
				return (AudioType)13;
			default:
				BoomboxPlugin.LogError("Unsupported extension type: " + text);
				return (AudioType)0;
			}
		}
	}
}
namespace CustomBoomboxTracks.Configuration
{
	internal static class Config
	{
		private const string CONFIG_FILE_NAME = "boombox.cfg";

		private static ConfigFile _config;

		private static ConfigEntry<bool> _useDefaultSongs;

		private static ConfigEntry<bool> _streamAudioFromDisk;

		public static bool UseDefaultSongs
		{
			get
			{
				if (!_useDefaultSongs.Value)
				{
					return AudioManager.HasNoSongs;
				}
				return true;
			}
		}

		public static bool StreamFromDisk => _streamAudioFromDisk.Value;

		public static void Init()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			BoomboxPlugin.LogInfo("Initializing config...");
			_config = new ConfigFile(Path.Combine(Paths.ConfigPath, "boombox.cfg"), true);
			_useDefaultSongs = _config.Bind<bool>("Config", "Use Default Songs", false, "Include the default songs in the rotation.");
			_streamAudioFromDisk = _config.Bind<bool>("Config", "Stream Audio From Disk", false, "Requires less memory and takes less time to load, but prevents playing the same song twice at once.");
			BoomboxPlugin.LogInfo("Config initialized!");
		}

		private static void PrintConfig()
		{
			BoomboxPlugin.LogInfo($"Use Default Songs: {_useDefaultSongs.Value}");
			BoomboxPlugin.LogInfo($"Stream From Disk: {_streamAudioFromDisk}");
		}
	}
}

BepInEx/plugins/EnemyScan.dll

Decompiled 7 months ago
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using EnemyScan.Helper;
using HarmonyLib;
using TerminalApi;
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("EnemyScan")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EnemyScan")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("f9c8f099-56b1-4532-bf30-fcefcdb185c1")]
[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 EnemyScan
{
	[BepInPlugin("299792458.EnemyScan", "EnemyScan", "1.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class EnemyScan : BaseUnityPlugin
	{
		private const string modGUID = "299792458.EnemyScan";

		private const string modName = "EnemyScan";

		private const string modVersion = "1.1.1";

		private void Awake()
		{
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
			TerminalKeyword val = TerminalApi.CreateTerminalKeyword("list", true, (TerminalNode)null);
			TerminalKeyword val2 = TerminalApi.CreateTerminalKeyword("enemies", false, (TerminalNode)null);
			TerminalNode val3 = TerminalApi.CreateTerminalNode("No Enemies Found.\n", true, "");
			TerminalApi.AddTerminalKeyword(val2.defaultVerb = TerminalExtenstionMethods.AddCompatibleNoun(val, val2, val3));
			TerminalApi.AddTerminalKeyword(val2);
		}

		public static void UpdateEnemyCommand()
		{
			TerminalApi.UpdateKeywordCompatibleNoun("list", "enemies", TerminalApi.CreateTerminalNode(ScanEnemies.enemyString + "\n", true, ""));
		}
	}
}
namespace EnemyScan.Helper
{
	[HarmonyPatch(typeof(RoundManager))]
	public static class ScanEnemies
	{
		public static string enemyString = "No Enemies Found";

		[HarmonyPatch("BeginEnemySpawning")]
		[HarmonyPostfix]
		public static void BeginEnemySpawningUpdate()
		{
			UpdateEnemyCount();
		}

		[HarmonyPatch("SpawnEnemyFromVent")]
		[HarmonyPostfix]
		public static void SpawnEnemyFromVentUpdate()
		{
			UpdateEnemyCount();
		}

		[HarmonyPatch("AdvanceHourAndSpawnNewBatchOfEnemies")]
		[HarmonyPostfix]
		public static void AdvanceHourAndSpawnNewBatchOfEnemiesUpdate()
		{
			UpdateEnemyCount();
		}

		private static void UpdateEnemyCount()
		{
			EnemyAI[] source = Object.FindObjectsOfType<EnemyAI>();
			enemyString = BuildEnemyCountString(source.ToList());
			EnemyScan.UpdateEnemyCommand();
		}

		private static string BuildEnemyCountString(List<EnemyAI> enemies)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			foreach (EnemyAI enemy in enemies)
			{
				string enemyName = enemy.enemyType.enemyName;
				if (dictionary.ContainsKey(enemyName))
				{
					dictionary[enemyName]++;
				}
				else
				{
					dictionary[enemyName] = 1;
				}
			}
			StringBuilder stringBuilder = new StringBuilder();
			foreach (KeyValuePair<string, int> item in dictionary)
			{
				stringBuilder.AppendLine($"{item.Key}: {item.Value}");
			}
			if (stringBuilder.ToString() == "")
			{
				return "No Enemies Found.";
			}
			return stringBuilder.ToString();
		}
	}
}

BepInEx/plugins/HealthMetrics.dll

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

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

		private const string modName = "HealthMetrics";

		private const string modVersion = "1.0.0";

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

		private static HealthMetricsBase _instance;

		private static ManualLogSource _logSource;

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

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

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

		private static readonly string DefaultValueHealthText = " ¤";

		public static int _oldValuehealthValueForUpdater = 0;

		public static int _healthValueForUpdater = 100;

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

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

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void Start(ref HUDManager __instance)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("HealthHUDDisplay");
			val.AddComponent<RectTransform>();
			TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>();
			RectTransform rectTransform = ((TMP_Text)obj).rectTransform;
			((Transform)rectTransform).SetParent(((Component)__instance.PTTIcon).transform, false);
			rectTransform.anchoredPosition = new Vector2(8f, -57f);
			((TMP_Text)obj).font = ((TMP_Text)__instance.controlTipLines[0]).font;
			((TMP_Text)obj).fontSize = 16f;
			((TMP_Text)obj).text = "100";
			((Graphic)obj).color = _healthyColor;
			((TMP_Text)obj).overflowMode = (TextOverflowModes)0;
			((Behaviour)obj).enabled = true;
			_healthText = obj;
		}

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

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

		public static Color ColorInterpolation(Color start, Color end, double percentage)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			return new Color(hexToFloat(LinearInterpolation(floatToHex(start.r), floatToHex(end.r), percentage)), hexToFloat(LinearInterpolation(floatToHex(start.g), floatToHex(end.g), percentage)), hexToFloat(LinearInterpolation(floatToHex(start.b), floatToHex((int)end.b), percentage)), 1f);
		}

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

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

BepInEx/plugins/HelmetCamera.dll

Decompiled 7 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();
		}
	}
}

BepInEx/plugins/HideChat.dll

Decompiled 7 months ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("HideChat")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HideChat")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("fa900f4d-71b1-433a-ad23-a10fc53dc3d8")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HideChat
{
	[BepInPlugin("Miodec.HideChat", "Hide Chat", "1.0.0")]
	public class HidePlayerNames : BaseUnityPlugin
	{
		private const string modGUID = "Miodec.HideChat";

		private const string modName = "Hide Chat";

		private const string modVersion = "1.0.0";

		private static HidePlayerNames Instance;

		internal ManualLogSource mls;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("Miodec.HideChat");
			mls.LogDebug((object)"hidechat is awake");
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		}
	}
}
namespace HideChat.Patches
{
	[HarmonyPatch(typeof(HUDManager))]
	internal class HUDManagerPatch
	{
		[HarmonyPatch("OpenMenu_performed")]
		[HarmonyPatch("SubmitChat_performed")]
		[HarmonyPatch("AddChatMessage")]
		[HarmonyPostfix]
		public static void FadeToNothing(ref HUDManager __instance)
		{
			__instance.PingHUDElement(__instance.Chat, 5f, 1f, 0f);
		}
	}
}

BepInEx/plugins/HullBreakerCompany.dll

Decompiled 7 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.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using HullBreakerCompany.Events;
using HullBreakerCompany.Hull;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("HullBreakerCompany")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Making it more challenging to work for the company")]
[assembly: AssemblyFileVersion("1.3.9.0")]
[assembly: AssemblyInformationalVersion("1.3.9")]
[assembly: AssemblyProduct("HullBreakerCompany")]
[assembly: AssemblyTitle("HullBreakerCompany")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.3.9.0")]
[module: UnverifiableCode]
namespace HullBreakerCompany
{
	[BepInPlugin("HullBreakerCompany", "HullBreakerCompany", "1.3.9")]
	public class Plugin : BaseUnityPlugin
	{
		private static Dictionary<int, SelectableLevelState> _levelStates = new Dictionary<int, SelectableLevelState>();

		private static bool _loaded;

		public static ManualLogSource Mls;

		public static bool OneForAllIsActive;

		public static bool BountyIsActive;

		public static int DaysPassed;

		public static float BunkerEnemyScale;

		public static float LandMineTurretScale;

		public static bool UseShortChatMessages;

		public static bool EnableEventMessages;

		public static bool UseHullBreakerLevelSettings;

		public static bool UseDefaultGameSettings;

		public static int MaxEnemyPowerCount;

		public static int MaxOutsideEnemyPowerCount;

		public static int MaxDaytimeEnemyPowerCount;

		public static int MinScrap;

		public static int MaxScrap;

		public static int MinTotalScrapValue;

		public static int MaxTotalScrapValue;

		public static bool ChangeQuotaValue;

		public static int QuotaIncrease;

		public static bool IncreaseEventCountPerDay;

		public static int EventCount;

		public static List<SpawnableItemWithRarity> NotModifiedSpawnableItemsWithRarity = new List<SpawnableItemWithRarity>();

		public static Dictionary<string, Type> EnemyBase = new Dictionary<string, Type>
		{
			{
				"flowerman",
				typeof(FlowermanAI)
			},
			{
				"hoarderbug",
				typeof(HoarderBugAI)
			},
			{
				"springman",
				typeof(SpringManAI)
			},
			{
				"crawler",
				typeof(CrawlerAI)
			},
			{
				"sandspider",
				typeof(SandSpiderAI)
			},
			{
				"jester",
				typeof(JesterAI)
			},
			{
				"centipede",
				typeof(CentipedeAI)
			},
			{
				"blobai",
				typeof(BlobAI)
			},
			{
				"dressgirl",
				typeof(DressGirlAI)
			},
			{
				"pufferenemy",
				typeof(PufferAI)
			},
			{
				"eyelessdogs",
				typeof(MouthDogAI)
			},
			{
				"forestgiant",
				typeof(ForestGiantAI)
			},
			{
				"sandworm",
				typeof(SandWormAI)
			},
			{
				"baboonbird",
				typeof(BaboonBirdAI)
			},
			{
				"nutcrackerenemy",
				typeof(NutcrackerEnemyAI)
			},
			{
				"maskedplayerenemy",
				typeof(MaskedPlayerEnemy)
			}
		};

		public static List<HullEvent> EventDictionary = new List<HullEvent>
		{
			new FlowerManEvent(),
			new LandMineEvent(),
			new HoarderBugEvent(),
			new SpringManEvent(),
			new LizardsEvent(),
			new ArachnophobiaEvent(),
			new BeeEvent(),
			new SlimeEvent(),
			new DevochkaPizdecEvent(),
			new EnemyBountyEvent(),
			new OpenTheNoorEvent(),
			new OnAPowderKegEvent(),
			new OutSideEnemyDayEvent(),
			new HellEvent(),
			new NothingEvent(),
			new HackedTurretsEvent(),
			new BabkinPogrebEvent(),
			new HullBreakEvent(),
			new NutcrackerEvent()
		};

		private readonly Harmony _harmony = new Harmony("HULLBREAKER");

		private void Awake()
		{
			Mls = Logger.CreateLogSource("HULLBREAKER 1.3.9");
			Mls.LogInfo((object)"Ready to break hull; HullBreakerCompany");
			_harmony.PatchAll(typeof(Plugin));
			if (!_loaded)
			{
				Initialize();
			}
		}

		public void Start()
		{
			if (!_loaded)
			{
				Initialize();
			}
		}

		public void OnDestroy()
		{
			if (!_loaded)
			{
				Initialize();
			}
		}

		public void Initialize()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			ConfigManager.SetConfigValue();
			GameObject val = new GameObject("HullManager");
			Object.DontDestroyOnLoad((Object)(object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<HullManager>();
			Mls.LogInfo((object)"HullManager created");
			CustomEventLoader.LoadCustomEvents();
			_loaded = true;
		}

		[HarmonyPatch(typeof(RoundManager), "LoadNewLevel")]
		[HarmonyPrefix]
		private static bool ModifiedLoad(ref SelectableLevel newLevel)
		{
			//IL_0392: Unknown result type (might be due to invalid IL or missing references)
			//IL_0397: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bc: Expected O, but got Unknown
			//IL_03cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e3: Expected O, but got Unknown
			//IL_0469: Unknown result type (might be due to invalid IL or missing references)
			//IL_046e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0473: Unknown result type (might be due to invalid IL or missing references)
			//IL_047d: Expected O, but got Unknown
			Mls.LogInfo((object)("Client is host: " + ((NetworkBehaviour)RoundManager.Instance).IsHost));
			if (!((NetworkBehaviour)RoundManager.Instance).IsHost)
			{
				return true;
			}
			CustomEventLoader.DebugLoadCustomEvents();
			int levelID = newLevel.levelID;
			if (!_levelStates.ContainsKey(levelID))
			{
				_levelStates[levelID] = new SelectableLevelState(newLevel);
			}
			else
			{
				_levelStates[levelID].RestoreState(newLevel);
			}
			if (newLevel.levelID == 3)
			{
				Mls.LogInfo((object)"Level is company, skipping");
				DaysPassed = 0;
				return true;
			}
			DaysPassed++;
			Mls.LogInfo((object)$"Days passed: {DaysPassed}");
			BountyIsActive = false;
			OneForAllIsActive = false;
			ResetLevelUnits(newLevel);
			SelectableLevel val = newLevel;
			List<string> randomGameEvents = RandomSelector.GetRandomGameEvents();
			Dictionary<Type, int> dictionary = new Dictionary<Type, int>();
			Dictionary<Type, int> dictionary2 = new Dictionary<Type, int>();
			dictionary.Clear();
			NotModifiedSpawnableItemsWithRarity.Clear();
			foreach (SpawnableItemWithRarity item in val.spawnableScrap)
			{
				NotModifiedSpawnableItemsWithRarity.Add(item);
			}
			if (EventCount != 0 && EnableEventMessages)
			{
				HUDManager.Instance.AddTextToChatOnServer("<color=red>NOTES ABOUT MOON:</color>\"", -1);
			}
			foreach (string gameEvent in randomGameEvents)
			{
				try
				{
					HullEvent hullEvent = EventDictionary.FirstOrDefault((HullEvent e) => e.ID() == gameEvent);
					if (hullEvent != null)
					{
						hullEvent.Execute(newLevel, dictionary, dictionary2);
						Mls.LogInfo((object)("Event: " + gameEvent));
						UpdateRarity(newLevel.Enemies, dictionary);
						UpdateRarity(newLevel.OutsideEnemies, dictionary2);
					}
				}
				catch (NullReferenceException ex)
				{
					Mls.LogError((object)$"NullReferenceException caught while processing event: {gameEvent}. Exception message: {ex.Message}. Caused : {ex.InnerException}");
				}
			}
			HullManager.LogEnemyRarity(newLevel.Enemies, "⬛⬛⬛⬛⬛⬛ENEMIES RARITY⬛⬛⬛⬛⬛⬛");
			HullManager.LogEnemyRarity(newLevel.DaytimeEnemies, "⬛⬛⬛⬛⬛⬛DAYTIME ENEMIES RARITY⬛⬛⬛⬛⬛⬛");
			HullManager.LogEnemyRarity(newLevel.OutsideEnemies, "⬛⬛⬛⬛⬛⬛OUTSIDE ENEMIES RARITY⬛⬛⬛⬛⬛⬛");
			if (!randomGameEvents.Contains("Bee"))
			{
				using IEnumerator<SpawnableEnemyWithRarity> enumerator3 = val.DaytimeEnemies.Where((SpawnableEnemyWithRarity unit) => (Object)(object)unit.enemyType.enemyPrefab.GetComponent<RedLocustBees>() != (Object)null).GetEnumerator();
				if (enumerator3.MoveNext())
				{
					SpawnableEnemyWithRarity current2 = enumerator3.Current;
					current2.rarity = 22;
				}
			}
			if (UseHullBreakerLevelSettings)
			{
				val.maxEnemyPowerCount += 16;
				val.maxOutsideEnemyPowerCount += 20;
				val.maxScrap += Random.Range(6, 24);
				val.maxTotalScrapValue += Random.Range(400, 800);
				val.daytimeEnemySpawnChanceThroughDay = new AnimationCurve((Keyframe[])(object)new Keyframe[2]
				{
					new Keyframe(0f, 5f),
					new Keyframe(0.5f, 5f)
				});
				val.enemySpawnChanceThroughoutDay = new AnimationCurve((Keyframe[])(object)new Keyframe[1]
				{
					new Keyframe(0f, 256f)
				});
			}
			else if (UseDefaultGameSettings)
			{
				Mls.LogInfo((object)"Default settings");
			}
			else
			{
				val.maxEnemyPowerCount = MaxEnemyPowerCount;
				val.maxOutsideEnemyPowerCount = MaxOutsideEnemyPowerCount;
				val.maxDaytimeEnemyPowerCount = MaxDaytimeEnemyPowerCount;
				val.minScrap = MinScrap;
				val.maxScrap = MaxScrap;
				val.minTotalScrapValue = MinTotalScrapValue;
				val.maxTotalScrapValue = MaxTotalScrapValue;
				val.enemySpawnChanceThroughoutDay = new AnimationCurve((Keyframe[])(object)new Keyframe[1]
				{
					new Keyframe(0f, BunkerEnemyScale)
				});
			}
			newLevel = val;
			return true;
		}

		private static void UpdateRarity(List<SpawnableEnemyWithRarity> enemies, Dictionary<Type, int> componentRarity)
		{
			if (componentRarity.Count <= 0)
			{
				return;
			}
			foreach (SpawnableEnemyWithRarity unit in enemies)
			{
				foreach (KeyValuePair<Type, int> item in componentRarity)
				{
					if ((Object)(object)unit.enemyType.enemyPrefab.GetComponent(item.Key) == (Object)null)
					{
						continue;
					}
					if (enemies.Any((SpawnableEnemyWithRarity e) => (Object)(object)e.enemyType == (Object)(object)unit.enemyType))
					{
						unit.rarity = item.Value;
						componentRarity.Remove(item.Key);
					}
					break;
				}
			}
		}

		public static void LevelUnits(SelectableLevel n, bool turret = false, bool landmine = false)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: 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_005a: Expected O, but got Unknown
			Mls.LogInfo((object)$"Turret: {turret}, Landmine: {landmine}");
			AnimationCurve numberToSpawn = new AnimationCurve((Keyframe[])(object)new Keyframe[2]
			{
				new Keyframe(0f, LandMineTurretScale),
				new Keyframe(1f, 25f)
			});
			SpawnableMapObject[] spawnableMapObjects = n.spawnableMapObjects;
			foreach (SpawnableMapObject val in spawnableMapObjects)
			{
				Landmine componentInChildren = val.prefabToSpawn.GetComponentInChildren<Landmine>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					val.numberToSpawn = numberToSpawn;
				}
			}
		}

		private static void ResetLevelUnits(SelectableLevel level)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			SpawnableMapObject[] spawnableMapObjects = level.spawnableMapObjects;
			foreach (SpawnableMapObject val in spawnableMapObjects)
			{
				Landmine componentInChildren = val.prefabToSpawn.GetComponentInChildren<Landmine>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					val.numberToSpawn = new AnimationCurve((Keyframe[])(object)new Keyframe[1]
					{
						new Keyframe(0f, 2.5f)
					});
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAI), "KillEnemyServerRpc")]
		private static void EnemyBounty()
		{
			Mls.LogInfo((object)$"Enemy killed, bounty is active: {BountyIsActive}");
			if (BountyIsActive)
			{
				Terminal val = Object.FindObjectOfType<Terminal>();
				val.groupCredits += 30;
				val.SyncGroupCreditsServerRpc(val.groupCredits, val.numberOfItemsInDropship);
				HullManager.SendChatEventMessage("<color=green>Workers get paid for killing enemy</color>");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayerServerRpc")]
		private static void OneForAll()
		{
			Mls.LogInfo((object)$"Player killed, one for all is active: {OneForAllIsActive}");
			if (OneForAllIsActive)
			{
				HullManager hullManager = Object.FindObjectOfType<HullManager>();
				hullManager.timeOfDay.votedShipToLeaveEarlyThisRound = true;
				hullManager.timeOfDay.SetShipLeaveEarlyServerRpc();
				HullManager.SendChatEventMessage("<color=red>One of the workers died, the ship will go into orbit in an hour</color>");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartHost")]
		private static void ResetDayPassed()
		{
			DaysPassed = 0;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "HullBreakerCompany";

		public const string PLUGIN_NAME = "HullBreakerCompany";

		public const string PLUGIN_VERSION = "1.3.9";
	}
}
namespace HullBreakerCompany.Hull
{
	public class ConfigManager
	{
		private static string _configPath = Path.Combine(Paths.ConfigPath, "HullBreakerCompany.cfg");

		private static ConfigFile _configFile;

		public static T GetConfigValue<T>(string key, T defaultValue, string description = null)
		{
			EnsureConfigExists();
			return _configFile.Bind<T>("Settings", key, defaultValue, description).Value;
		}

		public static void SetConfigValue()
		{
			Plugin.LandMineTurretScale = GetConfigValue("LandMineTurretScale", 64, "Should change amount of Landmines & Turrets when these events are active: (Landmine & Turret)");
			Plugin.UseShortChatMessages = GetConfigValue("UseShortChatMessages", defaultValue: false, "Use short event message (one/two words), can add surprise effect & difficulty");
			Plugin.EnableEventMessages = GetConfigValue("EnableEventMessages", defaultValue: true, "Enable chat event messages");
			Plugin.UseHullBreakerLevelSettings = GetConfigValue("UseHullBreakerLevelSettings", defaultValue: true, "Use HullBreaker level settings, if false, use default level settings");
			Plugin.UseDefaultGameSettings = GetConfigValue("UseDefaultLevelSettings", defaultValue: false, "Use default level settings, if false, you can change on one's own");
			Plugin.ChangeQuotaValue = GetConfigValue("ChangeQuota", defaultValue: true, "Change quota");
			Plugin.QuotaIncrease = GetConfigValue("IncreasedQuota", 256, "Increased quota");
			Plugin.MaxEnemyPowerCount = GetConfigValue("MaxEnemyPowerCount", 10, "Max enemy power count");
			Plugin.MaxOutsideEnemyPowerCount = GetConfigValue("MaxOutsideEnemyPowerCount", 10, "Max outside enemy power count");
			Plugin.MaxDaytimeEnemyPowerCount = GetConfigValue("MaxDaytimeEnemyPowerCount", 20, "Max daytime enemy power count");
			Plugin.MinScrap = GetConfigValue("MinScrap", 10, "Min scrap");
			Plugin.MaxScrap = GetConfigValue("MaxScrap", 15, "Max scrap");
			Plugin.MinTotalScrapValue = GetConfigValue("MinTotalScrapValue", 300, "Min total scrap value");
			Plugin.MaxTotalScrapValue = GetConfigValue("MaxTotalScrapValue", 700, "Max total scrap value");
			Plugin.BunkerEnemyScale = GetConfigValue("BunkerEnemyScale", 256, "Should change global bunker enemy spawn rate, not sure if its work");
			Plugin.IncreaseEventCountPerDay = GetConfigValue("IncreaseEventCountPerDay", defaultValue: false, "The number of events will increase every day. Visit the company building to reset");
			Plugin.EventCount = GetConfigValue("EventCount", 3, "The number of events that will be active at the same time");
		}

		public static Dictionary<string, int> GetWeights()
		{
			EnsureConfigExists();
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			foreach (HullEvent item in Plugin.EventDictionary)
			{
				dictionary[item.ID()] = _configFile.Bind<int>("Weights", item.ID(), item.GetWeight(), item.GetDescription()).Value;
			}
			return dictionary;
		}

		private static void EnsureConfigExists()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			if (_configFile == null)
			{
				if (!File.Exists(_configPath))
				{
					CreateDefaultConfigFile();
				}
				_configFile = new ConfigFile(_configPath, true);
			}
		}

		private static void CreateDefaultConfigFile()
		{
			using StreamWriter streamWriter = File.CreateText(_configPath);
			streamWriter.WriteLine("[Weights]");
			foreach (HullEvent item in Plugin.EventDictionary)
			{
				streamWriter.WriteLine(item.ID() + "=" + item.GetWeight());
			}
		}
	}
	public class CustomEventLoader
	{
		public static void LoadCustomEvents()
		{
			List<Dictionary<string, string>> list = LoadEventDataFromCfgFiles();
			if (list.Count == 0)
			{
				return;
			}
			foreach (Dictionary<string, string> item in list)
			{
				CustomEvent customEvent = new CustomEvent();
				customEvent.SetID(item["EventID"]);
				customEvent.SetWeight(int.Parse(item["EventWeight"]));
				customEvent.Rarity = int.Parse(item["EnemyRarity"]);
				if (item.ContainsKey("SpawnableEnemies"))
				{
					customEvent.EnemySpawnList = new HashSet<string>(item["SpawnableEnemies"].Split(',')).ToList();
				}
				if (item.ContainsKey("SpawnableOutsideEnemies"))
				{
					customEvent.OutsideSpawnList = new HashSet<string>(item["SpawnableOutsideEnemies"].Split(',')).ToList();
				}
				customEvent.SetMessage(item["InGameMessage"]);
				customEvent.SetShortMessage(item["InGameShortMessage"]);
				Plugin.EventDictionary.Add(customEvent);
			}
		}

		private static List<Dictionary<string, string>> LoadEventDataFromCfgFiles()
		{
			string text = Paths.BepInExRootPath + "\\HullEvents";
			if (!Directory.Exists(text))
			{
				Plugin.Mls.LogError((object)("Directory does not exist: " + text));
				return new List<Dictionary<string, string>>();
			}
			string[] files = Directory.GetFiles(text, "*.cfg");
			List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
			string[] array = files;
			foreach (string path in array)
			{
				string[] array2 = File.ReadAllLines(path);
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				string[] array3 = array2;
				foreach (string text2 in array3)
				{
					if (!text2.StartsWith("[") && !string.IsNullOrWhiteSpace(text2))
					{
						string[] array4 = text2.Split('=');
						if (array4.Length == 2)
						{
							string key = array4[0].Trim();
							string value = array4[1].Trim();
							dictionary[key] = value;
						}
					}
				}
				list.Add(dictionary);
				Plugin.Mls.LogInfo((object)("Loaded event: " + dictionary["EventID"]));
			}
			return list;
		}

		public static void AddEvent(HullEvent newEvent)
		{
			Plugin.Mls.LogInfo((object)("Adding new event" + newEvent.ID() + " to dictionary"));
			Plugin.EventDictionary.Add(newEvent);
		}

		public static void DebugLoadCustomEvents()
		{
			foreach (HullEvent item in Plugin.EventDictionary)
			{
				if (item is CustomEvent customEvent)
				{
					Plugin.Mls.LogInfo((object)("Event ID: " + customEvent.ID()));
					Plugin.Mls.LogInfo((object)("Spawnable Enemies: " + string.Join(", ", customEvent.EnemySpawnList)));
					Plugin.Mls.LogInfo((object)("Message: " + customEvent.GetMessage()));
				}
			}
		}
	}
	public abstract class HullEvent
	{
		public abstract string ID();

		public virtual int GetWeight()
		{
			return 1;
		}

		public virtual string GetDescription()
		{
			return "Default description";
		}

		public virtual string GetMessage()
		{
			return "Default message";
		}

		public virtual string GetShortMessage()
		{
			return "SHORT";
		}

		public virtual void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
		}
	}
	public class HullManager : MonoBehaviour
	{
		public TimeOfDay timeOfDay;

		public static HullManager Instance { get; private set; }

		public void Update()
		{
			if ((Object)(object)timeOfDay == (Object)null)
			{
				timeOfDay = Object.FindFirstObjectByType<TimeOfDay>();
			}
			else if (Plugin.ChangeQuotaValue)
			{
				timeOfDay.quotaVariables.baseIncrease = Plugin.QuotaIncrease;
			}
		}

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
				Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			}
			else
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}

		public void AddMoney(int amount)
		{
			Terminal val = Object.FindObjectOfType<Terminal>();
			val.groupCredits += amount;
			val.SyncGroupCreditsServerRpc(val.groupCredits, val.numberOfItemsInDropship);
		}

		public void ExecuteAfterDelay(Action action, float delay)
		{
			((MonoBehaviour)this).StartCoroutine(DelayedExecution(action, delay));
		}

		private IEnumerator DelayedExecution(Action action, float delay)
		{
			yield return (object)new WaitForSeconds(delay);
			action();
		}

		public static void SendChatEventMessage(HullEvent hullEvent)
		{
			if ((Object)(object)HUDManager.Instance != (Object)null && hullEvent != null && Plugin.EnableEventMessages)
			{
				HUDManager.Instance.AddTextToChatOnServer(Plugin.UseShortChatMessages ? hullEvent.GetShortMessage() : hullEvent.GetMessage(), -1);
			}
		}

		public static void SendChatEventMessage(string message)
		{
			if ((Object)(object)HUDManager.Instance != (Object)null && message != null && Plugin.EnableEventMessages)
			{
				HUDManager.Instance.AddTextToChatOnServer(message, -1);
			}
		}

		public static void LogEnemyRarity(List<SpawnableEnemyWithRarity> enemies, string title)
		{
			Plugin.Mls.LogInfo((object)"");
			Plugin.Mls.LogInfo((object)title);
			foreach (SpawnableEnemyWithRarity enemy in enemies)
			{
				Plugin.Mls.LogInfo((object)$"{((Object)enemy.enemyType.enemyPrefab).name} - {enemy.rarity}");
			}
		}
	}
	public abstract class RandomSelector
	{
		private static Random _random = new Random();

		public static List<string> GetRandomGameEvents()
		{
			int count = (Plugin.IncreaseEventCountPerDay ? Plugin.DaysPassed : Plugin.EventCount);
			return GetWeightedRandomGameEvents(ConfigManager.GetWeights(), count);
		}

		private static List<T> GetWeightedRandomGameEvents<T>(Dictionary<T, int> weights, int count)
		{
			int maxValue = weights.Where((KeyValuePair<T, int> x) => x.Value > 0).Sum((KeyValuePair<T, int> x) => x.Value);
			HashSet<T> hashSet = new HashSet<T>();
			while (hashSet.Count < count)
			{
				int num = _random.Next(maxValue);
				foreach (KeyValuePair<T, int> weight in weights)
				{
					if (weight.Value != 0)
					{
						if (num < weight.Value)
						{
							hashSet.Add(weight.Key);
							break;
						}
						num -= weight.Value;
					}
				}
			}
			return hashSet.ToList();
		}

		private static void Shuffle<T>(IList<T> list)
		{
			int num = list.Count;
			while (num > 1)
			{
				num--;
				int num2 = _random.Next(num + 1);
				int index = num2;
				int index2 = num;
				T val = list[num];
				T val2 = list[num2];
				T val4 = (list[index] = val);
				val4 = (list[index2] = val2);
			}
		}
	}
	public class SelectableLevelState
	{
		public int MinScrap;

		public int MaxScrap;

		public int MinTotalScrapValue;

		public int MaxTotalScrapValue;

		public int MaxEnemyPowerCount = 8;

		public int MaxOutsideEnemyPowerCount = 15;

		public int MaxDaytimeEnemyPowerCount = 20;

		public AnimationCurve EnemySpawnChanceThroughoutDay;

		public AnimationCurve OutsideEnemySpawnChanceThroughDay;

		public AnimationCurve DaytimeEnemySpawnChanceThroughDay;

		public List<SpawnableEnemyWithRarity> EnemyList = new List<SpawnableEnemyWithRarity>();

		public List<SpawnableEnemyWithRarity> OutsideEnemyList = new List<SpawnableEnemyWithRarity>();

		public List<SpawnableEnemyWithRarity> DaytimeEnemyList = new List<SpawnableEnemyWithRarity>();

		public SelectableLevelState(SelectableLevel level)
		{
			MinScrap = level.minScrap;
			MaxScrap = level.maxScrap;
			MinTotalScrapValue = level.minTotalScrapValue;
			MaxTotalScrapValue = level.maxTotalScrapValue;
			MaxEnemyPowerCount = level.maxEnemyPowerCount;
			MaxOutsideEnemyPowerCount = level.maxOutsideEnemyPowerCount;
			MaxDaytimeEnemyPowerCount = level.maxDaytimeEnemyPowerCount;
			EnemySpawnChanceThroughoutDay = level.enemySpawnChanceThroughoutDay;
			OutsideEnemySpawnChanceThroughDay = level.outsideEnemySpawnChanceThroughDay;
			DaytimeEnemySpawnChanceThroughDay = level.daytimeEnemySpawnChanceThroughDay;
			CloneEnemies(level.Enemies, EnemyList);
			CloneEnemies(level.OutsideEnemies, OutsideEnemyList);
			CloneEnemies(level.DaytimeEnemies, DaytimeEnemyList);
		}

		public void RestoreState(SelectableLevel level)
		{
			level.minScrap = MinScrap;
			level.maxScrap = MaxScrap;
			level.minTotalScrapValue = MinTotalScrapValue;
			level.maxTotalScrapValue = MaxTotalScrapValue;
			level.maxEnemyPowerCount = MaxEnemyPowerCount;
			level.maxOutsideEnemyPowerCount = MaxOutsideEnemyPowerCount;
			level.maxDaytimeEnemyPowerCount = MaxDaytimeEnemyPowerCount;
			level.enemySpawnChanceThroughoutDay = EnemySpawnChanceThroughoutDay;
			level.outsideEnemySpawnChanceThroughDay = OutsideEnemySpawnChanceThroughDay;
			level.daytimeEnemySpawnChanceThroughDay = DaytimeEnemySpawnChanceThroughDay;
			level.Enemies.Clear();
			CloneEnemies(EnemyList, level.Enemies);
			level.OutsideEnemies.Clear();
			CloneEnemies(OutsideEnemyList, level.OutsideEnemies);
			level.DaytimeEnemies.Clear();
			CloneEnemies(DaytimeEnemyList, level.DaytimeEnemies);
		}

		private void CloneEnemies(List<SpawnableEnemyWithRarity> source, List<SpawnableEnemyWithRarity> destination)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			foreach (SpawnableEnemyWithRarity item2 in source)
			{
				SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity
				{
					enemyType = item2.enemyType,
					rarity = item2.rarity
				};
				destination.Add(item);
			}
		}
	}
}
namespace HullBreakerCompany.Events
{
	public class ArachnophobiaEvent : HullEvent
	{
		public override string ID()
		{
			return "Arachnophobia";
		}

		public override int GetWeight()
		{
			return 20;
		}

		public override string GetDescription()
		{
			return "Increased chance of spider spawning";
		}

		public override string GetMessage()
		{
			return "<color=white>Possible habitat of spiders</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>ARACHNOPHOBIA</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			enemyComponentRarity.Add(typeof(SandSpiderAI), 256);
			HullManager.SendChatEventMessage(this);
		}
	}
	public class BabkinPogrebEvent : HullEvent
	{
		public override string ID()
		{
			return "BabkinPogreb";
		}

		public override int GetWeight()
		{
			return 10;
		}

		public override string GetDescription()
		{
			return "Only jars of pickles spawn on the moon";
		}

		public override string GetMessage()
		{
			return "<color=white>On the this moon, something strange happened with scrap...</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>ITEM MYSTERY</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			try
			{
				if ((Object)(object)HullManager.Instance == (Object)null)
				{
					Plugin.Mls.LogError((object)"HullManager.Instance is null");
					return;
				}
				if ((Object)(object)level == (Object)null)
				{
					Plugin.Mls.LogError((object)"level is null");
					return;
				}
				level.spawnableScrap.RemoveAll((SpawnableItemWithRarity item) => item.spawnableItem.itemName != "Jar of pickles");
				if (level.spawnableScrap.Count == 0)
				{
					Plugin.Mls.LogError((object)"No jars of pickles found in spawnableScrap list!");
					DelayedReturnList(level);
					return;
				}
				foreach (SpawnableItemWithRarity item in level.spawnableScrap.Where((SpawnableItemWithRarity item) => item.spawnableItem.itemName == "Jar of pickles"))
				{
					item.rarity = 100;
				}
				HullManager.Instance.ExecuteAfterDelay(delegate
				{
					DelayedReturnList(level);
				}, 12f);
				HullManager.SendChatEventMessage(this);
			}
			catch (ArgumentOutOfRangeException ex)
			{
				Plugin.Mls.LogError((object)("ArgumentOutOfRangeException caught in BabkinPogrebEvent.Execute: " + ex.Message));
			}
		}

		private void DelayedReturnList(SelectableLevel level)
		{
			Plugin.Mls.LogInfo((object)"Resetting spawnable items...");
			level.spawnableScrap.Clear();
			foreach (SpawnableItemWithRarity item in Plugin.NotModifiedSpawnableItemsWithRarity)
			{
				level.spawnableScrap.Add(item);
			}
		}
	}
	public class BeeEvent : HullEvent
	{
		public override string ID()
		{
			return "Bee";
		}

		public override int GetWeight()
		{
			return 30;
		}

		public override string GetDescription()
		{
			return "Increased chance of bee hives spawning";
		}

		public override string GetMessage()
		{
			return "<color=white>Possibly a large amount of bee hives</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>ANNOYING BUZZING</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			using (IEnumerator<SpawnableEnemyWithRarity> enumerator = level.DaytimeEnemies.Where((SpawnableEnemyWithRarity unit) => (Object)(object)unit.enemyType.enemyPrefab.GetComponent<RedLocustBees>() != (Object)null).GetEnumerator())
			{
				if (enumerator.MoveNext())
				{
					SpawnableEnemyWithRarity current = enumerator.Current;
					current.rarity = 256;
				}
			}
			HullManager.SendChatEventMessage(this);
		}
	}
	public class CustomEvent : HullEvent
	{
		private string _id;

		private int _weight;

		private string _message;

		private string _shortMessage;

		public List<string> EnemySpawnList = new List<string>();

		public List<string> OutsideSpawnList = new List<string>();

		public int Rarity = 1;

		public override string ID()
		{
			return _id;
		}

		public void SetID(string value)
		{
			_id = value;
		}

		public void SetWeight(int value)
		{
			_weight = value;
		}

		public override int GetWeight()
		{
			return _weight;
		}

		public void SetMessage(string value)
		{
			_message = value;
		}

		public void SetShortMessage(string value)
		{
			_shortMessage = value;
		}

		public override string GetMessage()
		{
			return _message;
		}

		public override string GetShortMessage()
		{
			return _shortMessage;
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> componentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			foreach (string item in EnemySpawnList.TakeWhile((string enemy) => enemy != "off"))
			{
				componentRarity.Add(Plugin.EnemyBase[item], Rarity);
			}
			foreach (string item2 in OutsideSpawnList.TakeWhile((string enemy) => enemy != "off"))
			{
				outsideComponentRarity.Add(Plugin.EnemyBase[item2], Rarity);
			}
			HullManager.SendChatEventMessage(Plugin.UseShortChatMessages ? GetShortMessage() : GetMessage());
		}
	}
	public class DevochkaPizdecEvent : HullEvent
	{
		public override string ID()
		{
			return "DevochkaPizdec";
		}

		public override int GetWeight()
		{
			return 5;
		}

		public override string GetDescription()
		{
			return "Increased chance of phantom girl spawn";
		}

		public override string GetMessage()
		{
			return "<color=white>A lot of workers are going crazy here</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>COTARD SYNDROME</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			enemyComponentRarity.Add(typeof(DressGirlAI), 32);
			HullManager.SendChatEventMessage(this);
		}
	}
	public class EnemyBountyEvent : HullEvent
	{
		public override string ID()
		{
			return "EnemyBounty";
		}

		public override int GetWeight()
		{
			return 50;
		}

		public override string GetDescription()
		{
			return "Company pays money for killing the enemies / 60 per enemy";
		}

		public override string GetMessage()
		{
			return "<color=white>Company pays money for killing the enemies!</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>ENEMY BOUNTY</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			Plugin.BountyIsActive = true;
			HullManager.SendChatEventMessage(this);
		}
	}
	public class FlowerManEvent : HullEvent
	{
		public override string ID()
		{
			return "FlowerMan";
		}

		public override int GetWeight()
		{
			return 20;
		}

		public override string GetDescription()
		{
			return "Increased chance of flowerman spawn";
		}

		public override string GetMessage()
		{
			return "<color=white>So many eyes in the dark, carefully</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>WHITE EYES...</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			enemyComponentRarity.Add(typeof(FlowermanAI), 256);
			HullManager.SendChatEventMessage(this);
		}
	}
	public class HackedTurretsEvent : HullEvent
	{
		public override string ID()
		{
			return "HackedTurrets";
		}

		public override int GetWeight()
		{
			return 10;
		}

		public override string GetDescription()
		{
			return "Turrets dont work on the moon";
		}

		public override string GetMessage()
		{
			return "<color=white>The company's hackers have disabled all turrets on this moon, you can breathe easy</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>SYSTEM FAILURE</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			if ((Object)(object)HullManager.Instance == (Object)null)
			{
				Plugin.Mls.LogError((object)"HullManager.Instance is null");
				return;
			}
			if ((Object)(object)level == (Object)null)
			{
				Plugin.Mls.LogError((object)"level is null");
				return;
			}
			HullManager.Instance.ExecuteAfterDelay(delegate
			{
				HackTurrets();
			}, 16f);
			HullManager.SendChatEventMessage(this);
		}

		private void HackTurrets()
		{
			Turret[] array = Object.FindObjectsOfType<Turret>();
			Turret[] array2 = array;
			foreach (Turret val in array2)
			{
				val.ToggleTurretServerRpc(false);
			}
		}
	}
	public class HellEvent : HullEvent
	{
		public override string ID()
		{
			return "Hell";
		}

		public override int GetWeight()
		{
			return 1;
		}

		public override string GetDescription()
		{
			return "Increased chance of spawning Jester and more enemies";
		}

		public override string GetMessage()
		{
			return "<color=orange>It says here that there is total hell happening on the this moon</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>HELL</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			enemyComponentRarity.Add(typeof(JesterAI), 64);
			HullManager.SendChatEventMessage(this);
			RoundManager.Instance.hourTimeBetweenEnemySpawnBatches = 1;
			HullManager.Instance.ExecuteAfterDelay(delegate
			{
				Hell();
			}, 16f);
		}

		private void Hell()
		{
			EnemyVent[] array = Object.FindObjectsOfType<EnemyVent>();
			for (int i = 0; i < 8; i++)
			{
				if (array.Length != 0)
				{
					EnemyVent val = array[Random.Range(0, array.Length)];
					RoundManager.Instance.SpawnEnemyFromVent(val);
				}
			}
		}
	}
	public class HoarderBugEvent : HullEvent
	{
		public override string ID()
		{
			return "HoarderBug";
		}

		public override int GetWeight()
		{
			return 50;
		}

		public override string GetDescription()
		{
			return "Increased chance of hoarder bug spawn";
		}

		public override string GetMessage()
		{
			return "<color=white>Keep an eye on the loot, Hoarding Bugs nearby</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>BUG INVASION</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			enemyComponentRarity.Add(typeof(HoarderBugAI), 512);
			HullManager.SendChatEventMessage(this);
		}
	}
	public class HullBreakEvent : HullEvent
	{
		public override string ID()
		{
			return "HullBreak";
		}

		public override int GetWeight()
		{
			return 5;
		}

		public override string GetDescription()
		{
			return "Getting money for visiting this moon";
		}

		public override string GetMessage()
		{
			return "<color=green>Take a break, the company is sending money for visiting the moon</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>TAKE A BREAK</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			HullManager.Instance.AddMoney(120);
			HullManager.SendChatEventMessage(this);
		}
	}
	public class LandMineEvent : HullEvent
	{
		public override string ID()
		{
			return "LandMine";
		}

		public override int GetWeight()
		{
			return 30;
		}

		public override string GetDescription()
		{
			return "Increased chance of landmines spawning";
		}

		public override string GetMessage()
		{
			return "<color=white>Watch your step, there are a lot of landmines</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>LANDMINE</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			Plugin.LevelUnits(level, turret: false, landmine: true);
			HullManager.SendChatEventMessage(this);
		}
	}
	public class LizardsEvent : HullEvent
	{
		public override string ID()
		{
			return "Lizards";
		}

		public override int GetWeight()
		{
			return 15;
		}

		public override string GetDescription()
		{
			return "Increased chance of puffers spawn";
		}

		public override string GetMessage()
		{
			return "<color=white>Horrible smell from toxic lizards</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>LIZARDSSS</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			enemyComponentRarity.Add(typeof(PufferAI), 64);
			HullManager.SendChatEventMessage(this);
		}
	}
	public class NothingEvent : HullEvent
	{
		public override string ID()
		{
			return "Nothing";
		}

		public override int GetWeight()
		{
			return 60;
		}

		public override string GetDescription()
		{
			return "Nothing happens";
		}

		public override string GetMessage()
		{
			return "<color=white>---</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>---</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			HullManager.SendChatEventMessage(this);
		}
	}
	public class NutcrackerEvent : HullEvent
	{
		public override string ID()
		{
			return "Nutcracker";
		}

		public override int GetWeight()
		{
			return 5;
		}

		public override string GetDescription()
		{
			return "Increased chance of NutCracker spawn";
		}

		public override string GetMessage()
		{
			return "<color=white>NutCrackers detected in the area!</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=orange>NUTCRACKERS INCOMING</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			enemyComponentRarity.Add(typeof(NutcrackerEnemyAI), 64);
			HullManager.SendChatEventMessage(this);
		}
	}
	public class OnAPowderKegEvent : HullEvent
	{
		public override string ID()
		{
			return "OnAPowderKeg";
		}

		public override int GetWeight()
		{
			return 10;
		}

		public override string GetDescription()
		{
			return "Landmines can detonate at any time";
		}

		public override string GetMessage()
		{
			return "<color=red>CAUTION,</color> <color=white>landmines can detonate at any time</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=red>ON A POWDER KEG</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			HullManager.Instance.ExecuteAfterDelay(delegate
			{
				DetonateLandMine();
			}, Random.Range(30, 680));
			HullManager.SendChatEventMessage(this);
		}

		private void DetonateLandMine()
		{
			Landmine[] array = Object.FindObjectsOfType<Landmine>();
			Landmine[] array2 = array;
			foreach (Landmine val in array2)
			{
				val.ExplodeMineServerRpc();
			}
		}
	}
	public class OneForAllEvent : HullEvent
	{
		public override string ID()
		{
			return "OneForAll";
		}

		public override int GetWeight()
		{
			return 5;
		}

		public override string GetDescription()
		{
			return "The ship will fly into orbit in an hour if one of the workers dies";
		}

		public override string GetMessage()
		{
			return "<color=white>The ship will fly into orbit in an hour if one of the workers dies</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=red>ONE FOR ALL!</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			Plugin.OneForAllIsActive = true;
			HullManager.SendChatEventMessage(this);
		}
	}
	public class OpenTheNoorEvent : HullEvent
	{
		public override string ID()
		{
			return "OpenTheNoor";
		}

		public override int GetWeight()
		{
			return 25;
		}

		public override string GetDescription()
		{
			return "All big doors are locked in the level";
		}

		public override string GetMessage()
		{
			return "<color=white>All big doors are locked in the level</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>OPEN THE NOOR...</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			if ((Object)(object)HullManager.Instance == (Object)null)
			{
				Plugin.Mls.LogError((object)"HullManager.Instance is null");
				return;
			}
			if ((Object)(object)level == (Object)null)
			{
				Plugin.Mls.LogError((object)"level is null");
				return;
			}
			HullManager.Instance.ExecuteAfterDelay(delegate
			{
				CloseBigDoors();
			}, 16f);
			HullManager.SendChatEventMessage(this);
		}

		private void CloseBigDoors()
		{
			TerminalAccessibleObject[] array = Object.FindObjectsOfType<TerminalAccessibleObject>();
			TerminalAccessibleObject[] array2 = array;
			foreach (TerminalAccessibleObject val in array2)
			{
				val.SetDoorOpenServerRpc(false);
			}
		}
	}
	public class OutSideEnemyDayEvent : HullEvent
	{
		public override string ID()
		{
			return "OutSideEnemyDay";
		}

		public override int GetWeight()
		{
			return 3;
		}

		public override string GetDescription()
		{
			return "Increased amount of enemies on the surface during the daytime";
		}

		public override string GetMessage()
		{
			return "<color=white>Increased amount of enemies on the surface during the daytime</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=red>SILENCE SEASON</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			level.outsideEnemySpawnChanceThroughDay = new AnimationCurve((Keyframe[])(object)new Keyframe[1]
			{
				new Keyframe(0f, 512f)
			});
			HullManager.SendChatEventMessage(this);
		}
	}
	public class SlimeEvent : HullEvent
	{
		public override string ID()
		{
			return "Slime";
		}

		public override int GetWeight()
		{
			return 20;
		}

		public override string GetDescription()
		{
			return "Increased chance of slime spawn";
		}

		public override string GetMessage()
		{
			return "<color=white>Inhabited with slime</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>SO SLIMY</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			enemyComponentRarity.Add(typeof(BlobAI), 48);
			HullManager.SendChatEventMessage(this);
		}
	}
	public class SpringManEvent : HullEvent
	{
		public override string ID()
		{
			return "SpringMan";
		}

		public override int GetWeight()
		{
			return 10;
		}

		public override string GetDescription()
		{
			return "Increased chance of spring man spawning (coil-head)";
		}

		public override string GetMessage()
		{
			return "<color=white>It's impossible not to look at them</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>SKULL COILS</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			enemyComponentRarity.Add(typeof(SpringManAI), 128);
			HullManager.SendChatEventMessage(this);
		}
	}
	public class TurretEvent : HullEvent
	{
		public override string ID()
		{
			return "Turret";
		}

		public override int GetWeight()
		{
			return 5;
		}

		public override string GetDescription()
		{
			return "Increased chance of turrets spawning";
		}

		public override string GetMessage()
		{
			return "<color=white>Alert, turrets detected</color>";
		}

		public override string GetShortMessage()
		{
			return "<color=white>TURRETS</color>";
		}

		public override void Execute(SelectableLevel level, Dictionary<Type, int> enemyComponentRarity, Dictionary<Type, int> outsideComponentRarity)
		{
			Plugin.LevelUnits(level, turret: true);
			HullManager.SendChatEventMessage(this);
		}
	}
}

BepInEx/plugins/JumpDelayPatch.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace JumpDelayPatch
{
	[BepInPlugin("monke.lc.jumpdelay", "Jump Delay Patch", "0.0.0.1")]
	public class monkeDelayPatch : BaseUnityPlugin
	{
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		internal class PlayerControllerB_PlayerJump
		{
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Expected O, but got Unknown
				List<CodeInstruction> list = instructions.ToList();
				for (int i = 0; i < list.Count; i++)
				{
					if (list[i].opcode == OpCodes.Ldc_R4)
					{
						list[i] = new CodeInstruction(OpCodes.Ldc_R4, (object)0f);
					}
				}
				return list;
			}
		}

		private void Awake()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin JumpDelayPatch is loaded!");
			Harmony val = new Harmony("monke.lc.jumpdelay");
			val.PatchAll();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "JumpDelayPatch";

		public const string PLUGIN_NAME = "JumpDelayPatch";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

BepInEx/plugins/LateCompanyV1.0.6.dll

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

BepInEx/plugins/lbtokg.dll

Decompiled 7 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace lbtokg
{
	[BepInPlugin("com.zduniusz.lethalcompany.lbtokg", "LbToKg", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch]
		private class Patch
		{
			[HarmonyPatch(typeof(HUDManager), "Update")]
			[HarmonyPostfix]
			private static void SetClock(ref TextMeshProUGUI ___weightCounter, ref Animator ___weightCounterAnimator)
			{
				float num = Mathf.RoundToInt(Mathf.Clamp((GameNetworkManager.Instance.localPlayerController.carryWeight - 1f) * 0.4535f, 0f, 100f) * 105f);
				float num2 = Mathf.RoundToInt(Mathf.Clamp(GameNetworkManager.Instance.localPlayerController.carryWeight - 1f, 0f, 100f) * 105f);
				((TMP_Text)___weightCounter).text = $"{num} kg";
				___weightCounterAnimator.SetFloat("weight", num2 / 130f);
			}
		}

		private const string PLUGIN_GUID = "com.zduniusz.lethalcompany.lbtokg";

		private const string PLUGIN_NAME = "LbToKg";

		private const string PLUGIN_VERSION = "1.0.0";

		private void Awake()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			new Harmony("com.zduniusz.lethalcompany.lbtokg").PatchAll();
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "lbtokg";

		public const string PLUGIN_NAME = "My first plugin";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

BepInEx/plugins/LCBetterSaves.dll

Decompiled 7 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using LCBetterSaves;
using LCBetterSaves.Properties;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public class NewFileUISlot_BetterSaves : MonoBehaviour
{
	public Animator buttonAnimator;

	public Button button;

	public bool isSelected;

	public void Awake()
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Expected O, but got Unknown
		buttonAnimator = ((Component)this).GetComponent<Animator>();
		button = ((Component)this).GetComponent<Button>();
		((UnityEvent)button.onClick).AddListener(new UnityAction(SetFileToThis));
	}

	public void SetFileToThis()
	{
		string currentSaveFileName = "LCSaveFile" + Plugin.newSaveFileNum;
		GameNetworkManager.Instance.currentSaveFileName = currentSaveFileName;
		GameNetworkManager.Instance.saveFileNum = Plugin.newSaveFileNum;
		SetButtonColorForAllFileSlots();
		isSelected = true;
		SetButtonColor();
	}

	public void SetButtonColorForAllFileSlots()
	{
		SaveFileUISlot_BetterSaves[] array = Object.FindObjectsOfType<SaveFileUISlot_BetterSaves>();
		SaveFileUISlot_BetterSaves[] array2 = array;
		foreach (SaveFileUISlot_BetterSaves saveFileUISlot_BetterSaves in array2)
		{
			saveFileUISlot_BetterSaves.SetButtonColor();
			saveFileUISlot_BetterSaves.deleteButton.SetActive(false);
			saveFileUISlot_BetterSaves.renameButton.SetActive(false);
		}
	}

	public void SetButtonColor()
	{
		buttonAnimator.SetBool("isPressed", isSelected);
	}
}
public class SaveFileUISlot_BetterSaves : MonoBehaviour
{
	public Animator buttonAnimator;

	public Button button;

	public TextMeshProUGUI fileStatsText;

	public int fileNum;

	public string fileString;

	public TextMeshProUGUI fileNotCompatibleAlert;

	public GameObject deleteButton;

	public GameObject renameButton;

	public void Awake()
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Expected O, but got Unknown
		buttonAnimator = ((Component)this).GetComponent<Animator>();
		button = ((Component)this).GetComponent<Button>();
		((UnityEvent)button.onClick).AddListener(new UnityAction(SetFileToThis));
		fileStatsText = ((Component)((Component)this).transform.GetChild(2)).GetComponent<TextMeshProUGUI>();
		fileNotCompatibleAlert = ((Component)((Component)this).transform.GetChild(4)).GetComponent<TextMeshProUGUI>();
		deleteButton = ((Component)((Component)this).transform.GetChild(3)).gameObject;
	}

	public void Start()
	{
		UpdateStats();
	}

	private void OnEnable()
	{
		if (!Object.FindObjectOfType<MenuManager>().filesCompatible[fileNum])
		{
			((Behaviour)fileNotCompatibleAlert).enabled = true;
		}
	}

	public void UpdateStats()
	{
		try
		{
			if (ES3.FileExists(fileString))
			{
				int num = ES3.Load<int>("GroupCredits", fileString, 30);
				int num2 = ES3.Load<int>("Stats_DaysSpent", fileString, 0);
				((TMP_Text)fileStatsText).text = $"${num}\nDays: {num2}";
			}
			else
			{
				((TMP_Text)fileStatsText).text = "";
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Error updating stats: " + ex.Message));
		}
	}

	public void SetButtonColor()
	{
		buttonAnimator.SetBool("isPressed", GameNetworkManager.Instance.currentSaveFileName == fileString);
	}

	public void SetFileToThis()
	{
		Plugin.fileToModify = fileNum;
		GameNetworkManager.Instance.currentSaveFileName = fileString;
		GameNetworkManager.Instance.saveFileNum = fileNum;
		SetButtonColorForAllFileSlots();
	}

	public void SetButtonColorForAllFileSlots()
	{
		SaveFileUISlot_BetterSaves[] array = Object.FindObjectsOfType<SaveFileUISlot_BetterSaves>();
		SaveFileUISlot_BetterSaves[] array2 = array;
		foreach (SaveFileUISlot_BetterSaves saveFileUISlot_BetterSaves in array2)
		{
			saveFileUISlot_BetterSaves.SetButtonColor();
			saveFileUISlot_BetterSaves.deleteButton.SetActive((Object)(object)saveFileUISlot_BetterSaves == (Object)(object)this);
			saveFileUISlot_BetterSaves.renameButton.SetActive((Object)(object)saveFileUISlot_BetterSaves == (Object)(object)this);
		}
		NewFileUISlot_BetterSaves newFileUISlot_BetterSaves = Object.FindObjectOfType<NewFileUISlot_BetterSaves>();
		newFileUISlot_BetterSaves.isSelected = false;
		newFileUISlot_BetterSaves.SetButtonColor();
	}
}
public class RenameFileButton_BetterSaves : MonoBehaviour
{
	public void RenameFile()
	{
		string text = $"LCSaveFile{Plugin.fileToModify}";
		string text2 = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/Panel/LobbyHostOptions/OptionsNormal/ServerNameField/Text Area/Text").GetComponent<TMP_Text>().text;
		if (ES3.FileExists(text))
		{
			ES3.Save<string>("Alias_BetterSaves", text2, text);
			Debug.Log((object)("Granted alias " + text2 + " to file " + text));
		}
		Plugin.RefreshNameFields();
	}
}
public class DeleteFileButton_BetterSaves : MonoBehaviour
{
	public int fileToDelete;

	public AudioClip deleteFileSFX;

	public TextMeshProUGUI deleteFileText;

	public void UpdateFileToDelete()
	{
		fileToDelete = Plugin.fileToModify;
		if (ES3.Load<string>("Alias_BetterSaves", $"LCSaveFile{fileToDelete}", "") != "")
		{
			((TMP_Text)deleteFileText).text = "Do you want to delete file (" + ES3.Load<string>("Alias_BetterSaves", $"LCSaveFile{fileToDelete}", "") + ")?";
		}
		else
		{
			((TMP_Text)deleteFileText).text = $"Do you want to delete File {fileToDelete + 1}?";
		}
	}

	public void DeleteFile()
	{
		string text = $"LCSaveFile{fileToDelete}";
		if (ES3.FileExists(text))
		{
			ES3.DeleteFile(text);
			Object.FindObjectOfType<MenuManager>().MenuAudio.PlayOneShot(deleteFileSFX);
		}
		SaveFileUISlot_BetterSaves[] array = Object.FindObjectsOfType<SaveFileUISlot_BetterSaves>(true);
		SaveFileUISlot_BetterSaves[] array2 = array;
		foreach (SaveFileUISlot_BetterSaves saveFileUISlot_BetterSaves in array2)
		{
			Debug.Log((object)$"Deleted {fileToDelete}");
			if (saveFileUISlot_BetterSaves.fileNum == fileToDelete)
			{
				((Behaviour)saveFileUISlot_BetterSaves.fileNotCompatibleAlert).enabled = false;
				Object.FindObjectOfType<MenuManager>().filesCompatible[fileToDelete] = true;
			}
		}
		Plugin.InitializeBetterSaves();
	}
}
namespace LCBetterSaves
{
	[BepInPlugin("LCBetterSaves", "LCBetterSaves", "1.4.0")]
	public class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony = new Harmony("BetterSaves");

		public static int fileToModify = -1;

		public static int newSaveFileNum;

		public static Sprite renameSprite;

		public static MenuManager menuManager;

		public static AudioClip deleteFileSFX;

		public static TextMeshProUGUI deleteFileText;

		public static float buttonBaseY;

		public void Awake()
		{
			_harmony.PatchAll(typeof(Plugin));
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LCBetterSaves is loaded!");
		}

		[HarmonyPatch(typeof(MenuManager), "Start")]
		public static void Postfix(MenuManager __instance)
		{
			//IL_0047: 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)
			menuManager = __instance;
			if ((Object)(object)renameSprite == (Object)null)
			{
				AssetBundle val = AssetBundle.LoadFromMemory(Resources.lcbettersaves);
				Texture2D val2 = val.LoadAsset<Texture2D>("Assets/RenameSprite.png");
				renameSprite = Sprite.Create(val2, new Rect(0f, 0f, (float)((Texture)val2).width, (float)((Texture)val2).height), new Vector2(0.5f, 0.5f));
			}
			InitializeBetterSaves();
		}

		public static void InitializeBetterSaves()
		{
			try
			{
				DestroyBetterSavesButtons();
				DestroyOriginalSaveButtons();
				UpdateTopText();
				CreateModdedDeleteFileButton();
				CreateBetterSaveButtons();
				UpdateFilesPanelRect(CountSaveFiles());
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("An error occurred during initialization: " + ex.Message));
			}
		}

		public static void DestroyBetterSavesButtons()
		{
			try
			{
				SaveFileUISlot_BetterSaves[] array = Object.FindObjectsOfType<SaveFileUISlot_BetterSaves>();
				foreach (SaveFileUISlot_BetterSaves saveFileUISlot_BetterSaves in array)
				{
					Object.Destroy((Object)(object)((Component)saveFileUISlot_BetterSaves).gameObject);
				}
				NewFileUISlot_BetterSaves[] array2 = Object.FindObjectsOfType<NewFileUISlot_BetterSaves>();
				foreach (NewFileUISlot_BetterSaves newFileUISlot_BetterSaves in array2)
				{
					Object.Destroy((Object)(object)((Component)newFileUISlot_BetterSaves).gameObject);
				}
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("Error occurred while destroying better saves buttons: " + ex.Message));
			}
		}

		public static void UpdateTopText()
		{
			GameObject val = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/EnterAName");
			if ((Object)(object)val == (Object)null)
			{
				Debug.LogError((object)"Panel label not found.");
			}
			else
			{
				((TMP_Text)val.GetComponent<TextMeshProUGUI>()).text = "BetterSaves";
			}
		}

		public static void CreateModdedDeleteFileButton()
		{
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			GameObject val = GameObject.Find("Canvas/MenuContainer/DeleteFileConfirmation/Panel/Delete");
			if ((Object)(object)val == (Object)null)
			{
				Debug.LogError((object)"Delete file game object not found.");
				return;
			}
			if ((Object)(object)val.GetComponent<DeleteFileButton_BetterSaves>() != (Object)null)
			{
				Debug.LogWarning((object)"DeleteFileButton_BetterSaves component already exists on deleteFileGO");
				return;
			}
			DeleteFileButton component = val.GetComponent<DeleteFileButton>();
			if ((Object)(object)component == (Object)null)
			{
				Debug.LogError((object)"DeleteFileButton component not found on deleteFileGO");
				return;
			}
			if ((Object)(object)deleteFileSFX == (Object)null)
			{
				deleteFileSFX = component.deleteFileSFX;
			}
			if ((Object)(object)deleteFileText == (Object)null)
			{
				deleteFileText = component.deleteFileText;
			}
			Object.Destroy((Object)(object)component);
			if ((Object)(object)val.GetComponent<DeleteFileButton_BetterSaves>() == (Object)null)
			{
				DeleteFileButton_BetterSaves deleteFileButton_BetterSaves = val.AddComponent<DeleteFileButton_BetterSaves>();
				deleteFileButton_BetterSaves.deleteFileSFX = deleteFileSFX;
				deleteFileButton_BetterSaves.deleteFileText = deleteFileText;
				Button component2 = val.GetComponent<Button>();
				if ((Object)(object)component2 != (Object)null)
				{
					((UnityEventBase)component2.onClick).RemoveAllListeners();
					((UnityEvent)component2.onClick).AddListener(new UnityAction(deleteFileButton_BetterSaves.DeleteFile));
				}
				else
				{
					Debug.LogError((object)"Button component not found on deleteFileGO");
				}
			}
			else
			{
				Debug.LogWarning((object)"DeleteFileButton_BetterSaves component already exists on deleteFileGO");
			}
		}

		public static void CreateBetterSaveButtons()
		{
			try
			{
				GameObject val = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File1");
				val.SetActive(true);
				int numSaves = CountSaveFiles();
				Debug.Log((object)("Positioning based on " + numSaves + " saves."));
				NewFileUISlot_BetterSaves newFileUISlot_BetterSaves = CreateNewFileNode(numSaves);
				List<string> list = NormalizeFileNames();
				newSaveFileNum = list.Count;
				menuManager.filesCompatible = new bool[16];
				for (int i = 0; i < menuManager.filesCompatible.Length; i++)
				{
					menuManager.filesCompatible[i] = true;
				}
				for (int j = 0; j < list.Count; j++)
				{
					CreateModdedSaveNode(int.Parse(list[j].Replace("LCSaveFile", "")), j, ((Component)newFileUISlot_BetterSaves).gameObject);
				}
				val.SetActive(false);
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("Error occurred while refreshing save buttons: " + ex.Message));
			}
		}

		public static NewFileUISlot_BetterSaves CreateNewFileNode(int numSaves)
		{
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File1");
			if ((Object)(object)val == (Object)null)
			{
				Debug.LogError((object)"Original GameObject not found.");
				return null;
			}
			Transform parent = val.transform.parent;
			SaveFileUISlot component = val.GetComponent<SaveFileUISlot>();
			if ((Object)(object)component != (Object)null)
			{
				Object.Destroy((Object)(object)component);
			}
			GameObject val2 = Object.Instantiate<GameObject>(val, parent);
			((Object)val2).name = "NewFile";
			TMP_Text component2 = ((Component)val2.transform.GetChild(1)).GetComponent<TMP_Text>();
			if ((Object)(object)component2 != (Object)null)
			{
				component2.text = "New File";
				NewFileUISlot_BetterSaves newFileUISlot_BetterSaves = val2.AddComponent<NewFileUISlot_BetterSaves>();
				if ((Object)(object)newFileUISlot_BetterSaves == (Object)null)
				{
					Debug.LogError((object)"Failed to add NewFileUISlot_BetterSaves component.");
					return null;
				}
				Transform child = val2.transform.GetChild(3);
				if ((Object)(object)child != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)child).gameObject);
					try
					{
						RectTransform component3 = val2.GetComponent<RectTransform>();
						if (!((Object)(object)component3 != (Object)null))
						{
							Debug.LogError((object)"RectTransform component not found.");
							return null;
						}
						float x = component3.anchoredPosition.x;
						if (buttonBaseY == 0f)
						{
							buttonBaseY = component3.anchoredPosition.y - component3.sizeDelta.y * 1.75f;
						}
						float num = buttonBaseY + component3.sizeDelta.y * (float)numSaves / 2f;
						component3.anchoredPosition = new Vector2(x, num);
					}
					catch (Exception ex)
					{
						Debug.LogError((object)("Error setting anchored position: " + ex.Message));
						return null;
					}
					return newFileUISlot_BetterSaves;
				}
				Debug.LogError((object)"Delete button not found.");
				return null;
			}
			Debug.LogError((object)"Text component not found.");
			return null;
		}

		private static int CountSaveFiles()
		{
			int num = 0;
			string[] files = ES3.GetFiles();
			foreach (string text in files)
			{
				if (ES3.FileExists(text) && text.StartsWith("LCSaveFile"))
				{
					num++;
				}
			}
			return num;
		}

		public static void DestroyOriginalSaveButtons()
		{
			Object.Destroy((Object)(object)GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File2"));
			Object.Destroy((Object)(object)GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File3"));
		}

		public static List<string> NormalizeFileNames()
		{
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			string[] files = ES3.GetFiles();
			foreach (string text in files)
			{
				if (ES3.FileExists(text) && text.StartsWith("LCSaveFile"))
				{
					Debug.Log((object)("Found file: " + text));
					list.Add(text);
				}
				if (ES3.FileExists(text) && text.StartsWith("LGU"))
				{
					Debug.Log((object)("Found LGU file: " + text));
					list2.Add(text);
				}
				else if (ES3.FileExists(text) && text.StartsWith("LCSaveFile"))
				{
					list2.Add("placeholder");
				}
			}
			int num = 0;
			foreach (string item in list)
			{
				string text2 = "TempFile" + num;
				ES3.RenameFile(item, text2);
				Debug.Log((object)("Renamed " + item + " to " + text2));
				num++;
			}
			num = 0;
			foreach (string item2 in list2)
			{
				if (item2 == "placeholder")
				{
					num++;
					continue;
				}
				string text3 = "LGUTempFile" + num;
				ES3.RenameFile(item2, text3);
				Debug.Log((object)("Renamed " + item2 + " to " + text3));
				num++;
			}
			int num2 = 0;
			List<string> list3 = new List<string>();
			foreach (string item3 in list)
			{
				string text4 = "TempFile" + num2;
				string text5 = "LCSaveFile" + num2;
				if (ES3.FileExists(text4))
				{
					ES3.RenameFile(text4, text5);
					list3.Add(text5);
					Debug.Log((object)("Renamed " + text4 + " to " + text5));
				}
				else
				{
					Debug.Log((object)("Temporary file " + text4 + " not found. It might have been moved or deleted."));
				}
				num2++;
			}
			num2 = 0;
			List<string> list4 = new List<string>();
			foreach (string item4 in list2)
			{
				string text6 = "LGUTempFile" + num2;
				string text7 = "LGU_" + num2;
				if (item4 == "placeholder")
				{
					num2++;
					continue;
				}
				if (ES3.FileExists(text6))
				{
					ES3.RenameFile(text6, text7);
					list3.Add(text7);
					Debug.Log((object)("Renamed " + text6 + " to " + text7));
				}
				else
				{
					Debug.Log((object)("Temporary file " + text6 + " not found. It might have been moved or deleted."));
				}
				num2++;
			}
			return list3;
		}

		public static void CreateModdedSaveNode(int fileIndex, int listIndex, GameObject newFileButton)
		{
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Expected O, but got Unknown
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			int num = fileIndex + 1;
			GameObject val = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File1");
			if ((Object)(object)val == (Object)null)
			{
				Debug.LogError((object)"Original GameObject not found.");
				return;
			}
			Transform parent = val.transform.parent;
			GameObject val2 = Object.Instantiate<GameObject>(val, parent);
			((Object)val2).name = "File" + num + "_BetterSaves";
			string text = ES3.Load<string>("Alias_BetterSaves", "LCSaveFile" + fileIndex, "");
			if (text == "")
			{
				((Component)val2.transform.GetChild(1)).GetComponent<TMP_Text>().text = "File " + num;
			}
			else
			{
				((Component)val2.transform.GetChild(1)).GetComponent<TMP_Text>().text = text;
			}
			val2.AddComponent<SaveFileUISlot_BetterSaves>();
			SaveFileUISlot_BetterSaves component = val2.GetComponent<SaveFileUISlot_BetterSaves>();
			if ((Object)(object)component != (Object)null)
			{
				component.fileNum = fileIndex;
				component.fileString = "LCSaveFile" + fileIndex;
				RectTransform component2 = val2.GetComponent<RectTransform>();
				if ((Object)(object)component2 != (Object)null)
				{
					float x = component2.anchoredPosition.x;
					float y = newFileButton.GetComponent<RectTransform>().anchoredPosition.y;
					float num2 = y - component2.sizeDelta.y * (float)num;
					component2.anchoredPosition = new Vector2(x, num2);
				}
				GameObject gameObject = ((Component)val2.transform.GetChild(3)).gameObject;
				DeleteFileButton_BetterSaves component3 = GameObject.Find("Canvas/MenuContainer/DeleteFileConfirmation/Panel/Delete").GetComponent<DeleteFileButton_BetterSaves>();
				((UnityEvent)gameObject.gameObject.GetComponent<Button>().onClick).AddListener(new UnityAction(component3.UpdateFileToDelete));
				gameObject.SetActive(false);
				component.renameButton = CreateRenameFileButton(val2);
			}
			else
			{
				Debug.LogError((object)"SaveFileUISlot_BetterSaves component not found on the cloned GameObject.");
				Object.Destroy((Object)(object)val2);
			}
		}

		public static GameObject CreateRenameFileButton(GameObject fileNode)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: 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)
			try
			{
				GameObject gameObject = ((Component)fileNode.transform.GetChild(3)).gameObject;
				GameObject val = Object.Instantiate<GameObject>(gameObject, fileNode.transform);
				((Object)val).name = "RenameButton";
				val.GetComponent<Image>().sprite = renameSprite;
				Button component = val.GetComponent<Button>();
				component.onClick = new ButtonClickedEvent();
				val.AddComponent<RenameFileButton_BetterSaves>();
				RenameFileButton_BetterSaves component2 = val.GetComponent<RenameFileButton_BetterSaves>();
				if ((Object)(object)component2 != (Object)null)
				{
					((UnityEvent)component.onClick).AddListener(new UnityAction(component2.RenameFile));
				}
				else
				{
					Debug.LogError((object)"RenameFileButton_BetterSaves component not found on renameButton");
				}
				RectTransform component3 = val.GetComponent<RectTransform>();
				if ((Object)(object)component3 != (Object)null)
				{
					float num = ((Transform)component3).localPosition.x + 20f;
					float y = ((Transform)component3).localPosition.y;
					((Transform)component3).localPosition = Vector2.op_Implicit(new Vector2(num, y));
				}
				val.SetActive(false);
				return val;
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("Error occurred while creating rename file button: " + ex.Message));
				return null;
			}
		}

		public static void UpdateFilesPanelRect(int numSaves)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: 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)
			try
			{
				GameObject obj = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel");
				RectTransform val = ((obj != null) ? obj.GetComponent<RectTransform>() : null);
				if ((Object)(object)val == (Object)null)
				{
					throw new Exception("Failed to find FilesPanel RectTransform.");
				}
				Vector2 sizeDelta = val.sizeDelta;
				GameObject obj2 = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File1");
				RectTransform val2 = ((obj2 != null) ? obj2.GetComponent<RectTransform>() : null);
				if ((Object)(object)val2 == (Object)null)
				{
					throw new Exception("Failed to find File1 RectTransform.");
				}
				float y = val2.sizeDelta.y;
				sizeDelta.y = y * (float)(numSaves + 3);
				val.sizeDelta = sizeDelta;
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("Error occurred while updating files panel rect: " + ex.Message));
			}
		}

		public static void RefreshNameFields()
		{
			SaveFileUISlot_BetterSaves[] array = Object.FindObjectsOfType<SaveFileUISlot_BetterSaves>();
			SaveFileUISlot_BetterSaves[] array2 = array;
			foreach (SaveFileUISlot_BetterSaves saveFileUISlot_BetterSaves in array2)
			{
				string text = ES3.Load<string>("Alias_BetterSaves", saveFileUISlot_BetterSaves.fileString, "");
				if (text == "")
				{
					((Component)((Component)saveFileUISlot_BetterSaves).transform.GetChild(1)).GetComponent<TMP_Text>().text = "File " + (saveFileUISlot_BetterSaves.fileNum + 1);
				}
				else
				{
					((Component)((Component)saveFileUISlot_BetterSaves).transform.GetChild(1)).GetComponent<TMP_Text>().text = text;
				}
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LCBetterSaves";

		public const string PLUGIN_NAME = "LCBetterSaves";

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

		private static CultureInfo resourceCulture;

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

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

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

		internal Resources()
		{
		}
	}
}

BepInEx/plugins/LCFartLizards.dll

Decompiled 7 months ago
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using LCFartLizards.Properties;
using Microsoft.CodeAnalysis;
using UnityEngine;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LCFartLizards
{
	[BepInPlugin("LCFartLizards", "LCFartLizards", "1.2.1")]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(PufferAI), "Start")]
		public static class PufferAIPatch
		{
			public static void Prefix(ref PufferAI __instance)
			{
				__instance.puff = audioClip;
			}
		}

		private Harmony harmony;

		public static AudioClip audioClip;

		public static bool audioClipLoaded;

		public void Awake()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LCFartLizards is loaded!");
			harmony = new Harmony("LCFartLizards");
			harmony.PatchAll();
			LoadAudioClip();
		}

		private void LoadAudioClip()
		{
			AssetBundle val = AssetBundle.LoadFromMemory(Resources.lcfartlizards);
			if ((Object)(object)val != (Object)null)
			{
				audioClip = val.LoadAsset<AudioClip>("Assets/LizardSound.mp3");
				if ((Object)(object)audioClip != (Object)null)
				{
					audioClipLoaded = true;
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Audio clip loaded successfully!");
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogError((object)"Failed to load audio clip!");
				}
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Failed to load asset bundle!");
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LCFartLizards";

		public const string PLUGIN_NAME = "LCFartLizards";

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

		private static CultureInfo resourceCulture;

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

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

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

		internal Resources()
		{
		}
	}
}

BepInEx/plugins/LC_API.dll

Decompiled 7 months ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.BundleAPI;
using LC_API.ClientAPI;
using LC_API.Comp;
using LC_API.Data;
using LC_API.Extensions;
using LC_API.GameInterfaceAPI;
using LC_API.ManualPatches;
using LC_API.ServerAPI;
using Microsoft.CodeAnalysis;
using Steamworks;
using Steamworks.Data;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("LC_API")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Utilities for plugin devs")]
[assembly: AssemblyFileVersion("2.1.4.0")]
[assembly: AssemblyInformationalVersion("2.1.4")]
[assembly: AssemblyProduct("LC_API")]
[assembly: AssemblyTitle("LC_API")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.1.4.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LC_API
{
	internal static class CheatDatabase
	{
		private const string DAT_CD_BROADCAST = "LC_API_CD_Broadcast";

		private const string SIG_REQ_GUID = "LC_API_ReqGUID";

		private const string SIG_SEND_MODS = "LC_APISendMods";

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

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

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

		internal static void CDNetGetString(string data, string signature)
		{
			if (data == "LC_API_CD_Broadcast" && signature == "LC_API_ReqGUID")
			{
				string text = "";
				foreach (PluginInfo value in PluginsLoaded.Values)
				{
					text = text + "\n" + value.Metadata.GUID;
				}
				Networking.Broadcast(GameNetworkManager.Instance.localPlayerController.playerUsername + " responded with these mods:" + text, "LC_APISendMods");
			}
			if (signature == "LC_APISendMods")
			{
				GameTips.ShowTip("Mod List:", data);
				Plugin.Log.LogWarning((object)data);
			}
		}
	}
	[BepInPlugin("LC_API", "LC_API", "2.1.4")]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		private ConfigEntry<bool> configOverrideModServer;

		private ConfigEntry<bool> configLegacyAssetLoading;

		private ConfigEntry<bool> configDisableBundleLoader;

		public static bool Initialized { get; private set; }

		private void Awake()
		{
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Expected O, but got Unknown
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Expected O, but got Unknown
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Expected O, but got Unknown
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Expected O, but got Unknown
			configOverrideModServer = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Force modded server browser", false, "Should the API force you into the modded server browser?");
			configLegacyAssetLoading = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Legacy asset bundle loading", false, "Should the BundleLoader use legacy asset loading? Turning this on may help with loading assets from older plugins.");
			configDisableBundleLoader = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Disable BundleLoader", false, "Should the BundleLoader be turned off? Enable this if you are having problems with mods that load assets using a different method from LC_API's BundleLoader.");
			CommandHandler.commandPrefix = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Prefix", "/", "Command prefix");
			Log = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogWarning((object)"\n.____    _________           _____  __________ .___  \r\n|    |   \\_   ___ \\         /  _  \\ \\______   \\|   | \r\n|    |   /    \\  \\/        /  /_\\  \\ |     ___/|   | \r\n|    |___\\     \\____      /    |    \\|    |    |   | \r\n|_______ \\\\______  /______\\____|__  /|____|    |___| \r\n        \\/       \\//_____/        \\/                 \r\n                                                     ");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Starting up..");
			if (configOverrideModServer.Value)
			{
				ModdedServer.SetServerModdedOnly();
			}
			Harmony val = new Harmony("ModAPI");
			MethodInfo methodInfo = AccessTools.Method(typeof(GameNetworkManager), "SteamMatchmaking_OnLobbyCreated", (Type[])null, (Type[])null);
			AccessTools.Method(typeof(GameNetworkManager), "LobbyDataIsJoinable", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(ServerPatch), "OnLobbyCreate", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(MenuManager), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(ServerPatch), "CacheMenuManager", (Type[])null, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.Method(typeof(ServerPatch), "ChatInterpreter", (Type[])null, (Type[])null);
			MethodInfo methodInfo7 = AccessTools.Method(typeof(HUDManager), "SubmitChat_performed", (Type[])null, (Type[])null);
			MethodInfo methodInfo8 = AccessTools.Method(typeof(CommandHandler.SubmitChatPatch), "Transpiler", (Type[])null, (Type[])null);
			val.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo5, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo7, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo8), (HarmonyMethod)null, (HarmonyMethod)null);
			Networking.GetString = (Action<string, string>)Delegate.Combine(Networking.GetString, new Action<string, string>(CheatDatabase.CDNetGetString));
			Networking.GetListString = (Action<List<string>, string>)Delegate.Combine(Networking.GetListString, new Action<List<string>, string>(Networking.LCAPI_NET_SYNCVAR_SET));
		}

		internal void Start()
		{
			Initialize();
		}

		internal void OnDestroy()
		{
			Initialize();
		}

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

		internal static void PatchMethodManual(MethodInfo method, MethodInfo patch, Harmony harmony)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			harmony.Patch((MethodBase)method, new HarmonyMethod(patch), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "LC_API";

		public const string PLUGIN_NAME = "LC_API";

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

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

		public static bool ModdedOnly => moddedOnly;

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

		public static void OnSceneLoaded()
		{
			if (Object.op_Implicit((Object)(object)GameNetworkManager.Instance) && ModdedOnly)
			{
				GameNetworkManager instance = GameNetworkManager.Instance;
				instance.gameVersionNum += 16440;
				setModdedOnly = true;
			}
		}
	}
	public static class Networking
	{
		public static Action<string, string> GetString = delegate
		{
		};

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

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

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

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

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

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

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

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

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

		public static void Broadcast(Vector3 data, string signature)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			HUDManager instance = HUDManager.Instance;
			string[] obj = new string[9] { "<size=0>NWE/", null, null, null, null, null, null, null, null };
			Vector3 val = data;
			obj[1] = ((object)(Vector3)(ref val)).ToString();
			obj[2] = "/";
			obj[3] = signature;
			obj[4] = "/";
			obj[5] = NetworkBroadcastDataType.BDvector3.ToString();
			obj[6] = "/";
			obj[7] = GameNetworkManager.Instance.localPlayerController.playerClientId.ToString();
			obj[8] = "/</size>";
			instance.AddTextToChatOnServer(string.Concat(obj), -1);
		}

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

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

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

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

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

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

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

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

		private static void GotVector3(Vector3 data, string signature)
		{
		}
	}
}
namespace LC_API.ManualPatches
{
	internal static class ServerPatch
	{
		internal static bool OnLobbyCreate(GameNetworkManager __instance, Result result, Lobby lobby)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if ((int)result != 1)
			{
				Debug.LogError((object)$"Lobby could not be created! {result}", (Object)(object)__instance);
			}
			__instance.lobbyHostSettings.lobbyName = "[MODDED]" + __instance.lobbyHostSettings.lobbyName.ToString();
			Plugin.Log.LogMessage((object)"server pre-setup success");
			return true;
		}

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

		internal static bool ChatInterpreter(HUDManager __instance, string chatMessage)
		{
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			if (!chatMessage.Contains("NWE") || !chatMessage.Contains("<size=0>"))
			{
				return true;
			}
			string[] array = chatMessage.Split(new char[1] { '/' });
			if (array.Length < 5)
			{
				if (array.Length >= 3)
				{
					if (!int.TryParse(array[4], out var result))
					{
						Plugin.Log.LogWarning((object)"Failed to parse player ID!!");
						return false;
					}
					if ((result == (int)GameNetworkManager.Instance.localPlayerController.playerClientId) & !LC_APIManager.netTester)
					{
						return false;
					}
					Enum.TryParse<NetworkBroadcastDataType>(array[3], out var result2);
					switch (result2)
					{
					case NetworkBroadcastDataType.BDstring:
						Networking.GetString(array[1], array[2]);
						break;
					case NetworkBroadcastDataType.BDint:
						Networking.GetInt(int.Parse(array[1]), array[2]);
						break;
					case NetworkBroadcastDataType.BDfloat:
						Networking.GetFloat(float.Parse(array[1]), array[2]);
						break;
					case NetworkBroadcastDataType.BDvector3:
					{
						string[] array2 = array[1].Replace("(", "").Replace(")", "").Split(new char[1] { ',' });
						Vector3 arg = default(Vector3);
						if (array2.Length == 3)
						{
							if (float.TryParse(array2[0], out var result3) && float.TryParse(array2[1], out var result4) && float.TryParse(array2[2], out var result5))
							{
								arg.x = result3;
								arg.y = result4;
								arg.z = result5;
							}
							else
							{
								Plugin.Log.LogError((object)"Vector3 Network receive fail. This is a failure of the API, and it should be reported as a bug.");
							}
						}
						else
						{
							Plugin.Log.LogError((object)"Vector3 Network receive fail. This is a failure of the API, and it should be reported as a bug.");
						}
						Networking.GetVector3(arg, array[2]);
						break;
					}
					case NetworkBroadcastDataType.BDlistString:
					{
						string[] source = array[1].Split(new char[1] { '\n' });
						Networking.GetListString(source.ToList(), array[2]);
						break;
					}
					}
					_ = LC_APIManager.netTester;
					return false;
				}
				Plugin.Log.LogError((object)"Generic Network receive fail. This is a failure of the API, and it should be reported as a bug.");
				Plugin.Log.LogError((object)$"Generic Network receive fail (expected 5+ data fragments, got {array.Length}). This is a failure of the API, and it should be reported as a bug.");
				return true;
			}
			if (!int.TryParse(array[4], out var result6))
			{
				Plugin.Log.LogWarning((object)("Failed to parse player ID '" + array[4] + "'!!"));
				return false;
			}
			if ((result6 == (int)GameNetworkManager.Instance.localPlayerController.playerClientId) & !LC_APIManager.netTester)
			{
				return false;
			}
			if (!Enum.TryParse<NetworkBroadcastDataType>(array[3], out var result7))
			{
				Plugin.Log.LogError((object)("Unknown datatype - unable to parse '" + array[3] + "' into a known data type!"));
				return false;
			}
			switch (result7)
			{
			case NetworkBroadcastDataType.BDstring:
				Networking.GetString.InvokeActionSafe(array[1], array[2]);
				break;
			case NetworkBroadcastDataType.BDint:
				Networking.GetInt.InvokeActionSafe(int.Parse(array[1]), array[2]);
				break;
			case NetworkBroadcastDataType.BDfloat:
				Networking.GetFloat.InvokeActionSafe(float.Parse(array[1]), array[2]);
				break;
			case NetworkBroadcastDataType.BDvector3:
			{
				string text = array[1].Trim('(', ')');
				string[] array3 = text.Split(new char[1] { ',' });
				Vector3 param = default(Vector3);
				float result8;
				float result9;
				float result10;
				if (array3.Length != 3)
				{
					Plugin.Log.LogError((object)$"Vector3 Network receive fail (expected 3 numbers, got {array3.Length} number(?)(s) instead). This is a failure of the API, and it should be reported as a bug. (passing an empty Vector3 in its place)");
				}
				else if (float.TryParse(array3[0], out result8) && float.TryParse(array3[1], out result9) && float.TryParse(array3[2], out result10))
				{
					param.x = result8;
					param.y = result9;
					param.z = result10;
				}
				else
				{
					Plugin.Log.LogError((object)("Vector3 Network receive fail (failed to parse '" + text + "' as numbers). This is a failure of the API, and it should be reported as a bug."));
				}
				Networking.GetVector3.InvokeActionSafe(param, array[2]);
				break;
			}
			}
			_ = LC_APIManager.netTester;
			return false;
		}

		internal static bool ChatCommands(HUDManager __instance, CallbackContext context)
		{
			if (__instance.chatTextField.text.ToLower().Contains("/modcheck"))
			{
				CheatDatabase.OtherPlayerCheatDetector();
				return false;
			}
			return true;
		}
	}
}
namespace LC_API.GameInterfaceAPI
{
	public static class GameState
	{
		private static readonly Action NothingAction = delegate
		{
		};

		public static int AlivePlayerCount { get; private set; }

		public static ShipState ShipState { get; private set; }

		public static event Action PlayerDied;

		public static event Action LandOnMoon;

		public static event Action WentIntoOrbit;

		public static event Action ShipStartedLeaving;

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

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

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

		private static float lastMessageTime;

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

		public static void UpdateInternal()
		{
			lastMessageTime -= Time.deltaTime;
			if ((tipHeaders.Count > 0) & (lastMessageTime < 0f))
			{
				lastMessageTime = 5f;
				if ((Object)(object)HUDManager.Instance != (Object)null)
				{
					HUDManager.Instance.DisplayTip(tipHeaders[0], tipBodys[0], false, false, "LC_Tip1");
				}
				tipHeaders.RemoveAt(0);
				tipBodys.RemoveAt(0);
			}
		}
	}
}
namespace LC_API.Extensions
{
	public static class DelegateExtensions
	{
		private static readonly PropertyInfo PluginGetLogger = AccessTools.Property(typeof(BaseUnityPlugin), "Logger");

		public static void InvokeActionSafe(this Action action)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if (action == null)
			{
				return;
			}
			Delegate[] invocationList = action.GetInvocationList();
			foreach (Delegate @delegate in invocationList)
			{
				try
				{
					((Action)@delegate)();
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)"Exception while invoking hook callback!");
					string asmName = @delegate.GetMethodInfo().DeclaringType.Assembly.FullName;
					PluginInfo val = ((IEnumerable<PluginInfo>)Chainloader.PluginInfos.Values).FirstOrDefault((Func<PluginInfo, bool>)((PluginInfo pi) => ((object)pi.Instance).GetType().Assembly.FullName == asmName));
					if (val == null)
					{
						Plugin.Log.LogError((object)ex.ToString());
						break;
					}
					((ManualLogSource)PluginGetLogger.GetValue(val.Instance)).LogError((object)ex.ToString());
				}
			}
		}

		public static void InvokeActionSafe<T>(this Action<T> action, T param)
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			if (action == null)
			{
				return;
			}
			Delegate[] invocationList = action.GetInvocationList();
			foreach (Delegate @delegate in invocationList)
			{
				try
				{
					((Action<T>)@delegate)(param);
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)"Exception while invoking hook callback!");
					string asmName = @delegate.GetMethodInfo().DeclaringType.Assembly.FullName;
					PluginInfo val = ((IEnumerable<PluginInfo>)Chainloader.PluginInfos.Values).FirstOrDefault((Func<PluginInfo, bool>)((PluginInfo pi) => ((object)pi.Instance).GetType().Assembly.FullName == asmName));
					if (val == null)
					{
						Plugin.Log.LogError((object)ex.ToString());
						break;
					}
					((ManualLogSource)PluginGetLogger.GetValue(val.Instance)).LogError((object)ex.ToString());
				}
			}
		}

		public static void InvokeActionSafe<T1, T2>(this Action<T1, T2> action, T1 param1, T2 param2)
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			if (action == null)
			{
				return;
			}
			Delegate[] invocationList = action.GetInvocationList();
			foreach (Delegate @delegate in invocationList)
			{
				try
				{
					((Action<T1, T2>)@delegate)(param1, param2);
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)"Exception while invoking hook callback!");
					string asmName = @delegate.GetMethodInfo().DeclaringType.Assembly.FullName;
					PluginInfo val = ((IEnumerable<PluginInfo>)Chainloader.PluginInfos.Values).FirstOrDefault((Func<PluginInfo, bool>)((PluginInfo pi) => ((object)pi.Instance).GetType().Assembly.FullName == asmName));
					if (val == null)
					{
						Plugin.Log.LogError((object)ex.ToString());
						break;
					}
					((ManualLogSource)PluginGetLogger.GetValue(val.Instance)).LogError((object)ex.ToString());
				}
			}
		}

		internal static void InvokeParameterlessDelegate<T>(this T paramlessDelegate) where T : Delegate
		{
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			if ((Delegate?)paramlessDelegate == (Delegate?)null)
			{
				return;
			}
			Delegate[] invocationList = paramlessDelegate.GetInvocationList();
			foreach (Delegate @delegate in invocationList)
			{
				try
				{
					((T)@delegate).DynamicInvoke();
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)"Exception while invoking hook callback!");
					string asmName = @delegate.GetMethodInfo().DeclaringType.Assembly.FullName;
					PluginInfo val = ((IEnumerable<PluginInfo>)Chainloader.PluginInfos.Values).FirstOrDefault((Func<PluginInfo, bool>)((PluginInfo pi) => ((object)pi.Instance).GetType().Assembly.FullName == asmName));
					if (val == null)
					{
						Plugin.Log.LogError((object)ex.ToString());
						break;
					}
					((ManualLogSource)PluginGetLogger.GetValue(val.Instance)).LogError((object)ex.ToString());
				}
			}
		}
	}
}
namespace LC_API.Data
{
	internal enum NetworkBroadcastDataType
	{
		Unknown,
		BDint,
		BDfloat,
		BDvector3,
		BDstring,
		BDlistString
	}
	public enum ShipState
	{
		InOrbit,
		OnMoon,
		LeavingMoon
	}
}
namespace LC_API.Comp
{
	internal class LC_APIManager : MonoBehaviour
	{
		public static MenuManager MenuManager;

		public static bool netTester;

		private static int playerCount;

		private static bool wanttoCheckMods;

		private static float lobbychecktimer;

		public void Update()
		{
			GameState.GSUpdate();
			GameTips.UpdateInternal();
			if ((((Object)(object)HUDManager.Instance != (Object)null) & netTester) && (Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null)
			{
				Networking.Broadcast("testerData", "testerSignature");
			}
			if (!ModdedServer.setModdedOnly)
			{
				ModdedServer.OnSceneLoaded();
			}
			else if (ModdedServer.ModdedOnly && (Object)(object)MenuManager != (Object)null && Object.op_Implicit((Object)(object)MenuManager.versionNumberText))
			{
				((TMP_Text)MenuManager.versionNumberText).text = $"v{GameNetworkManager.Instance.gameVersionNum - 16440}\nMOD";
			}
			if ((Object)(object)GameNetworkManager.Instance != (Object)null)
			{
				if (playerCount < GameNetworkManager.Instance.connectedPlayers)
				{
					lobbychecktimer = -4.5f;
					wanttoCheckMods = true;
				}
				playerCount = GameNetworkManager.Instance.connectedPlayers;
			}
			if (lobbychecktimer < 0f)
			{
				lobbychecktimer += Time.deltaTime;
			}
			else if (wanttoCheckMods && (Object)(object)HUDManager.Instance != (Object)null)
			{
				wanttoCheckMods = false;
				CD();
			}
		}

		private void CD()
		{
			CheatDatabase.OtherPlayerCheatDetector();
		}
	}
}
namespace LC_API.ClientAPI
{
	public static class CommandHandler
	{
		internal static class SubmitChatPatch
		{
			private static bool HandleMessage(HUDManager manager)
			{
				string text = manager.chatTextField.text;
				if (!Utility.IsNullOrWhiteSpace(text) && text.StartsWith(commandPrefix.Value))
				{
					string[] array = text.Split(new char[1] { ' ' });
					string text2 = array[0].Substring(commandPrefix.Value.Length);
					if (TryGetCommandHandler(text2, out var handler))
					{
						string[] obj = array.Skip(1).ToArray();
						try
						{
							handler(obj);
						}
						catch (Exception ex)
						{
							Plugin.Log.LogError((object)("Error handling command: " + text2));
							Plugin.Log.LogError((object)ex);
						}
					}
					manager.localPlayer.isTypingChat = false;
					manager.chatTextField.text = "";
					EventSystem.current.SetSelectedGameObject((GameObject)null);
					((Behaviour)manager.typingIndicator).enabled = false;
					return true;
				}
				return false;
			}

			internal static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
			{
				List<CodeInstruction> newInstructions = new List<CodeInstruction>(instructions);
				Label label = generator.DefineLabel();
				newInstructions[newInstructions.Count - 1].labels.Add(label);
				int index = newInstructions.FindIndex((CodeInstruction i) => i.opcode == OpCodes.Ldfld && (FieldInfo)i.operand == AccessTools.Field(typeof(PlayerControllerB), "isPlayerDead")) - 2;
				newInstructions.InsertRange(index, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[3]
				{
					CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), newInstructions[index]),
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(SubmitChatPatch), "HandleMessage", (Type[])null, (Type[])null)),
					new CodeInstruction(OpCodes.Brtrue, (object)label)
				});
				for (int z = 0; z < newInstructions.Count; z++)
				{
					yield return newInstructions[z];
				}
			}
		}

		internal static ConfigEntry<string> commandPrefix;

		internal static Dictionary<string, Action<string[]>> CommandHandlers = new Dictionary<string, Action<string[]>>();

		internal static Dictionary<string, List<string>> CommandAliases = new Dictionary<string, List<string>>();

		public static bool RegisterCommand(string command, Action<string[]> handler)
		{
			if (command.Contains(" ") || CommandHandlers.ContainsKey(command))
			{
				return false;
			}
			CommandHandlers.Add(command, handler);
			return true;
		}

		public static bool RegisterCommand(string command, List<string> aliases, Action<string[]> handler)
		{
			if (command.Contains(" ") || GetCommandHandler(command) != null)
			{
				return false;
			}
			foreach (string alias in aliases)
			{
				if (alias.Contains(" ") || GetCommandHandler(alias) != null)
				{
					return false;
				}
			}
			CommandHandlers.Add(command, handler);
			CommandAliases.Add(command, aliases);
			return true;
		}

		public static bool UnregisterCommand(string command)
		{
			CommandAliases.Remove(command);
			return CommandHandlers.Remove(command);
		}

		internal static Action<string[]> GetCommandHandler(string command)
		{
			if (CommandHandlers.TryGetValue(command, out var value))
			{
				return value;
			}
			foreach (KeyValuePair<string, List<string>> commandAlias in CommandAliases)
			{
				if (commandAlias.Value.Contains(command))
				{
					return CommandHandlers[commandAlias.Key];
				}
			}
			return null;
		}

		internal static bool TryGetCommandHandler(string command, out Action<string[]> handler)
		{
			handler = GetCommandHandler(command);
			return handler != null;
		}
	}
}
namespace LC_API.BundleAPI
{
	public static class BundleLoader
	{
		[Obsolete("Use OnLoadedBundles instead. This will be removed/private in a future update.")]
		public delegate void OnLoadedAssetsDelegate();

		[Obsolete("Use GetLoadedAsset instead. This will be removed/private in a future update.")]
		public static ConcurrentDictionary<string, Object> assets = new ConcurrentDictionary<string, Object>();

		[Obsolete("Use OnLoadedBundles instead. This will be removed/private in a future update.")]
		public static OnLoadedAssetsDelegate OnLoadedAssets = LoadAssetsCompleted;

		public static bool AssetsInLegacyDirectory { get; private set; }

		public static bool LegacyLoadingEnabled { get; private set; }

		public static event Action OnLoadedBundles;

		internal static void Load(bool legacyLoading)
		{
			LegacyLoadingEnabled = legacyLoading;
			Plugin.Log.LogMessage((object)"BundleAPI will now load all asset bundles...");
			string path = Path.Combine(Paths.BepInExRootPath, "Bundles");
			if (!Directory.Exists(path))
			{
				Directory.CreateDirectory(path);
				Plugin.Log.LogMessage((object)"BundleAPI Created legacy bundle directory in BepInEx/Bundles");
			}
			string[] array = (from x in Directory.GetFiles(path, "*", SearchOption.AllDirectories)
				where !x.EndsWith(".manifest", StringComparison.CurrentCultureIgnoreCase)
				select x).ToArray();
			AssetsInLegacyDirectory = array.Length != 0;
			if (!AssetsInLegacyDirectory)
			{
				Plugin.Log.LogMessage((object)"BundleAPI got no assets to load from legacy directory");
			}
			if (AssetsInLegacyDirectory)
			{
				Plugin.Log.LogWarning((object)"The path BepInEx > Bundles is outdated and should not be used anymore! Bundles will be loaded from BepInEx > plugins from now on");
				LoadAllAssetsFromDirectory(array, legacyLoading);
			}
			string[] invalidEndings = new string[8] { ".dll", ".json", ".png", ".md", ".old", ".txt", ".exe", ".lem" };
			path = Path.Combine(Paths.BepInExRootPath, "plugins");
			array = (from file in Directory.GetFiles(path, "*", SearchOption.AllDirectories)
				where !invalidEndings.Any((string ending) => file.EndsWith(ending, StringComparison.CurrentCultureIgnoreCase))
				select file).ToArray();
			byte[] bytes = Encoding.ASCII.GetBytes("UnityFS");
			List<string> list = new List<string>();
			string[] array2 = array;
			foreach (string text in array2)
			{
				byte[] array3 = new byte[bytes.Length];
				using (FileStream fileStream = File.Open(text, FileMode.Open))
				{
					fileStream.Read(array3, 0, array3.Length);
				}
				if (array3.SequenceEqual(bytes))
				{
					list.Add(text);
				}
			}
			array = list.ToArray();
			if (array.Length == 0)
			{
				Plugin.Log.LogMessage((object)"BundleAPI got no assets to load from plugins folder");
			}
			else
			{
				LoadAllAssetsFromDirectory(array, legacyLoading);
			}
			OnLoadedAssets.InvokeParameterlessDelegate();
			BundleLoader.OnLoadedBundles.InvokeActionSafe();
		}

		private static void LoadAllAssetsFromDirectory(string[] array, bool legacyLoading)
		{
			if (legacyLoading)
			{
				Plugin.Log.LogMessage((object)("BundleAPI got " + array.Length + " AssetBundles to load!"));
				for (int i = 0; i < array.Length; i++)
				{
					try
					{
						SaveAsset(array[i], legacyLoading);
					}
					catch (Exception)
					{
						Plugin.Log.LogError((object)("Failed to load an assetbundle! Path: " + array[i]));
					}
				}
				return;
			}
			Plugin.Log.LogMessage((object)("BundleAPI got " + array.Length + " AssetBundles to load!"));
			for (int j = 0; j < array.Length; j++)
			{
				try
				{
					SaveAsset(array[j], legacyLoading);
				}
				catch (Exception)
				{
					Plugin.Log.LogError((object)("Failed to load an assetbundle! Path: " + array[j]));
				}
			}
		}

		public static void SaveAsset(string path, bool legacyLoad)
		{
			AssetBundle val = AssetBundle.LoadFromFile(path);
			try
			{
				string[] allAssetNames = val.GetAllAssetNames();
				foreach (string text in allAssetNames)
				{
					Plugin.Log.LogMessage((object)("Got asset for load: " + text));
					Object val2 = val.LoadAsset(text);
					if (val2 == (Object)null)
					{
						Plugin.Log.LogWarning((object)$"Skipped/failed loading an asset (from bundle '{((Object)val).name}') - Asset path: {val2}");
						continue;
					}
					string key = (legacyLoad ? text.ToUpper() : text.ToLower());
					if (assets.ContainsKey(key))
					{
						Plugin.Log.LogError((object)"BundleAPI got duplicate asset!");
						break;
					}
					assets.TryAdd(key, val2);
					Plugin.Log.LogMessage((object)("Loaded asset: " + val2.name));
				}
			}
			finally
			{
				if (val != null)
				{
					val.Unload(false);
				}
			}
		}

		public static TAsset GetLoadedAsset<TAsset>(string itemPath) where TAsset : Object
		{
			Object value = null;
			if (LegacyLoadingEnabled)
			{
				assets.TryGetValue(itemPath.ToUpper(), out value);
			}
			if (value == (Object)null)
			{
				assets.TryGetValue(itemPath.ToLower(), out value);
			}
			return (TAsset)(object)value;
		}

		private static void LoadAssetsCompleted()
		{
			Plugin.Log.LogMessage((object)"BundleAPI finished loading all assets.");
		}

		static BundleLoader()
		{
			BundleLoader.OnLoadedBundles = LoadAssetsCompleted;
		}
	}
}

BepInEx/plugins/LC_Masked_Fix.dll

Decompiled 7 months ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using LC_MIMICFIX.Patches;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("LC_MIMICFIX")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LC_MIMICFIX")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("52a8c306-f1df-46d3-a634-8db137e227d7")]
[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 LC_MIMICFIX
{
	[BepInPlugin("kuba6000.LC_MimicFixMod", "LC_Masked_Fix", "0.0.1")]
	public class LC_MimicFixMod : BaseUnityPlugin
	{
		private const string ModGUID = "kuba6000.LC_MimicFixMod";

		private const string ModName = "LC_Masked_Fix";

		private const string ModVersion = "0.0.1";

		private readonly Harmony harmony = new Harmony("kuba6000.LC_MimicFixMod");

		public static LC_MimicFixMod instance;

		internal ManualLogSource log;

		private void Awake()
		{
			instance = this;
			log = Logger.CreateLogSource("kuba6000.LC_MimicFixMod");
			log.LogInfo((object)"Mimic Fix Awaken!");
			log.LogInfo((object)"Patching MaskedPlayerEnemy");
			harmony.PatchAll(typeof(LC_MimicFixMod));
			harmony.PatchAll(typeof(MaskedPlayerEnemyPatch));
		}
	}
}
namespace LC_MIMICFIX.Patches
{
	[HarmonyPatch(typeof(MaskedPlayerEnemy))]
	internal class MaskedPlayerEnemyPatch
	{
		[HarmonyPatch("CancelSpecialAnimationWithPlayer")]
		[HarmonyPrefix]
		private static bool CancelSpecialAnimationWithPlayerPatch(MaskedPlayerEnemy __instance)
		{
			if ((Object)(object)((EnemyAI)__instance).inSpecialAnimationWithPlayer == (Object)(object)GameNetworkManager.Instance.localPlayerController)
			{
				LC_MimicFixMod.instance.log.LogInfo((object)"Removing biohazardDamage animation");
				HUDManager.Instance.HUDAnimator.SetBool("biohazardDamage", false);
				HUDManager.Instance.HideHUD(true);
				HUDManager.Instance.HideHUD(false);
			}
			LC_MimicFixMod.instance.log.LogInfo((object)"Directly finishing kill animation");
			__instance.FinishKillAnimation(false);
			return false;
		}
	}
}

BepInEx/plugins/LetMeLookDown.dll

Decompiled 7 months ago
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using GameNetcodeStuff;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("LetMeLookDown")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LetMeLookDown")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("a9c88d54-8f01-44a7-be0d-bd61d38aadcb")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace LetMeLookDown
{
	[BepInPlugin("FlipMods.LetMeLookDown", "LetMeLookDown", "1.0.1")]
	public class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		private static Plugin instance;

		public static float maxAngle = 80f;

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

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

		public const string PLUGIN_NAME = "LetMeLookDown";

		public const string PLUGIN_VERSION = "1.0.1";
	}
}
namespace LetMeLookDown.Patches
{
	[HarmonyPatch]
	internal class AdjustSmoothLookingPatcher
	{
		[HarmonyPatch(typeof(PlayerControllerB), "CalculateSmoothLookingInput")]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 60f)
				{
					list[i].operand = Plugin.maxAngle;
					break;
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch]
	internal class AdjustNormalLookingPatcher
	{
		[HarmonyPatch(typeof(PlayerControllerB), "CalculateNormalLookingInput")]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 60f)
				{
					list[i].operand = Plugin.maxAngle;
					break;
				}
			}
			return list.AsEnumerable();
		}
	}
}

BepInEx/plugins/MikesTweaks.dll

Decompiled 7 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.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MikesTweaks.Scripts.Configs;
using MikesTweaks.Scripts.Environment;
using MikesTweaks.Scripts.Input;
using MikesTweaks.Scripts.Inventory;
using MikesTweaks.Scripts.Items;
using MikesTweaks.Scripts.Moons;
using MikesTweaks.Scripts.Networking;
using MikesTweaks.Scripts.Player;
using MikesTweaks.Scripts.Systems;
using MikesTweaks.Scripts.Utilities;
using MikesTweaks.Scripts.World;
using Newtonsoft.Json;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MikesTweaks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Mod for Lethal Company with multiple configurable item weights, item prices, inventory slots amount, inventory/item slot keybinds, flashlight/walkie talkie keybinds, player stamina/sprint values and moons cost to travel to customize your own experience.")]
[assembly: AssemblyFileVersion("1.9.2.0")]
[assembly: AssemblyInformationalVersion("1.9.2")]
[assembly: AssemblyProduct("MikesTweaks")]
[assembly: AssemblyTitle("MikesTweaks")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.9.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

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

		public const string PLUGIN_NAME = "MikesTweaks";

		public const string PLUGIN_VERSION = "1.9.2";
	}
}
namespace MikesTweaks.Scripts
{
	[BepInPlugin("mikes.lethalcompany.mikestweaks", "MikesTweaks", "1.9.2")]
	public class MikesTweaks : BaseUnityPlugin
	{
		public static class Compatibility
		{
			public static bool ReservedSlotsCompat;
		}

		public const string GUID = "mikes.lethalcompany.mikestweaks";

		public const bool DebugMode = false;

		public static ManualLogSource Log;

		public static MikesTweaks Instance { get; private set; }

		public void BindConfig<T>(ref ConfigEntrySettings<T> config, string SectionName)
		{
			config.Entry = ((BaseUnityPlugin)this).Config.Bind<T>(SectionName, config.ConfigName, config.DefaultValue, config.ConfigDesc);
		}

		public void LoadConfigs()
		{
			((BaseUnityPlugin)this).Config.Reload();
			ConfigsSynchronizer.ConfigsReceived = false;
		}

		private void Awake()
		{
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			WorldTweaks.RegisterConfigs();
			MoonTweaks.RegisterConfigs();
			PlayerTweaks.RegisterConfigs();
			InventoryTweaks.RegisterConfigs();
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			Harmony.CreateAndPatchAll(typeof(MenuManager_Patches), (string)null);
			Harmony.CreateAndPatchAll(typeof(IngamePlayerSettings_Patches), (string)null);
			Harmony.CreateAndPatchAll(typeof(HUDManager_Patches), (string)null);
			Harmony.CreateAndPatchAll(typeof(NetworkManager_Patches), (string)null);
			Harmony.CreateAndPatchAll(typeof(StartOfRound_Patches), (string)null);
			Harmony.CreateAndPatchAll(typeof(TimeOfDay_Patches), (string)null);
			Harmony.CreateAndPatchAll(typeof(InteractTrigger_Patches), (string)null);
			Harmony.CreateAndPatchAll(typeof(Terminal_Patches), (string)null);
			Harmony.CreateAndPatchAll(typeof(PlayerControllerB_Patches), (string)null);
			Harmony.CreateAndPatchAll(typeof(GrabbableObject_Patches), (string)null);
			CheckCompatibilities();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin mikes.lethalcompany.mikestweaks is loaded!");
		}

		private void CheckCompatibilities()
		{
			Compatibility.ReservedSlotsCompat = IsModPresent("ReservedItemSlotCore");
			if (Compatibility.ReservedSlotsCompat)
			{
				Log.LogInfo((object)"Found: ReservedItemSlotCore");
			}
		}

		public static bool IsModPresent(string name)
		{
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				if (name == pluginInfo.Value.Metadata.Name)
				{
					return true;
				}
			}
			return false;
		}
	}
}
namespace MikesTweaks.Scripts.World
{
	public class WorldTweaks
	{
		public class Configs
		{
			public static ConfigEntrySettings<float> GlobalTimeSpeedMulti = new ConfigEntrySettings<float>("GlobalTimeSpeedMultiplier", 0.7f, 1.4f, "Think of this as a percentage, the lower it is, the slower the time goes by, the higher it is, the faster time passes.");

			public static ConfigEntrySettings<bool> AllowHotbarKeybinds = new ConfigEntrySettings<bool>("AllowHotbarKeybinds", defaultValue: true, vanillaValue: false, "Set this to false if you don't want people who join your lobby to be able to use the hotbar keybinds and to true if you want them to be able to.");

			public static ConfigEntrySettings<bool> AllowFlashlightKeybind = new ConfigEntrySettings<bool>("AllowFlashlightKeybind", defaultValue: true, vanillaValue: false, "Set this to false if you don't want people who join your lobby to be able to use the flashlight keybind and to true if you want them to be able to.");

			public static ConfigEntrySettings<bool> AllowWalkieTalkieKeybind = new ConfigEntrySettings<bool>("AllowWalkieTalkieKeybind", defaultValue: true, vanillaValue: false, "Set this to false if you don't want people who join your lobby to be able to use the flashlight keybind and to true if you want them to be able to.");

			public static ConfigEntrySettings<bool> AllowClientsToUseTerminal = new ConfigEntrySettings<bool>("AllowClientsToUseTerminal", defaultValue: true, vanillaValue: true, "Set this to false if you don't want people who join your lobby to be able to use the terminal and to true if you want them to be able to.\nYou probably want to set this to true if you're hosting a lobby with people you know and trust.");

			public static ConfigEntrySettings<bool> UseVanillaSprintSpeedValues = new ConfigEntrySettings<bool>("UseVanillaSprintSpeedValues", defaultValue: false, vanillaValue: true, "Set this to true if you want to use all the vanilla values tied to sprinting.\nStamina drain related configs not included.");

			public static ConfigEntrySettings<bool> UseVanillaStaminaValues = new ConfigEntrySettings<bool>("UseVanillaStaminaValues", defaultValue: false, vanillaValue: true, "Set this to true if you want to use all the vanilla values tied to stamina.\nSprint speed related configs not included.");

			public static ConfigEntrySettings<bool> UseVanillaToolItemWeights = new ConfigEntrySettings<bool>("UseVanillaToolItemWeights", defaultValue: false, vanillaValue: true, "Set this to true if you want to use all the vanilla values for the weight of every tool item.");

			public static ConfigEntrySettings<bool> UseVanillaToolItemPrices = new ConfigEntrySettings<bool>("UseVanillaToolItemPrices", defaultValue: false, vanillaValue: true, "Set this to true if you want to use all the vanilla values for the price of every tool item.");

			public static ConfigEntrySettings<bool> UseVanillaMoonCosts = new ConfigEntrySettings<bool>("UseVanillaMoonCosts", defaultValue: false, vanillaValue: true, "Set this to true if you want to use all the vanilla values for the cost of traveling to the moons.");

			public static string GameRulesSectionHeader => "GameRules";
		}

		public static Terminal TerminalInstance = null;

		public static InteractTrigger TerminalInteractTriggerInstance = null;

		private static readonly MethodInfo TerminalTriggerInUseRPC = typeof(InteractTrigger).GetMethod("UpdateUsedByPlayerServerRpc", BindingFlags.Instance | BindingFlags.NonPublic);

		public static void RegisterConfigs()
		{
			MikesTweaks.Instance.BindConfig(ref Configs.GlobalTimeSpeedMulti, Configs.GameRulesSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.AllowHotbarKeybinds, Configs.GameRulesSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.AllowFlashlightKeybind, Configs.GameRulesSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.AllowWalkieTalkieKeybind, Configs.GameRulesSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.AllowClientsToUseTerminal, Configs.GameRulesSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.UseVanillaSprintSpeedValues, Configs.GameRulesSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.UseVanillaStaminaValues, Configs.GameRulesSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.UseVanillaToolItemWeights, Configs.GameRulesSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.UseVanillaToolItemPrices, Configs.GameRulesSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.UseVanillaMoonCosts, Configs.GameRulesSectionHeader);
			ConfigsSynchronizer.OnConfigsChangedDelegate = (Action)Delegate.Combine(ConfigsSynchronizer.OnConfigsChangedDelegate, (Action)delegate
			{
				ReapplyConfigs(TimeOfDay.Instance);
			});
			ConfigsSynchronizer.Instance.AddConfigGetter(WriteConfigsToWriter);
			ConfigsSynchronizer.Instance.AddConfigSetter(ReadConfigChanges);
			ConfigsSynchronizer.Instance.AddConfigSizeGetter(() => 9);
		}

		public static FastBufferWriter WriteConfigsToWriter(FastBufferWriter writer)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: 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_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: 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_00b4: Unknown result type (might be due to invalid IL or missing references)
			float num = Configs.GlobalTimeSpeedMulti.Value();
			((FastBufferWriter)(ref writer)).WriteValueSafe<float>(ref num, default(ForPrimitives));
			bool flag = Configs.AllowFlashlightKeybind.Value();
			((FastBufferWriter)(ref writer)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
			flag = Configs.AllowWalkieTalkieKeybind.Value();
			((FastBufferWriter)(ref writer)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
			flag = Configs.AllowHotbarKeybinds.Value();
			((FastBufferWriter)(ref writer)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
			flag = Configs.UseVanillaToolItemPrices.Value();
			((FastBufferWriter)(ref writer)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
			flag = Configs.UseVanillaMoonCosts.Value();
			((FastBufferWriter)(ref writer)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
			return writer;
		}

		public static FastBufferReader ReadConfigChanges(FastBufferReader payload)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			float value = default(float);
			((FastBufferReader)(ref payload)).ReadValue<float>(ref value, default(ForPrimitives));
			Configs.GlobalTimeSpeedMulti.Entry.Value = value;
			bool value2 = default(bool);
			((FastBufferReader)(ref payload)).ReadValue<bool>(ref value2, default(ForPrimitives));
			Configs.AllowFlashlightKeybind.Entry.Value = value2;
			((FastBufferReader)(ref payload)).ReadValue<bool>(ref value2, default(ForPrimitives));
			Configs.AllowWalkieTalkieKeybind.Entry.Value = value2;
			((FastBufferReader)(ref payload)).ReadValue<bool>(ref value2, default(ForPrimitives));
			Configs.AllowHotbarKeybinds.Entry.Value = value2;
			((FastBufferReader)(ref payload)).ReadValue<bool>(ref value2, default(ForPrimitives));
			Configs.UseVanillaToolItemPrices.Entry.Value = value2;
			((FastBufferReader)(ref payload)).ReadValue<bool>(ref value2, default(ForPrimitives));
			Configs.UseVanillaMoonCosts.Entry.Value = value2;
			return payload;
		}

		public static void ReapplyConfigs(TimeOfDay timeOfDay)
		{
			timeOfDay.globalTimeSpeedMultiplier = Configs.GlobalTimeSpeedMulti.Value();
		}

		public static bool CanInteractWithTerminal(InteractTrigger __instance)
		{
			if (!NetworkManager.Singleton.IsServer)
			{
				return false;
			}
			if (Configs.AllowClientsToUseTerminal.Value())
			{
				return false;
			}
			return (Object)(object)TerminalInteractTriggerInstance == (Object)(object)__instance;
		}

		public static void MakeTerminalUnusableForAnyoneButHost()
		{
			if (NetworkManager.Singleton.IsServer && !Configs.AllowClientsToUseTerminal.Value())
			{
				object[] parameters = new object[1] { 0 };
				TerminalTriggerInUseRPC.Invoke(TerminalInteractTriggerInstance, parameters);
			}
		}

		public static void ResetValues(InteractTrigger trigger)
		{
			if (trigger.hidePlayerItem && (Object)(object)StartOfRound.Instance.allPlayerScripts[0].currentlyHeldObjectServer != (Object)null)
			{
				StartOfRound.Instance.allPlayerScripts[0].currentlyHeldObjectServer.EnableItemMeshes(true);
				typeof(InteractTrigger).GetField("playerUsingId", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(trigger, -1);
			}
			StartOfRound.Instance.allPlayerScripts[0].currentTriggerInAnimationWith = null;
			trigger.isPlayingSpecialAnimation = false;
		}
	}
}
namespace MikesTweaks.Scripts.Utilities
{
	public static class StringUtils
	{
		public static void RemoveChar(ref string str, char character)
		{
			List<int> list = new List<int>();
			for (int num = str.Length - 1; num >= 0; num--)
			{
				if (str[num] == character)
				{
					list.Add(num);
				}
			}
			for (int i = 0; i < list.Count; i++)
			{
				str = str.Remove(list[i], 1);
			}
		}
	}
}
namespace MikesTweaks.Scripts.Systems
{
	[HarmonyPatch(typeof(HUDManager))]
	public class HUDManager_Patches
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		public static void Awake(HUDManager __instance)
		{
			if (NetworkManager.Singleton.IsServer && !MikesTweaks.Compatibility.ReservedSlotsCompat)
			{
				InventoryTweaks.ChangeItemSlotsAmountUI();
			}
		}
	}
	[HarmonyPatch(typeof(IngamePlayerSettings))]
	public class IngamePlayerSettings_Patches
	{
		[HarmonyPatch("RebindKey")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> AllowMouseBinding(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				CodeInstruction val = list[i];
				if (!(val.opcode != OpCodes.Ldstr) && !((string)val.operand != "Mouse"))
				{
					list.RemoveAt(i + 1);
					list.RemoveAt(i);
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(MenuManager))]
	public class MenuManager_Patches
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void MenuManager_Start(MenuManager __instance)
		{
			MikesTweaks.Instance.LoadConfigs();
		}
	}
	[HarmonyPatch(typeof(NetworkManager))]
	public static class NetworkManager_Patches
	{
		[HarmonyPatch("StartHost")]
		[HarmonyPostfix]
		private static void StartHost_Post(GameNetworkManager __instance)
		{
			ConfigsSynchronizer.Instance.RegisterMessages();
		}

		[HarmonyPatch("StartClient")]
		[HarmonyPostfix]
		private static void StartClient_Post(GameNetworkManager __instance)
		{
			ConfigsSynchronizer.Instance.RegisterMessages();
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	public static class StartOfRound_Patches
	{
		[HarmonyPatch("OnPlayerConnectedClientRpc")]
		[HarmonyPostfix]
		private static void OnPlayerConnectedClientRpc(StartOfRound __instance, ulong clientId, int assignedPlayerObjectId)
		{
			if (!NetworkManager.Singleton.IsServer)
			{
				ConfigsSynchronizer.Instance.RequestConfigs();
			}
		}
	}
	[HarmonyPatch(typeof(TimeOfDay))]
	public class TimeOfDay_Patches
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void ChangeTimeSpeedMultiplier(TimeOfDay __instance)
		{
			if (NetworkManager.Singleton.IsServer)
			{
				WorldTweaks.ReapplyConfigs(__instance);
			}
		}
	}
}
namespace MikesTweaks.Scripts.Player
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	public static class PlayerControllerB_Patches
	{
		private static PlayerInputRedirection inputRedirection;

		public static void SetupKeybinds(PlayerControllerB player)
		{
			if (PlayerTweaks.IsLocallyControlled(player))
			{
				inputRedirection = ((Component)player).gameObject.GetComponent<PlayerInputRedirection>();
				inputRedirection.InitializeKeybinds();
			}
		}

		private static bool InsertStaminaRechargeMovementHinderedWalking(ref List<CodeInstruction> instructions, CodeInstruction instruction, int i, ref List<int> IndexesToRemove)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			if (instruction.opcode != OpCodes.Ldc_R4)
			{
				return false;
			}
			if (Math.Abs((float)instruction.operand - 0.5f) > 0.01f)
			{
				return false;
			}
			instructions[i - 7] = new CodeInstruction(OpCodes.Ldloc_0, (object)null);
			instructions[i - 6] = CodeInstruction.Call(typeof(PlayerTweaks), "StaminaRechargeMovementHinderedWalking", (Type[])null, (Type[])null);
			instructions[i - 5] = CodeInstruction.StoreField(typeof(PlayerControllerB), "sprintMeter");
			for (int j = i - 4; j <= i + 6; j++)
			{
				IndexesToRemove.Add(j);
			}
			return true;
		}

		private static bool InsertStaminaRechargeMovementNotHinderedWalking(ref List<CodeInstruction> instructions, CodeInstruction instruction, int i, ref List<int> IndexesToRemove)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			if (instruction.opcode != OpCodes.Ldc_R4)
			{
				return false;
			}
			if (Math.Abs((float)instruction.operand - 9f) > 0.01f)
			{
				return false;
			}
			instructions[i - 4] = new CodeInstruction(OpCodes.Ldloc_0, (object)null);
			instructions[i - 3] = CodeInstruction.Call(typeof(PlayerTweaks), "StaminaRechargeMovementNotHinderedWalking", (Type[])null, (Type[])null);
			instructions[i - 2] = CodeInstruction.StoreField(typeof(PlayerControllerB), "sprintMeter");
			for (int j = i - 1; j <= i + 9; j++)
			{
				IndexesToRemove.Add(j);
			}
			return true;
		}

		private static bool InsertStaminaRechargeMovementNotHinderedNotWalking(ref List<CodeInstruction> instructions, CodeInstruction instruction, int i, ref List<int> IndexesToRemove)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			if (instruction.opcode != OpCodes.Ldc_R4)
			{
				return false;
			}
			if (Math.Abs((float)instruction.operand - 4f) > 0.01f)
			{
				return false;
			}
			instructions[i - 4] = new CodeInstruction(OpCodes.Ldloc_0, (object)null);
			instructions[i - 3] = CodeInstruction.Call(typeof(PlayerTweaks), "StaminaRechargeMovementNotHinderedNotWalking", (Type[])null, (Type[])null);
			instructions[i - 2] = CodeInstruction.StoreField(typeof(PlayerControllerB), "sprintMeter");
			for (int j = i - 1; j <= i + 9; j++)
			{
				IndexesToRemove.Add(j);
			}
			return true;
		}

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void Awake(PlayerControllerB __instance)
		{
			((Component)__instance).gameObject.AddComponent<PlayerInputRedirection>();
			if (NetworkManager.Singleton.IsServer)
			{
				PlayerTweaks.ReapplyConfigs(__instance);
			}
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void Start(PlayerControllerB __instance)
		{
			PlayerTweaks.RegisterSwitchSlotMessage();
		}

		private static void ModifySprintMultiplierValues(ref List<CodeInstruction> instructions)
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Expected O, but got Unknown
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Expected O, but got Unknown
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Expected O, but got Unknown
			//IL_0343: Unknown result type (might be due to invalid IL or missing references)
			//IL_034d: Expected O, but got Unknown
			float num = 2.25f;
			float num2 = 1f;
			float num3 = 1f;
			float num4 = 10f;
			int num5 = -1;
			bool flag = false;
			bool flag2 = false;
			bool flag3 = false;
			for (int i = 0; i < instructions.Count; i++)
			{
				CodeInstruction val = instructions[i];
				if (!(val.opcode != OpCodes.Ldc_R4) && !((double)Math.Abs((float)val.operand - num) > 0.1))
				{
					num5 = i;
					instructions[i] = CodeInstruction.Call(typeof(ConfigEntrySettings<float>), "Value", (Type[])null, (Type[])null);
					instructions.Insert(i, CodeInstruction.Call(typeof(ConfigEntrySettings<bool>), "Value", (Type[])null, (Type[])null));
					instructions.Insert(i, new CodeInstruction(OpCodes.Ldc_I4_0, (object)null));
					instructions.Insert(i, CodeInstruction.LoadField(typeof(WorldTweaks.Configs), "UseVanillaSprintSpeedValues", false));
					instructions.Insert(i, CodeInstruction.LoadField(typeof(PlayerTweaks.Configs), "MaxSprintSpeed", false));
					break;
				}
			}
			if (num5 == -1)
			{
				return;
			}
			for (int j = num5; j < instructions.Count; j++)
			{
				CodeInstruction val2 = instructions[j];
				if (val2.opcode == OpCodes.Ldc_R4)
				{
					if (flag2 && flag3 && flag)
					{
						break;
					}
					if (!flag && (double)Math.Abs((float)val2.operand - num2) < 0.1)
					{
						instructions[j] = CodeInstruction.Call(typeof(ConfigEntrySettings<float>), "Value", (Type[])null, (Type[])null);
						instructions.Insert(j, CodeInstruction.Call(typeof(ConfigEntrySettings<bool>), "Value", (Type[])null, (Type[])null));
						instructions.Insert(j, new CodeInstruction(OpCodes.Ldc_I4_0, (object)null));
						instructions.Insert(j, CodeInstruction.LoadField(typeof(WorldTweaks.Configs), "UseVanillaSprintSpeedValues", false));
						instructions.Insert(j, CodeInstruction.LoadField(typeof(PlayerTweaks.Configs), "SprintSpeedIncreasePerFrame", false));
						flag = true;
					}
					else if (!flag2 && (double)Math.Abs((float)val2.operand - num3) < 0.1)
					{
						instructions[j] = CodeInstruction.Call(typeof(ConfigEntrySettings<float>), "Value", (Type[])null, (Type[])null);
						instructions.Insert(j, CodeInstruction.Call(typeof(ConfigEntrySettings<bool>), "Value", (Type[])null, (Type[])null));
						instructions.Insert(j, new CodeInstruction(OpCodes.Ldc_I4_0, (object)null));
						instructions.Insert(j, CodeInstruction.LoadField(typeof(WorldTweaks.Configs), "UseVanillaSprintSpeedValues", false));
						instructions.Insert(j, CodeInstruction.LoadField(typeof(PlayerTweaks.Configs), "DefaultSprintSpeed", false));
						flag2 = true;
					}
					else if (!flag3 && (double)Math.Abs((float)val2.operand - num4) < 0.1)
					{
						instructions[j] = CodeInstruction.Call(typeof(ConfigEntrySettings<float>), "Value", (Type[])null, (Type[])null);
						instructions.Insert(j, CodeInstruction.Call(typeof(ConfigEntrySettings<bool>), "Value", (Type[])null, (Type[])null));
						instructions.Insert(j, new CodeInstruction(OpCodes.Ldc_I4_0, (object)null));
						instructions.Insert(j, CodeInstruction.LoadField(typeof(WorldTweaks.Configs), "UseVanillaSprintSpeedValues", false));
						instructions.Insert(j, CodeInstruction.LoadField(typeof(PlayerTweaks.Configs), "SprintSpeedDecreasePerFrame", false));
						flag3 = true;
					}
				}
			}
		}

		[HarmonyPatch("Update")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> Update_Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> instructions2 = new List<CodeInstruction>(instructions);
			ModifySprintMultiplierValues(ref instructions2);
			return instructions2.AsEnumerable();
		}

		[HarmonyPatch("ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		private static void AddHotkeys(PlayerControllerB __instance)
		{
			SetupKeybinds(__instance);
		}

		[HarmonyPatch("LateUpdate")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> LateUpdate_Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			bool flag = false;
			bool flag2 = false;
			bool flag3 = false;
			List<int> IndexesToRemove = new List<int>();
			List<CodeInstruction> instructions2 = new List<CodeInstruction>(instructions);
			for (int i = 0; i < instructions2.Count; i++)
			{
				CodeInstruction instruction = instructions2[i];
				if (!flag)
				{
					flag = InsertStaminaRechargeMovementHinderedWalking(ref instructions2, instruction, i, ref IndexesToRemove);
				}
				if (!flag3)
				{
					flag3 = InsertStaminaRechargeMovementNotHinderedNotWalking(ref instructions2, instruction, i, ref IndexesToRemove);
				}
				if (!flag2)
				{
					flag2 = InsertStaminaRechargeMovementNotHinderedWalking(ref instructions2, instruction, i, ref IndexesToRemove);
				}
				if (flag && flag3 && flag2)
				{
					break;
				}
			}
			IndexesToRemove.Sort();
			for (int num = IndexesToRemove.Count - 1; num >= 0; num--)
			{
				instructions2.RemoveAt(IndexesToRemove[num]);
			}
			return instructions2.AsEnumerable();
		}

		[HarmonyPatch("Jump_performed")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> ModifyJumpDrain(IEnumerable<CodeInstruction> instructions)
		{
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			float num = 0.08f;
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				CodeInstruction val = list[i];
				if (!(val.opcode != OpCodes.Ldc_R4) && !(Math.Abs((float)val.operand - num) > 0.01f))
				{
					list[i] = CodeInstruction.Call(typeof(ConfigEntrySettings<float>), "Value", (Type[])null, (Type[])null);
					list.Insert(i, CodeInstruction.Call(typeof(ConfigEntrySettings<bool>), "Value", (Type[])null, (Type[])null));
					list.Insert(i, new CodeInstruction(OpCodes.Ldc_I4_0, (object)null));
					list.Insert(i, CodeInstruction.LoadField(typeof(WorldTweaks.Configs), "UseVanillaStaminaValues", false));
					list.Insert(i, CodeInstruction.LoadField(typeof(PlayerTweaks.Configs), "JumpStaminaDrain", false));
					break;
				}
			}
			return instructions.AsEnumerable();
		}

		[HarmonyPatch("Emote1_performed")]
		[HarmonyPrefix]
		private static bool Emote1_performed()
		{
			return false;
		}

		[HarmonyPatch("Emote2_performed")]
		[HarmonyPrefix]
		private static bool Emote2_performed()
		{
			return false;
		}

		[HarmonyPatch("SendNewPlayerValuesClientRpc")]
		[HarmonyPostfix]
		private static void ConnectClientToPlayerObject(PlayerControllerB __instance)
		{
			WorldTweaks.MakeTerminalUnusableForAnyoneButHost();
		}

		[HarmonyPatch("OnEnable")]
		[HarmonyPostfix]
		private static void OnEnable(PlayerControllerB __instance)
		{
			if (PlayerTweaks.IsLocallyControlled(__instance))
			{
				inputRedirection?.OnEnable();
			}
		}

		[HarmonyPatch("OnDisable")]
		[HarmonyPostfix]
		private static void OnDisable(PlayerControllerB __instance)
		{
			if (PlayerTweaks.IsLocallyControlled(__instance))
			{
				inputRedirection?.OnDisable();
			}
		}

		[HarmonyPatch("OnDestroy")]
		[HarmonyPrefix]
		public static void OnDestroy(PlayerControllerB __instance)
		{
			if (PlayerTweaks.IsLocallyControlled(__instance))
			{
				inputRedirection?.Destroy();
				inputRedirection = null;
			}
		}
	}
	public class PlayerInputRedirection : MonoBehaviour, MikesTweaksPlayerInput.IHotbarActions, MikesTweaksPlayerInput.IEmotesActions, MikesTweaksPlayerInput.IActionsActions
	{
		private PlayerControllerB owner;

		private MikesTweaksPlayerInput input;

		private MethodInfo SwitchToSlotMethod;

		private WalkieTalkie WalkieTalkieToStop;

		public void OnHotbar1(CallbackContext context)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)((CallbackContext)(ref context)).phase == 3)
			{
				RequestSlotChange(0);
			}
		}

		public void OnHotbar2(CallbackContext context)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)((CallbackContext)(ref context)).phase == 3)
			{
				RequestSlotChange(1);
			}
		}

		public void OnHotbar3(CallbackContext context)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)((CallbackContext)(ref context)).phase == 3)
			{
				RequestSlotChange(2);
			}
		}

		public void OnHotbar4(CallbackContext context)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)((CallbackContext)(ref context)).phase == 3)
			{
				RequestSlotChange(3);
			}
		}

		public void OnHotbar5(CallbackContext context)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)((CallbackContext)(ref context)).phase == 3 && InventoryTweaks.HasEnoughSlots(4))
			{
				RequestSlotChange(4);
			}
		}

		public void OnHotbar6(CallbackContext context)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)((CallbackContext)(ref context)).phase == 3 && InventoryTweaks.HasEnoughSlots(5))
			{
				RequestSlotChange(5);
			}
		}

		public void OnHotbar7(CallbackContext context)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)((CallbackContext)(ref context)).phase == 3 && InventoryTweaks.HasEnoughSlots(6))
			{
				RequestSlotChange(6);
			}
		}

		public void OnHotbar8(CallbackContext context)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)((CallbackContext)(ref context)).phase == 3 && InventoryTweaks.HasEnoughSlots(7))
			{
				RequestSlotChange(7);
			}
		}

		public void OnHotbar9(CallbackContext context)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)((CallbackContext)(ref context)).phase == 3 && InventoryTweaks.HasEnoughSlots(8))
			{
				RequestSlotChange(8);
			}
		}

		public void OnEmote1(CallbackContext context)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB obj = owner;
			if (obj != null)
			{
				obj.PerformEmote(context, 1);
			}
		}

		public void OnEmote2(CallbackContext context)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB obj = owner;
			if (obj != null)
			{
				obj.PerformEmote(context, 2);
			}
		}

		public void OnFlashlightToggle(CallbackContext context)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)((CallbackContext)(ref context)).phase == 3)
			{
				ToggleFlashlight();
			}
		}

		public void OnWalkieTalkieSpeak(CallbackContext context)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Invalid comparison between Unknown and I4
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			InputActionPhase phase = ((CallbackContext)(ref context)).phase;
			if ((int)phase != 3)
			{
				if ((int)phase == 4)
				{
					StopUsingWalkieTalkie();
				}
			}
			else
			{
				UseWalkieTalkie();
			}
		}

		public void OnEnable()
		{
			input?.Enable();
		}

		public void OnDisable()
		{
			input?.Disable();
		}

		private void ToggleFlashlight()
		{
			if (!WorldTweaks.Configs.AllowFlashlightKeybind.Value() || MikesTweaks.Compatibility.ReservedSlotsCompat || !PlayerTweaks.CanUseItem(owner))
			{
				return;
			}
			FieldInfo field = typeof(PlayerControllerB).GetField("timeSinceSwitchingSlots", BindingFlags.Instance | BindingFlags.NonPublic);
			if ((float)field.GetValue(owner) < 0.075f)
			{
				return;
			}
			GrabbableObject[] itemSlots = owner.ItemSlots;
			foreach (GrabbableObject obj in itemSlots)
			{
				FlashlightItem val = (FlashlightItem)(object)((obj is FlashlightItem) ? obj : null);
				if (!((Object)(object)val == (Object)null))
				{
					bool isPocketed = ((GrabbableObject)val).isPocketed;
					((GrabbableObject)val).UseItemOnClient(true);
					field.SetValue(owner, 0f);
					if (isPocketed)
					{
						((GrabbableObject)val).PocketItem();
					}
					break;
				}
			}
		}

		private void UseWalkieTalkie()
		{
			if (!WorldTweaks.Configs.AllowWalkieTalkieKeybind.Value() || MikesTweaks.Compatibility.ReservedSlotsCompat || !PlayerTweaks.CanUseItem(owner))
			{
				return;
			}
			FieldInfo field = typeof(PlayerControllerB).GetField("timeSinceSwitchingSlots", BindingFlags.Instance | BindingFlags.NonPublic);
			if ((float)field.GetValue(owner) < 0.075f)
			{
				return;
			}
			GrabbableObject[] itemSlots = owner.ItemSlots;
			foreach (GrabbableObject val in itemSlots)
			{
				WalkieTalkieToStop = (WalkieTalkie)(object)((val is WalkieTalkie) ? val : null);
				if (!((Object)(object)WalkieTalkieToStop == (Object)null))
				{
					((GrabbableObject)WalkieTalkieToStop).UseItemOnClient(true);
					field.SetValue(owner, 0f);
					break;
				}
			}
		}

		private void StopUsingWalkieTalkie()
		{
			WalkieTalkie walkieTalkieToStop = WalkieTalkieToStop;
			if (walkieTalkieToStop != null)
			{
				((GrabbableObject)walkieTalkieToStop).UseItemOnClient(false);
			}
		}

		public void Destroy()
		{
			input?.Dispose();
		}

		public void InitializeKeybinds()
		{
			owner = ((Component)this).gameObject.GetComponent<PlayerControllerB>();
			input = new MikesTweaksPlayerInput();
			input.Hotbar.SetCallbacks(this);
			input.Emotes.SetCallbacks(this);
			input.Actions.SetCallbacks(this);
			input.Enable();
			SetupKeybinds();
		}

		public void SetupKeybinds()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: 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_0114: 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_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			BindingSyntax val = InputActionSetupExtensions.ChangeBinding(input.Hotbar.Hotbar1, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.SlotKeybinds[0].Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Hotbar.Hotbar2, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.SlotKeybinds[1].Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Hotbar.Hotbar3, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.SlotKeybinds[2].Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Hotbar.Hotbar4, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.SlotKeybinds[3].Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Hotbar.Hotbar5, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.SlotKeybinds[4].Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Hotbar.Hotbar6, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.SlotKeybinds[5].Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Hotbar.Hotbar7, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.SlotKeybinds[6].Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Hotbar.Hotbar8, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.SlotKeybinds[7].Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Hotbar.Hotbar9, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.SlotKeybinds[8].Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Emotes.Emote1, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.EmoteKeybinds[0].Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Emotes.Emote2, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.EmoteKeybinds[1].Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Actions.FlashlightToggle, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.FlashlightKeybind.Value());
			val = InputActionSetupExtensions.ChangeBinding(input.Actions.WalkieTalkieSpeak, 0);
			((BindingSyntax)(ref val)).WithPath(PlayerTweaks.Configs.WalkieTalkieKeybind.Value());
		}

		private void Awake()
		{
			owner = ((Component)this).gameObject.GetComponent<PlayerControllerB>();
			SwitchToSlotMethod = typeof(PlayerControllerB).GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic);
		}

		private void RequestSlotChange(int slot)
		{
			//IL_006d: 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_0080: Unknown result type (might be due to invalid IL or missing references)
			if (PlayerTweaks.CanSwitchSlot(owner) && WorldTweaks.Configs.AllowHotbarKeybinds.Value())
			{
				SwitchToSlot(slot);
				typeof(PlayerControllerB).GetField("timeSinceSwitchingSlots", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(owner, 0f);
				CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1);
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref slot, default(ForPrimitives));
				customMessagingManager.SendNamedMessage(PlayerTweaks.PlayerSwitchSlotRequestChannel, 0uL, val, (NetworkDelivery)2);
			}
		}

		public void SwitchToSlot(int slot)
		{
			ShipBuildModeManager.Instance.CancelBuildMode(true);
			_ = owner.currentItemSlot;
			owner.playerBodyAnimator.SetBool("GrabValidated", false);
			object[] parameters = new object[2] { slot, null };
			SwitchToSlotMethod.Invoke(owner, parameters);
		}
	}
	public class PlayerTweaks
	{
		public static class Configs
		{
			public static ConfigEntrySettings<float> MaxStamina = new ConfigEntrySettings<float>("MaxStamina", 15f, 11f, "This is the maximum amount of time you can run.\nThe higher the number, the longer you can run for.");

			public static ConfigEntrySettings<float> DefaultSprintSpeed = new ConfigEntrySettings<float>("DefaultSprintSpeed", 1.5f, 1f, "This is the floor of your sprint speed.\nEvery frame your sprint speed decreases when you don't run and this is as low as it can go.");

			public static ConfigEntrySettings<float> SprintSpeedIncreasePerFrame = new ConfigEntrySettings<float>("SprintSpeedIncreasePerFrame", 1f, 1f, "The higher this value is, the faster your sprint speed reaches the maximum sprint speed.\nYour sprint speed increments every frame you're running.");

			public static ConfigEntrySettings<float> SprintSpeedDecreasePerFrame = new ConfigEntrySettings<float>("SprintSpeedDecreasePerFrame", 10f, 10f, "The higher this value is, the faster your sprint speed goes to the default sprint speed.\nYour sprint speed decrements every frame you're not running.");

			public static ConfigEntrySettings<float> MaxSprintSpeed = new ConfigEntrySettings<float>("MaxSprintSpeed", 3f, 2.25f, "This is your sprint speed ceiling.\nEvery frame your sprint speed increases and this is how high it can go.");

			public static ConfigEntrySettings<float> StaminaRechargePerFrame = new ConfigEntrySettings<float>("StaminaRechargePerFrame", 5f, 1f, "The bigger number this is the faster your stamina recharges.");

			public static ConfigEntrySettings<float> StaminaWeightWhileWalking = new ConfigEntrySettings<float>("StaminaWeightWhileWalking", 9f, 9f, "The bigger number this is, the slower your stamina recharges while walking.");

			public static ConfigEntrySettings<float> StaminaWeightWhileStandingStill = new ConfigEntrySettings<float>("StaminaWeightWhileStandingStill", 4f, 4f, "The bigger number this is, the slower your stamina recharges while standing still");

			public static ConfigEntrySettings<float> JumpStaminaDrain = new ConfigEntrySettings<float>("JumpStaminaDrain", 0.04f, 0.08f, "The lower this amount is, the less stamina jumping drains.\n");

			public static ConfigEntrySettings<string>[] SlotKeybinds = new ConfigEntrySettings<string>[9]
			{
				new ConfigEntrySettings<string>("Slot1", "<Keyboard>/1", ""),
				new ConfigEntrySettings<string>("Slot2", "<Keyboard>/2", ""),
				new ConfigEntrySettings<string>("Slot3", "<Keyboard>/3", ""),
				new ConfigEntrySettings<string>("Slot4", "<Keyboard>/4", ""),
				new ConfigEntrySettings<string>("Slot5", "<Keyboard>/5", ""),
				new ConfigEntrySettings<string>("Slot6", "<Keyboard>/6", ""),
				new ConfigEntrySettings<string>("Slot7", "<Keyboard>/7", ""),
				new ConfigEntrySettings<string>("Slot8", "<Keyboard>/8", ""),
				new ConfigEntrySettings<string>("Slot9", "<Keyboard>/9", "")
			};

			public static ConfigEntrySettings<string>[] EmoteKeybinds = new ConfigEntrySettings<string>[2]
			{
				new ConfigEntrySettings<string>("Emote1", "<Keyboard>/y", "<Keyboard>/1"),
				new ConfigEntrySettings<string>("Emote2", "<Keyboard>/u", "<Keyboard>/2")
			};

			public static ConfigEntrySettings<string> FlashlightKeybind = new ConfigEntrySettings<string>("Flashlight", "<Keyboard>/f", "");

			public static ConfigEntrySettings<string> WalkieTalkieKeybind = new ConfigEntrySettings<string>("WalkieTalkieKeybind", "<Keyboard>/r", "");

			public static string PlayerTweaksSectionHeader => "PlayerTweaks";

			public static string KeybindsSectionHeader => "Keybinds";
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static Func<FastBufferWriter, FastBufferWriter> <0>__WriteConfigsToWriter;

			public static Func<FastBufferReader, FastBufferReader> <1>__ReadConfigChanges;

			public static HandleNamedMessageDelegate <2>__ReceiveSwitchSlot;

			public static HandleNamedMessageDelegate <3>__ReceiveSwitchSlotRequest;
		}

		public static PlayerControllerB LocalPlayerController => GameNetworkManager.Instance.localPlayerController;

		public static string PlayerSwitchSlotChannel => "PlayerChangeSlot";

		public static string PlayerSwitchSlotRequestChannel => "PlayerChangeSlotRequest";

		public static void RegisterConfigs()
		{
			MikesTweaks.Instance.BindConfig(ref Configs.MaxStamina, Configs.PlayerTweaksSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.DefaultSprintSpeed, Configs.PlayerTweaksSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.SprintSpeedIncreasePerFrame, Configs.PlayerTweaksSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.SprintSpeedDecreasePerFrame, Configs.PlayerTweaksSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.MaxSprintSpeed, Configs.PlayerTweaksSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.StaminaRechargePerFrame, Configs.PlayerTweaksSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.StaminaWeightWhileWalking, Configs.PlayerTweaksSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.StaminaWeightWhileStandingStill, Configs.PlayerTweaksSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.JumpStaminaDrain, Configs.PlayerTweaksSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.FlashlightKeybind, Configs.KeybindsSectionHeader);
			MikesTweaks.Instance.BindConfig(ref Configs.WalkieTalkieKeybind, Configs.KeybindsSectionHeader);
			for (int i = 0; i < Configs.SlotKeybinds.Length; i++)
			{
				MikesTweaks.Instance.BindConfig(ref Configs.SlotKeybinds[i], Configs.KeybindsSectionHeader);
			}
			for (int j = 0; j < Configs.EmoteKeybinds.Length; j++)
			{
				MikesTweaks.Instance.BindConfig(ref Configs.EmoteKeybinds[j], Configs.KeybindsSectionHeader);
			}
			ConfigsSynchronizer.OnConfigsChangedDelegate = (Action)Delegate.Combine(ConfigsSynchronizer.OnConfigsChangedDelegate, (Action)delegate
			{
				ReapplyConfigs(LocalPlayerController, applyToAllPlayers: true, force: true, updateHud: true);
			});
			ConfigsSynchronizer.Instance.AddConfigGetter(WriteConfigsToWriter);
			ConfigsSynchronizer.Instance.AddConfigSetter(ReadConfigChanges);
			ConfigsSynchronizer.Instance.AddConfigSizeGetter(() => 36);
		}

		public static FastBufferWriter WriteConfigsToWriter(FastBufferWriter writer)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//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_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: 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_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: 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_0168: Unknown result type (might be due to invalid IL or missing references)
			float num = Configs.DefaultSprintSpeed.Value(WorldTweaks.Configs.UseVanillaSprintSpeedValues.Value());
			((FastBufferWriter)(ref writer)).WriteValueSafe<float>(ref num, default(ForPrimitives));
			num = Configs.SprintSpeedIncreasePerFrame.Value(WorldTweaks.Configs.UseVanillaSprintSpeedValues.Value());
			((FastBufferWriter)(ref writer)).WriteValueSafe<float>(ref num, default(ForPrimitives));
			num = Configs.SprintSpeedDecreasePerFrame.Value(WorldTweaks.Configs.UseVanillaSprintSpeedValues.Value());
			((FastBufferWriter)(ref writer)).WriteValueSafe<float>(ref num, default(ForPrimitives));
			num = Configs.MaxSprintSpeed.Value(WorldTweaks.Configs.UseVanillaSprintSpeedValues.Value());
			((FastBufferWriter)(ref writer)).WriteValueSafe<float>(ref num, default(ForPrimitives));
			num = Configs.MaxStamina.Value(WorldTweaks.Configs.UseVanillaStaminaValues.Value());
			((FastBufferWriter)(ref writer)).WriteValueSafe<float>(ref num, default(ForPrimitives));
			num = Configs.StaminaRechargePerFrame.Value(WorldTweaks.Configs.UseVanillaStaminaValues.Value());
			((FastBufferWriter)(ref writer)).WriteValueSafe<float>(ref num, default(ForPrimitives));
			num = Configs.StaminaWeightWhileWalking.Value(WorldTweaks.Configs.UseVanillaStaminaValues.Value());
			((FastBufferWriter)(ref writer)).WriteValueSafe<float>(ref num, default(ForPrimitives));
			num = Configs.StaminaWeightWhileStandingStill.Value(WorldTweaks.Configs.UseVanillaStaminaValues.Value());
			((FastBufferWriter)(ref writer)).WriteValueSafe<float>(ref num, default(ForPrimitives));
			num = Configs.JumpStaminaDrain.Value(WorldTweaks.Configs.UseVanillaStaminaValues.Value());
			((FastBufferWriter)(ref writer)).WriteValueSafe<float>(ref num, default(ForPrimitives));
			return writer;
		}

		public static FastBufferReader ReadConfigChanges(FastBufferReader payload)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: 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_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			float value = default(float);
			((FastBufferReader)(ref payload)).ReadValue<float>(ref value, default(ForPrimitives));
			Configs.DefaultSprintSpeed.Entry.Value = value;
			((FastBufferReader)(ref payload)).ReadValue<float>(ref value, default(ForPrimitives));
			Configs.SprintSpeedIncreasePerFrame.Entry.Value = value;
			((FastBufferReader)(ref payload)).ReadValue<float>(ref value, default(ForPrimitives));
			Configs.SprintSpeedDecreasePerFrame.Entry.Value = value;
			((FastBufferReader)(ref payload)).ReadValue<float>(ref value, default(ForPrimitives));
			Configs.MaxSprintSpeed.Entry.Value = value;
			((FastBufferReader)(ref payload)).ReadValue<float>(ref value, default(ForPrimitives));
			Configs.MaxStamina.Entry.Value = value;
			((FastBufferReader)(ref payload)).ReadValue<float>(ref value, default(ForPrimitives));
			Configs.StaminaRechargePerFrame.Entry.Value = value;
			((FastBufferReader)(ref payload)).ReadValue<float>(ref value, default(ForPrimitives));
			Configs.StaminaWeightWhileWalking.Entry.Value = value;
			((FastBufferReader)(ref payload)).ReadValue<float>(ref value, default(ForPrimitives));
			Configs.StaminaWeightWhileStandingStill.Entry.Value = value;
			((FastBufferReader)(ref payload)).ReadValue<float>(ref value, default(ForPrimitives));
			Configs.JumpStaminaDrain.Entry.Value = value;
			return payload;
		}

		public static void ReapplyConfigs(PlayerControllerB player, bool applyToAllPlayers = false, bool force = false, bool updateHud = false)
		{
			float sprintTime = player.sprintTime;
			int num = player.ItemSlots.Length;
			player.sprintTime = Configs.MaxStamina.Value(WorldTweaks.Configs.UseVanillaStaminaValues.Value());
			if (MikesTweaks.Compatibility.ReservedSlotsCompat)
			{
				return;
			}
			if (!applyToAllPlayers)
			{
				InventoryTweaks.ChangeItemSlotsAmount(player, force);
			}
			else
			{
				PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
				for (int i = 0; i < allPlayerScripts.Length; i++)
				{
					InventoryTweaks.ChangeItemSlotsAmount(allPlayerScripts[i], force);
				}
			}
			if (updateHud)
			{
				InventoryTweaks.ChangeItemSlotsAmountUI();
			}
		}

		public static void RegisterSwitchSlotMessage()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
			string playerSwitchSlotChannel = PlayerSwitchSlotChannel;
			object obj = <>O.<2>__ReceiveSwitchSlot;
			if (obj == null)
			{
				HandleNamedMessageDelegate val = ReceiveSwitchSlot;
				<>O.<2>__ReceiveSwitchSlot = val;
				obj = (object)val;
			}
			customMessagingManager.RegisterNamedMessageHandler(playerSwitchSlotChannel, (HandleNamedMessageDelegate)obj);
			CustomMessagingManager customMessagingManager2 = NetworkManager.Singleton.CustomMessagingManager;
			string playerSwitchSlotRequestChannel = PlayerSwitchSlotRequestChannel;
			object obj2 = <>O.<3>__ReceiveSwitchSlotRequest;
			if (obj2 == null)
			{
				HandleNamedMessageDelegate val2 = ReceiveSwitchSlotRequest;
				<>O.<3>__ReceiveSwitchSlotRequest = val2;
				obj2 = (object)val2;
			}
			customMessagingManager2.RegisterNamedMessageHandler(playerSwitchSlotRequestChannel, (HandleNamedMessageDelegate)obj2);
		}

		public static void SwitchSlot_Server(int slot, ulong clientIDOfChangedSlot)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsServer)
			{
				CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(12, (Allocator)2, -1);
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref slot, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref clientIDOfChangedSlot, default(ForPrimitives));
				customMessagingManager.SendNamedMessageToAll(PlayerSwitchSlotChannel, val, (NetworkDelivery)2);
			}
		}

		public static void ReceiveSwitchSlotRequest(ulong senderID, FastBufferReader payload)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkManager.Singleton.IsServer)
			{
				int slot = default(int);
				((FastBufferReader)(ref payload)).ReadValueSafe<int>(ref slot, default(ForPrimitives));
				SwitchSlot_Server(slot, senderID);
			}
		}

		public static void ReceiveSwitchSlot(ulong senderID, FastBufferReader payload)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			int slot = default(int);
			((FastBufferReader)(ref payload)).ReadValueSafe<int>(ref slot, default(ForPrimitives));
			ulong num = default(ulong);
			((FastBufferReader)(ref payload)).ReadValueSafe<ulong>(ref num, default(ForPrimitives));
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if (val.playerClientId == num)
				{
					((Component)val).gameObject.GetComponent<PlayerInputRedirection>().SwitchToSlot(slot);
					break;
				}
			}
		}

		public static float StaminaRechargeMovementHinderedWalking(PlayerControllerB player, float num2)
		{
			return Mathf.Clamp(player.sprintMeter - Time.deltaTime / player.sprintTime * num2 * 0.5f, 0f, 1f);
		}

		public static float StaminaRechargeMovementNotHinderedWalking(PlayerControllerB player, float num2)
		{
			return Mathf.Clamp(player.sprintMeter + Time.deltaTime * Configs.StaminaRechargePerFrame.Value(WorldTweaks.Configs.UseVanillaStaminaValues.Value()) / (player.sprintTime + Configs.StaminaWeightWhileWalking.Value(WorldTweaks.Configs.UseVanillaStaminaValues.Value())) * num2, 0f, 1f);
		}

		public static float StaminaRechargeMovementNotHinderedNotWalking(PlayerControllerB player, float num2)
		{
			return Mathf.Clamp(player.sprintMeter + Time.deltaTime * Configs.StaminaRechargePerFrame.Value(WorldTweaks.Configs.UseVanillaStaminaValues.Value()) / (player.sprintTime + Configs.StaminaWeightWhileStandingStill.Value(WorldTweaks.Configs.UseVanillaStaminaValues.Value())) * num2, 0f, 1f);
		}

		public static bool IsLocallyControlled(PlayerControllerB player)
		{
			return (Object)(object)player == (Object)(object)GameNetworkManager.Instance.localPlayerController;
		}

		public static bool CanSwitchSlot(PlayerControllerB player)
		{
			Type typeFromHandle = typeof(PlayerControllerB);
			bool flag = (bool)typeFromHandle.GetField("throwingObject", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(player);
			float num = (float)typeFromHandle.GetField("timeSinceSwitchingSlots", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(player);
			if (((!((NetworkBehaviour)player).IsOwner || !player.isPlayerControlled || (((NetworkBehaviour)player).IsServer && !player.isHostPlayerObject)) && !player.isTestingPlayer) || num < 0.3f || player.isGrabbingObjectAnimation || player.inSpecialInteractAnimation || flag || player.isTypingChat || player.twoHanded || player.activatingItem || player.jetpackControls || player.disablingJetpackControls)
			{
				return false;
			}
			return true;
		}

		public static bool CanUseItem(PlayerControllerB player)
		{
			bool flag = true;
			if ((Object)(object)player.currentlyHeldObjectServer != (Object)null)
			{
				flag = player.currentlyHeldObjectServer.itemProperties.usableInSpecialAnimations;
			}
			if (((((NetworkBehaviour)player).IsOwner && player.isPlayerControlled && (!((NetworkBehaviour)player).IsServer || player.isHostPlayerObject)) || player.isTestingPlayer) && !player.quickMenuManager.isMenuOpen && !player.isPlayerDead)
			{
				if (!flag)
				{
					if (!player.isGrabbingObjectAnimation && !player.inTerminalMenu && !player.isTypingChat)
					{
						if (player.inSpecialInteractAnimation)
						{
							return player.inShockingMinigame;
						}
						return true;
					}
					return false;
				}
				return true;
			}
			return false;
		}
	}
}
namespace MikesTweaks.Scripts.Moons
{
	public class MoonTweaks
	{
		public static class Configs
		{
			public static readonly Dictionary<string, int> DefaultMoonCosts = new Dictionary<string, int>
			{
				{ "Experimentation", 0 },
				{ "Assurance", 0 },
				{ "Vow", 0 },
				{ "Offense", 0 },
				{ "March", 0 },
				{ "Rend", 550 },
				{ "Dine", 600 },
				{ "Titan", 700 }
			};

			public static ConfigEntrySettings<string> MoonPrices = new ConfigEntrySettings<string>("MoonPrices", JsonConvert.SerializeObject((object)DefaultMoonCosts), JsonConvert.SerializeObject((object)DefaultMoonCosts), "To change the cost to go to a planet you can change the amount corresponding to the moon you want to modify.\nYou can also modify the cost of moons from different mods here, by just adding another entry anywhere in the dictionary with the planet's name and the cost you want it to be\nThe value is a json string which is why you see \\ everywhere before \".\nTo add another moon, just add , after Titan's value and write it like so \\\"MoonName\\\":Value");

			public static Dictionary<string, int> MoonPricesDeserialized;

			public static string MoonPricesHeader => "MoonPrices";

			public static int MoonPricesSize => FastBufferWriter.GetWriteSize<byte>(ConfigsSynchronizer.ToBytes(JsonConvert.SerializeObject((object)MoonPricesDeserialized)), -1, 0);
		}

		public static void RegisterConfigs()
		{
			MikesTweaks.Instance.BindConfig(ref Configs.MoonPrices, Configs.MoonPricesHeader);
			((BaseUnityPlugin)MikesTweaks.Instance).Config.ConfigReloaded += delegate
			{
				ReadMoonPrices();
				ApplyVanillaMoonCosts(ref Configs.MoonPricesDeserialized, WorldTweaks.Configs.UseVanillaMoonCosts.Value());
			};
			ReadMoonPrices();
			ApplyVanillaMoonCosts(ref Configs.MoonPricesDeserialized, WorldTweaks.Configs.UseVanillaMoonCosts.Value());
			ConfigsSynchronizer.OnConfigsChangedDelegate = (Action)Delegate.Combine(ConfigsSynchronizer.OnConfigsChangedDelegate, (Action)delegate
			{
				ReapplyConfigs(WorldTweaks.TerminalInstance);
			});
			ConfigsSynchronizer.Instance.AddConfigSizeGetter(() => Configs.MoonPricesSize);
			ConfigsSynchronizer.Instance.AddConfigGetter(SendConfigs);
			ConfigsSynchronizer.Instance.AddConfigSetter(OnConfigsReceived);
		}

		public static FastBufferWriter SendConfigs(FastBufferWriter writer)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = ConfigsSynchronizer.ToBytes(JsonConvert.SerializeObject((object)Configs.MoonPricesDeserialized));
			((FastBufferWriter)(ref writer)).WriteValueSafe<byte>(array, default(ForPrimitives));
			return writer;
		}

		public static FastBufferReader OnConfigsReceived(FastBufferReader payload)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			byte[] bytes = default(byte[]);
			((FastBufferReader)(ref payload)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
			Configs.MoonPricesDeserialized = JsonConvert.DeserializeObject<Dictionary<string, int>>((string)ConfigsSynchronizer.ToObject(bytes));
			return payload;
		}

		public static void ReapplyConfigs(Terminal terminal)
		{
			if (!Object.op_Implicit((Object)(object)terminal))
			{
				return;
			}
			TerminalKeyword val = Array.Find(terminal.terminalNodes.allKeywords, (TerminalKeyword keyword) => ((Object)keyword).name == "Route");
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Dictionary<string, int> dictionary = new Dictionary<string, int>(Configs.MoonPricesDeserialized);
			CompatibleNoun[] compatibleNouns = val.compatibleNouns;
			foreach (CompatibleNoun val2 in compatibleNouns)
			{
				foreach (KeyValuePair<string, int> item in dictionary)
				{
					if (!((Object)val2.noun).name.Contains(item.Key))
					{
						continue;
					}
					val2.result.itemCost = item.Value;
					CompatibleNoun[] terminalOptions = val2.result.terminalOptions;
					foreach (CompatibleNoun val3 in terminalOptions)
					{
						if (!((Object)val3.noun).name.ToLower().Contains("deny"))
						{
							val3.result.itemCost = item.Value;
							break;
						}
					}
					dictionary.Remove(item.Key);
					break;
				}
			}
		}

		private static void ApplyVanillaMoonCosts(ref Dictionary<string, int> MoonCosts, bool vanilla)
		{
			if (!vanilla)
			{
				return;
			}
			foreach (KeyValuePair<string, int> defaultMoonCost in Configs.DefaultMoonCosts)
			{
				MoonCosts[defaultMoonCost.Key] = defaultMoonCost.Value;
			}
		}

		private static void ReadMoonPrices()
		{
			Configs.MoonPricesDeserialized = JsonConvert.DeserializeObject<Dictionary<string, int>>(Configs.MoonPrices.Value());
		}
	}
}
namespace MikesTweaks.Scripts.Items
{
	[HarmonyPatch(typeof(GrabbableObject))]
	public class GrabbableObject_Patches
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void ChangeTerminalItemWeights(GrabbableObject __instance)
		{
			if (NetworkManager.Singleton.IsServer || ConfigsSynchronizer.ConfigsReceived)
			{
				InventoryTweaks.ModifyItemWeight(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	public class Terminal_Patches
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void Start(Terminal __instance)
		{
			if (NetworkManager.Singleton.IsServer)
			{
				MoonTweaks.ReapplyConfigs(__instance);
				InventoryTweaks.ApplyItemPrices(__instance);
			}
		}
	}
}
namespace MikesTweaks.Scripts.Inventory
{
	public class InventoryTweaks
	{
		public static class Configs
		{
			public static ConfigEntrySettings<int> ExtraItemSlotsAmount = new ConfigEntrySettings<int>("ExtraItemSlots", 2, 0, "This increases how many slots you have.\n0 Slots means you have the default 4 from the vanilla game, if you increase this number you get additional slots in addition to the original 4.");

			public static ConfigEntrySettings<int>[] ToolItemWeights = new ConfigEntrySettings<int>[13]
			{
				new ConfigEntrySettings<int>("WalkieTalkieWeight", 0, 0),
				new ConfigEntrySettings<int>("FlashlightWeight", 0, 0),
				new ConfigEntrySettings<int>("ShovelWeight", 5, 18),
				new ConfigEntrySettings<int>("LockPickerWeight", 2, 15),
				new ConfigEntrySettings<int>("ProFlashlightWeight", 0, 5),
				new ConfigEntrySettings<int>("StunGrenadeWeight", 2, 5),
				new ConfigEntrySettings<int>("BoomboxWeight", 5, 15),
				new ConfigEntrySettings<int>("TZPInhalantWeight", 0, 0),
				new ConfigEntrySettings<int>("ZapGunWeight", 4, 10),
				new ConfigEntrySettings<int>("JetpackWeight", 10, 50),
				new ConfigEntrySettings<int>("ExtensionLadderWeight", 0, 0),
				new ConfigEntrySettings<int>("RadarBoosterWeight", 5, 18),
				new ConfigEntrySettings<int>("SprayPaintWeight", 1, 1)
			};

			public static ConfigEntrySettings<int>[] ToolItemPrices = new ConfigEntrySettings<int>[13]
			{
				new ConfigEntrySettings<int>("WalkieTalkiePrice", 12, 12),
				new ConfigEntrySettings<int>("FlashlightPrice", 15, 15),
				new ConfigEntrySettings<int>("ShovelPrice", 30, 30),
				new ConfigEntrySettings<int>("LockPickerPrice", 20, 20),
				new ConfigEntrySettings<int>("ProFlashlightPrice", 25, 25),
				new ConfigEntrySettings<int>("StunGrenadePrice", 30, 30),
				new ConfigEntrySettings<int>("BoomboxPrice", 60, 60),
				new ConfigEntrySettings<int>("TZPInhalantPrice", 120, 120),
				new ConfigEntrySettings<int>("ZapGunPrice", 400, 400),
				new ConfigEntrySettings<int>("JetpackPrice", 700, 700),
				new ConfigEntrySettings<int>("ExtensionLadderPrice", 60, 60),
				new ConfigEntrySettings<int>("RadarBoosterPrice", 60, 60),
				new ConfigEntrySettings<int>("SprayPaintPrice", 50, 50)
			};

			public static string InventoryTweaksSectionHeader => "InventoryTweaks";

			public static string TerminalItemProperties => "TerminalItemProperties";
		}

		public static void RegisterConfigs()
		{
			MikesTweaks.Instance.BindConfig(ref Configs.ExtraItemSlotsAmount, Configs.InventoryTweaksSectionHeader);
			for (int i = 0; i < Configs.ToolItemWeights.Length; i++)
			{
				MikesTweaks.Instance.BindConfig(ref Configs.ToolItemWeights[i], Configs.TerminalItemProperties);
				MikesTweaks.Instance.BindConfig(ref Configs.ToolItemPrices[i], Configs.TerminalItemProperties);
			}
			ConfigsSynchronizer.OnConfigsChangedDelegate = (Action)Delegate.Combine(ConfigsSynchronizer.OnConfigsChangedDelegate, (Action)delegate
			{
				ReapplyConfigs();
				ApplyItemPrices(WorldTweaks.TerminalInstance);
			});
			ConfigsSynchronizer.Instance.AddConfigGetter(WriteConfigsToWriter);
			ConfigsSynchronizer.Instance.AddConfigSetter(ReadConfigChanges);
			ConfigsSynchronizer.Instance.AddConfigSizeGetter(() => 4 + 4 * Configs.ToolItemWeights.Length + 4 * Configs.ToolItemPrices.Length);
		}

		public static FastBufferWriter WriteConfigsToWriter(FastBufferWriter writer)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: 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_0084: 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_009a: Unknown result type (might be due to invalid IL or missing references)
			int num = Configs.ExtraItemSlotsAmount.Value();
			((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref num, default(ForPrimitives));
			ConfigEntrySettings<int>[] toolItemWeights = Configs.ToolItemWeights;
			foreach (ConfigEntrySettings<int> configEntrySettings in toolItemWeights)
			{
				int num2 = configEntrySettings.Value(WorldTweaks.Configs.UseVanillaToolItemWeights.Value());
				((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref num2, default(ForPrimitives));
			}
			toolItemWeights = Configs.ToolItemPrices;
			foreach (ConfigEntrySettings<int> configEntrySettings2 in toolItemWeights)
			{
				int num2 = configEntrySettings2.Value(WorldTweaks.Configs.UseVanillaToolItemPrices.Value());
				((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref num2, default(ForPrimitives));
			}
			return writer;
		}

		public static FastBufferReader ReadConfigChanges(FastBufferReader payload)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			int value = default(int);
			((FastBufferReader)(ref payload)).ReadValueSafe<int>(ref value, default(ForPrimitives));
			Configs.ExtraItemSlotsAmount.Entry.Value = value;
			ConfigEntrySettings<int>[] toolItemWeights = Configs.ToolItemWeights;
			foreach (ConfigEntrySettings<int> obj in toolItemWeights)
			{
				((FastBufferReader)(ref payload)).ReadValueSafe<int>(ref value, default(ForPrimitives));
				obj.Entry.Value = value;
			}
			toolItemWeights = Configs.ToolItemPrices;
			foreach (ConfigEntrySettings<int> obj2 in toolItemWeights)
			{
				((FastBufferReader)(ref payload)).ReadValueSafe<int>(ref value, default(ForPrimitives));
				obj2.Entry.Value = value;
			}
			return payload;
		}

		public static bool HasEnoughSlots(int slotID)
		{
			return PlayerTweaks.LocalPlayerController.ItemSlots.Length - (slotID + 1) > -1;
		}

		public static void ChangeItemSlotsAmount(PlayerControllerB __instance, bool force = false)
		{
			if (force || Configs.ExtraItemSlotsAmount.Value() != 0)
			{
				List<GrabbableObject> list = new List<GrabbableObject>(__instance.ItemSlots);
				__instance.ItemSlots = (GrabbableObject[])(object)new GrabbableObject[4 + Configs.ExtraItemSlotsAmount.Value()];
				for (int i = 0; i < list.Count; i++)
				{
					__instance.ItemSlots[i] = list[i];
				}
			}
		}

		public static void ReapplyConfigs()
		{
			GrabbableObject[] array = Resources.FindObjectsOfTypeAll<GrabbableObject>();
			for (int i = 0; i < array.Length; i++)
			{
				ModifyItemWeight(array[i]);
			}
			ApplyItemPrices(WorldTweaks.TerminalInstance);
		}

		public static void ApplyItemPrices(Terminal terminal)
		{
			if (!Object.op_Implicit((Object)(object)terminal))
			{
				return;
			}
			TerminalKeyword val = Array.Find(terminal.terminalNodes.allKeywords, (TerminalKeyword keyword) => ((Object)keyword).name.ToLower() == "buy");
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			bool vanilla = WorldTweaks.Configs.UseVanillaToolItemPrices.Value();
			CompatibleNoun[] compatibleNouns = val.compatibleNouns;
			foreach (CompatibleNoun val2 in compatibleNouns)
			{
				ConfigEntrySettings<int>[] toolItemPrices = Configs.ToolItemPrices;
				foreach (ConfigEntrySettings<int> configEntrySettings in toolItemPrices)
				{
					string str = ((Object)val2.noun).name.ToLower();
					StringUtils.RemoveChar(ref str, ' ');
					if (!configEntrySettings.ConfigName.ToLower().Contains(str))
					{
						continue;
					}
					val2.result.itemCost = configEntrySettings.Value(vanilla);
					terminal.buyableItemsList[val2.result.buyItemIndex].creditsWorth = configEntrySettings.Value(vanilla);
					CompatibleNoun[] terminalOptions = val2.result.terminalOptions;
					foreach (CompatibleNoun val3 in terminalOptions)
					{
						if (!((Object)val3.noun).name.ToLower().Contains("deny"))
						{
							val3.result.itemCost = configEntrySettings.Value(vanilla);
							break;
						}
					}
					break;
				}
			}
		}

		public static void ModifyItemWeight(GrabbableObject item)
		{
			if (!((Object)(object)item == (Object)null))
			{
				string itemName = ((Object)item.itemProperties).name.ToLower();
				StringUtils.RemoveChar(ref itemName, ' ');
				int num = Array.FindIndex(Configs.ToolItemWeights, (ConfigEntrySettings<int> config) => config.ConfigName.ToLower().Contains(itemName));
				if (num != -1)
				{
					item.itemProperties.weight = (float)Configs.ToolItemWeights[num].Value(WorldTweaks.Configs.UseVanillaToolItemWeights.Value()) / 100f + 1f;
				}
			}
		}

		public static void ChangeItemSlotsAmountUI()
		{
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			if (Configs.ExtraItemSlotsAmount.Value() == 0)
			{
				return;
			}
			GameObject val = GameObject.Find("Systems/UI/Canvas/IngamePlayerHUD/Inventory");
			List<string> list = new List<string> { "Slot0", "Slot1", "Slot2", "Slot3" };
			for (int i = 0; i < val.transform.childCount; i++)
			{
				Transform child = val.transform.GetChild(i);
				if (!list.Contains(((Object)((Component)child).gameObject).name))
				{
					Object.Destroy((Object)(object)((Component)child).gameObject);
				}
			}
			Image[] array = (Image[])(object)new Image[4 + Configs.ExtraItemSlotsAmount.Value()];
			array[0] = HUDManager.Instance.itemSlotIconFrames[0];
			array[1] = HUDManager.Instance.itemSlotIconFrames[1];
			array[2] = HUDManager.Instance.itemSlotIconFrames[2];
			array[3] = HUDManager.Instance.itemSlotIconFrames[3];
			Image[] array2 = (Image[])(object)new Image[4 + Configs.ExtraItemSlotsAmount.Value()];
			array2[0] = HUDManager.Instance.itemSlotIcons[0];
			array2[1] = HUDManager.Instance.itemSlotIcons[1];
			array2[2] = HUDManager.Instance.itemSlotIcons[2];
			array2[3] = HUDManager.Instance.itemSlotIcons[3];
			GameObject val2 = GameObject.Find("Systems/UI/Canvas/IngamePlayerHUD/Inventory/Slot3");
			GameObject val3 = val2;
			for (int j = 0; j < Configs.ExtraItemSlotsAmount.Value(); j++)
			{
				GameObject val4 = Object.Instantiate<GameObject>(val2);
				((Object)val4).name = $"Slot{3 + (j + 1)}";
				val4.transform.parent = val.transform;
				Vector3 localPosition = val3.transform.localPosition;
				val4.transform.SetLocalPositionAndRotation(new Vector3(localPosition.x + 50f, localPosition.y, localPosition.z), val3.transform.localRotation);
				val3 = val4;
				array[3 + (j + 1)] = val4.GetComponent<Image>();
				array2[3 + (j + 1)] = ((Component)val4.transform.GetChild(0)).GetComponent<Image>();
			}
			HUDManager.Instance.itemSlotIconFrames = array;
			HUDManager.Instance.itemSlotIcons = array2;
		}
	}
}
namespace MikesTweaks.Scripts.Input
{
	public class MikesTweaksPlayerInput : IInputActionCollection2, IInputActionCollection, IEnumerable<InputAction>, IEnumerable, IDisposable
	{
		public struct HotbarActions
		{
			private MikesTweaksPlayerInput m_Wrapper;

			public InputAction Hotbar1 => m_Wrapper.m_Hotbar_Hotbar1;

			public InputAction Hotbar2 => m_Wrapper.m_Hotbar_Hotbar2;

			public InputAction Hotbar3 => m_Wrapper.m_Hotbar_Hotbar3;

			public InputAction Hotbar4 => m_Wrapper.m_Hotbar_Hotbar4;

			public InputAction Hotbar5 => m_Wrapper.m_Hotbar_Hotbar5;

			public InputAction Hotbar6 => m_Wrapper.m_Hotbar_Hotbar6;

			public InputAction Hotbar7 => m_Wrapper.m_Hotbar_Hotbar7;

			public InputAction Hotbar8 => m_Wrapper.m_Hotbar_Hotbar8;

			public InputAction Hotbar9 => m_Wrapper.m_Hotbar_Hotbar9;

			public bool enabled => Get().enabled;

			public HotbarActions(MikesTweaksPlayerInput wrapper)
			{
				m_Wrapper = wrapper;
			}

			public InputActionMap Get()
			{
				return m_Wrapper.m_Hotbar;
			}

			public void Enable()
			{
				Get().Enable();
			}

			public void Disable()
			{
				Get().Disable();
			}

			public static implicit operator InputActionMap(HotbarActions set)
			{
				return set.Get();
			}

			public void AddCallbacks(IHotbarActions instance)
			{
				if (instance != null && !m_Wrapper.m_HotbarActionsCallbackInterfaces.Contains(instance))
				{
					m_Wrapper.m_HotbarActionsCallbackInterfaces.Add(instance);
					Hotbar1.started += instance.OnHotbar1;
					Hotbar1.performed += instance.OnHotbar1;
					Hotbar1.canceled += instance.OnHotbar1;
					Hotbar2.started += instance.OnHotbar2;
					Hotbar2.performed += instance.OnHotbar2;
					Hotbar2.canceled += instance.OnHotbar2;
					Hotbar3.started += instance.OnHotbar3;
					Hotbar3.performed += instance.OnHotbar3;
					Hotbar3.canceled += instance.OnHotbar3;
					Hotbar4.started += instance.OnHotbar4;
					Hotbar4.performed += instance.OnHotbar4;
					Hotbar4.canceled += instance.OnHotbar4;
					Hotbar5.started += instance.OnHotbar5;
					Hotbar5.performed += instance.OnHotbar5;
					Hotbar5.canceled += instance.OnHotbar5;
					Hotbar6.started += instance.OnHotbar6;
					Hotbar6.performed += instance.OnHotbar6;
					Hotbar6.canceled += instance.OnHotbar6;
					Hotbar7.started += instance.OnHotbar7;
					Hotbar7.performed += instance.OnHotbar7;
					Hotbar7.canceled += instance.OnHotbar7;
					Hotbar8.started += instance.OnHotbar8;
					Hotbar8.performed += instance.OnHotbar8;
					Hotbar8.canceled += instance.OnHotbar8;
					Hotbar9.started += instance.OnHotbar9;
					Hotbar9.performed += instance.OnHotbar9;
					Hotbar9.canceled += instance.OnHotbar9;
				}
			}

			private void UnregisterCallbacks(IHotbarActions instance)
			{
				Hotbar1.started -= instance.OnHotbar1;
				Hotbar1.performed -= instance.OnHotbar1;
				Hotbar1.canceled -= instance.OnHotbar1;
				Hotbar2.started -= instance.OnHotbar2;
				Hotbar2.performed -= instance.OnHotbar2;
				Hotbar2.canceled -= instance.OnHotbar2;
				Hotbar3.started -= instance.OnHotbar3;
				Hotbar3.performed -= instance.OnHotbar3;
				Hotbar3.canceled -= instance.OnHotbar3;
				Hotbar4.started -= instance.OnHotbar4;
				Hotbar4.performed -= instance.OnHotbar4;
				Hotbar4.canceled -= instance.OnHotbar4;
				Hotbar5.started -= instance.OnHotbar5;
				Hotbar5.performed -= instance.OnHotbar5;
				Hotbar5.canceled -= instance.OnHotbar5;
				Hotbar6.started -= instance.OnHotbar6;
				Hotbar6.performed -= instance.OnHotbar6;
				Hotbar6.canceled -= instance.OnHotbar6;
				Hotbar7.started -= instance.OnHotbar7;
				Hotbar7.performed -= instance.OnHotbar7;
				Hotbar7.canceled -= instance.OnHotbar7;
				Hotbar8.started -= instance.OnHotbar8;
				Hotbar8.performed -= instance.OnHotbar8;
				Hotbar8.canceled -= instance.OnHotbar8;
				Hotbar9.started -= instance.OnHotbar9;
				Hotbar9.performed -= instance.OnHotbar9;
				Hotbar9.canceled -= instance.OnHotbar9;
			}

			public void RemoveCallbacks(IHotbarActions instance)
			{
				if (m_Wrapper.m_HotbarActionsCallbackInterfaces.Remove(instance))
				{
					UnregisterCallbacks(instance);
				}
			}

			public void SetCallbacks(IHotbarActions instance)
			{
				foreach (IHotbarActions hotbarActionsCallbackInterface in m_Wrapper.m_HotbarActionsCallbackInterfaces)
				{
					UnregisterCallbacks(hotbarActionsCallbackInterface);
				}
				m_Wrapper.m_HotbarActionsCallbackInterfaces.Clear();
				AddCallbacks(instance);
			}
		}

		public struct EmotesActions
		{
			private MikesTweaksPlayerInput m_Wrapper;

			public InputAction Emote1 => m_Wrapper.m_Emotes_Emote1;

			public InputAction Emote2 => m_Wrapper.m_Emotes_Emote2;

			public bool enabled => Get().enabled;

			public EmotesActions(MikesTweaksPlayerInput wrapper)
			{
				m_Wrapper = wrapper;
			}

			public InputActionMap Get()
			{
				return m_Wrapper.m_Emotes;
			}

			public void Enable()
			{
				Get().Enable();
			}

			public void Disable()
			{
				Get().Disable();
			}

			public static implicit operator InputActionMap(EmotesActions set)
			{
				return set.Get();
			}

			public void AddCallbacks(IEmotesActions instance)
			{
				if (instance != null && !m_Wrapper.m_EmotesActionsCallbackInterfaces.Contains(instance))
				{
					m_Wrapper.m_EmotesActionsCallbackInterfaces.Add(instance);
					Emote1.started += instance.OnEmote1;
					Emote1.performed += instance.OnEmote1;
					Emote1.canceled += instance.OnEmote1;
					Emote2.started += instance.OnEmote2;
					Emote2.performed += instance.OnEmote2;
					Emote2.canceled += instance.OnEmote2;
				}
			}

			private void UnregisterCallbacks(IEmotesActions instance)
			{
				Emote1.started -= instance.OnEmote1;
				Emote1.performed -= instance.OnEmote1;
				Emote1.canceled -= instance.OnEmote1;
				Emote2.started -= instance.OnEmote2;
				Emote2.performed -= instance.OnEmote2;
				Emote2.canceled -= instance.OnEmote2;
			}

			public void RemoveCallbacks(IEmotesActions instance)
			{
				if (m_Wrapper.m_EmotesActionsCallbackInterfaces.Remove(instance))
				{
					UnregisterCallbacks(instance);
				}
			}

			public void SetCallbacks(IEmotesActions instance)
			{
				foreach (IEmotesActions emotesActionsCallbackInterface in m_Wrapper.m_EmotesActionsCallbackInterfaces)
				{
					UnregisterCallbacks(emotesActionsCallbackInterface);
				}
				m_Wrapper.m_EmotesActionsCallbackInterfaces.Clear();
				AddCallbacks(instance);
			}
		}

		public struct ActionsActions
		{
			private MikesTweaksPlayerInput m_Wrapper;

			public InputAction FlashlightToggle => m_Wrapper.m_Actions_FlashlightToggle;

			public InputAction WalkieTalkieSpeak => m_Wrapper.m_Actions_WalkieTalkieSpeak;

			public bool enabled => Get().enabled;

			public ActionsActions(MikesTweaksPlayerInput wrapper)
			{
				m_Wrapper = wrapper;
			}

			public InputActionMap Get()
			{
				return m_Wrapper.m_Actions;
			}

			public void Enable()
			{
				Get().Enable();
			}

			public void Disable()
			{
				Get().Disable();
			}

			public static implicit operator InputActionMap(ActionsActions set)
			{
				return set.Get();
			}

			public void AddCallbacks(IActionsActions instance)
			{
				if (instance != null && !m_Wrapper.m_ActionsActionsCallbackInterfaces.Contains(instance))
				{
					m_Wrapper.m_ActionsActionsCallbackInterfaces.Add(instance);
					FlashlightToggle.started += instance.OnFlashlightToggle;
					FlashlightToggle.performed += instance.OnFlashlightToggle;
					FlashlightToggle.canceled += instance.OnFlashlightToggle;
					WalkieTalkieSpeak.started += instance.OnWalkieTalkieSpeak;
					WalkieTalkieSpeak.performed += instance.OnWalkieTalkieSpeak;
					WalkieTalkieSpeak.canceled += instance.OnWalkieTalkieSpeak;
				}
			}

			private void UnregisterCallbacks(IActionsActions instance)
			{
				FlashlightToggle.started -= instance.OnFlashlightToggle;
				FlashlightToggle.performed -= instance.OnFlashlightToggle;
				FlashlightToggle.canceled -= instance.OnFlashlightToggle;
				WalkieTalkieSpeak.started -= instance.OnWalkieTalkieSpeak;
				WalkieTalkieSpeak.performed -= instance.OnWalkieTalkieSpeak;
				WalkieTalkieSpeak.canceled -= instance.OnWalkieTalkieSpeak;
			}

			public void RemoveCallbacks(IActionsActions instance)
			{
				if (m_Wrapper.m_ActionsActionsCallbackInterfaces.Remove(instance))
				{
					UnregisterCallbacks(instance);
				}
			}

			public void SetCallbacks(IActionsActions instance)
			{
				foreach (IActionsActions actionsActionsCallbackInterface in m_Wrapper.m_ActionsActionsCallbackInterfaces)
				{
					UnregisterCallbacks(actionsActionsCallbackInterface);
				}
				m_Wrapper.m_ActionsActionsCallbackInterfaces.Clear();
				AddCallbacks(instance);
			}
		}

		public interface IHotbarActions
		{
			void OnHotbar1(CallbackContext context);

			void OnHotbar2(CallbackContext context);

			void OnHotbar3(CallbackContext context);

			void OnHotbar4(CallbackContext context);

			void OnHotbar5(CallbackContext context);

			void OnHotbar6(CallbackContext context);

			void OnHotbar7(CallbackContext context);

			void OnHotbar8(CallbackContext context);

			void OnHotbar9(CallbackContext context);
		}

		public interface IEmotesActions
		{
			void OnEmote1(CallbackContext context);

			void OnEmote2(CallbackContext context);
		}

		public interface IActionsActions
		{
			void OnFlashlightToggle(CallbackContext context);

			void OnWalkieTalkieSpeak(CallbackContext context);
		}

		private readonly InputActionMap m_Hotbar;

		private List<IHotbarActions> m_HotbarActionsCallbackInterfaces = new List<IHotbarActions>();

		private readonly InputAction m_Hotbar_Hotbar1;

		private readonly InputAction m_Hotbar_Hotbar2;

		private readonly InputAction m_Hotbar_Hotbar3;

		private readonly InputAction m_Hotbar_Hotbar4;

		private readonly InputAction m_Hotbar_Hotbar5;

		private readonly InputAction m_Hotbar_Hotbar6;

		private readonly InputAction m_Hotbar_Hotbar7;

		private readonly InputAction m_Hotbar_Hotbar8;

		private readonly InputAction m_Hotbar_Hotbar9;

		private readonly InputActionMap m_Emotes;

		private List<IEmotesActions> m_EmotesActionsCallbackInterfaces = new List<IEmotesActions>();

		private readonly InputAction m_Emotes_Emote1;

		private readonly InputAction m_Emotes_Emote2;

		private readonly InputActionMap m_Actions;

		private List<IActionsActions> m_ActionsActionsCallbackInterfaces = new List<IActionsActions>();

		private readonly InputAction m_Actions_FlashlightToggle;

		private readonly InputAction m_Actions_WalkieTalkieSpeak;

		public InputActionAsset asset { get; }

		public InputBinding? bindingMask
		{
			get
			{
				return asset.bindingMask;
			}
			set
			{
				asset.bindingMask = value;
			}
		}

		public ReadOnlyArray<InputDevice>? devices
		{
			get
			{
				return asset.devices;
			}
			set
			{
				asset.devices = value;
			}
		}

		public ReadOnlyArray<InputControlScheme> controlSchemes => asset.controlSchemes;

		public IEnumerable<InputBinding> bindings => asset.bindings;

		public HotbarActions Hotbar => new HotbarActions(this);

		public EmotesActions Emotes => new EmotesActions(this);

		public ActionsActions Actions => new ActionsActions(this);

		public MikesTweaksPlayerInput()
		{
			asset = InputActionAsset.FromJson("{\r\n    \"name\": \"MikesTweaksPlayerInput\",\r\n    \"maps\": [\r\n        {\r\n            \"name\": \"Hotbar\",\r\n            \"id\": \"acedaef2-b06f-4287-a2ed-00f0260b63da\",\r\n            \"actions\": [\r\n                {\r\n                    \"name\": \"Hotbar1\",\r\n                    \"type\": \"Button\",\r\n                    \"id\": \"afdaf0de-d9cb-4835-93df-06ff8a407e18\",\r\n                    \"expectedControlType\": \"Button\",\r\n                    \"processors\": \"\",\r\n                    \"interactions\": \"\",\r\n                    \"initialStateCheck\": false\r\n                },\r\n                {\r\n                    \"name\": \"Hotbar2\",\r\n                    \"type\": \"Button\",\r\n                    \"id\": \"1cf91964-9e69-4db5-90ae-65b813acbceb\",\r\n                    \"expectedControlType\": \"Button\",\r\n                    \"processors\": \"\",\r\n                    \"interactions\": \"\",\r\n                    \"initialStateCheck\": false\r\n                },\r\n                {\r\n                    \"name\": \"Hotbar3\",\r\n                    \"type\": \"Button\",\r\n                    \"id\": \"9787ab53-1dcb-439c-91cb-683e0e6e0fc2\",\r\n                    \"expectedControlType\": \"Button\",\r\n                    \"processors\": \"\",\r\n                    \"interactions\": \"\",\r\n                    \"initialStateCheck\": false\r\n                },\r\n                {\r\n                    \"name\": \"Hotbar4\",\r\n                    \"type\": \"Button\",\r\n                    \"id\": \"a63eb6ea-bced-4246-a625-439815fb3c86\",\r\n                    \"expectedControlType\": \"Button\",\r\n                    \"processors\": \"\",\r\n                    \"interactions\": \"\",\r\n                    \"initialStateCheck\": false\r\n                },\r\n                {\r\n                    \"name\": \"Hotbar5\",\r\n                    \"type\": \"Button\",\r\n                    \"id\": \"8810962b-a9c4-4244-9202-05886a4dd217\",\r\n                    \"expectedControlType\": \"Button\",\r\n                    \"processors\": \"\",\r\n                    \"interactions\": \"\",\r\n                    \"initialStateCheck\": false\r\n                },\r\n                {\r\n                    \"name\": \"Hotbar6\",\r\n                    \"type\": \"Button\",\r\n                    \"id\": \"4e4ccd85-b20d-422d-836a-6c30d64e8ada\",\r\n                    \"expectedControlType\": \"Button\",\r\n                    \"processors\": \"\",\r\n                    \"interactions\": \"\",\r\n                    \"initialStateCheck\": false\r\n                },\r\n                {\r\n                    \"name\": \"Hotbar7\",\r\n                    \"type\": \"Button\",\r\n                    \"id\": \"cc6d7e8c-4c89-4a7f-8f69-07d40af41569\",\r\n                    \"expectedControlType\": \"Button\",\r\n                    \"processors\": \"\",\r\n                    \"interactions\": \"\",\r\n                    \"initialStateCheck\": false\r\n                },\r\n                {\r\n                    \"name\": \"Hotbar8\",\r\n                    \"type\": \"Button\",\r\n                    \"id\": \"71e7f8d9-ddd6-45de-acdb-0e427b5cf883\",\r\n                    \"expectedControlType\": \"Button\",\r\n                    \"processors\": \"\",\r\n                    \"interactions\": \"\",\r\n                    \"initialStateCheck\": false\r\n                },\r\n                {\r\n                    \"name\": \"Hotbar9\",\r\n                    \"type\": \"Button\",\r\n                    \"id\": \"9f3aee6a-4474-4e45-895f-4384d31e2651\",\r\n                    \"expectedControlType\": \"Button\",\r\n                    \"processors\": \"\",\r\n                    \"interactions\": \"\",\r\n                    \"initialStateCheck\": false\r\n                }\r\n            ],\r\n            \"bindings\": [\r\n                {\r\n                    \"name\": \"\",\r\n                    \"id\": \"75fed245-d23a-4c28-842f-5f5c2e244087\",\r\n                    \"path\": \"<Keyboard>/1\",\r\n                    \"interactions\": \"\",\r\n                    \"processors\": \"\",\r\n                    \"groups\": \"\",\r\n                    \"action\": \"Hotbar1\",\r\n                    \"isComposite\": false,\r\n                    \"isPartOfComposite\": false\r\n                },\r\n                {\r\n                    \"name\": \"\",\r\n                    \"id\": \"e3020d01-d049-4c17-98a4-c8e7b52e6f7e\",\r\n                    \"path\": \"<Keyboard>/2\",\r\n                    \"interactions\": \"\",\r\n                    \"processors\": \"\",\r\n                    \"groups\": \"\",\r\n                    \"action\": \"Hotbar2\",\r\n                    \"isComposite\": false,\r\n                    \"isPartOfComposite\": false\r\n                },\r\n                {\r\n                    \"name\": \"\",\r\n                    \"id\": \"fd0c3e9e-f967-4970-91eb-611774d404f3\",\r\n                    \"path\": \"<Keyboard>/3\",\r\n                    \"interactions\": \"\",\r\n                    \"processors\": \"\",\r\n                    \"groups\": \"\",\r\n                    \"action\": \"Hotbar3\",\r\n                    \"isComposite\": false,\r\n                    \"isPartOfComposite\": false\r\n                },\r\n                {\r\n                    \"name\": \"\",\r\n                    \"id\": \"201a61fa-e2d7-4c32-a293-89f48ce8b772\",\r\n                    \"path\": \"<Keyboard>/4\",\r\n                    \"interactions\": \"\",\r\n                    \"processors\": \"\",\r\n                    \"groups\": \"\",\r\n                    \"action\": \"Hotbar4\",\r\n                    \"isComposite\": false,\r\n                    \"isPartOfComposite\": false\r\n                },\r\n                {\r\n                    \"name\": \"\",\r\n                    \"id\": \"0b0ce1b1-d25e-4e30-97d3-24b67a08b018\",\r\n                    \"path\": \"<Keyboard>/5\",\r\n                    \"interactions\": \"\",\r\n                    \"processors\": \"\",\r\n                    \"groups\": \"\",\r\n                    \"action\": \"Hotbar5\",\r\n                    \"isComposite\": false,\r\n                    \"isPartOfComposite\": false\r\n                },\r\n                {\r\n                    \"name\": \"\",\r\n                    \"id\": \"91c0c96d-9e51-424c-a6ae-150e99cacde5\",\r\n                    \"path\": \"<Keyboard>/6\",\r\n                    \"interactions\": \"\",\r\n                    \"processors\": \"\",\r\n                    \"groups\": \"\",\r\n                    \"action\": \"Hotbar6\",\r\n                    \"isComposite\": false,\r\n                    \"isPartOfComposite\": false\r\n                },\r\n                {\r\n                    \"name\": \"\",\r\n                    \"id\": \"de949a83-e142-4d7e-96b4-885ec2abdd76\",\r\n                    \"path\": \"<Keyboard>/7\",\r\n                    \"interactions\": \"\",\r\n                    \"processors\": \"\",\r\n                    \"groups\": \"\",\r\n                    \"action\": \"Hotbar7\",\r\n                    \"isComposite\": false,\r\n                    \"isPartOfComposite\": false\r\n                },\r\n                {\r\n                    \"name\": \"\",\r\n                    \"id\": \"b40a6f2b-d2a4-4db7-8eb1-9d585882ff0e\",\r\n                    \"path\": \"<Keyboard>/8\",\r\n                    \"interactions\": \"\",\r\n                    \"processors\": \"\",\r\n                    \"groups\": \"\",\r\n                    \"action\": \"Hotbar8\",\r\n                    \"isComposite\": false,\r\n                    \"isPartOfComposite\": false\r\n                },\r\n                {\r\n                    \"name\": \"\",\r\n                    \"id\": \"7089d993-a703-4246-aef3-2bfa18bf49f1\",\r\n                    \"path\": \"<Keyboard>/9\",\r\n                    \"interactions\": \"\",\r\n                    \"processors\": \"\",\r\n                    \"groups\": \"\",\r\n                    \"action\": \"Hotbar9\",\r\n                    \"isComposite\": false,\r\n                    \"isPartOfComposite\": false\r\n                }\r\n            ]\r\n        },\r\n        {\r\n            \"name\": \"Emotes\",\r\n            \"id\": \"be4a715c-dafa-4ad6-a448-e3b0e60b12bc\",\r\n            \"actions\": [\r\n                {\r\n                    \"name\": \"Emote1\",\r\n                    \"type\": \"Button\",\r\n                    \"id\": \"e84b4354-1c58-4917-9862-f895484d9d3c\",\r\n                    \"expectedControlType\": \"Button\",\r\n                    \"processors\": \"\",\r\n                    \"interactions\": \"\",\r\n                    \"initialStateCheck\": false\r\n                },\r\n                {\r\n                    \"name\": \"Emote2\",\r\n                    \"type\": \"Button\",\r\n                    \"id\": \"7b86f2b9-734b-40f9-a267-19a31d181491\",\r\n                    \"expectedControlType\": \"Button\",\r\n                    \"processors\": \"\",\r\n                    \"interactions\": \"\",\r\n                    \"initialStateCheck\": false\r\n                }\r\n            ],\r\n            \"bindings\": [\r\n                {\r\n                    \"name\": \"\",\r\n                    \"id\": \"e15911b8-3ebe-4adf-ae17-97bf2e9237ef\",\r\n                    \"path\": \"<Ke

BepInEx/plugins/Mimics.dll

Decompiled 7 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.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using DunGen;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyMimics.Properties;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Mimics")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A mod that adds mimics to Lethal Company")]
[assembly: AssemblyFileVersion("2.2.0.0")]
[assembly: AssemblyInformationalVersion("2.2.0")]
[assembly: AssemblyProduct("Mimics")]
[assembly: AssemblyTitle("Mimics")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.2.0.0")]
[module: UnverifiableCode]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace LethalCompanyMimics.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.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("LethalCompanyMimics.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[] mimicdoor
		{
			get
			{
				object @object = ResourceManager.GetObject("mimicdoor", resourceCulture);
				return (byte[])@object;
			}
		}

		internal Resources()
		{
		}
	}
}
namespace Mimics
{
	[BepInPlugin("x753.Mimics", "Mimics", "2.2.0")]
	public class Mimics : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(GameNetworkManager))]
		internal class GameNetworkManagerPatch
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			private static void StartPatch()
			{
				((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().AddNetworkPrefab(MimicNetworkerPrefab);
			}
		}

		[HarmonyPatch(typeof(RoundManager))]
		internal class RoundManagerPatch
		{
			[HarmonyPatch("SetExitIDs")]
			[HarmonyPostfix]
			private static void SetExitIDsPatch(ref RoundManager __instance, Vector3 mainEntrancePosition)
			{
				//IL_00ee: 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_010e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0113: Unknown result type (might be due to invalid IL or missing references)
				//IL_0118: 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_013f: Unknown result type (might be due to invalid IL or missing references)
				//IL_014f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0154: Unknown result type (might be due to invalid IL or missing references)
				//IL_0160: Unknown result type (might be due to invalid IL or missing references)
				//IL_0167: Unknown result type (might be due to invalid IL or missing references)
				//IL_0173: Unknown result type (might be due to invalid IL or missing references)
				//IL_0480: Unknown result type (might be due to invalid IL or missing references)
				//IL_0491: Unknown result type (might be due to invalid IL or missing references)
				//IL_0496: Unknown result type (might be due to invalid IL or missing references)
				//IL_049b: Unknown result type (might be due to invalid IL or missing references)
				//IL_04a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_04ae: Unknown result type (might be due to invalid IL or missing references)
				//IL_04b3: Unknown result type (might be due to invalid IL or missing references)
				//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
				//IL_04b7: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
				//IL_0207: Unknown result type (might be due to invalid IL or missing references)
				//IL_020c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0211: Unknown result type (might be due to invalid IL or missing references)
				//IL_0216: Unknown result type (might be due to invalid IL or missing references)
				//IL_0220: Unknown result type (might be due to invalid IL or missing references)
				//IL_0225: Unknown result type (might be due to invalid IL or missing references)
				//IL_022a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0230: Unknown result type (might be due to invalid IL or missing references)
				//IL_0238: 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_024b: Unknown result type (might be due to invalid IL or missing references)
				//IL_04eb: Unknown result type (might be due to invalid IL or missing references)
				//IL_052c: Unknown result type (might be due to invalid IL or missing references)
				//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_02de: Unknown result type (might be due to invalid IL or missing references)
				//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
				//IL_05c6: Unknown result type (might be due to invalid IL or missing references)
				//IL_05cb: Unknown result type (might be due to invalid IL or missing references)
				//IL_05cf: Unknown result type (might be due to invalid IL or missing references)
				//IL_05db: Unknown result type (might be due to invalid IL or missing references)
				//IL_05e0: Unknown result type (might be due to invalid IL or missing references)
				//IL_05e4: Unknown result type (might be due to invalid IL or missing references)
				//IL_05e9: Unknown result type (might be due to invalid IL or missing references)
				//IL_06d9: Unknown result type (might be due to invalid IL or missing references)
				//IL_06e3: Expected O, but got Unknown
				//IL_07b2: Unknown result type (might be due to invalid IL or missing references)
				//IL_07d9: Unknown result type (might be due to invalid IL or missing references)
				//IL_0753: Unknown result type (might be due to invalid IL or missing references)
				//IL_077a: Unknown result type (might be due to invalid IL or missing references)
				//IL_088d: Unknown result type (might be due to invalid IL or missing references)
				//IL_08b4: Unknown result type (might be due to invalid IL or missing references)
				if (((NetworkBehaviour)__instance).IsServer && (Object)(object)MimicNetworker.Instance == (Object)null)
				{
					GameObject val = Object.Instantiate<GameObject>(MimicNetworkerPrefab);
					val.GetComponent<NetworkObject>().Spawn(true);
				}
				MimicDoor.allMimics = new List<MimicDoor>();
				int num = 0;
				Dungeon currentDungeon = __instance.dungeonGenerator.Generator.CurrentDungeon;
				List<Doorway> list = new List<Doorway>();
				Bounds val3 = default(Bounds);
				foreach (Tile allTile in currentDungeon.AllTiles)
				{
					foreach (Doorway unusedDoorway in allTile.UnusedDoorways)
					{
						if (unusedDoorway.HasDoorPrefabInstance || (Object)(object)((Component)unusedDoorway).GetComponentInChildren<SpawnSyncedObject>(true) == (Object)null)
						{
							continue;
						}
						GameObject gameObject = ((Component)((Component)((Component)unusedDoorway).GetComponentInChildren<SpawnSyncedObject>(true)).transform.parent).gameObject;
						if (!((Object)gameObject).name.StartsWith("AlleyExitDoorContainer") || gameObject.activeSelf)
						{
							continue;
						}
						bool flag = false;
						Matrix4x4 val2 = Matrix4x4.TRS(((Component)unusedDoorway).transform.position, ((Component)unusedDoorway).transform.rotation, new Vector3(1f, 1f, 1f));
						((Bounds)(ref val3))..ctor(new Vector3(0f, 1.5f, 5.5f), new Vector3(2f, 6f, 8f));
						((Bounds)(ref val3)).center = ((Matrix4x4)(ref val2)).MultiplyPoint3x4(((Bounds)(ref val3)).center);
						Collider[] array = Physics.OverlapBox(((Bounds)(ref val3)).center, ((Bounds)(ref val3)).extents, ((Component)unusedDoorway).transform.rotation, LayerMask.GetMask(new string[3] { "Room", "Railing", "MapHazards" }));
						Collider[] array2 = array;
						int num2 = 0;
						if (num2 < array2.Length)
						{
							Collider val4 = array2[num2];
							flag = true;
						}
						if (flag)
						{
							continue;
						}
						foreach (Tile allTile2 in currentDungeon.AllTiles)
						{
							if (!((Object)(object)allTile == (Object)(object)allTile2))
							{
								Vector3 origin = ((Component)unusedDoorway).transform.position + 5f * ((Component)unusedDoorway).transform.forward;
								Bounds val5 = UnityUtil.CalculateProxyBounds(((Component)allTile2).gameObject, true, Vector3.up);
								Ray val6 = default(Ray);
								((Ray)(ref val6)).origin = origin;
								((Ray)(ref val6)).direction = Vector3.up;
								if (((Bounds)(ref val5)).IntersectRay(val6) && (((Object)allTile2).name.Contains("Catwalk") || ((Object)allTile2).name.Contains("LargeForkTile") || ((Object)allTile2).name.Contains("4x4BigStair") || ((Object)allTile2).name.Contains("ElevatorConnector") || (((Object)allTile2).name.Contains("StartRoom") && !((Object)allTile2).name.Contains("Manor"))))
								{
									flag = true;
								}
								val6 = default(Ray);
								((Ray)(ref val6)).origin = origin;
								((Ray)(ref val6)).direction = Vector3.down;
								if (((Bounds)(ref val5)).IntersectRay(val6) && (((Object)allTile2).name.Contains("MediumRoomHallway1B") || ((Object)allTile2).name.Contains("LargeForkTile") || ((Object)allTile2).name.Contains("4x4BigStair") || ((Object)allTile2).name.Contains("ElevatorConnector") || ((Object)allTile2).name.Contains("StartRoom")))
								{
									flag = true;
								}
							}
						}
						if (!flag)
						{
							list.Add(unusedDoorway);
						}
					}
				}
				Shuffle(list, StartOfRound.Instance.randomMapSeed);
				List<Vector3> list2 = new List<Vector3>();
				foreach (Doorway item in list)
				{
					int num3 = 0;
					int num4 = 0;
					int[] spawnRates = SpawnRates;
					foreach (int num5 in spawnRates)
					{
						num4 += num5;
					}
					Random random = new Random(StartOfRound.Instance.randomMapSeed + 753);
					int num6 = random.Next(0, num4);
					int num7 = 0;
					for (int j = 0; j < SpawnRates.Length; j++)
					{
						if (num6 < SpawnRates[j] + num7)
						{
							num3 = j;
							break;
						}
						num7 += SpawnRates[j];
					}
					if (num3 == num && num3 != 6)
					{
						break;
					}
					bool flag2 = false;
					Vector3 val7 = ((Component)item).transform.position + 5f * ((Component)item).transform.forward;
					foreach (Vector3 item2 in list2)
					{
						if (Vector3.Distance(val7, item2) < 4f)
						{
							flag2 = true;
							break;
						}
					}
					if (flag2)
					{
						continue;
					}
					list2.Add(val7);
					GameObject gameObject2 = ((Component)((Component)((Component)item).GetComponentInChildren<SpawnSyncedObject>(true)).transform.parent).gameObject;
					GameObject val8 = Object.Instantiate<GameObject>(MimicPrefab, ((Component)item).transform);
					val8.transform.position = gameObject2.transform.position;
					MimicDoor component = val8.GetComponent<MimicDoor>();
					AudioSource[] componentsInChildren = val8.GetComponentsInChildren<AudioSource>(true);
					foreach (AudioSource val9 in componentsInChildren)
					{
						val9.volume = MimicVolume / 100f;
						val9.outputAudioMixerGroup = StartOfRound.Instance.ship3DAudio.outputAudioMixerGroup;
					}
					MimicDoor.allMimics.Add(component);
					component.mimicIndex = num;
					num++;
					GameObject gameObject3 = ((Component)((Component)item).transform.GetChild(0)).gameObject;
					gameObject3.SetActive(false);
					Bounds bounds = ((Collider)component.frameBox).bounds;
					Vector3 center = ((Bounds)(ref bounds)).center;
					bounds = ((Collider)component.frameBox).bounds;
					Collider[] array3 = Physics.OverlapBox(center, ((Bounds)(ref bounds)).extents, Quaternion.identity);
					foreach (Collider val10 in array3)
					{
						if (((Object)((Component)val10).gameObject).name.Contains("Shelf"))
						{
							((Component)val10).gameObject.SetActive(false);
						}
					}
					Light componentInChildren = gameObject2.GetComponentInChildren<Light>(true);
					((Component)componentInChildren).transform.parent.SetParent(val8.transform);
					MeshRenderer[] componentsInChildren2 = val8.GetComponentsInChildren<MeshRenderer>();
					MeshRenderer[] array4 = componentsInChildren2;
					foreach (MeshRenderer val11 in array4)
					{
						Material[] materials = ((Renderer)val11).materials;
						foreach (Material val12 in materials)
						{
							val12.shader = ((Renderer)gameObject3.GetComponentInChildren<MeshRenderer>(true)).material.shader;
							val12.renderQueue = ((Renderer)gameObject3.GetComponentInChildren<MeshRenderer>(true)).material.renderQueue;
						}
					}
					component.interactTrigger.onInteract = new InteractEvent();
					((UnityEvent<PlayerControllerB>)(object)component.interactTrigger.onInteract).AddListener((UnityAction<PlayerControllerB>)component.TouchMimic);
					if (MimicPerfection)
					{
						continue;
					}
					component.interactTrigger.timeToHold = 0.9f;
					if (!ColorBlindMode)
					{
						if ((StartOfRound.Instance.randomMapSeed + num) % 2 == 0)
						{
							((Renderer)val8.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.490566f, 0.1226415f, 0.1302275f);
							((Renderer)val8.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(0.4339623f, 0.1043965f, 0.1150277f);
							componentInChildren.colorTemperature = 1250f;
						}
						else
						{
							((Renderer)val8.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.5f, 0.1580188f, 0.1657038f);
							((Renderer)val8.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(43f / 106f, 0.1358579f, 0.1393619f);
							componentInChildren.colorTemperature = 1300f;
						}
					}
					else if ((StartOfRound.Instance.randomMapSeed + num) % 2 == 0)
					{
						component.interactTrigger.timeToHold = 1.1f;
					}
					else
					{
						component.interactTrigger.timeToHold = 1f;
					}
					if (!EasyMode)
					{
						continue;
					}
					Random random2 = new Random(StartOfRound.Instance.randomMapSeed + num);
					switch (random2.Next(0, 4))
					{
					case 0:
						if (!ColorBlindMode)
						{
							((Renderer)val8.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.489f, 0.2415526f, 0.1479868f);
							((Renderer)val8.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(0.489f, 0.2415526f, 0.1479868f);
						}
						else
						{
							component.interactTrigger.timeToHold = 1.5f;
						}
						break;
					case 1:
						component.interactTrigger.hoverTip = "Feed : [LMB]";
						component.interactTrigger.holdTip = "Feed : [LMB]";
						break;
					case 2:
						component.interactTrigger.hoverIcon = component.LostFingersIcon;
						break;
					case 3:
						component.interactTrigger.holdTip = "DIE : [LMB]";
						component.interactTrigger.timeToHold = 0.5f;
						break;
					default:
						component.interactTrigger.hoverTip = "BUG, REPORT TO DEVELOPER";
						break;
					}
				}
			}
		}

		[HarmonyPatch(typeof(SprayPaintItem))]
		internal class SprayPaintItemPatch
		{
			private static FieldInfo SprayHit = typeof(SprayPaintItem).GetField("sprayHit", BindingFlags.Instance | BindingFlags.NonPublic);

			[HarmonyPatch("SprayPaintClientRpc")]
			[HarmonyPostfix]
			private static void SprayPaintClientRpcPatch(SprayPaintItem __instance, Vector3 sprayPos, Vector3 sprayRot)
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				RaycastHit val = (RaycastHit)SprayHit.GetValue(__instance);
				if ((Object)(object)((RaycastHit)(ref val)).collider != (Object)null && ((Object)((RaycastHit)(ref val)).collider).name == "MimicSprayCollider")
				{
					MimicDoor component = ((Component)((Component)((RaycastHit)(ref val)).collider).transform.parent.parent).GetComponent<MimicDoor>();
					component.sprayCount++;
					if (component.sprayCount > 9)
					{
						MimicNetworker.Instance.MimicAddAnger(1, component.mimicIndex);
					}
				}
			}
		}

		private const string modGUID = "x753.Mimics";

		private const string modName = "Mimics";

		private const string modVersion = "2.2.0";

		private readonly Harmony harmony = new Harmony("x753.Mimics");

		private static Mimics Instance;

		public static GameObject MimicPrefab;

		public static GameObject MimicNetworkerPrefab;

		public static int[] SpawnRates;

		public static bool MimicPerfection;

		public static bool EasyMode;

		public static bool ColorBlindMode;

		public static float MimicVolume;

		private void Awake()
		{
			AssetBundle val = AssetBundle.LoadFromMemory(Resources.mimicdoor);
			MimicPrefab = val.LoadAsset<GameObject>("Assets/MimicDoor.prefab");
			MimicNetworkerPrefab = val.LoadAsset<GameObject>("Assets/MimicNetworker.prefab");
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Mimics is loaded!");
			SpawnRates = new int[7]
			{
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Zero Mimics", 22, "Weight of zero mimics spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "One Mimic", 69, "Weight of one mimic spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Two Mimics", 7, "Weight of two mimics spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Three Mimics", 1, "Weight of three mimics spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Four Mimics", 1, "Weight of four mimics spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Five Mimics", 0, "Weight of five mimics spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Maximum Mimics", 0, "Weight of maximum mimics spawning").Value
			};
			MimicPerfection = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Perfect Mimics", false, "Select this if you want mimics to be the exact same color as the real thing. Overrides all difficulty settings.").Value;
			EasyMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Easy Mode", false, "Each mimic will have one of several possible imperfections to help you tell if it's a mimic.").Value;
			ColorBlindMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Color Blind Mode", false, "Replaces all color differences with another way to differentiate mimics.").Value;
			MimicVolume = ((BaseUnityPlugin)this).Config.Bind<int>("General", "SFX Volume", 100, "Volume of the mimic's SFX (0-100)").Value;
			if (MimicVolume < 0f)
			{
				MimicVolume = 0f;
			}
			if (MimicVolume > 100f)
			{
				MimicVolume = 100f;
			}
			((BaseUnityPlugin)this).Config.Bind<int>("Difficulty", "Difficulty Level", 0, "This is an old setting, ignore it.");
			((BaseUnityPlugin)this).Config.Remove(((BaseUnityPlugin)this).Config["Difficulty", "Difficulty Level"].Definition);
			((BaseUnityPlugin)this).Config.Save();
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}

		public static void Shuffle<T>(IList<T> list, int seed)
		{
			Random random = new Random(seed);
			int num = list.Count;
			while (num > 1)
			{
				num--;
				int index = random.Next(num + 1);
				T value = list[index];
				list[index] = list[num];
				list[num] = value;
			}
		}
	}
	public class MimicNetworker : NetworkBehaviour
	{
		public static MimicNetworker Instance;

		private void Awake()
		{
			Instance = this;
		}

		public void MimicAttack(int playerId, int mimicIndex, bool ownerOnly = false)
		{
			if (((NetworkBehaviour)this).IsOwner)
			{
				Instance.MimicAttackClientRpc(playerId, mimicIndex);
			}
			else if (!ownerOnly)
			{
				Instance.MimicAttackServerRpc(playerId, mimicIndex);
			}
		}

		[ClientRpc]
		public void MimicAttackClientRpc(int playerId, int mimicIndex)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2885019175u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2885019175u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					((MonoBehaviour)this).StartCoroutine(MimicDoor.allMimics[mimicIndex].Attack(playerId));
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void MimicAttackServerRpc(int playerId, int mimicIndex)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1024971481u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1024971481u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					Instance.MimicAttackClientRpc(playerId, mimicIndex);
				}
			}
		}

		public void MimicAddAnger(int amount, int mimicIndex)
		{
			if (((NetworkBehaviour)this).IsOwner)
			{
				Instance.MimicAddAngerClientRpc(amount, mimicIndex);
			}
			else
			{
				Instance.MimicAddAngerServerRpc(amount, mimicIndex);
			}
		}

		[ClientRpc]
		public void MimicAddAngerClientRpc(int amount, int mimicIndex)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1137632670u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, amount);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1137632670u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					((MonoBehaviour)this).StartCoroutine(MimicDoor.allMimics[mimicIndex].AddAnger(amount));
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void MimicAddAngerServerRpc(int amount, int mimicIndex)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(669208889u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, amount);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 669208889u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					Instance.MimicAddAngerClientRpc(amount, mimicIndex);
				}
			}
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_MimicNetworker()
		{
			//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
			NetworkManager.__rpc_func_table.Add(2885019175u, new RpcReceiveHandler(__rpc_handler_2885019175));
			NetworkManager.__rpc_func_table.Add(1024971481u, new RpcReceiveHandler(__rpc_handler_1024971481));
			NetworkManager.__rpc_func_table.Add(1137632670u, new RpcReceiveHandler(__rpc_handler_1137632670));
			NetworkManager.__rpc_func_table.Add(669208889u, new RpcReceiveHandler(__rpc_handler_669208889));
		}

		private static void __rpc_handler_2885019175(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				int mimicIndex = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((MimicNetworker)(object)target).MimicAttackClientRpc(playerId, mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1024971481(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				int mimicIndex = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((MimicNetworker)(object)target).MimicAttackServerRpc(playerId, mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1137632670(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int amount = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref amount);
				int mimicIndex = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((MimicNetworker)(object)target).MimicAddAngerClientRpc(amount, mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_669208889(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int amount = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref amount);
				int mimicIndex = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((MimicNetworker)(object)target).MimicAddAngerServerRpc(amount, mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "MimicNetworker";
		}
	}
	public class MimicDoor : MonoBehaviour
	{
		public GameObject playerTarget;

		public BoxCollider frameBox;

		public Sprite LostFingersIcon;

		public Animator mimicAnimator;

		public GameObject grabPoint;

		public InteractTrigger interactTrigger;

		public int anger;

		public bool angering;

		public int sprayCount;

		private bool attacking;

		public static List<MimicDoor> allMimics;

		public int mimicIndex;

		public void TouchMimic(PlayerControllerB player)
		{
			if (!attacking)
			{
				MimicNetworker.Instance.MimicAttack((int)player.playerClientId, mimicIndex);
			}
		}

		public IEnumerator Attack(int playerId)
		{
			attacking = true;
			interactTrigger.interactable = false;
			PlayerControllerB player = StartOfRound.Instance.allPlayerScripts[playerId];
			mimicAnimator.SetTrigger("Attack");
			playerTarget.transform.position = ((Component)player).transform.position;
			yield return (object)new WaitForSeconds(0.1f);
			playerTarget.transform.position = ((Component)player).transform.position;
			yield return (object)new WaitForSeconds(0.1f);
			playerTarget.transform.position = ((Component)player).transform.position;
			yield return (object)new WaitForSeconds(0.1f);
			playerTarget.transform.position = ((Component)player).transform.position;
			yield return (object)new WaitForSeconds(0.1f);
			float num = Vector3.Distance(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, ((Component)frameBox).transform.position);
			if (num < 8f)
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)1);
			}
			else if (num < 14f)
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)0);
			}
			yield return (object)new WaitForSeconds(0.2f);
			if (((NetworkBehaviour)player).IsOwner && Vector3.Distance(((Component)player).transform.position, ((Component)this).transform.position) < 8.75f)
			{
				player.KillPlayer(Vector3.zero, true, (CauseOfDeath)0, 0);
			}
			float startTime = Time.timeSinceLevelLoad;
			yield return (object)new WaitUntil((Func<bool>)(() => (Object)(object)player.deadBody != (Object)null || Time.timeSinceLevelLoad - startTime > 4f));
			if ((Object)(object)player.deadBody != (Object)null)
			{
				player.deadBody.attachedTo = grabPoint.transform;
				player.deadBody.attachedLimb = player.deadBody.bodyParts[5];
				player.deadBody.matchPositionExactly = true;
				for (int i = 0; i < player.deadBody.bodyParts.Length; i++)
				{
					((Component)player.deadBody.bodyParts[i]).GetComponent<Collider>().excludeLayers = LayerMask.op_Implicit(-1);
				}
			}
			yield return (object)new WaitForSeconds(2f);
			if ((Object)(object)player.deadBody != (Object)null)
			{
				player.deadBody.attachedTo = null;
				player.deadBody.attachedLimb = null;
				player.deadBody.matchPositionExactly = false;
				((Component)((Component)player.deadBody).transform.GetChild(0)).gameObject.SetActive(false);
				player.deadBody = null;
			}
			yield return (object)new WaitForSeconds(4.5f);
			attacking = false;
			interactTrigger.interactable = true;
		}

		public IEnumerator AddAnger(int amount)
		{
			if (angering || attacking)
			{
				yield break;
			}
			angering = true;
			anger += amount;
			if (anger == 1)
			{
				Sprite oldIcon2 = interactTrigger.hoverIcon;
				interactTrigger.hoverIcon = LostFingersIcon;
				mimicAnimator.SetTrigger("Growl");
				yield return (object)new WaitForSeconds(2.75f);
				interactTrigger.hoverIcon = oldIcon2;
				sprayCount = 0;
				angering = false;
				yield break;
			}
			if (anger == 2)
			{
				interactTrigger.holdTip = "DIE : [LMB]";
				interactTrigger.timeToHold = 0.25f;
				Sprite oldIcon2 = interactTrigger.hoverIcon;
				interactTrigger.hoverIcon = LostFingersIcon;
				mimicAnimator.SetTrigger("Growl");
				yield return (object)new WaitForSeconds(2.75f);
				interactTrigger.hoverIcon = oldIcon2;
				sprayCount = 0;
				angering = false;
				yield break;
			}
			if (anger > 2)
			{
				PlayerControllerB val = null;
				float num = 9999f;
				PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
				foreach (PlayerControllerB val2 in allPlayerScripts)
				{
					float num2 = Vector3.Distance(((Component)this).transform.position, ((Component)val2).transform.position);
					if (num2 < num)
					{
						num = num2;
						val = val2;
					}
				}
				if ((Object)(object)val != (Object)null)
				{
					MimicNetworker.Instance.MimicAttackClientRpc((int)val.playerClientId, mimicIndex);
				}
			}
			sprayCount = 0;
			angering = false;
		}
	}
	public class MimicCollider : MonoBehaviour, IHittable
	{
		public MimicDoor mimic;

		void IHittable.Hit(int force, Vector3 hitDirection, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
		{
			MimicNetworker.Instance.MimicAddAnger(force, mimic.mimicIndex);
		}
	}
	public class MimicListener : MonoBehaviour, INoiseListener
	{
		public MimicDoor mimic;

		private int tolerance = 100;

		void INoiseListener.DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot, int noiseID)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			if ((noiseLoudness >= 0.9f || noiseID == 101158) && Vector3.Distance(noisePosition, ((Component)mimic).transform.position) < 5f)
			{
				switch (noiseID)
				{
				case 75:
					tolerance--;
					break;
				case 5:
					tolerance -= 15;
					break;
				case 101158:
					tolerance -= 35;
					break;
				default:
					tolerance -= 30;
					break;
				}
				if (tolerance <= 0)
				{
					tolerance = 100;
					MimicNetworker.Instance.MimicAddAnger(1, mimic.mimicIndex);
				}
			}
		}
	}
}

BepInEx/plugins/MoreCompany.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using MoreCompany.Cosmetics;
using MoreCompany.Utils;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("MoreCompany")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MoreCompany")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("511a1e5e-0611-49f1-b60f-cec69c668fd8")]
[assembly: AssemblyFileVersion("1.7.2")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.7.2.0")]
namespace MoreCompany
{
	[HarmonyPatch(typeof(AudioMixer), "SetFloat")]
	public static class AudioMixerSetFloatPatch
	{
		public static bool Prefix(string name, float value)
		{
			if (name.StartsWith("PlayerVolume") || name.StartsWith("PlayerPitch"))
			{
				string s = name.Replace("PlayerVolume", "").Replace("PlayerPitch", "");
				int num = int.Parse(s);
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[num];
				AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource;
				if ((Object)(object)val != (Object)null && Object.op_Implicit((Object)(object)currentVoiceChatAudioSource))
				{
					if (name.StartsWith("PlayerVolume"))
					{
						currentVoiceChatAudioSource.volume = value / 16f;
					}
					else if (name.StartsWith("PlayerPitch"))
					{
						currentVoiceChatAudioSource.pitch = value;
					}
				}
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddTextToChatOnServer")]
	public static class SendChatToServerPatch
	{
		public static bool Prefix(HUDManager __instance, string chatMessage, int playerId = -1)
		{
			if (((NetworkBehaviour)StartOfRound.Instance).IsHost && chatMessage.StartsWith("/mc") && DebugCommandRegistry.commandEnabled)
			{
				string text = chatMessage.Replace("/mc ", "");
				DebugCommandRegistry.HandleCommand(text.Split(new char[1] { ' ' }));
				return false;
			}
			if (chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				ReflectionUtils.InvokeMethod(__instance, "AddPlayerChatMessageServerRpc", new object[2] { chatMessage, 99 });
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageServerRpc")]
	public static class ServerReceiveMessagePatch
	{
		public static string previousDataMessage = "";

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

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

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

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

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

			public static UnityAction <>9__2_2;

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

		public static GameObject quickMenuScrollInstance;

		public static void Postfix(QuickMenuManager __instance)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject = ((Component)__instance.playerListPanel.transform.Find("Image")).gameObject;
			GameObject val = Object.Instantiate<GameObject>(MainClass.quickMenuScrollParent);
			val.transform.SetParent(gameObject.transform);
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).localPosition = new Vector3(0f, -31.2f, 0f);
			((Transform)component).localScale = Vector3.one;
			quickMenuScrollInstance = val;
		}

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

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

		public const string PLUGIN_VERSION = "1.7.2";

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

		public static int maxPlayerCount = 50;

		public static bool showCosmetics = true;

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

		public static Texture2D mainLogo;

		public static GameObject quickMenuScrollParent;

		public static GameObject playerEntry;

		public static GameObject crewCountUI;

		public static GameObject cosmeticGUIInstance;

		public static GameObject cosmeticButton;

		public static ManualLogSource StaticLogger;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		public Transform hip;

		public Transform lowerArmRight;

		public Transform shinLeft;

		public Transform shinRight;

		public Transform chest;

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

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

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

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

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

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

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

		private void ParentCosmetic(CosmeticInstance cosmeticInstance)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			Transform val = null;
			switch (cosmeticInstance.cosmeticType)
			{
			case CosmeticType.HAT:
				val = head;
				break;
			case CosmeticType.R_LOWER_ARM:
				val = lowerArmRight;
				break;
			case CosmeticType.HIP:
				val = hip;
				break;
			case CosmeticType.L_SHIN:
				val = shinLeft;
				break;
			case CosmeticType.R_SHIN:
				val = shinRight;
				break;
			case CosmeticType.CHEST:
				val = chest;
				break;
			}
			((Component)cosmeticInstance).transform.position = val.position;
			((Component)cosmeticInstance).transform.rotation = val.rotation;
			((Component)cosmeticInstance).transform.parent = val;
		}
	}
	public class CosmeticInstance : MonoBehaviour
	{
		public CosmeticType cosmeticType;

		public string cosmeticId;

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

		public virtual string cosmeticId { get; }

		public virtual string textureIconPath { get; }

		public CosmeticType cosmeticType { get; }

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

			public static UnityAction <>9__8_0;

			public static UnityAction <>9__8_1;

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

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

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

		public static GameObject cosmeticGUI;

		private static GameObject displayGuy;

		private static CosmeticApplication cosmeticApplication;

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

		public const float COSMETIC_PLAYER_SCALE_MULT = 0.38f;

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

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

		public static void SpawnCosmeticGUI()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Expected O, but got Unknown
			cosmeticGUI = Object.Instantiate<GameObject>(MainClass.cosmeticGUIInstance);
			((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale")).transform.localScale = new Vector3(2f, 2f, 2f);
			displayGuy = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("ObjectHolder")
				.Find("ScavengerModel")
				.Find("metarig")).gameObject;
			cosmeticApplication = displayGuy.AddComponent<CosmeticApplication>();
			GameObject gameObject = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("EnableButton")).gameObject;
			ButtonClickedEvent onClick = gameObject.GetComponent<Button>().onClick;
			object obj = <>c.<>9__8_0;
			if (obj == null)
			{
				UnityAction val = delegate
				{
					MainClass.showCosmetics = true;
					MainClass.SaveSettingsToFile();
				};
				<>c.<>9__8_0 = val;
				obj = (object)val;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
			GameObject gameObject2 = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("DisableButton")).gameObject;
			ButtonClickedEvent onClick2 = gameObject2.GetComponent<Button>().onClick;
			object obj2 = <>c.<>9__8_1;
			if (obj2 == null)
			{
				UnityAction val2 = delegate
				{
					MainClass.showCosmetics = false;
					MainClass.SaveSettingsToFile();
				};
				<>c.<>9__8_1 = val2;
				obj2 = (object)val2;
			}
			((UnityEvent)onClick2).AddListener((UnityAction)obj2);
			if (MainClass.showCosmetics)
			{
				gameObject.SetActive(false);
				gameObject2.SetActive(true);
			}
			else
			{
				gameObject.SetActive(true);
				gameObject2.SetActive(false);
			}
			PopulateCosmetics();
			UpdateCosmeticsOnDisplayGuy(startEnabled: false);
		}

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

		private static Color HexToColor(string hex)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			Color result = default(Color);
			ColorUtility.TryParseHtmlString(hex, ref result);
			return result;
		}

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

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

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

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

		private Vector2 lastMousePosition;

		private bool dragging = false;

		private Vector3 rotationalVelocity = Vector3.zero;

		public float dragSpeed = 1f;

		public float airDrag = 0.99f;

		public GameObject target;

		private void Update()
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			if (dragging)
			{
				Vector3 val = Vector2.op_Implicit(((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue() - lastMousePosition);
				rotationalVelocity += new Vector3(0f, 0f - val.x, 0f) * dragSpeed;
				lastMousePosition = ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue();
			}
			rotationalVelocity *= airDrag;
			target.transform.Rotate(rotationalVelocity * Time.deltaTime * speed, (Space)0);
		}

		public void OnPointerDown(PointerEventData eventData)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			lastMousePosition = ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue();
			dragging = true;
		}

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

BepInEx/plugins/MoreEmotes1.2.0.dll

Decompiled 7 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;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FuckYouMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FuckYouMod")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5ecc2bf2-af12-4e83-a6f1-cf2eacbf3060")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Tools
{
	public class Reflection
	{
		public static object GetInstanceField(Type type, object instance, string fieldName)
		{
			BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
			FieldInfo field = type.GetField(fieldName, bindingAttr);
			return field.GetValue(instance);
		}

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

		private ConfigEntry<string> config_KeyWheel;

		private ConfigEntry<bool> config_InventoryCheck;

		private ConfigEntry<string> config_KeyEmote3;

		private ConfigEntry<string> config_KeyEmote4;

		private ConfigEntry<string> config_KeyEmote5;

		private ConfigEntry<string> config_KeyEmote6;

		private ConfigEntry<string> config_KeyEmote7;

		private ConfigEntry<string> config_KeyEmote8;

		private ConfigEntry<bool> config_toggleEmote3;

		private ConfigEntry<bool> config_toggleEmote4;

		private ConfigEntry<bool> config_toggleEmote5;

		private ConfigEntry<bool> config_toggleEmote6;

		private ConfigEntry<bool> config_toggleEmote7;

		private ConfigEntry<bool> config_toggleEmote8;

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

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

		private void ConfigFile()
		{
			EmotePatch.keybinds = new string[8];
			config_KeyWheel = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL", "Key", "v", "SUPPORTED KEYS A-Z | 0-9 | F1-F12 ");
			EmotePatch.wheelKeybind = config_KeyWheel.Value;
			config_InventoryCheck = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "InventoryCheck", true, "Prevents some emotes from performing while holding any item/scrap");
			EmotePatch.InvCheck = config_InventoryCheck.Value;
			config_KeyEmote3 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Middle Finger", "3", "MIDDLEFINGER: SUPPORTED KEYS A-Z | 0-9 | F1-F12 ");
			config_toggleEmote3 = ((BaseUnityPlugin)this).Config.Bind<bool>("QUICK EMOTES", "Enable Middle Finger", true, "ENABLE QUICK MIDDLEFINGER");
			EmotePatch.keybinds[2] = (config_toggleEmote3.Value ? config_KeyEmote3.Value : "/");
			EmotePatch.enable3 = config_toggleEmote3.Value;
			config_KeyEmote4 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "The Griddy", "6", "THE GRIDDY: SUPPORTED KEYS A-Z | 0-9 | F1-F12 ");
			config_toggleEmote4 = ((BaseUnityPlugin)this).Config.Bind<bool>("QUICK EMOTES", "Enable The Griddy", true, "ENABLE QUICK THE GRIDDY");
			EmotePatch.keybinds[5] = (config_toggleEmote4.Value ? config_KeyEmote4.Value : "/");
			EmotePatch.enable4 = config_toggleEmote4.Value;
			config_KeyEmote5 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Shy", "5", "SHY: SUPPORTED KEYS A-Z | 0-9 | F1-F12 ");
			config_toggleEmote5 = ((BaseUnityPlugin)this).Config.Bind<bool>("QUICK EMOTES", "Enable Shy", true, "ENABLE QUICK SHY");
			EmotePatch.keybinds[4] = (config_toggleEmote5.Value ? config_KeyEmote5.Value : "/");
			EmotePatch.enable5 = config_toggleEmote5.Value;
			config_KeyEmote6 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Clap", "4", "CLAP: SUPPORTED KEYS A-Z | 0-9 | F1-F12 ");
			config_toggleEmote6 = ((BaseUnityPlugin)this).Config.Bind<bool>("QUICK EMOTES", "Enable Clap", true, "ENABLE QUICK CLAP");
			EmotePatch.keybinds[3] = (config_toggleEmote6.Value ? config_KeyEmote6.Value : "/");
			EmotePatch.enable6 = config_toggleEmote6.Value;
			config_KeyEmote7 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Twerk", "7", "TWERK: SUPPORTED KEYS A-Z | 0-9 | F1-F12 ");
			config_toggleEmote7 = ((BaseUnityPlugin)this).Config.Bind<bool>("QUICK EMOTES", "Enable Twerk", true, "ENABLE QUICK TWERK");
			EmotePatch.keybinds[6] = (config_toggleEmote7.Value ? config_KeyEmote7.Value : "/");
			EmotePatch.enable7 = config_toggleEmote7.Value;
			config_KeyEmote8 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Salute", "8", "SALUTE: SUPPORTED KEYS A-Z | 0-9 | F1-F12 ");
			config_toggleEmote8 = ((BaseUnityPlugin)this).Config.Bind<bool>("QUICK EMOTES", "Enable Salute", true, "ENABLE QUICK SALUTE");
			EmotePatch.keybinds[7] = (config_toggleEmote8.Value ? config_KeyEmote8.Value : "/");
			EmotePatch.enable8 = config_toggleEmote8.Value;
		}
	}
	public static class PluginInfo
	{
		public const string Guid = "MoreEmotes";

		public const string Name = "MoreEmotes-Sligili";

		public const string Ver = "1.2.0";
	}
}
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 bool enable7;

		public static bool enable8;

		public static string[] keybinds;

		public static string wheelKeybind;

		private static CallbackContext context;

		public static RuntimeAnimatorController local;

		public static RuntimeAnimatorController others;

		private static int currentEmoteID;

		private static float svMovSpeed;

		public static bool IncompatibleStuff;

		public static bool InvCheck;

		public static bool emoteWheelIsOpened;

		public static GameObject wheel;

		private static SelectionWheel selectionWheel;

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPostfix]
		private static void StartPostfix(PlayerControllerB __instance)
		{
			GameObject gameObject = ((Component)((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel")).transform.Find("metarig")).gameObject;
			CustomAudioAnimationEvent customAudioAnimationEvent = gameObject.AddComponent<CustomAudioAnimationEvent>();
			svMovSpeed = __instance.movementSpeed;
			customAudioAnimationEvent.player = __instance;
			if (Object.FindObjectsOfType(typeof(SelectionWheel)).Length == 0)
			{
				GameObject val = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesMenu.prefab");
				GameObject gameObject2 = ((Component)((Component)GameObject.Find("Systems").gameObject.transform.Find("UI")).gameObject.transform.Find("Canvas")).gameObject;
				if ((Object)(object)wheel != (Object)null)
				{
					Object.Destroy((Object)(object)wheel.gameObject);
				}
				wheel = Object.Instantiate<GameObject>(val, gameObject2.transform);
				selectionWheel = wheel.AddComponent<SelectionWheel>();
				SelectionWheel.emotes_Keybinds = new string[keybinds.Length + 1];
				SelectionWheel.emotes_Keybinds = keybinds;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(PlayerControllerB __instance)
		{
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.isPlayerControlled || !((NetworkBehaviour)__instance).IsOwner)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = others;
				return;
			}
			if ((Object)(object)__instance.playerBodyAnimator != (Object)(object)local)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = local;
			}
			if (__instance.performingEmote)
			{
				currentEmoteID = __instance.playerBodyAnimator.GetInteger("emoteNumber");
			}
			if (!IncompatibleStuff)
			{
				bool flag = (bool)Reflection.CallMethod(__instance, "CheckConditionsForEmote") && currentEmoteID == 6 && __instance.performingEmote;
				__instance.movementSpeed = (flag ? (svMovSpeed / 2f) : svMovSpeed);
			}
			if (InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[wheelKeybind], 0f) && !emoteWheelIsOpened && !__instance.isPlayerDead && !__instance.inTerminalMenu && !__instance.quickMenuManager.isMenuOpen)
			{
				emoteWheelIsOpened = true;
				Cursor.visible = true;
				Cursor.lockState = (CursorLockMode)2;
				wheel.SetActive(emoteWheelIsOpened);
				__instance.disableLookInput = true;
			}
			else if ((!InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[wheelKeybind], 0f) && emoteWheelIsOpened) || __instance.quickMenuManager.isMenuOpen)
			{
				if (!__instance.quickMenuManager.isMenuOpen || __instance.isPlayerDead)
				{
					int selectedEmoteID = selectionWheel.selectedEmoteID;
					if (selectedEmoteID <= 3 || selectedEmoteID == 6 || !InvCheck)
					{
						__instance.PerformEmote(context, selectedEmoteID);
					}
					else if (!__instance.isHoldingObject)
					{
						__instance.PerformEmote(context, selectedEmoteID);
					}
					Cursor.visible = false;
					Cursor.lockState = (CursorLockMode)1;
				}
				if (__instance.isPlayerDead && !__instance.quickMenuManager.isMenuOpen)
				{
					Cursor.visible = false;
					Cursor.lockState = (CursorLockMode)1;
				}
				__instance.disableLookInput = false;
				emoteWheelIsOpened = false;
				wheel.SetActive(emoteWheelIsOpened);
			}
			if (!__instance.performingEmote || currentEmoteID == 7)
			{
			}
			if (!emoteWheelIsOpened)
			{
				EmoteInput(keybinds[2], enable3, needsEmptyHands: false, 3, __instance);
				EmoteInput(keybinds[3], enable6, needsEmptyHands: true, 4, __instance);
				EmoteInput(keybinds[4], enable5, needsEmptyHands: true, 5, __instance);
				EmoteInput(keybinds[5], enable4, needsEmptyHands: false, 6, __instance);
				EmoteInput(keybinds[6], enable7, needsEmptyHands: true, 7, __instance);
				EmoteInput(keybinds[7], enable8, needsEmptyHands: true, 8, __instance);
			}
		}

		private static void EmoteInput(string keyBind, bool enabled, bool needsEmptyHands, int emoteID, PlayerControllerB player)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			if (InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keyBind], 0f) && enabled && (!player.isHoldingObject || !needsEmptyHands || !InvCheck) && (!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 == 6)
			{
				__result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && __instance.moveInputVector.x == 0f && !__instance.isSprinting && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu && !__instance.isTypingChat;
				return false;
			}
			return true;
		}

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

		private AudioSource SoundsSource;

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

		public PlayerControllerB player;

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

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

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

		public Text emoteInformation;

		public Text pageInformation;

		private int blocksNumber = 8;

		private int currentBlock = 1;

		public int pageNumber;

		public int selectedEmoteID;

		private float angle;

		private float pageCooldown = 0.1f;

		public GameObject[] Pages;

		private int cuadrante = 0;

		public string selectedEmoteName;

		public float wheelMovementOffset = 3.3f;

		public static string[] emotes_Keybinds;

		private Vector2 center;

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

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

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

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

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

BepInEx/plugins/MoreItems.dll

Decompiled 7 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MoreItems.Patches;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MoreItems
{
	[BepInPlugin("MoreItems", "MoreItems", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("MoreItems");

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MoreItems is loaded!");
			harmony.PatchAll(typeof(StartOfRoundPatch));
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "MoreItems";

		public const string PLUGIN_NAME = "MoreItems";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace MoreItems.Patches
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		private const int newMaxItemCapacity = 999;

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void IncreaseShipItemCapacity(ref int ___maxShipItemCapacity)
		{
			___maxShipItemCapacity = 999;
			Logger.CreateLogSource("MoreItems").LogInfo((object)$"Maximum amount of items that can be saved set to {999}.");
		}
	}
}

BepInEx/plugins/MoreSuits.dll

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

BepInEx/plugins/MoreTerminalCommands.dll

Decompiled 7 months ago
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using GameNetcodeStuff;
using HarmonyLib;
using TerminalApi;
using TerminalApi.Events;
using UnityEngine;
using UnityEngine.Events;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("NexiumTech")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NexiumTech")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("b0fe5129-1447-4aa0-9416-bbb736787bf1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace MoreTerminalCommands;

[BepInPlugin("net.navarrotech.MoreTerminalCommands", "MoreTerminalCommands", "1.0.1")]
[BepInDependency("atomic.terminalapi", "1.2.0")]
public class Plugin : BaseUnityPlugin
{
	public const string ModGUID = "net.navarrotech.MoreTerminalCommands";

	public const string ModName = "MoreTerminalCommands";

	public const string ModVersion = "1.0.1";

	private const string TeleportCommand = "teleport";

	private const string TeleportCommandAlt = "tp";

	private const string TeleportCommandAlt2 = "scotty";

	private const string InverseTeleportCommand = "iteleport";

	private const string InverseTeleportCommandAlt = "itp";

	private const string LightsCommand = "lights";

	private const string LightsCommandAlt = "light";

	private const string ShipDoorCommand = "shipdoor";

	private const string ShipDoorCommandAlt = "door";

	private const string LockShipDoorCommand = "lockdoor";

	private const string UnlockShipDoorCommand = "unlockdoor";

	private const string GreatAssetCommand = "greatasset";

	private const string RandomTeleportCommand = "randomtp";

	private const string ExplodeCommand = "explode";

	private const string TakeoffCommand = "takeoff";

	internal bool lockDoor = false;

	internal HangarShipDoor door = null;

	public void Awake()
	{
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Expected O, but got Unknown
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Expected O, but got Unknown
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Expected O, but got Unknown
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin net.navarrotech.MoreTerminalCommands is loaded!");
		Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		Events.TerminalAwake += new TerminalEventHandler(TerminalIsAwake);
		Events.TerminalParsedSentence += new TerminalParseSentenceEventHandler(TextSubmitted);
		Events.TerminalBeginUsing += new TerminalEventHandler(OnBeginUsing);
	}

	[HarmonyPatch("Update")]
	[HarmonyPostfix]
	public void Update()
	{
		if (Object.op_Implicit((Object)(object)door) && lockDoor)
		{
			door.doorPower = 1f;
		}
	}

	private void TerminalIsAwake(object sender, TerminalEventArgs e)
	{
		((BaseUnityPlugin)this).Logger.LogMessage((object)"Terminal is awake");
		TerminalApi.AddCommand("teleport", "Attempting Teleport...\n\n", "tele1", true);
		TerminalApi.AddCommand("tp", "Attempting Teleport...\n\n", "tele2", true);
		TerminalApi.AddCommand("scotty", "Attempting Teleport...\n\n", "tele2", true);
		TerminalApi.AddCommand("iteleport", "Attempting Inverse Teleport...\n\n", "intele", true);
		TerminalApi.AddCommand("itp", "Attempting Inverse Teleport...\n\n", "intele", true);
		TerminalApi.AddCommand("lights", "Toggling lights...\n\n", "lightswitch1", true);
		TerminalApi.AddCommand("light", "Toggling lights...\n\n", "lightswitch2", true);
		TerminalApi.AddCommand("shipdoor", "Toggling door...\n\n", "doorhydraulic", true);
		TerminalApi.AddCommand("door", "Toggling door...\n\n", "doorhydraulic", true);
		TerminalApi.AddCommand("lockdoor", "Locking door...\n\n", "doorhydraulic1", true);
		TerminalApi.AddCommand("unlockdoor", "Unlocking ship door...\n\n", "doorhydraulic4", true);
		TerminalApi.AddCommand("randomtp", "Attempting random teleport...", "randomteleport", true);
		TerminalApi.AddCommand("greatasset", "Welcome...", "greatasset", true);
		door = Object.FindObjectOfType<HangarShipDoor>();
	}

	private ShipTeleporter GetTeleporter(bool selectInverse = false)
	{
		ShipTeleporter[] array = Object.FindObjectsOfType<ShipTeleporter>();
		for (int i = 0; i < array.Length; i++)
		{
			if (selectInverse == array[i].isInverseTeleporter)
			{
				return array[i];
			}
		}
		return null;
	}

	private InteractTrigger GetTrigger(string name)
	{
		InteractTrigger[] array = Object.FindObjectsOfType<InteractTrigger>();
		for (int i = 0; i < array.Length; i++)
		{
			if (((Object)array[i]).name == name)
			{
				return array[i];
			}
		}
		return null;
	}

	private void ToggleShipDoor()
	{
		HangarShipDoor val = Object.FindObjectOfType<HangarShipDoor>();
		if (!((Object)(object)val == (Object)null) && !val.overheated)
		{
			if (val.doorPower == 1f)
			{
				((UnityEvent<PlayerControllerB>)(object)val.triggerScript.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
			}
			else
			{
				((UnityEvent<PlayerControllerB>)(object)val.triggerScript.onStopInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
			}
		}
	}

	private Landmine GetLandmine(string tag)
	{
		Landmine[] array = Object.FindObjectsOfType<Landmine>();
		for (int i = 0; i < array.Length; i++)
		{
			if (((Component)array[i]).tag == tag)
			{
				return array[i];
			}
		}
		return null;
	}

	private void ExplodeLandmine(string tag)
	{
		Landmine landmine = GetLandmine(tag);
		if (Object.op_Implicit((Object)(object)landmine) && ((Behaviour)landmine).enabled)
		{
			landmine.Detonate();
		}
	}

	private void PlayGreatAssetIntro()
	{
		StartOfRound val = Object.FindObjectOfType<StartOfRound>();
		Terminal val2 = Object.FindObjectOfType<Terminal>();
		if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null))
		{
			val2.terminalAudio.PlayOneShot(val.shipIntroSpeechSFX);
		}
	}

	private void TextSubmitted(object sender, TerminalParseSentenceEventArgs e)
	{
		((BaseUnityPlugin)this).Logger.LogMessage((object)$"Text submitted: {e.SubmittedText} Node Returned: {e.ReturnedNode}");
		string text = e.SubmittedText.ToLower();
		if (text.StartsWith("explode"))
		{
			ExplodeLandmine(text.Substring(8));
			return;
		}
		string text2 = text;
		string text3 = text2;
		if (text3 == null)
		{
			return;
		}
		ShipTeleporter teleporter;
		ShipTeleporter teleporter2;
		switch (text3.Length)
		{
		default:
			return;
		case 8:
			switch (text3[0])
			{
			default:
				return;
			case 't':
				break;
			case 's':
				goto IL_0127;
			case 'l':
				if (text3 == "lockdoor")
				{
					HangarShipDoorPatch.SetLocked(locked: true);
				}
				return;
			case 'r':
				if (text3 == "randomtp")
				{
					DoubleTp();
				}
				return;
			}
			if (!(text3 == "teleport"))
			{
				return;
			}
			goto IL_0245;
		case 6:
		{
			char c = text3[0];
			if (c != 'l')
			{
				if (c != 's' || !(text3 == "scotty"))
				{
					return;
				}
				goto IL_0245;
			}
			if (!(text3 == "lights"))
			{
				return;
			}
			break;
		}
		case 10:
			switch (text3[0])
			{
			case 'u':
				if (text3 == "unlockdoor")
				{
					HangarShipDoorPatch.SetLocked();
				}
				break;
			case 'g':
				if (text3 == "greatasset")
				{
					PlayGreatAssetIntro();
				}
				break;
			}
			return;
		case 2:
			if (!(text3 == "tp"))
			{
				return;
			}
			goto IL_0245;
		case 9:
			if (!(text3 == "iteleport"))
			{
				return;
			}
			goto IL_0290;
		case 3:
			if (!(text3 == "itp"))
			{
				return;
			}
			goto IL_0290;
		case 7:
			if (text3 == "takeoff")
			{
				InteractTrigger trigger = GetTrigger("StartGameLever");
				if ((Object)(object)trigger != (Object)null)
				{
					((UnityEvent<PlayerControllerB>)(object)trigger.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
				}
			}
			return;
		case 4:
			if (!(text3 == "door"))
			{
				return;
			}
			goto IL_0316;
		case 5:
			{
				if (!(text3 == "light"))
				{
					return;
				}
				break;
			}
			IL_0127:
			if (!(text3 == "shipdoor"))
			{
				return;
			}
			goto IL_0316;
			IL_0245:
			teleporter = GetTeleporter();
			if (Object.op_Implicit((Object)(object)teleporter) && teleporter.buttonTrigger.interactable)
			{
				((UnityEvent<PlayerControllerB>)(object)teleporter.buttonTrigger.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
			}
			return;
			IL_0290:
			teleporter2 = GetTeleporter(selectInverse: true);
			if (Object.op_Implicit((Object)(object)teleporter2) && teleporter2.buttonTrigger.interactable)
			{
				((UnityEvent<PlayerControllerB>)(object)teleporter2.buttonTrigger.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
			}
			return;
			IL_0316:
			ToggleShipDoor();
			return;
		}
		InteractTrigger trigger2 = GetTrigger("LightSwitch");
		if (Object.op_Implicit((Object)(object)trigger2))
		{
			((UnityEvent<PlayerControllerB>)(object)trigger2.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
		}
	}

	private IEnumerator DoubleTp()
	{
		ShipTeleporter regular = GetTeleporter();
		ShipTeleporter inverse = GetTeleporter(selectInverse: true);
		if ((Object)(object)regular == (Object)null || (Object)(object)inverse == (Object)null)
		{
			((BaseUnityPlugin)this).Logger.LogDebug((object)"No regular and inverse teleporter owned");
			yield return (object)new WaitForSeconds(0f);
		}
		((UnityEvent<PlayerControllerB>)(object)inverse.buttonTrigger.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
		yield return (object)new WaitForSeconds(2.5f);
		((UnityEvent<PlayerControllerB>)(object)regular.buttonTrigger.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
	}

	private void OnBeginUsing(object sender, TerminalEventArgs e)
	{
		((BaseUnityPlugin)this).Logger.LogMessage((object)"Player has just started using the terminal");
		List<GrabbableObject> list = new List<GrabbableObject>();
		GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
		int num = 0;
		for (int i = 0; i < array.Length; i++)
		{
			if (array[i].itemProperties.isScrap && !array[i].scrapPersistedThroughRounds && !array[i].isInShipRoom)
			{
				list.Add(array[i]);
				num += array[i].scrapValue;
			}
		}
		string text = string.Join("\n", list.Select((GrabbableObject x) => x.itemProperties.itemName + " : " + x.scrapValue + " Value"));
		string text2 = "Items not in ship: " + list.Count() + "\n\n" + text + "\n\nWith a total value of: " + num + "\n\n";
	}
}
[HarmonyPatch(typeof(HangarShipDoor))]
internal class HangarShipDoorPatch
{
	public static bool keepLocked;

	[HarmonyPatch("Update")]
	[HarmonyPostfix]
	private static void DoorUpdate(ref float ___doorPower, ref bool ___overheated, ref float ___doorPowerDuration)
	{
		if (keepLocked)
		{
			___doorPower = 1f;
			___overheated = false;
			___doorPowerDuration = 0f;
		}
		else
		{
			___doorPowerDuration = 20f;
		}
	}

	public static void SetLocked(bool locked = false)
	{
		keepLocked = locked;
	}
}

BepInEx/plugins/ShipLoot/ShipLoot.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("ShipLoot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("ShipLoot")]
[assembly: AssemblyCopyright("Copyright © tinyhoot 2023")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("1.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace ShipLoot
{
	[BepInPlugin("com.github.tinyhoot.ShipLoot", "ShipLoot", "1.0")]
	internal class ShipLoot : BaseUnityPlugin
	{
		public const string GUID = "com.github.tinyhoot.ShipLoot";

		public const string NAME = "ShipLoot";

		public const string VERSION = "1.0";

		internal static ManualLogSource Log;

		private void Awake()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			new Harmony("com.github.tinyhoot.ShipLoot").PatchAll(Assembly.GetExecutingAssembly());
		}
	}
}
namespace ShipLoot.Patches
{
	[HarmonyPatch]
	internal class HudManagerPatcher
	{
		private static GameObject _totalCounter;

		private static TextMeshProUGUI _textMesh;

		private static float _displayTimeLeft;

		private const float DisplayTime = 5f;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HUDManager), "PingScan_performed")]
		private static void OnScan(HUDManager __instance, CallbackContext context)
		{
			if (!((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && __instance.CanPlayerScan() && !(__instance.playerPingingScan > -0.5f) && (StartOfRound.Instance.inShipPhase || GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom))
			{
				if (!Object.op_Implicit((Object)(object)_totalCounter))
				{
					CopyValueCounter();
				}
				float num = CalculateLootValue();
				((TMP_Text)_textMesh).text = $"SHIP: ${num:F0}";
				_displayTimeLeft = 5f;
				if (!_totalCounter.activeSelf)
				{
					((MonoBehaviour)GameNetworkManager.Instance).StartCoroutine(ShipLootCoroutine());
				}
			}
		}

		private static IEnumerator ShipLootCoroutine()
		{
			_totalCounter.SetActive(true);
			while (_displayTimeLeft > 0f)
			{
				float displayTimeLeft = _displayTimeLeft;
				_displayTimeLeft = 0f;
				yield return (object)new WaitForSeconds(displayTimeLeft);
			}
			_totalCounter.SetActive(false);
		}

		private static float CalculateLootValue()
		{
			List<GrabbableObject> list = (from obj in GameObject.Find("/Environment/HangarShip").GetComponentsInChildren<GrabbableObject>()
				where ((Object)obj).name != "ClipboardManual" && ((Object)obj).name != "StickyNoteItem"
				select obj).ToList();
			ShipLoot.Log.LogDebug((object)"Calculating total ship scrap value.");
			CollectionExtensions.Do<GrabbableObject>((IEnumerable<GrabbableObject>)list, (Action<GrabbableObject>)delegate(GrabbableObject scrap)
			{
				ShipLoot.Log.LogDebug((object)$"{((Object)scrap).name} - ${scrap.scrapValue}");
			});
			return list.Sum((GrabbableObject scrap) => scrap.scrapValue);
		}

		private static void CopyValueCounter()
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GameObject.Find("/Systems/UI/Canvas/IngamePlayerHUD/BottomMiddle/ValueCounter");
			if (!Object.op_Implicit((Object)(object)val))
			{
				ShipLoot.Log.LogError((object)"Failed to find ValueCounter object to copy!");
			}
			_totalCounter = Object.Instantiate<GameObject>(val.gameObject, val.transform.parent, false);
			_totalCounter.transform.Translate(0f, 1f, 0f);
			Vector3 localPosition = _totalCounter.transform.localPosition;
			_totalCounter.transform.localPosition = new Vector3(localPosition.x + 50f, -50f, localPosition.z);
			_textMesh = _totalCounter.GetComponentInChildren<TextMeshProUGUI>();
		}
	}
}

BepInEx/plugins/SkinwalkerMod.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Dissonance.Config;
using HarmonyLib;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

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

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

	private const string modGUID = "RugbugRedfern.SkinwalkerMod";

	private const string modVersion = "1.0.8";

	private static bool initialized;

	public static PluginLoader Instance { get; private set; }

	private void Awake()
	{
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Expected O, but got Unknown
		if (initialized)
		{
			return;
		}
		initialized = true;
		Instance = this;
		harmony.PatchAll(Assembly.GetExecutingAssembly());
		Type[] types = Assembly.GetExecutingAssembly().GetTypes();
		Type[] array = types;
		foreach (Type type in array)
		{
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
			MethodInfo[] array2 = methods;
			foreach (MethodInfo methodInfo in array2)
			{
				object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
				if (customAttributes.Length != 0)
				{
					methodInfo.Invoke(null, null);
				}
			}
		}
		SkinwalkerLogger.Initialize("RugbugRedfern.SkinwalkerMod");
		SkinwalkerLogger.Log("SKINWALKER MOD STARTING UP 1.0.8");
		SkinwalkerConfig.InitConfig();
		SceneManager.sceneLoaded += SkinwalkerNetworkManagerHandler.ClientConnectInitializer;
		GameObject val = new GameObject("Skinwalker Mod");
		val.AddComponent<SkinwalkerModPersistent>();
		((Object)val).hideFlags = (HideFlags)61;
		Object.DontDestroyOnLoad((Object)(object)val);
	}

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

	public const float PLAY_INTERVAL_MIN = 15f;

	public const float PLAY_INTERVAL_MAX = 40f;

	private const float MAX_DIST = 100f;

	private float nextTimeToPlayAudio;

	private EnemyAI ai;

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

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

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

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

	public static ConfigEntry<bool> VoiceEnabled_Bracken;

	public static ConfigEntry<bool> VoiceEnabled_BunkerSpider;

	public static ConfigEntry<bool> VoiceEnabled_Centipede;

	public static ConfigEntry<bool> VoiceEnabled_CoilHead;

	public static ConfigEntry<bool> VoiceEnabled_EyelessDog;

	public static ConfigEntry<bool> VoiceEnabled_ForestGiant;

	public static ConfigEntry<bool> VoiceEnabled_GhostGirl;

	public static ConfigEntry<bool> VoiceEnabled_GiantWorm;

	public static ConfigEntry<bool> VoiceEnabled_HoardingBug;

	public static ConfigEntry<bool> VoiceEnabled_Hygrodere;

	public static ConfigEntry<bool> VoiceEnabled_Jester;

	public static ConfigEntry<bool> VoiceEnabled_Masked;

	public static ConfigEntry<bool> VoiceEnabled_Nutcracker;

	public static ConfigEntry<bool> VoiceEnabled_SporeLizard;

	public static ConfigEntry<bool> VoiceEnabled_Thumper;

	public static ConfigEntry<float> VoiceLineFrequency;

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

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

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

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

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

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

	private float nextTimeToCheckFolder = 30f;

	private float nextTimeToCheckEnemies = 30f;

	private const float folderScanInterval = 8f;

	private const float enemyScanInterval = 5f;

	public static SkinwalkerModPersistent Instance { get; private set; }

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

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

	private void OnApplicationQuit()
	{
		DisableRecording();
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	public static SkinwalkerNetworkManager Instance { get; private set; }

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

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

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

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

BepInEx/plugins/SpectateEnemy.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
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: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SpectateEnemy")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: AssemblyInformationalVersion("1.5.0+fedd7299567cd8f4569b5f35b2cc9b6f25f17c2f")]
[assembly: AssemblyProduct("SpectateEnemy")]
[assembly: AssemblyTitle("SpectateEnemy")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SpectateEnemy
{
	[BepInPlugin("SpectateEnemy", "SpectateEnemy", "1.5.0")]
	public class Plugin : BaseUnityPlugin
	{
		public static int spectatedEnemyIndex = -1;

		public static bool spectatingEnemies = false;

		public static MethodInfo raycastSpectate = null;

		public static MethodInfo displaySpectatorTip = null;

		private ConfigEntry<bool> spectateTurrets;

		private ConfigEntry<bool> spectateLandmines;

		private ConfigEntry<bool> spectatePassives;

		public static bool doSpectateTurrets;

		public static bool doSpectateLandmines;

		public static bool doSpectatePassives;

		private Harmony harmony;

		private void Awake()
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			spectateTurrets = ((BaseUnityPlugin)this).Config.Bind<bool>("Config", "Spectate Turrets", false, "Enables spectating turrets.");
			doSpectateTurrets = spectateTurrets.Value;
			spectateLandmines = ((BaseUnityPlugin)this).Config.Bind<bool>("Config", "Spectate Landmines", false, "Enables spectating landmines.");
			doSpectateLandmines = spectateLandmines.Value;
			spectatePassives = ((BaseUnityPlugin)this).Config.Bind<bool>("Config", "Spectate Passives", false, "Enables spectating passive enemies, such as Docile Locust Bees and Manticoils.");
			doSpectatePassives = spectatePassives.Value;
			harmony = new Harmony("SpectateEnemy");
			harmony.PatchAll();
			raycastSpectate = AccessTools.Method(typeof(PlayerControllerB), "RaycastSpectateCameraAroundPivot", (Type[])null, (Type[])null);
			displaySpectatorTip = AccessTools.Method(typeof(HUDManager), "DisplaySpectatorTip", (Type[])null, (Type[])null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"SpectateEnemy loaded!");
		}
	}
	public class Spectatable : MonoBehaviour
	{
		public SpectatableType type = SpectatableType.Enemy;

		public string enemyName = "Enemy";
	}
	public enum SpectatableType
	{
		Enemy,
		Turret,
		Landmine
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "SpectateEnemy";

		public const string PLUGIN_NAME = "SpectateEnemy";

		public const string PLUGIN_VERSION = "1.5.0";
	}
}
namespace SpectateEnemy.Patches
{
	[HarmonyPatch(typeof(EnemyAI), "Start")]
	public class EnemyAI_Patches
	{
		private static void Postfix(EnemyAI __instance)
		{
			if (Plugin.doSpectatePassives || (!(__instance.enemyType.enemyName == "Docile Locust Bees") && !(__instance.enemyType.enemyName == "Manticoil")))
			{
				Spectatable spectatable = ((Component)__instance).gameObject.AddComponent<Spectatable>();
				spectatable.enemyName = __instance.enemyType.enemyName;
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "Disconnect")]
	public class GameNetworkManager_Patches
	{
		private static void Postfix()
		{
			Plugin.spectatedEnemyIndex = -1;
			Plugin.spectatingEnemies = false;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "Update")]
	public class HUDManager_Patches
	{
		private static void Postfix(HUDManager __instance)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			if (!GameNetworkManager.Instance.localPlayerController.isPlayerDead)
			{
				return;
			}
			if (StartOfRound.Instance.shipIsLeaving)
			{
				Light component = ((Component)__instance.playersManager.spectateCamera).GetComponent<Light>();
				if ((Object)(object)component != (Object)null)
				{
					((Behaviour)component).enabled = false;
				}
				return;
			}
			MovementActions movement = __instance.playerActions.Movement;
			InputBinding val = ((MovementActions)(ref movement)).Interact.bindings[0];
			string text = InputControlPath.ToHumanReadableString(((InputBinding)(ref val)).effectivePath, (HumanReadableStringOptions)2, (InputControl)null);
			TextMeshProUGUI holdButtonToEndGameEarlyText = __instance.holdButtonToEndGameEarlyText;
			((TMP_Text)holdButtonToEndGameEarlyText).text = ((TMP_Text)holdButtonToEndGameEarlyText).text + "\n\n\n\n\nSwitch to " + (Plugin.spectatingEnemies ? "Players" : "Enemies") + ": [" + text + "]\nToggle Flashlight : [RMB] (Click)";
			movement = __instance.playerActions.Movement;
			if (((MovementActions)(ref movement)).PingScan.WasReleasedThisFrame())
			{
				Light component2 = ((Component)__instance.playersManager.spectateCamera).GetComponent<Light>();
				if ((Object)(object)component2 != (Object)null)
				{
					((Behaviour)component2).enabled = !((Behaviour)component2).enabled;
				}
			}
		}
	}
	[HarmonyPatch(typeof(Landmine), "Start")]
	public class Landmine_Patches
	{
		private static void Postfix(Landmine __instance)
		{
			if (Plugin.doSpectateLandmines)
			{
				Spectatable spectatable = ((Component)__instance).gameObject.AddComponent<Spectatable>();
				spectatable.type = SpectatableType.Landmine;
				spectatable.enemyName = "Landmine";
			}
		}
	}
	[HarmonyPatch(typeof(MaskedPlayerEnemy), "Start")]
	public class MaskedPlayerEnemy_Patches
	{
		private static void Postfix(MaskedPlayerEnemy __instance)
		{
			Spectatable spectatable = ((Component)__instance).gameObject.AddComponent<Spectatable>();
			if ((Object)(object)__instance.mimickingPlayer != (Object)null)
			{
				spectatable.enemyName = __instance.mimickingPlayer.playerUsername;
			}
			else
			{
				spectatable.enemyName = ((EnemyAI)__instance).enemyType.enemyName;
			}
		}
	}
	internal class Handler
	{
		public static Spectatable[] spectatorList;

		public static bool Spectate()
		{
			if (Plugin.spectatingEnemies)
			{
				if (spectatorList.Length == 0)
				{
					Plugin.spectatingEnemies = false;
					return true;
				}
				Plugin.spectatedEnemyIndex++;
				if (Plugin.spectatedEnemyIndex >= spectatorList.Length)
				{
					Plugin.spectatedEnemyIndex = 0;
				}
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "Interact_performed")]
	public class PlayerControllerB_Interact
	{
		private static bool Prefix(PlayerControllerB __instance)
		{
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerDead && !StartOfRound.Instance.shipIsLeaving && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject))
			{
				Plugin.spectatingEnemies = !Plugin.spectatingEnemies;
				if (Plugin.spectatingEnemies)
				{
					Handler.spectatorList = Object.FindObjectsByType<Spectatable>((FindObjectsSortMode)0);
					if (Handler.spectatorList.Length == 0)
					{
						Plugin.spectatingEnemies = false;
						Plugin.displaySpectatorTip.Invoke(HUDManager.Instance, new object[1] { "No enemies to spectate" });
						return false;
					}
					if (Plugin.spectatedEnemyIndex == -1 || Plugin.spectatedEnemyIndex >= Handler.spectatorList.Length)
					{
						if ((Object)(object)__instance.spectatedPlayerScript == (Object)null)
						{
							Plugin.spectatedEnemyIndex = 0;
						}
						else
						{
							float num = 999999f;
							int spectatedEnemyIndex = 0;
							for (int i = 0; i < Handler.spectatorList.Length; i++)
							{
								Vector3 val = ((Component)Handler.spectatorList[i]).transform.position - ((Component)__instance.spectatedPlayerScript).transform.position;
								float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
								if (sqrMagnitude < num * num)
								{
									num = sqrMagnitude;
									spectatedEnemyIndex = i;
								}
							}
							Plugin.spectatedEnemyIndex = spectatedEnemyIndex;
						}
					}
					__instance.spectatedPlayerScript = null;
				}
				else
				{
					__instance.spectatedPlayerScript = ((IEnumerable<PlayerControllerB>)__instance.playersManager.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB x) => !x.isPlayerDead));
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_performed")]
	public class PlayerControllerB_Use
	{
		private static bool Prefix(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerDead && !StartOfRound.Instance.shipIsLeaving && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject))
			{
				return Handler.Spectate();
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")]
	public class PlayerControllerB_LateUpdate
	{
		private static void Postfix(PlayerControllerB __instance)
		{
			//IL_00fd: 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)
			if (!Plugin.spectatingEnemies)
			{
				return;
			}
			if (Handler.spectatorList.Length == 0)
			{
				Plugin.spectatingEnemies = false;
				return;
			}
			if (Plugin.spectatedEnemyIndex >= Handler.spectatorList.Length)
			{
				Plugin.spectatedEnemyIndex = 0;
			}
			Spectatable obj = Handler.spectatorList[Plugin.spectatedEnemyIndex];
			if ((Object)(object)obj == (Object)null)
			{
				Plugin.spectatedEnemyIndex++;
				if (Plugin.spectatedEnemyIndex >= Handler.spectatorList.Length)
				{
					Plugin.spectatedEnemyIndex = 0;
				}
				return;
			}
			Vector3? spectatePosition = GetSpectatePosition(obj);
			if (!spectatePosition.HasValue)
			{
				Plugin.spectatedEnemyIndex++;
				if (Plugin.spectatedEnemyIndex >= Handler.spectatorList.Length)
				{
					Plugin.spectatedEnemyIndex = 0;
				}
				return;
			}
			if (obj.enemyName == "Enemy")
			{
				TryFixName(ref obj);
			}
			__instance.spectateCameraPivot.position = spectatePosition.Value + GetZoomDistance(obj);
			((TMP_Text)HUDManager.Instance.spectatingPlayerText).text = "(Spectating: " + obj.enemyName + ")";
			Plugin.raycastSpectate.Invoke(__instance, Array.Empty<object>());
		}

		private static void TryFixName(ref Spectatable obj)
		{
			EnemyAI val = default(EnemyAI);
			Turret val2 = default(Turret);
			Landmine val3 = default(Landmine);
			if (((Component)obj).gameObject.TryGetComponent<EnemyAI>(ref val))
			{
				obj.enemyName = val.enemyType.enemyName;
			}
			else if (((Component)obj).gameObject.TryGetComponent<Turret>(ref val2))
			{
				obj.enemyName = "Turret";
			}
			else if (((Component)obj).gameObject.TryGetComponent<Landmine>(ref val3))
			{
				obj.enemyName = "Landmine";
			}
		}

		private static Vector3 GetZoomDistance(Spectatable obj)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (obj.enemyName == "ForestGiant")
			{
				return Vector3.up * 3f;
			}
			if (obj.enemyName == "MouthDog" || obj.enemyName == "Jester")
			{
				return Vector3.up * 2f;
			}
			return Vector3.up;
		}

		private static Vector3? GetSpectatePosition(Spectatable obj)
		{
			//IL_00b2: 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_0043: 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)
			if (obj.type == SpectatableType.Enemy)
			{
				EnemyAI component = ((Component)obj).GetComponent<EnemyAI>();
				if ((Object)(object)component != (Object)null)
				{
					return ((Object)(object)component.eye == (Object)null) ? ((Component)component).transform.position : component.eye.position;
				}
			}
			else if (obj.type == SpectatableType.Turret)
			{
				Turret component2 = ((Component)obj).GetComponent<Turret>();
				if ((Object)(object)component2 != (Object)null)
				{
					return ((Component)component2.centerPoint).transform.position;
				}
			}
			else
			{
				if (obj.type == SpectatableType.Landmine)
				{
					return ((Component)obj).transform.position;
				}
				Debug.LogError((object)("[SpectateEnemy]: Error when spectating: no handler for SpectatableType " + obj.type));
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SpectateNextPlayer")]
	public class PlayerControllerB_SpectateNext
	{
		private static bool Prefix()
		{
			return !Plugin.spectatingEnemies;
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "ShipLeave")]
	public class StartOfRound_Patches
	{
		private static void Postfix()
		{
			Plugin.spectatedEnemyIndex = -1;
			Plugin.spectatingEnemies = false;
		}
	}
	[HarmonyPatch(typeof(Turret), "Start")]
	public class Turret_Patches
	{
		private static void Postfix(Turret __instance)
		{
			if (Plugin.doSpectateTurrets)
			{
				Spectatable spectatable = ((Component)__instance).gameObject.AddComponent<Spectatable>();
				spectatable.type = SpectatableType.Turret;
				spectatable.enemyName = "Turret";
			}
		}
	}
}

BepInEx/plugins/TerminalApi.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("NotAtomicBomb")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Terminal Api for the terminal in Lethal Company")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.0+b87452af897d2b57619d1b55b8887fd436be901a")]
[assembly: AssemblyProduct("TerminalApi")]
[assembly: AssemblyTitle("TerminalApi")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/NotAtomicBomb/TerminalApi")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TerminalApi
{
	internal class DelayedAction
	{
		internal Action<TerminalKeyword> Action { get; set; }

		internal TerminalKeyword Keyword { get; set; }

		internal void Run()
		{
			Action(Keyword);
		}
	}
	[BepInPlugin("atomic.terminalapi", "Terminal Api", "1.3.0")]
	public class Plugin : BaseUnityPlugin
	{
		public ManualLogSource Log = new ManualLogSource("Terminal Api");

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin TerminalApi is loaded!");
			Logger.Sources.Add((ILogSource)(object)Log);
			TerminalApi.plugin = this;
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		}
	}
	public static class TerminalApi
	{
		public static Plugin plugin;

		internal static List<DelayedAction> QueuedActions = new List<DelayedAction>();

		public static Terminal Terminal { get; internal set; }

		public static string CurrentText => Terminal.currentText;

		public static TMP_InputField ScreenText => Terminal.screenText;

		public static bool IsInGame()
		{
			try
			{
				return Terminal != null;
			}
			catch (NullReferenceException)
			{
				return false;
			}
		}

		public static void AddCommand(string commandWord, string displayText, string verbWord = null, bool clearPreviousText = true)
		{
			commandWord = commandWord.ToLower();
			TerminalKeyword val = CreateTerminalKeyword(commandWord);
			TerminalNode val2 = CreateTerminalNode(displayText, clearPreviousText);
			if (verbWord != null)
			{
				verbWord = verbWord.ToLower();
				TerminalKeyword terminalKeyword = CreateTerminalKeyword(verbWord, isVerb: true);
				AddTerminalKeyword(val.defaultVerb = terminalKeyword.AddCompatibleNoun(val, val2));
				AddTerminalKeyword(val);
			}
			else
			{
				val.specialKeywordResult = val2;
				AddTerminalKeyword(val);
			}
		}

		public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, TerminalNode triggeringNode = null)
		{
			TerminalKeyword obj = ScriptableObject.CreateInstance<TerminalKeyword>();
			obj.word = word.ToLower();
			obj.isVerb = isVerb;
			obj.specialKeywordResult = triggeringNode;
			return obj;
		}

		public static TerminalKeyword CreateTerminalKeyword(string word, string displayText, bool clearPreviousText = false, string terminalEvent = "")
		{
			TerminalKeyword obj = ScriptableObject.CreateInstance<TerminalKeyword>();
			obj.word = word.ToLower();
			obj.isVerb = false;
			obj.specialKeywordResult = CreateTerminalNode(displayText, clearPreviousText, terminalEvent);
			return obj;
		}

		public static TerminalNode CreateTerminalNode(string displayText, bool clearPreviousText = false, string terminalEvent = "")
		{
			TerminalNode obj = ScriptableObject.CreateInstance<TerminalNode>();
			obj.displayText = displayText;
			obj.clearPreviousText = clearPreviousText;
			obj.terminalEvent = terminalEvent;
			return obj;
		}

		public static void AddTerminalKeyword(TerminalKeyword terminalKeyword)
		{
			if (IsInGame())
			{
				if (GetKeyword(terminalKeyword.word) == null)
				{
					Terminal.terminalNodes.allKeywords = Terminal.terminalNodes.allKeywords.Add(terminalKeyword);
					plugin.Log.LogMessage((object)("Added " + terminalKeyword.word + " keyword to terminal keywords."));
				}
				else
				{
					plugin.Log.LogWarning((object)("Failed to add " + terminalKeyword.word + " keyword. Already exists."));
				}
			}
			else
			{
				plugin.Log.LogMessage((object)("Not in game, waiting to be in game to add " + terminalKeyword.word + " keyword."));
				Action<TerminalKeyword> action = AddTerminalKeyword;
				DelayedAction item = new DelayedAction
				{
					Action = action,
					Keyword = terminalKeyword
				};
				QueuedActions.Add(item);
			}
		}

		public static TerminalKeyword GetKeyword(string keyword)
		{
			if (IsInGame())
			{
				return ((IEnumerable<TerminalKeyword>)Terminal.terminalNodes.allKeywords).FirstOrDefault((Func<TerminalKeyword, bool>)((TerminalKeyword Kw) => Kw.word == keyword));
			}
			return null;
		}

		public static void UpdateKeyword(TerminalKeyword keyword)
		{
			if (!IsInGame())
			{
				return;
			}
			for (int i = 0; i < Terminal.terminalNodes.allKeywords.Length; i++)
			{
				if (Terminal.terminalNodes.allKeywords[i].word == keyword.word)
				{
					Terminal.terminalNodes.allKeywords[i] = keyword;
					return;
				}
			}
			plugin.Log.LogWarning((object)("Failed to update " + keyword.word + ". Was not found in keywords."));
		}

		public static void DeleteKeyword(string word)
		{
			if (!IsInGame())
			{
				return;
			}
			for (int i = 0; i < Terminal.terminalNodes.allKeywords.Length; i++)
			{
				if (Terminal.terminalNodes.allKeywords[i].word == word.ToLower())
				{
					int newSize = Terminal.terminalNodes.allKeywords.Length - 1;
					for (int j = i + 1; j < Terminal.terminalNodes.allKeywords.Length; j++)
					{
						Terminal.terminalNodes.allKeywords[j - 1] = Terminal.terminalNodes.allKeywords[j];
					}
					Array.Resize(ref Terminal.terminalNodes.allKeywords, newSize);
					plugin.Log.LogMessage((object)(word + " was deleted successfully."));
					return;
				}
			}
			plugin.Log.LogWarning((object)("Failed to delete " + word + ". Was not found in keywords."));
		}

		public static void UpdateKeywordCompatibleNoun(TerminalKeyword verbKeyword, string noun, TerminalNode newTriggerNode)
		{
			if (!IsInGame() || !verbKeyword.isVerb)
			{
				return;
			}
			for (int i = 0; i < verbKeyword.compatibleNouns.Length; i++)
			{
				CompatibleNoun val = verbKeyword.compatibleNouns[i];
				if (val.noun.word == noun)
				{
					val.result = newTriggerNode;
					UpdateKeyword(verbKeyword);
					return;
				}
			}
			plugin.Log.LogWarning((object)$"WARNING: No noun found for {verbKeyword}");
		}

		public static void UpdateKeywordCompatibleNoun(string verbWord, string noun, TerminalNode newTriggerNode)
		{
			if (!IsInGame())
			{
				return;
			}
			TerminalKeyword keyword = GetKeyword(verbWord);
			if (!keyword.isVerb || verbWord == null)
			{
				return;
			}
			for (int i = 0; i < keyword.compatibleNouns.Length; i++)
			{
				CompatibleNoun val = keyword.compatibleNouns[i];
				if (val.noun.word == noun)
				{
					val.result = newTriggerNode;
					UpdateKeyword(keyword);
					return;
				}
			}
			plugin.Log.LogWarning((object)$"WARNING: No noun found for {keyword}");
		}

		public static void UpdateKeywordCompatibleNoun(TerminalKeyword verbKeyword, string noun, string newDisplayText)
		{
			if (!IsInGame() || !verbKeyword.isVerb)
			{
				return;
			}
			for (int i = 0; i < verbKeyword.compatibleNouns.Length; i++)
			{
				CompatibleNoun val = verbKeyword.compatibleNouns[i];
				if (val.noun.word == noun)
				{
					val.result.displayText = newDisplayText;
					UpdateKeyword(verbKeyword);
					return;
				}
			}
			plugin.Log.LogWarning((object)$"WARNING: No noun found for {verbKeyword}");
		}

		public static void UpdateKeywordCompatibleNoun(string verbWord, string noun, string newDisplayText)
		{
			if (!IsInGame())
			{
				return;
			}
			TerminalKeyword keyword = GetKeyword(verbWord);
			if (!keyword.isVerb)
			{
				return;
			}
			for (int i = 0; i < keyword.compatibleNouns.Length; i++)
			{
				CompatibleNoun val = keyword.compatibleNouns[i];
				if (val.noun.word == noun)
				{
					val.result.displayText = newDisplayText;
					UpdateKeyword(keyword);
					return;
				}
			}
			plugin.Log.LogWarning((object)$"WARNING: No noun found for {keyword}");
		}

		public static void AddCompatibleNoun(TerminalKeyword verbKeyword, string noun, string displayText, bool clearPreviousText = false)
		{
			if (IsInGame())
			{
				TerminalKeyword keyword = GetKeyword(noun);
				verbKeyword = verbKeyword.AddCompatibleNoun(keyword, displayText, clearPreviousText);
				UpdateKeyword(verbKeyword);
			}
		}

		public static void AddCompatibleNoun(TerminalKeyword verbKeyword, string noun, TerminalNode triggerNode)
		{
			if (IsInGame())
			{
				TerminalKeyword keyword = GetKeyword(noun);
				verbKeyword = verbKeyword.AddCompatibleNoun(keyword, triggerNode);
				UpdateKeyword(verbKeyword);
			}
		}

		public static void AddCompatibleNoun(string verbWord, string noun, TerminalNode triggerNode)
		{
			if (IsInGame())
			{
				TerminalKeyword keyword = GetKeyword(verbWord);
				TerminalKeyword keyword2 = GetKeyword(noun);
				if ((Object)(object)keyword == (Object)null)
				{
					plugin.Log.LogWarning((object)"The verb given does not exist.");
					return;
				}
				keyword = keyword.AddCompatibleNoun(keyword2, triggerNode);
				UpdateKeyword(keyword);
			}
		}

		public static void AddCompatibleNoun(string verbWord, string noun, string displayText, bool clearPreviousText = false)
		{
			if (IsInGame())
			{
				TerminalKeyword keyword = GetKeyword(verbWord);
				TerminalKeyword keyword2 = GetKeyword(noun);
				if ((Object)(object)keyword == (Object)null)
				{
					plugin.Log.LogWarning((object)"The verb given does not exist.");
					return;
				}
				keyword = keyword.AddCompatibleNoun(keyword2, displayText, clearPreviousText);
				UpdateKeyword(keyword);
			}
		}

		public static string GetTerminalInput()
		{
			if (IsInGame())
			{
				return CurrentText.Substring(CurrentText.Length - Terminal.textAdded);
			}
			return "";
		}

		public static void SetTerminalInput(string terminalInput)
		{
			Terminal.TextChanged(CurrentText.Substring(0, CurrentText.Length - Terminal.textAdded) + terminalInput);
			ScreenText.text = CurrentText;
			Terminal.textAdded = terminalInput.Length;
		}
	}
	public static class TerminalExtenstionMethods
	{
		public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, TerminalKeyword noun, TerminalNode result)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (terminalKeyword.isVerb)
			{
				CompatibleNoun val = new CompatibleNoun
				{
					noun = noun,
					result = result
				};
				if (terminalKeyword.compatibleNouns == null)
				{
					terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val };
				}
				else
				{
					terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val);
				}
				return terminalKeyword;
			}
			return null;
		}

		public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, string noun, TerminalNode result)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			if (terminalKeyword.isVerb)
			{
				CompatibleNoun val = new CompatibleNoun
				{
					noun = TerminalApi.CreateTerminalKeyword(noun),
					result = result
				};
				if (terminalKeyword.compatibleNouns == null)
				{
					terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val };
				}
				else
				{
					terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val);
				}
				return terminalKeyword;
			}
			return null;
		}

		public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, string noun, string displayText)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			if (terminalKeyword.isVerb)
			{
				CompatibleNoun val = new CompatibleNoun
				{
					noun = TerminalApi.CreateTerminalKeyword(noun),
					result = TerminalApi.CreateTerminalNode(displayText)
				};
				if (terminalKeyword.compatibleNouns == null)
				{
					terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val };
				}
				else
				{
					terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val);
				}
				return terminalKeyword;
			}
			return null;
		}

		public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, TerminalKeyword noun, string displayText, bool clearPreviousText = false)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			if (terminalKeyword.isVerb)
			{
				CompatibleNoun val = new CompatibleNoun
				{
					noun = noun,
					result = TerminalApi.CreateTerminalNode(displayText, clearPreviousText)
				};
				if (terminalKeyword.compatibleNouns == null)
				{
					terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val };
				}
				else
				{
					terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val);
				}
				return terminalKeyword;
			}
			return null;
		}

		internal static T[] Add<T>(this T[] array, T newItem)
		{
			int num = array.Length + 1;
			Array.Resize(ref array, num);
			array[num - 1] = newItem;
			return array;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "TerminalApi";

		public const string PLUGIN_NAME = "TerminalApi";

		public const string PLUGIN_VERSION = "1.4.0";
	}
}
namespace TerminalApi.Events
{
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	public static class Events
	{
		public class TerminalEventArgs : EventArgs
		{
			public Terminal Terminal { get; set; }
		}

		public delegate void TerminalEventHandler(object sender, TerminalEventArgs e);

		public class TerminalParseSentenceEventArgs : TerminalEventArgs
		{
			public TerminalNode ReturnedNode { get; set; }

			public string SubmittedText { get; set; }
		}

		public delegate void TerminalParseSentenceEventHandler(object sender, TerminalParseSentenceEventArgs e);

		public class TerminalTextChangedEventArgs : TerminalEventArgs
		{
			public string NewText;

			public string CurrentInputText;
		}

		public delegate void TerminalTextChangedEventHandler(object sender, TerminalTextChangedEventArgs e);

		public static event TerminalEventHandler TerminalAwake;

		public static event TerminalEventHandler TerminalWaking;

		public static event TerminalEventHandler TerminalStarted;

		public static event TerminalEventHandler TerminalStarting;

		public static event TerminalEventHandler TerminalBeginUsing;

		public static event TerminalEventHandler TerminalBeganUsing;

		public static event TerminalEventHandler TerminalExited;

		public static event TerminalParseSentenceEventHandler TerminalParsedSentence;

		public static event TerminalTextChangedEventHandler TerminalTextChanged;

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		public static void Awake(ref Terminal __instance)
		{
			TerminalApi.Terminal = __instance;
			if (TerminalApi.QueuedActions.Count > 0)
			{
				TerminalApi.plugin.Log.LogMessage((object)"In game, now adding words.");
				foreach (DelayedAction queuedAction in TerminalApi.QueuedActions)
				{
					queuedAction.Run();
				}
				TerminalApi.QueuedActions.Clear();
			}
			Events.TerminalAwake?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("BeginUsingTerminal")]
		[HarmonyPostfix]
		public static void BeganUsing(ref Terminal __instance)
		{
			Events.TerminalBeganUsing?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("QuitTerminal")]
		[HarmonyPostfix]
		public static void OnQuitTerminal(ref Terminal __instance)
		{
			Events.TerminalExited?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("BeginUsingTerminal")]
		[HarmonyPrefix]
		public static void OnBeginUsing(ref Terminal __instance)
		{
			Events.TerminalBeginUsing?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("ParsePlayerSentence")]
		[HarmonyPostfix]
		public static void ParsePlayerSentence(ref Terminal __instance, TerminalNode __result)
		{
			string submittedText = __instance.screenText.text.Substring(__instance.screenText.text.Length - __instance.textAdded);
			Events.TerminalParsedSentence?.Invoke(__instance, new TerminalParseSentenceEventArgs
			{
				Terminal = __instance,
				SubmittedText = submittedText,
				ReturnedNode = __result
			});
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void Started(ref Terminal __instance)
		{
			Events.TerminalStarted?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		public static void Starting(ref Terminal __instance)
		{
			Events.TerminalStarting?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

		[HarmonyPatch("TextChanged")]
		[HarmonyPostfix]
		public static void OnTextChanged(ref Terminal __instance, string newText)
		{
			string currentInputText = "";
			if (newText.Trim().Length >= __instance.textAdded)
			{
				currentInputText = newText.Substring(newText.Length - __instance.textAdded);
			}
			Events.TerminalTextChanged?.Invoke(__instance, new TerminalTextChangedEventArgs
			{
				Terminal = __instance,
				NewText = newText,
				CurrentInputText = currentInputText
			});
		}

		[HarmonyPatch("Awake")]
		[HarmonyPrefix]
		public static void Waking(ref Terminal __instance)
		{
			Events.TerminalWaking?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}
	}
}

BepInEx/plugins/TooManySuits.dll

Decompiled 7 months ago
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MoreSuits;
using TMPro;
using TooManySuits.Helper;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("TooManySuits")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("TooManySuits")]
[assembly: AssemblyTitle("TooManySuits")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace TooManySuits
{
	[BepInPlugin("verity.TooManySuits", "Too Many Suits", "1.0.4")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static ManualLogSource LogSource;

		public static ConfigEntry<string> NextButton;

		public static ConfigEntry<string> BackButton;

		public static ConfigEntry<float> TextScale;

		private void Awake()
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			LogSource = ((BaseUnityPlugin)this).Logger;
			NextButton = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Next-Page-Keybind", "<Keyboard>/n", "Next page button.");
			BackButton = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Back-Page-Keybind", "<Keyboard>/b", "Back page button.");
			TextScale = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Text-Scale", 0.003f, "Size of the text above the suit rack.");
			GameObject val = new GameObject("TooManySuits");
			val.AddComponent<PluginLoader>();
			((Object)val).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)val);
		}
	}
	public class PluginLoader : MonoBehaviour
	{
		private class Hooks
		{
			public static bool SetUI;

			public static GameObject SuitPanel;

			public static void HookStartGame()
			{
				Plugin.LogSource.LogInfo((object)"StartOfRound!");
				Object.Instantiate<GameObject>(suitSelectBundle.LoadAsset<GameObject>("SuitSelect"));
				SuitPanel = GameObject.Find("SuitPanel");
				SuitPanel.SetActive(false);
				SetUI = true;
			}
		}

		private readonly Harmony Harmony = new Harmony("TooManySuits");

		private InputAction moveRightAction;

		private InputAction moveLeftAction;

		private int currentPage;

		private int suitsPerPage = 13;

		private int suitsLength;

		private UnlockableSuit[] allSuits;

		private static AssetBundle suitSelectBundle;

		private void Awake()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected O, but got Unknown
			Plugin.LogSource.LogInfo((object)"TooManySuits Mod Loaded.");
			moveRightAction = new InputAction((string)null, (InputActionType)0, Plugin.NextButton.Value, (string)null, (string)null, (string)null);
			moveRightAction.performed += MoveRightAction;
			moveRightAction.Enable();
			moveLeftAction = new InputAction((string)null, (InputActionType)0, Plugin.BackButton.Value, (string)null, (string)null, (string)null);
			moveLeftAction.performed += MoveLeftAction;
			moveLeftAction.Enable();
			MethodInfo method = typeof(StartOfRound).GetMethod("Start", BindingFlags.Instance | BindingFlags.NonPublic);
			MethodInfo method2 = typeof(Hooks).GetMethod("HookStartGame");
			Harmony.Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo method3 = typeof(PlayerControllerB).GetMethod("Start", BindingFlags.Instance | BindingFlags.NonPublic);
			MethodInfo method4 = typeof(LocalPlayer).GetMethod("PlayerControllerStart");
			Harmony.Patch((MethodBase)method3, (HarmonyMethod)null, new HarmonyMethod(method4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			suitSelectBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "suitselect"));
			if (MoreSuitsMod.MakeSuitsFitOnRack)
			{
				suitsPerPage = 20;
			}
		}

		private void Update()
		{
			if (!((Object)(object)StartOfRound.Instance == (Object)null))
			{
				allSuits = (from suit in Resources.FindObjectsOfTypeAll<UnlockableSuit>()
					orderby suit.syncedSuitID.Value
					select suit).ToArray();
				DisplaySuits();
			}
		}

		private void DisplaySuits()
		{
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			if (allSuits.Length == 0)
			{
				return;
			}
			int num = currentPage * suitsPerPage;
			int num2 = Mathf.Min(num + suitsPerPage, allSuits.Length);
			int num3 = 0;
			for (int i = 0; i < allSuits.Length; i++)
			{
				UnlockableSuit val = allSuits[i];
				AutoParentToShip component = ((Component)val).gameObject.GetComponent<AutoParentToShip>();
				if ((Object)(object)component == (Object)null)
				{
					continue;
				}
				bool flag = i >= num && i < num2;
				((Component)val).gameObject.SetActive(flag);
				if (flag)
				{
					component.overrideOffset = true;
					if (MoreSuitsMod.MakeSuitsFitOnRack && suitsLength > 13)
					{
						float num4 = 0.18f;
						num4 /= (float)Math.Min(suitsLength, 20) / 12f;
						component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + StartOfRound.Instance.rightmostSuitPosition.forward * (num4 * (float)num3);
						component.rotationOffset = new Vector3(0f, 90f, 0f);
					}
					else
					{
						component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + StartOfRound.Instance.rightmostSuitPosition.forward * (0.18f * (float)num3);
						component.rotationOffset = new Vector3(0f, 90f, 0f);
					}
					num3++;
				}
			}
			suitsLength = allSuits.Length;
			if (!LocalPlayer.isActive())
			{
				return;
			}
			if (LocalPlayer.localPlayer.isInHangarShipRoom)
			{
				((TMP_Text)Hooks.SuitPanel.GetComponentInChildren<TextMeshProUGUI>()).text = $"Page {currentPage + 1}/{suitsLength / suitsPerPage + 1}";
				Hooks.SuitPanel.SetActive(true);
				return;
			}
			Hooks.SuitPanel.SetActive(false);
			if (Hooks.SetUI)
			{
				Hooks.SetUI = false;
				Hooks.SuitPanel.GetComponentInParent<Canvas>().renderMode = (RenderMode)2;
				Hooks.SuitPanel.GetComponentInParent<Canvas>().worldCamera = LocalPlayer.localPlayer.gameplayCamera;
				Transform transform = Hooks.SuitPanel.transform;
				Bounds bounds = StartOfRound.Instance.shipBounds.bounds;
				transform.position = ((Bounds)(ref bounds)).center - new Vector3(2.8992f, 0.7998f, 2f);
				Hooks.SuitPanel.transform.rotation = Quaternion.Euler(0f, 180f, 0f);
				Hooks.SuitPanel.transform.localScale = new Vector3(Plugin.TextScale.Value, Plugin.TextScale.Value, Plugin.TextScale.Value);
				Hooks.SuitPanel.SetActive(true);
			}
		}

		private void MoveRightAction(CallbackContext obj)
		{
			currentPage = Mathf.Min(currentPage + 1, Mathf.CeilToInt((float)suitsLength / (float)suitsPerPage) - 1);
		}

		private void MoveLeftAction(CallbackContext obj)
		{
			currentPage = Mathf.Max(currentPage - 1, 0);
		}
	}
}
namespace TooManySuits.Helper
{
	public class LocalPlayer
	{
		public static PlayerControllerB localPlayer;

		public static bool isActive()
		{
			return (Object)(object)localPlayer != (Object)null;
		}

		public static void PlayerControllerStart(PlayerControllerB __instance)
		{
			if (NetworkManager.Singleton.LocalClientId == __instance.playerClientId)
			{
				localPlayer = __instance;
			}
		}
	}
}

BepInEx/plugins/YippeeMod.dll

Decompiled 7 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using YippeeMod.Patches;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("YippeeMod")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("YippeeMod")]
[assembly: AssemblyTitle("YippeeMod")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace YippeeMod
{
	[BepInPlugin("sunnobunno.YippeeMod", "Yippee tbh mod", "1.2.2")]
	public class YippeeModBase : BaseUnityPlugin
	{
		private const string modGUID = "sunnobunno.YippeeMod";

		private const string modName = "Yippee tbh mod";

		private const string modVersion = "1.2.2";

		private readonly Harmony harmony = new Harmony("sunnobunno.YippeeMod");

		private static YippeeModBase? Instance;

		internal ManualLogSource? mls;

		internal static AudioClip[]? newSFX;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("sunnobunno.YippeeMod");
			mls.LogInfo((object)"sunnobunno.YippeeMod is loading.");
			string location = ((BaseUnityPlugin)Instance).Info.Location;
			string text = "YippeeMod.dll";
			string text2 = location.TrimEnd(text.ToCharArray());
			string text3 = text2 + "yippeesound";
			AssetBundle val = AssetBundle.LoadFromFile(text3);
			if ((Object)(object)val == (Object)null)
			{
				mls.LogError((object)"Failed to load audio assets!");
				return;
			}
			newSFX = val.LoadAssetWithSubAssets<AudioClip>("assets/yippee-tbh.mp3");
			harmony.PatchAll(typeof(HoarderBugPatch));
			mls.LogInfo((object)"sunnobunno.YippeeMod is loaded. Yippee!!!");
		}
	}
}
namespace YippeeMod.Patches
{
	[HarmonyPatch(typeof(HoarderBugAI))]
	internal class HoarderBugPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void hoarderBugAudioPatch(ref AudioClip[] ___chitterSFX)
		{
			AudioClip[] newSFX = YippeeModBase.newSFX;
			___chitterSFX = newSFX;
		}
	}
}

BepInEx/plugins/YoutubeBoombox.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("YoutubeBoombox")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("YoutubeBoombox")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("50a0e49b-1441-46da-9fbf-11bd9a8df0fd")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
internal class <Module>
{
	static <Module>()
	{
	}
}
public sealed class HttpUtility
{
	private sealed class HttpQSCollection : NameValueCollection
	{
		public override string ToString()
		{
			int count = Count;
			if (count == 0)
			{
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder();
			string[] allKeys = AllKeys;
			for (int i = 0; i < count; i++)
			{
				stringBuilder.AppendFormat("{0}={1}&", allKeys[i], UrlEncode(base[allKeys[i]]));
			}
			if (stringBuilder.Length > 0)
			{
				stringBuilder.Length--;
			}
			return stringBuilder.ToString();
		}
	}

	public class HttpEncoder
	{
		private static char[] hexChars;

		private static object entitiesLock;

		private static SortedDictionary<string, char> entities;

		private static Lazy<HttpEncoder> defaultEncoder;

		private static Lazy<HttpEncoder> currentEncoderLazy;

		private static HttpEncoder currentEncoder;

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

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

		public static HttpEncoder Default => defaultEncoder.Value;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	public interface IHtmlString
	{
		string ToHtmlString();
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		public float Progress { get; }

		public string TotalDownloadSize { get; }

		public string DownloadSpeed { get; }

		public string ETA { get; }

		public int VideoIndex { get; }

		public string Data { get; }

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

		public string[] ErrorOutput { get; }

		public T Data { get; }

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

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

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

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

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

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

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

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

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

		private static readonly HttpClient _client = new HttpClient();

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

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

		public static string YtDlpBinaryName => GetYtDlpBinaryName();

		public static string FfmpegBinaryName => GetFfmpegBinaryName();

		public static string FfprobeBinaryName => GetFfprobeBinaryName();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		protected ProcessRunner runner;

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


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


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


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


		public bool RestrictFilenames { get; set; }

		public bool OverwriteFiles { get; set; } = true;


		public bool IgnoreDownloadErrors { get; set; } = true;


		public string Version => FileVersionInfo.GetVersionInfo(Utils.GetFullPath(YoutubeDLPath)).FileVersion;

		public YoutubeDL(byte maxNumberOfProcesses = 4)
		{
			runner = new ProcessRunner(maxNumberOfProcesses);
		}

		public async Task SetMaxNumberOfProcesses(byte count)
		{
			await runner.SetTotalCount(count);
		}

		public async Task<RunResult<string[]>> RunWithOptions(string[] urls, OptionSet options, CancellationToken ct)
		{
			List<string> output = new List<string>();
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				output.Add(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, urls, options, ct);
			return new RunResult<string[]>(num == 0, error, output.ToArray());
		}

		public async Task<RunResult<string>> RunWithOptions(string url, OptionSet options, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, bool showArgs = true)
		{
			string outFile = string.Empty;
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			if (showArgs)
			{
				output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, options) + "\n");
			}
			else
			{
				output?.Report("Starting Download: " + url);
			}
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				Match match = rgxFilePostProc.Match(e.Data);
				if (match.Success)
				{
					outFile = match.Groups[0].ToString().Replace("[download] Destination:", "").Replace(" ", "");
					progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outFile));
				}
				output?.Report(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, options, ct, progress);
			return new RunResult<string>(num == 0, error, outFile);
		}

		public async Task<string> RunUpdate()
		{
			string output = string.Empty;
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				output = e.Data;
			};
			await youtubeDLProcess.RunAsync(null, new OptionSet
			{
				Update = true
			});
			return output;
		}

		public async Task<RunResult<VideoData>> RunVideoDataFetch(string url, CancellationToken ct = default(CancellationToken), bool flat = true, bool fetchComments = false, OptionSet overrideOptions = null)
		{
			OptionSet optionSet = GetDownloadOptions();
			optionSet.DumpSingleJson = true;
			optionSet.FlatPlaylist = flat;
			optionSet.WriteComments = fetchComments;
			if (overrideOptions != null)
			{
				optionSet = optionSet.OverrideOptions(overrideOptions);
			}
			VideoData videoData = null;
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				videoData = JsonConvert.DeserializeObject<VideoData>(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct);
			return new RunResult<VideoData>(num == 0, error, videoData);
		}

		public async Task<RunResult<string>> RunVideoDownload(string url, string format = "bestvideo+bestaudio/best", DownloadMergeFormat mergeFormat = DownloadMergeFormat.Unspecified, VideoRecodeFormat recodeFormat = VideoRecodeFormat.None, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null)
		{
			OptionSet optionSet = GetDownloadOptions();
			optionSet.Format = format;
			optionSet.MergeOutputFormat = mergeFormat;
			optionSet.RecodeVideo = recodeFormat;
			if (overrideOptions != null)
			{
				optionSet = optionSet.OverrideOptions(overrideOptions);
			}
			string outputFile = string.Empty;
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n");
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				Match match = rgxFile.Match(e.Data);
				if (match.Success)
				{
					outputFile = match.Groups[1].ToString().Trim(new char[1] { '"' });
					progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outputFile));
				}
				output?.Report(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress);
			return new RunResult<string>(num == 0, error, outputFile);
		}

		public async Task<RunResult<string[]>> RunVideoPlaylistDownload(string url, int? start = 1, int? end = null, int[] items = null, string format = "bestvideo+bestaudio/best", VideoRecodeFormat recodeFormat = VideoRecodeFormat.None, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null)
		{
			OptionSet optionSet = GetDownloadOptions();
			optionSet.NoPlaylist = false;
			optionSet.PlaylistStart = start;
			optionSet.PlaylistEnd = end;
			if (items != null)
			{
				optionSet.PlaylistItems = string.Join(",", items);
			}
			optionSet.Format = format;
			optionSet.RecodeVideo = recodeFormat;
			if (overrideOptions != null)
			{
				optionSet = optionSet.OverrideOptions(overrideOptions);
			}
			List<string> outputFiles = new List<string>();
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n");
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				Match match = rgxFile.Match(e.Data);
				if (match.Success)
				{
					string text = match.Groups[1].ToString().Trim(new char[1] { '"' });
					outputFiles.Add(text);
					progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, text));
				}
				output?.Report(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress);
			return new RunResult<string[]>(num == 0, error, outputFiles.ToArray());
		}

		public async Task<RunResult<string>> RunAudioDownload(string url, AudioConversionFormat format = AudioConversionFormat.Best, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null)
		{
			OptionSet optionSet = GetDownloadOptions();
			optionSet.Format = "bestaudio/best";
			optionSet.ExtractAudio = true;
			optionSet.AudioFormat = format;
			if (overrideOptions != null)
			{
				optionSet = optionSet.OverrideOptions(overrideOptions);
			}
			string outputFile = string.Empty;
			new List<string>();
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n");
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				Match match = rgxFile.Match(e.Data);
				if (match.Success)
				{
					outputFile = match.Groups[1].ToString().Trim(new char[1] { '"' });
					progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outputFile));
				}
				output?.Report(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress);
			return new RunResult<string>(num == 0, error, outputFile);
		}

		public async Task<RunResult<string[]>> RunAudioPlaylistDownload(string url, int? start = 1, int? end = null, int[] items = null, AudioConversionFormat format = AudioConversionFormat.Best, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null)
		{
			List<string> outputFiles = new List<string>();
			OptionSet optionSet = GetDownloadOptions();
			optionSet.NoPlaylist = false;
			optionSet.PlaylistStart = start;
			optionSet.PlaylistEnd = end;
			if (items != null)
			{
				optionSet.PlaylistItems = string.Join(",", items);
			}
			optionSet.Format = "bestaudio/best";
			optionSet.ExtractAudio = true;
			optionSet.AudioFormat = format;
			if (overrideOptions != null)
			{
				optionSet = optionSet.OverrideOptions(overrideOptions);
			}
			YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath);
			output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n");
			youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e)
			{
				Match match = rgxFile.Match(e.Data);
				if (match.Success)
				{
					string text = match.Groups[1].ToString().Trim(new char[1] { '"' });
					outputFiles.Add(text);
					progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, text));
				}
				output?.Report(e.Data);
			};
			var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress);
			return new RunResult<string[]>(num == 0, error, outputFiles.ToArray());
		}

		protected virtual OptionSet GetDownloadOptions()
		{
			return new OptionSet
			{
				IgnoreErrors = IgnoreDownloadErrors,
				IgnoreConfig = true,
				NoPlaylist = true,
				Downloader = "m3u8:native",
				DownloaderArgs = "ffmpeg:-nostats -loglevel 0",
				Output = Path.Combine(OutputFolder, OutputFileTemplate),
				RestrictFilenames = RestrictFilenames,
				ForceOverwrites = OverwriteFiles,
				NoOverwrites = !OverwriteFiles,
				NoPart = true,
				FfmpegLocation = Utils.GetFullPath(FFmpegPath),
				Exec = "echo outfile: {}"
			};
		}
	}
	public class YoutubeDLProcess
	{
		private static readonly Regex rgxPlaylist = new Regex("Downloading video (\\d+) of (\\d+)", RegexOptions.Compiled);

		private static readonly Regex rgxProgress = new Regex("\\[download\\]\\s+(?:(?<percent>[\\d\\.]+)%(?:\\s+of\\s+\\~?\\s*(?<total>[\\d\\.\\w]+))?\\s+at\\s+(?:(?<speed>[\\d\\.\\w]+\\/s)|[\\w\\s]+)\\s+ETA\\s(?<eta>[\\d\\:]+))?", RegexOptions.Compiled);

		private static readonly Regex rgxPost = new Regex("\\[(\\w+)\\]\\s+", RegexOptions.Compiled);

		public string PythonPath { get; set; }

		public string ExecutablePath { get; set; }

		public bool UseWindowsEncodingWorkaround { get; set; } = true;


		public event EventHandler<DataReceivedEventArgs> OutputReceived;

		public event EventHandler<DataReceivedEventArgs> ErrorReceived;

		public YoutubeDLProcess(string executablePath = "yt-dlp.exe")
		{
			ExecutablePath = executablePath;
		}

		internal string ConvertToArgs(string[] urls, OptionSet options)
		{
			return ((urls != null) ? string.Join(" ", urls.Select((string s) => "\"" + s + "\"")) : string.Empty) + options.ToString();
		}

		public async Task<int> RunAsync(string[] urls, OptionSet options)
		{
			return await RunAsync(urls, options, CancellationToken.None);
		}

		public async Task<int> RunAsync(string[] urls, OptionSet options, CancellationToken ct, IProgress<DownloadProgress> progress = null)
		{
			TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
			Process process = new Process();
			ProcessStartInfo processStartInfo = new ProcessStartInfo
			{
				CreateNoWindow = true,
				UseShellExecute = false,
				RedirectStandardOutput = true,
				RedirectStandardError = true,
				StandardOutputEncoding = Encoding.UTF8,
				StandardErrorEncoding = Encoding.UTF8
			};
			if (OSHelper.IsWindows && UseWindowsEncodingWorkaround)
			{
				processStartInfo.FileName = "cmd.exe";
				string text = (string.IsNullOrEmpty(PythonPath) ? ("\"" + ExecutablePath + "\" " + ConvertToArgs(urls, options)) : (PythonPath + " \"" + ExecutablePath + "\" " + ConvertToArgs(urls, options)));
				processStartInfo.Arguments = "/C chcp 65001 >nul 2>&1 && " + text;
			}
			else if (!string.IsNullOrEmpty(PythonPath))
			{
				processStartInfo.FileName = PythonPath;
				processStartInfo.Arguments = "\"" + ExecutablePath + "\" " + ConvertToArgs(urls, options);
			}
			else
			{
				processStartInfo.FileName = ExecutablePath;
				processStartInfo.Arguments = ConvertToArgs(urls, options);
			}
			process.EnableRaisingEvents = true;
			process.StartInfo = processStartInfo;
			TaskCompletionSource<bool> tcsOut = new TaskCompletionSource<bool>();
			bool isDownloading = false;
			process.OutputDataReceived += delegate(object o, DataReceivedEventArgs e)
			{
				if (e.Data == null)
				{
					tcsOut.SetResult(result: true);
				}
				else
				{
					Match match;
					if ((match = rgxProgress.Match(e.Data)).Success)
					{
						if (match.Groups.Count > 1 && match.Groups[1].Length > 0)
						{
							float progress2 = float.Parse(match.Groups[1].ToString(), CultureInfo.InvariantCulture) / 100f;
							Group group = match.Groups["total"];
							string totalDownloadSize = (group.Success ? group.Value : null);
							Group group2 = match.Groups["speed"];
							string downloadSpeed = (group2.Success ? group2.Value : null);
							Group group3 = match.Groups["eta"];
							string eta = (group3.Success ? group3.Value : null);
							progress?.Report(new DownloadProgress(DownloadState.Downloading, progress2, totalDownloadSize, downloadSpeed, eta));
						}
						else
						{
							progress?.Report(new DownloadProgress(DownloadState.Downloading));
						}
						isDownloading = true;
					}
					else if ((match = rgxPlaylist.Match(e.Data)).Success)
					{
						int index = int.Parse(match.Groups[1].Value);
						progress?.Report(new DownloadProgress(DownloadState.PreProcessing, 0f, null, null, null, index));
						isDownloading = false;
					}
					else if (isDownloading && (match = rgxPost.Match(e.Data)).Success)
					{
						progress?.Report(new DownloadProgress(DownloadState.PostProcessing, 1f));
						isDownloading = false;
					}
					this.OutputReceived?.Invoke(this, e);
				}
			};
			TaskCompletionSource<bool> tcsError = new TaskCompletionSource<bool>();
			process.ErrorDataReceived += delegate(object o, DataReceivedEventArgs e)
			{
				if (e.Data == null)
				{
					tcsError.SetResult(result: true);
				}
				else
				{
					progress?.Report(new DownloadProgress(DownloadState.Error, 0f, null, null, null, 1, e.Data));
					this.ErrorReceived?.Invoke(this, e);
				}
			};
			process.Exited += async delegate
			{
				await tcsOut.Task;
				await tcsError.Task;
				tcs.TrySetResult(process.ExitCode);
				process.Dispose();
			};
			ct.Register(delegate
			{
				if (!tcs.Task.IsCompleted)
				{
					tcs.TrySetCanceled();
				}
				try
				{
					if (!process.HasExited)
					{
						process.KillTree();
					}
				}
				catch
				{
				}
			});
			if (!(await Task.Run(() => process.Start())))
			{
				tcs.TrySetException(new InvalidOperationException("Failed to start yt-dlp process."));
			}
			process.BeginOutputReadLine();
			process.BeginErrorReadLine();
			progress?.Report(new DownloadProgress(DownloadState.PreProcessing));
			return await tcs.Task;
		}
	}
}
namespace YoutubeDLSharp.Options
{
	public enum DownloadMergeFormat
	{
		Unspecified,
		Mp4,
		Mkv,
		Ogg,
		Webm,
		Flv
	}
	public enum AudioConversionFormat
	{
		Best,
		Aac,
		Flac,
		Mp3,
		M4a,
		Opus,
		Vorbis,
		Wav
	}
	public enum VideoRecodeFormat
	{
		None,
		Mp4,
		Mkv,
		Ogg,
		Webm,
		Flv,
		Avi
	}
	public interface IOption
	{
		string DefaultOptionString { get; }

		string[] OptionStrings { get; }

		bool IsSet { get; }

		bool IsCustom { get; }

		void SetFromString(string s);

		IEnumerable<string> ToStringCollection();
	}
	public class MultiOption<T> : IOption
	{
		private MultiValue<T> value;

		public string DefaultOptionString => OptionStrings.Last();

		public string[] OptionStrings { get; }

		public bool IsSet { get; private set; }

		public bool IsCustom { get; }

		public MultiValue<T> Value
		{
			get
			{
				return value;
			}
			set
			{
				IsSet = !object.Equals(value, default(T));
				this.value = value;
			}
		}

		public MultiOption(params string[] optionStrings)
		{
			OptionStrings = optionStrings;
			IsSet = false;
		}

		public MultiOption(bool isCustom, params string[] optionStrings)
		{
			OptionStrings = optionStrings;
			IsSet = false;
			IsCustom = isCustom;
		}

		public void SetFromString(string s)
		{
			string[] array = s.Split(new char[1] { ' ' });
			string stringValue = s.Substring(array[0].Length).Trim().Trim(new char[1] { '"' });
			if (!OptionStrings.Contains(array[0]))
			{
				throw new ArgumentException("Given string does not match required format.");
			}
			T val = Utils.OptionValueFromString<T>(stringValue);
			if (!IsSet)
			{
				Value = val;
			}
			else
			{
				Value.Values.Add(val);
			}
		}

		public override string ToString()
		{
			return string.Join(" ", ToStringCollection());
		}

		public IEnumerable<string> ToStringCollection()
		{
			if (!IsSet)
			{
				return new string[1] { "" };
			}
			List<string> list = new List<string>();
			foreach (T value in Value.Values)
			{
				list.Add(DefaultOptionString + Utils.OptionValueToString(value));
			}
			return list;
		}
	}
	public class MultiValue<T>
	{
		private readonly List<T> values;

		public List<T> Values => values;

		public MultiValue(params T[] values)
		{
			this.values = values.ToList();
		}

		public static implicit operator MultiValue<T>(T value)
		{
			return new MultiValue<T>(value);
		}

		public static implicit operator MultiValue<T>(T[] values)
		{
			return new MultiValue<T>(values);
		}

		public static explicit operator T(MultiValue<T> value)
		{
			if (value.Values.Count == 1)
			{
				return value.Values[0];
			}
			throw new InvalidCastException($"Cannot cast sequence of values to {typeof(T)}.");
		}

		public static explicit operator T[](MultiValue<T> value)
		{
			return value.Values.ToArray();
		}
	}
	public class Option<T> : IOption
	{
		private T value;

		public string DefaultOptionString => OptionStrings.Last();

		public string[] OptionStrings { get; }

		public bool IsSet { get; private set; }

		public T Value
		{
			get
			{
				return value;
			}
			set
			{
				IsSet = !object.Equals(value, default(T));
				this.value = value;
			}
		}

		public bool IsCustom { get; }

		public Option(params string[] optionStrings)
		{
			OptionStrings = optionStrings;
			IsSet = false;
		}

		public Option(bool isCustom, params string[] optionStrings)
		{
			OptionStrings = optionStrings;
			IsSet = false;
			IsCustom = isCustom;
		}

		public void SetFromString(string s)
		{
			string[] array = s.Split(new char[1] { ' ' });
			string stringValue = s.Substring(array[0].Length).Trim().Trim(new char[1] { '"' });
			if (!OptionStrings.Contains(array[0]))
			{
				throw new ArgumentException("Given string does not match required format.");
			}
			Value = Utils.OptionValueFromString<T>(stringValue);
		}

		public override string ToString()
		{
			if (!IsSet)
			{
				return string.Empty;
			}
			string text = Utils.OptionValueToString(Value);
			return DefaultOptionString + text;
		}

		public IEnumerable<string> ToStringCollection()
		{
			return new string[1] { ToString() };
		}
	}
	internal class OptionComparer : IEqualityComparer<IOption>
	{
		public bool Equals(IOption x, IOption y)
		{
			if (x != null)
			{
				if (y != null)
				{
					return x.ToString().Equals(y.ToString());
				}
				return false;
			}
			return y == null;
		}

		public int GetHashCode(IOption obj)
		{
			return obj.ToString().GetHashCode();
		}
	}
	public class OptionSet : ICloneable
	{
		private Option<string> username = new Option<string>("-u", "--username");

		private Option<string> password = new Option<string>("-p", "--password");

		private Option<string> twoFactor = new Option<string>("-2", "--twofactor");

		private Option<bool> netrc = new Option<bool>("-n", "--netrc");

		private Option<string> netrcLocation = new Option<string>("--netrc-location");

		private Option<string> videoPassword = new Option<string>("--video-password");

		private Option<string> apMso = new Option<string>("--ap-mso");

		private Option<string> apUsername = new Option<string>("--ap-username");

		private Option<string> apPassword = new Option<string>("--ap-password");

		private Option<bool> apListMso = new Option<bool>("--ap-list-mso");

		private Option<string> clientCertificate = new Option<string>("--client-certificate");

		private Option<string> clientCertificateKey = new Option<string>("--client-certificate-key");

		private Option<string> clientCertificatePassword = new Option<string>("--client-certificate-password");

		private static readonly OptionComparer Comparer = new OptionComparer();

		public static readonly OptionSet Default = new OptionSet();

		private Option<bool> getDescription = new Option<bool>("--get-description");

		private Option<bool> getDuration = new Option<bool>("--get-duration");

		private Option<bool> getFilename = new Option<bool>("--get-filename");

		private Option<bool> getFormat = new Option<bool>("--get-format");

		private Option<bool> getId = new Option<bool>("--get-id");

		private Option<bool> getThumbnail = new Option<bool>("--get-thumbnail");

		private Option<bool> getTitle = new Option<bool>("-e", "--get-title");

		private Option<bool> getUrl = new Option<bool>("-g", "--get-url");

		private Option<string> matchTitle = new Option<string>("--match-title");

		private Option<string> rejectTitle = new Option<string>("--reject-title");

		private Option<long?> minViews = new Option<long?>("--min-views");

		private Option<long?> maxViews = new Option<long?>("--max-views");

		private Option<string> userAgent = new Option<string>("--user-agent");

		private Option<string> referer = new Option<string>("--referer");

		private Option<int?> playlistStart = new Option<int?>("--playlist-start");

		private Option<int?> playlistEnd = new Option<int?>("--playlist-end");

		private Option<bool> playlistReverse = new Option<bool>("--playlist-reverse");

		private Option<bool> forceGenericExtractor = new Option<bool>("--force-generic-extractor");

		private Option<string> execBeforeDownload = new Option<string>("--exec-before-download");

		private Option<bool> noExecBeforeDownload = new Option<bool>("--no-exec-before-download");

		private Option<bool> allFormats = new Option<bool>("--all-formats");

		private Option<bool> allSubs = new Option<bool>("--all-subs");

		private Option<bool> printJson = new Option<bool>("--print-json");

		private Option<string> autonumberSize = new Option<string>("--autonumber-size");

		private Option<int?> autonumberStart = new Option<int?>("--autonumber-start");

		private Option<bool> id = new Option<bool>("--id");

		private Option<string> metadataFromTitle = new Option<string>("--metadata-from-title");

		private Option<bool> hlsPreferNative = new Option<bool>("--hls-prefer-native");

		private Option<bool> hlsPreferFfmpeg = new Option<bool>("--hls-prefer-ffmpeg");

		private Option<bool> listFormatsOld = new Option<bool>("--list-formats-old");

		private Option<bool> listFormatsAsTable = new Option<bool>("--list-formats-as-table");

		private Option<bool> youtubeSkipDashManifest = new Option<bool>("--youtube-skip-dash-manifest");

		private Option<bool> youtubeSkipHlsManifest = new Option<bool>("--youtube-skip-hls-manifest");

		private Option<int?> concurrentFragments = new Option<int?>("-N", "--concurrent-fragments");

		private Option<long?> limitRate = new Option<long?>("-r", "--limit-rate");

		private Option<long?> throttledRate = new Option<long?>("--throttled-rate");

		private Option<int?> retries = new Option<int?>("-R", "--retries");

		private Option<int?> fileAccessRetries = new Option<int?>("--file-access-retries");

		private Option<int?> fragmentRetries = new Option<int?>("--fragment-retries");

		private MultiOption<string> retrySleep = new MultiOption<string>("--retry-sleep");

		private Option<bool> skipUnavailableFragments = new Option<bool>("--skip-unavailable-fragments");

		private Option<bool> abortOnUnavailableFragment = new Option<bool>("--abort-on-unavailable-fragment");

		private Option<bool> keepFragments = new Option<bool>("--keep-fragments");

		private Option<bool> noKeepFragments = new Option<bool>("--no-keep-fragments");

		private Option<long?> bufferSize = new Option<long?>("--buffer-size");

		private Option<bool> resizeBuffer = new Option<bool>("--resize-buffer");

		private Option<bool> noResizeBuffer = new Option<bool>("--no-resize-buffer");

		private Option<long?> httpChunkSize = new Option<long?>("--http-chunk-size");

		private Option<bool> playlistRandom = new Option<bool>("--playlist-random");

		private Option<bool> lazyPlaylist = new Option<bool>("--lazy-playlist");

		private Option<bool> noLazyPlaylist = new Option<bool>("--no-lazy-playlist");

		private Option<bool> xattrSetFilesize = new Option<bool>("--xattr-set-filesize");

		private Option<bool> hlsUseMpegts = new Option<bool>("--hls-use-mpegts");

		private Option<bool> noHlsUseMpegts = new Option<bool>("--no-hls-use-mpegts");

		private MultiOption<string> downloadSections = new MultiOption<string>("--download-sections");

		private MultiOption<string> downloader = new MultiOption<string>("--downloader", "--external-downloader");

		private MultiOption<string> downloaderArgs = new MultiOption<string>("--downloader-args", "--external-downloader-args");

		private Option<int?> extractorRetries = new Option<int?>("--extractor-retries");

		private Option<bool> allowDynamicMpd = new Option<bool>("--allow-dynamic-mpd");

		private Option<bool> ignoreDynamicMpd = new Option<bool>("--ignore-dynamic-mpd");

		private Option<bool> hlsSplitDiscontinuity = new Option<bool>("--hls-split-discontinuity");

		private Option<bool> noHlsSplitDiscontinuity = new Option<bool>("--no-hls-split-discontinuity");

		private MultiOption<string> extractorArgs = new MultiOption<string>("--extractor-args");

		private Option<string> batchFile = new Option<string>("-a", "--batch-file");

		private Option<bool> noBatchFile = new Option<bool>("--no-batch-file");

		private Option<string> paths = new Option<string>("-P", "--paths");

		private Option<string> output = new Option<string>("-o", "--output");

		private Option<string> outputNaPlaceholder = new Option<string>("--output-na-placeholder");

		private Option<bool> restrictFilenames = new Option<bool>("--restrict-filenames");

		private Option<bool> noRestrictFilenames = new Option<bool>("--no-restrict-filenames");

		private Option<bool> windowsFilenames = new Option<bool>("--windows-filenames");

		private Option<bool> noWindowsFilenames = new Option<bool>("--no-windows-filenames");

		private Option<int?> trimFilenames = new Option<int?>("--trim-filenames");

		private Option<bool> noOverwrites = new Option<bool>("-w", "--no-overwrites");

		private Option<bool> forceOverwrites = new Option<bool>("--force-overwrites");

		private Option<bool> noForceOverwrites = new Option<bool>("--no-force-overwrites");

		private Option<bool> doContinue = new Option<bool>("-c", "--continue");

		private Option<bool> noContinue = new Option<bool>("--no-continue");

		private Option<bool> part = new Option<bool>("--part");

		private Option<bool> noPart = new Option<bool>("--no-part");

		private Option<bool> mtime = new Option<bool>("--mtime");

		private Option<bool> noMtime = new Option<bool>("--no-mtime");

		private Option<bool> writeDescription = new Option<bool>("--write-description");

		private Option<bool> noWriteDescription = new Option<bool>("--no-write-description");

		private Option<bool> writeInfoJson = new Option<bool>("--write-info-json");

		private Option<bool> noWriteInfoJson = new Option<bool>("--no-write-info-json");

		private Option<bool> writePlaylistMetafiles = new Option<bool>("--write-playlist-metafiles");

		private Option<bool> noWritePlaylistMetafiles = new Option<bool>("--no-write-playlist-metafiles");

		private Option<bool> cleanInfoJson = new Option<bool>("--clean-info-json");

		private Option<bool> noCleanInfoJson = new Option<bool>("--no-clean-info-json");

		private Option<bool> writeComments = new Option<bool>("--write-comments");

		private Option<bool> noWriteComments = new Option<bool>("--no-write-comments");

		private Option<string> loadInfoJson = new Option<string>("--load-info-json");

		private Option<string> cookies = new Option<string>("--cookies");

		private Option<bool> noCookies = new Option<bool>("--no-cookies");

		private Option<string> cookiesFromBrowser = new Option<string>("--cookies-from-browser");

		private Option<bool> noCookiesFromBrowser = new Option<bool>("--no-cookies-from-browser");

		private Option<string> cacheDir = new Option<string>("--cache-dir");

		private Option<bool> noCacheDir = new Option<bool>("--no-cache-dir");

		private Option<bool> removeCacheDir = new Option<bool>("--rm-cache-dir");

		private Option<bool> help = new Option<bool>("-h", "--help");

		private Option<bool> version = new Option<bool>("--version");

		private Option<bool> update = new Option<bool>("-U", "--update");

		private Option<bool> noUpdate = new Option<bool>("--no-update");

		private Option<bool> ignoreErrors = new Option<bool>("-i", "--ignore-errors");

		private Option<bool> noAbortOnError = new Option<bool>("--no-abort-on-error");

		private Option<bool> abortOnError = new Option<bool>("--abort-on-error");

		private Option<bool> dumpUserAgent = new Option<bool>("--dump-user-agent");

		private Option<bool> listExtractors = new Option<bool>("--list-extractors");

		private Option<bool> extractorDescriptions = new Option<bool>("--extractor-descriptions");

		private Option<string> useExtractors = new Option<string>("--use-extractors");

		private Option<string> defaultSearch = new Option<string>("--default-search");

		private Option<bool> ignoreConfig = new Option<bool>("--ignore-config");

		private Option<bool> noConfigLocations = new Option<bool>("--no-config-locations");

		private MultiOption<string> configLocations = new MultiOption<string>("--config-locations");

		private Option<bool> flatPlaylist = new Option<bool>("--flat-playlist");

		private Option<bool> noFlatPlaylist = new Option<bool>("--no-flat-playlist");

		private Option<bool> liveFromStart = new Option<bool>("--live-from-start");

		private Option<bool> noLiveFromStart = new Option<bool>("--no-live-from-start");

		private Option<string> waitForVideo = new Option<string>("--wait-for-video");

		private Option<bool> noWaitForVideo = new Option<bool>("--no-wait-for-video");

		private Option<bool> markWatched = new Option<bool>("--mark-watched");

		private Option<bool> noMarkWatched = new Option<bool>("--no-mark-watched");

		private Option<bool> noColors = new Option<bool>("--no-colors");

		private Option<string> compatOptions = new Option<string>("--compat-options");

		private Option<string> alias = new Option<string>("--alias");

		private Option<string> geoVerificationProxy = new Option<string>("--geo-verification-proxy");

		private Option<bool> geoBypass = new Option<bool>("--geo-bypass");

		private Option<bool> noGeoBypass = new Option<bool>("--no-geo-bypass");

		private Option<string> geoBypassCountry = new Option<string>("--geo-bypass-country");

		private Option<string> geoBypassIpBlock = new Option<string>("--geo-bypass-ip-block");

		private Option<bool> writeLink = new Option<bool>("--write-link");

		private Option<bool> writeUrlLink = new Option<bool>("--write-url-link");

		private Option<bool> writeWeblocLink = new Option<bool>("--write-webloc-link");

		private Option<bool> writeDesktopLink = new Option<bool>("--write-desktop-link");

		private Option<string> proxy = new Option<string>("--proxy");

		private Option<int?> socketTimeout = new Option<int?>("--socket-timeout");

		private Option<string> sourceAddress = new Option<string>("--source-address");

		private Option<bool> forceIPv4 = new Option<bool>("-4", "--force-ipv4");

		private Option<bool> forceIPv6 = new Option<bool>("-6", "--force-ipv6");

		private Option<bool> extractAudio = new Option<bool>("-x", "--extract-audio");

		private Option<AudioConversionFormat> audioFormat = new Option<AudioConversionFormat>("--audio-format");

		private Option<byte?> audioQuality = new Option<byte?>("--audio-quality");

		private Option<string> remuxVideo = new Option<string>("--remux-video");

		private Option<VideoRecodeFormat> recodeVideo = new Option<VideoRecodeFormat>("--recode-video");

		private MultiOption<string> postprocessorArgs = new MultiOption<string>("--postprocessor-args");

		private Option<bool> keepVideo = new Option<bool>("-k", "--keep-video");

		private Option<bool> noKeepVideo = new Option<bool>("--no-keep-video");

		private Option<bool> postOverwrites = new Option<bool>("--post-overwrites");

		private Option<bool> noPostOverwrites = new Option<bool>("--no-post-overwrites");

		private Option<bool> embedSubs = new Option<bool>("--embed-subs");

		private Option<bool> noEmbedSubs = new Option<bool>("--no-embed-subs");

		private Option<bool> embedThumbnail = new Option<bool>("--embed-thumbnail");

		private Option<bool> noEmbedThumbnail = new Option<bool>("--no-embed-thumbnail");

		private Option<bool> embedMetadata = new Option<bool>("--embed-metadata");

		private Option<bool> noEmbedMetadata = new Option<bool>("--no-embed-metadata");

		private Option<bool> embedChapters = new Option<bool>("--embed-chapters");

		private Option<bool> noEmbedChapters = new Option<bool>("--no-embed-chapters");

		private Option<bool> embedInfoJson = new Option<bool>("--embed-info-json");

		private Option<bool> noEmbedInfoJson = new Option<bool>("--no-embed-info-json");

		private Option<string> parseMetadata = new Option<string>("--parse-metadata");

		private MultiOption<string> replaceInMetadata = new MultiOption<string>("--replace-in-metadata");

		private Option<bool> xattrs = new Option<bool>("--xattrs");

		private Option<string> concatPlaylist = new Option<string>("--concat-playlist");

		private Option<string> fixup = new Option<string>("--fixup");

		private Option<string> ffmpegLocation = new Option<string>("--ffmpeg-location");

		private MultiOption<string> exec = new MultiOption<string>("--exec");

		private Option<bool> noExec = new Option<bool>("--no-exec");

		private Option<string> convertSubs = new Option<string>("--convert-subs");

		private Option<string> convertThumbnails = new Option<string>("--convert-thumbnails");

		private Option<bool> splitChapters = new Option<bool>("--split-chapters");

		private Option<bool> noSplitChapters = new Option<bool>("--no-split-chapters");

		private MultiOption<string> removeChapters = new MultiOption<string>("--remove-chapters");

		private Option<bool> noRemoveChapters = new Option<bool>("--no-remove-chapters");

		private Option<bool> forceKeyframesAtCuts = new Option<bool>("--force-keyframes-at-cuts");

		private Option<bool> noForceKeyframesAtCuts = new Option<bool>("--no-force-keyframes-at-cuts");

		private MultiOption<string> usePostprocessor = new MultiOption<string>("--use-postprocessor");

		private Option<string> sponsorblockMark = new Option<string>("--sponsorblock-mark");

		private Option<string> sponsorblockRemove = new Option<string>("--sponsorblock-remove");

		private Option<string> sponsorblockChapterTitle = new Option<string>("--sponsorblock-chapter-title");

		private Option<bool> noSponsorblock = new Option<bool>("--no-sponsorblock");

		private Option<string> sponsorblockApi = new Option<string>("--sponsorblock-api");

		private Option<bool> writeSubs = new Option<bool>("--write-subs");

		private Option<bool> noWriteSubs = new Option<bool>("--no-write-subs");

		private Option<bool> writeAutoSubs = new Option<bool>("--write-auto-subs");

		private Option<bool> noWriteAutoSubs = new Option<bool>("--no-write-auto-subs");

		private Option<bool> listSubs = new Option<bool>("--list-subs");

		private Option<string> subFormat = new Option<string>("--sub-format");

		private Option<string> subLangs = new Option<string>("--sub-langs");

		private Option<bool> writeThumbnail = new Option<bool>("--write-thumbnail");

		private Option<bool> noWriteThumbnail = new Option<bool>("--no-write-thumbnail");

		private Option<bool> writeAllThumbnails = new Option<bool>("--write-all-thumbnails");

		private Option<bool> listThumbnails = new Option<bool>("--list-thumbnails");

		private Option<bool> quiet = new Option<bool>("-q", "--quiet");

		private Option<bool> noWarnings = new Option<bool>("--no-warnings");

		private Option<bool> simulate = new Option<bool>("-s", "--simulate");

		private Option<bool> noSimulate = new Option<bool>("--no-simulate");

		private Option<bool> ignoreNoFormatsError = new Option<bool>("--ignore-no-formats-error");

		private Option<bool> noIgnoreNoFormatsError = new Option<bool>("--no-ignore-no-formats-error");

		private Option<bool> skipDownload = new Option<bool>("--skip-download");

		private MultiOption<string> print = new MultiOption<string>("-O", "--print");

		private MultiOption<string> printToFile = new MultiOption<string>("--print-to-file");

		private Option<bool> dumpJson = new Option<bool>("-j", "--dump-json");

		private Option<bool> dumpSingleJson = new Option<bool>("-J", "--dump-single-json");

		private Option<bool> forceWriteArchive = new Option<bool>("--force-write-archive");

		private Option<bool> newline = new Option<bool>("--newline");

		private Option<bool> noProgress = new Option<bool>("--no-progress");

		private Option<bool> progress = new Option<bool>("--progress");

		private Option<bool> consoleTitle = new Option<bool>("--console-title");

		private Option<string> progressTemplate = new Option<string>("--progress-template");

		private Option<bool> verbose = new Option<bool>("-v", "--verbose");

		private Option<bool> dumpPages = new Option<bool>("--dump-pages");

		private Option<bool> writePages = new Option<bool>("--write-pages");

		private Option<bool> printTraffic = new Option<bool>("--print-traffic");

		private Option<string> format = new Option<string>("-f", "--format");

		private Option<string> formatSort = new Option<string>("-S", "--format-sort");

		private Option<bool> formatSortForce = new Option<bool>("--format-sort-force");

		private Option<bool> noFormatSortForce = new Option<bool>("--no-format-sort-force");

		private Option<bool> videoMultistreams = new Option<bool>("--video-multistreams");

		private Option<bool> noVideoMultistreams = new Option<bool>("--no-video-multistreams");

		private Option<bool> audioMultistreams = new Option<bool>("--audio-multistreams");

		private Option<bool> noAudioMultistreams = new Option<bool>("--no-audio-multistreams");

		private Option<bool> preferFreeFormats = new Option<bool>("--prefer-free-formats");

		private Option<bool> noPreferFreeFormats = new Option<bool>("--no-prefer-free-formats");

		private Option<bool> checkFormats = new Option<bool>("--check-formats");

		private Option<bool> checkAllFormats = new Option<bool>("--check-all-formats");

		private Option<bool> noCheckFormats = new Option<bool>("--no-check-formats");

		private Option<bool> listFormats = new Option<bool>("-F", "--list-formats");

		private Option<DownloadMergeFormat> mergeOutputFormat = new Option<DownloadMergeFormat>("--merge-output-format");

		private Option<string> playlistItems = new Option<string>("-I", "--playlist-items");

		private Option<string> minFilesize = new Option<string>("--min-filesize");

		private Option<string> maxFilesize = new Option<string>("--max-filesize");

		private Option<DateTime> date = new Option<DateTime>("--date");

		private Option<DateTime> dateBefore = new Option<DateTime>("--datebefore");

		private Option<DateTime> dateAfter = new Option<DateTime>("--dateafter");

		private MultiOption<string> matchFilters = new MultiOption<string>("--match-filters");

		private Option<bool> noMatchFilter = new Option<bool>("--no-match-filter");

		private Option<bool> noPlaylist = new Option<bool>("--no-playlist");

		private Option<bool> yesPlaylist = new Option<bool>("--yes-playlist");

		private Option<byte?> ageLimit = new Option<byte?>("--age-limit");

		private Option<string> downloadArchive = new Option<string>("--download-archive");

		private Option<bool> noDownloadArchive = new Option<bool>("--no-download-archive");

		private Option<int?> maxDownloads = new Option<int?>("--max-downloads");

		private Option<bool> breakOnExisting = new Option<bool>("--break-on-existing");

		private Option<bool> breakOnReject = new Option<bool>("--break-on-reject");

		private Option<bool> breakPerInput = new Option<bool>("--break-per-input");

		private Option<bool> noBreakPerInput = new Option<bool>("--no-break-per-input");

		private Option<int?> skipPlaylistAfterErrors = new Option<int?>("--skip-playlist-after-errors");

		private Option<string> encoding = new Option<string>("--encoding");

		private Option<bool> legacyServerConnect = new Option<bool>("--legacy-server-connect");

		private Option<bool> noCheckCertificates = new Option<bool>("--no-check-certificates");

		private Option<bool> preferInsecure = new Option<bool>("--prefer-insecure");

		private MultiOption<string> addHeader = new MultiOption<string>("--add-header");

		private Option<bool> bidiWorkaround = new Option<bool>("--bidi-workaround");

		private Option<int?> sleepRequests = new Option<int?>("--sleep-requests");

		private Option<int?> sleepInterval = new Option<int?>("--sleep-interval");

		private Option<int?> maxSleepInterval = new Option<int?>("--max-sleep-interval");

		private Option<int?> sleepSubtitles = new Option<int?>("--sleep-subtitles");

		public string Username
		{
			get
			{
				return username.Value;
			}
			set
			{
				username.Value = value;
			}
		}

		public string Password
		{
			get
			{
				return password.Value;
			}
			set
			{
				password.Value = value;
			}
		}

		public string TwoFactor
		{
			get
			{
				return twoFactor.Value;
			}
			set
			{
				twoFactor.Value = value;
			}
		}

		public bool Netrc
		{
			get
			{
				return netrc.Value;
			}
			set
			{
				netrc.Value = value;
			}
		}

		public string NetrcLocation
		{
			get
			{
				return netrcLocation.Value;
			}
			set
			{
				netrcLocation.Value = value;
			}
		}

		public string VideoPassword
		{
			get
			{
				return videoPassword.Value;
			}
			set
			{
				videoPassword.Value = value;
			}
		}

		public string ApMso
		{
			get
			{
				return apMso.Value;
			}
			set
			{
				apMso.Value = value;
			}
		}

		public string ApUsername
		{
			get
			{
				return apUsername.Value;
			}
			set
			{
				apUsername.Value = value;
			}
		}

		public string ApPassword
		{
			get
			{
				return apPassword.Value;
			}
			set
			{
				apPassword.Value = value;
			}
		}

		public bool ApListMso
		{
			get
			{
				return apListMso.Value;
			}
			set
			{
				apListMso.Value = value;
			}
		}

		public string ClientCertificate
		{
			get
			{
				return clientCertificate.Value;
			}
			set
			{
				clientCertificate.Value = value;
			}
		}

		public string ClientCertificateKey
		{
			get
			{
				return clientCertificateKey.Value;
			}
			set
			{
				clientCertificateKey.Value = value;
			}
		}

		public string ClientCertificatePassword
		{
			get
			{
				return clientCertificatePassword.Value;
			}
			set
			{
				clientCertificatePassword.Value = value;
			}
		}

		public IOption[] CustomOptions { get; set; } = new IOption[0];


		[Obsolete("Deprecated in favor of: --print description.")]
		public bool GetDescription
		{
			get
			{
				return getDescription.Value;
			}
			set
			{
				getDescription.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print duration_string.")]
		public bool GetDuration
		{
			get
			{
				return getDuration.Value;
			}
			set
			{
				getDuration.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print filename.")]
		public bool GetFilename
		{
			get
			{
				return getFilename.Value;
			}
			set
			{
				getFilename.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print format.")]
		public bool GetFormat
		{
			get
			{
				return getFormat.Value;
			}
			set
			{
				getFormat.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print id.")]
		public bool GetId
		{
			get
			{
				return getId.Value;
			}
			set
			{
				getId.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print thumbnail.")]
		public bool GetThumbnail
		{
			get
			{
				return getThumbnail.Value;
			}
			set
			{
				getThumbnail.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print title.")]
		public bool GetTitle
		{
			get
			{
				return getTitle.Value;
			}
			set
			{
				getTitle.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --print urls.")]
		public bool GetUrl
		{
			get
			{
				return getUrl.Value;
			}
			set
			{
				getUrl.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --match-filter \"title ~= (?i)REGEX\".")]
		public string MatchTitle
		{
			get
			{
				return matchTitle.Value;
			}
			set
			{
				matchTitle.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --match-filter \"title !~= (?i)REGEX\".")]
		public string RejectTitle
		{
			get
			{
				return rejectTitle.Value;
			}
			set
			{
				rejectTitle.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --match-filter \"view_count >=? COUNT\".")]
		public long? MinViews
		{
			get
			{
				return minViews.Value;
			}
			set
			{
				minViews.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --match-filter \"view_count <=? COUNT\".")]
		public long? MaxViews
		{
			get
			{
				return maxViews.Value;
			}
			set
			{
				maxViews.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --add-header \"User-Agent:UA\".")]
		public string UserAgent
		{
			get
			{
				return userAgent.Value;
			}
			set
			{
				userAgent.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --add-header \"Referer:URL\".")]
		public string Referer
		{
			get
			{
				return referer.Value;
			}
			set
			{
				referer.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -I NUMBER:.")]
		public int? PlaylistStart
		{
			get
			{
				return playlistStart.Value;
			}
			set
			{
				playlistStart.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -I :NUMBER.")]
		public int? PlaylistEnd
		{
			get
			{
				return playlistEnd.Value;
			}
			set
			{
				playlistEnd.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -I ::-1.")]
		public bool PlaylistReverse
		{
			get
			{
				return playlistReverse.Value;
			}
			set
			{
				playlistReverse.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --ies generic,default.")]
		public bool ForceGenericExtractor
		{
			get
			{
				return forceGenericExtractor.Value;
			}
			set
			{
				forceGenericExtractor.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --exec \"before_dl:CMD\".")]
		public string ExecBeforeDownload
		{
			get
			{
				return execBeforeDownload.Value;
			}
			set
			{
				execBeforeDownload.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --no-exec.")]
		public bool NoExecBeforeDownload
		{
			get
			{
				return noExecBeforeDownload.Value;
			}
			set
			{
				noExecBeforeDownload.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -f all.")]
		public bool AllFormats
		{
			get
			{
				return allFormats.Value;
			}
			set
			{
				allFormats.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --sub-langs all --write-subs.")]
		public bool AllSubs
		{
			get
			{
				return allSubs.Value;
			}
			set
			{
				allSubs.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -j --no-simulate.")]
		public bool PrintJson
		{
			get
			{
				return printJson.Value;
			}
			set
			{
				printJson.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: Use string formatting, e.g. %(autonumber)03d.")]
		public string AutonumberSize
		{
			get
			{
				return autonumberSize.Value;
			}
			set
			{
				autonumberSize.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: Use internal field formatting like %(autonumber+NUMBER)s.")]
		public int? AutonumberStart
		{
			get
			{
				return autonumberStart.Value;
			}
			set
			{
				autonumberStart.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: -o \"%(id)s.%(ext)s\".")]
		public bool Id
		{
			get
			{
				return id.Value;
			}
			set
			{
				id.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --parse-metadata \"%(title)s:FORMAT\".")]
		public string MetadataFromTitle
		{
			get
			{
				return metadataFromTitle.Value;
			}
			set
			{
				metadataFromTitle.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --downloader \"m3u8:native\".")]
		public bool HlsPreferNative
		{
			get
			{
				return hlsPreferNative.Value;
			}
			set
			{
				hlsPreferNative.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --downloader \"m3u8:ffmpeg\".")]
		public bool HlsPreferFfmpeg
		{
			get
			{
				return hlsPreferFfmpeg.Value;
			}
			set
			{
				hlsPreferFfmpeg.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --compat-options list-formats (Alias: --no-list-formats-as-table).")]
		public bool ListFormatsOld
		{
			get
			{
				return listFormatsOld.Value;
			}
			set
			{
				listFormatsOld.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --compat-options -list-formats [Default] (Alias: --no-list-formats-old).")]
		public bool ListFormatsAsTable
		{
			get
			{
				return listFormatsAsTable.Value;
			}
			set
			{
				listFormatsAsTable.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --extractor-args \"youtube:skip=dash\" (Alias: --no-youtube-include-dash-manifest).")]
		public bool YoutubeSkipDashManifest
		{
			get
			{
				return youtubeSkipDashManifest.Value;
			}
			set
			{
				youtubeSkipDashManifest.Value = value;
			}
		}

		[Obsolete("Deprecated in favor of: --extractor-args \"youtube:skip=hls\" (Alias: --no-youtube-include-hls-manifest).")]
		public bool YoutubeSkipHlsManifest
		{
			get
			{
				return youtubeSkipHlsManifest.Value;
			}
			set
			{
				youtubeSkipHlsManifest.Value = value;
			}
		}

		public int? ConcurrentFragments
		{
			get
			{
				return concurrentFragments.Value;
			}
			set
			{
				concurrentFragments.Value = value;
			}
		}

		public long? LimitRate
		{
			get
			{
				return limitRate.Value;
			}
			set
			{
				limitRate.Value = value;
			}
		}

		public long? ThrottledRate
		{
			get
			{
				return throttledRate.Value;
			}
			set
			{
				throttledRate.Value = value;
			}
		}

		public int? Retries
		{
			get
			{
				return retries.Value;
			}
			set
			{
				retries.Value = value;
			}
		}

		public int? FileAccessRetries
		{
			get
			{
				return fileAccessRetries.Value;
			}
			set
			{
				fileAccessRetries.Value = value;
			}
		}

		public int? FragmentRetries
		{
			get
			{
				return fragmentRetries.Value;
			}
			set
			{
				fragmentRetries.Value = value;
			}
		}

		public MultiValue<string> RetrySleep
		{
			get
			{
				return retrySleep.Value;
			}
			set
			{
				retrySleep.Value = value;
			}
		}

		public bool SkipUnavailableFragments
		{
			get
			{
				return skipUnavailableFragments.Value;
			}
			set
			{
				skipUnavailableFragments.Value = value;
			}
		}

		public bool AbortOnUnavailableFragment
		{
			get
			{
				return abortOnUnavailableFragment.Value;
			}
			set
			{
				abortOnUnavailableFragment.Value = value;
			}
		}

		public bool KeepFragments
		{
			get
			{
				return keepFragments.Value;
			}
			set
			{
				keepFragments.Value = value;
			}
		}

		public bool NoKeepFragments
		{
			get
			{
				return noKeepFragments.Value;
			}
			set
			{
				noKeepFragments.Value = value;
			}
		}

		public long? BufferSize
		{
			get
			{
				return bufferSize.Value;
			}
			set
			{
				bufferSize.Value = value;
			}
		}

		public bool ResizeBuffer
		{
			get
			{
				return resizeBuffer.Value;
			}
			set
			{
				resizeBuffer.Value = value;
			}
		}

		public bool NoResizeBuffer
		{
			get
			{
				return noResizeBuffer.Value;
			}
			set
			{
				noResizeBuffer.Value = value;
			}
		}

		public long? HttpChunkSize
		{
			get
			{
				return httpChunkSize.Value;
			}
			set
			{
				httpChunkSize.Value = value;
			}
		}

		public bool PlaylistRandom
		{
			get
			{
				return playlistRandom.Value;
			}
			set
			{
				playlistRandom.Value = value;
			}
		}

		public bool LazyPlaylist
		{
			get
			{
				return lazyPlaylist.Value;
			}
			set
			{
				lazyPlaylist.Value = value;
			}
		}

		public bool NoLazyPlaylist
		{
			get
			{
				return noLazyPlaylist.Value;
			}
			set
			{
				noLazyPlaylist.Value = value;
			}
		}

		public bool XattrSetFilesize
		{
			get
			{
				return xattrSetFilesize.Value;
			}
			set
			{
				xattrSetFilesize.Value = value;
			}
		}

		public bool HlsUseMpegts
		{
			get
			{
				return hlsUseMpegts.Value;
			}
			set
			{
				hlsUseMpegts.Value = value;
			}
		}

		public bool NoHlsUseMpegts
		{
			get
			{
				return noHlsUseMpegts.Value;
			}
			set
			{
				noHlsUseMpegts.Value = value;
			}
		}

		public MultiValue<string> DownloadSections
		{
			get
			{
				return downloadSections.Value;
			}
			set
			{
				downloadSections.Value = value;
			}
		}

		public MultiValue<string> Downloader
		{
			get
			{
				return downloader.Value;
			}
			set
			{
				downloader.Value = value;
			}
		}

		public MultiValue<string> DownloaderArgs
		{
			get
			{
				return downloaderArgs.Value;
			}
			set
			{
				downloaderArgs.Value = value;
			}
		}

		public int? ExtractorRetries
		{
			get
			{
				return extractorRetries.Value;
			}
			set
			{
				extractorRetries.Value = value;
			}
		}

		public bool AllowDynamicMpd
		{
			get
			{
				return allowDynamicMpd.Value;
			}
			set
			{
				allowDynamicMpd.Value = value;
			}
		}

		public bool IgnoreDynamicMpd
		{
			get
			{
				return ignoreDynamicMpd.Value;
			}
			set
			{
				ignoreDynamicMpd.Value = value;
			}
		}

		public bool HlsSplitDiscontinuity
		{
			get
			{
				return hlsSplitDiscontinuity.Value;
			}
			set
			{
				hlsSplitDiscontinuity.Value = value;
			}
		}

		public bool NoHlsSplitDiscontinuity
		{
			get
			{
				return noHlsSplitDiscontinuity.Value;
			}
			set
			{
				noHlsSplitDiscontinuity.Value = value;
			}
		}

		public MultiValue<string> ExtractorArgs
		{
			get
			{
				return extractorArgs.Value;
			}
			set
			{
				extractorArgs.Value = value;
			}
		}

		public string BatchFile
		{
			get
			{
				return batchFile.Value;
			}
			set
			{
				batchFile.Value = value;
			}
		}

		public bool NoBatchFile
		{
			get
			{
				return noBatchFile.Value;
			}
			set
			{
				noBatchFile.Value = value;
			}
		}

		public string Paths
		{
			get
			{
				return paths.Value;
			}
			set
			{
				paths.Value = value;
			}
		}

		public string Output
		{
			get
			{
				return output.Value;
			}
			set
			{
				output.Value = value;
			}
		}

		public string OutputNaPlaceholder
		{
			get
			{
				return outputNaPlaceholder.Value;
			}
			set
			{
				outputNaPlaceholder.Value = value;
			}
		}

		public bool RestrictFilenames
		{
			get
			{
				return restrictFilenames.Value;
			}
			set
			{
				restrictFilenames.Value = value;
			}
		}

		public bool NoRestrictFilenames
		{
			get
			{
				return noRestrictFilenames.Value;
			}
			set
			{
				noRestrictFilenames.Value = value;
			}
		}

		public bool WindowsFilenames
		{
			get
			{
				return windowsFilenames.Value;
			}
			set
			{
				windowsFilenames.Value = value;
			}
		}

		public bool NoWindowsFilenames
		{
			get
			{
				return noWindowsFilenames.Value;
			}
			set
			{
				noWindowsFilenames.Value = value;
			}
		}

		public int? TrimFilenames
		{
			get
			{
				return trimFilenames.Value;
			}
			set
			{
				trimFilenames.Value = value;
			}
		}

		public bool NoOverwrites
		{
			get
			{
				return noOverwrites.Value;
			}
			set
			{
				noOverwrites.Value = value;
			}
		}

		public bool ForceOverwrites
		{
			get
			{
				return forceOverwrites.Value;
			}
			set
			{
				forceOverwrites.Value = value;
			}
		}

		public bool NoForceOverwrites
		{
			get
			{
				return noForceOverwrites.Value;
			}
			set
			{
				noForceOverwrites.Value = value;
			}
		}

		public bool Continue
		{
			get
			{
				return doContinue.Value;
			}
			set
			{
				doContinue.Value = value;
			}
		}

		public bool NoContinue
		{
			get
			{
				return noContinue.Value;
			}
			set
			{
				noContinue.Value = value;
			}
		}

		public bool Part
		{
			get
			{
				return part.Value;
			}
			set
			{
				part.Value = value;
			}
		}

		public bool NoPart
		{
			get
			{
				return noPart.Value;
			}
			set
			{
				noPart.Value = value;
			}
		}

		public bool Mtime
		{
			get
			{
				return mtime.Value;
			}
			set
			{
				mtime.Value = value;
			}
		}