Decompiled source of mod1 Modpack v1.1.0

pachers/BepInEx.MonoMod.HookGenPatcher/BepInEx.MonoMod.HookGenPatcher.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using BepInEx.Configuration;
using BepInEx.Logging;
using Mono.Cecil;
using MonoMod;
using MonoMod.RuntimeDetour.HookGen;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Bepinex.Monomod.HookGenPatcher")]
[assembly: AssemblyDescription("Runtime HookGen for BepInEx")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HarbingerOfMe")]
[assembly: AssemblyProduct("Bepinex.Monomod.HookGenPatcher")]
[assembly: AssemblyCopyright("HarbingerOfMe-2022")]
[assembly: AssemblyTrademark("MIT")]
[assembly: ComVisible(false)]
[assembly: Guid("12032e45-9577-4195-8f4f-a729911b2f08")]
[assembly: AssemblyFileVersion("1.2.1.0")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("1.2.1.0")]
namespace BepInEx.MonoMod.HookGenPatcher;

public static class HookGenPatcher
{
	internal static ManualLogSource Logger = Logger.CreateLogSource("HookGenPatcher");

	private const string CONFIG_FILE_NAME = "HookGenPatcher.cfg";

	private static readonly ConfigFile Config = new ConfigFile(Path.Combine(Paths.ConfigPath, "HookGenPatcher.cfg"), true);

	private const char EntrySeparator = ',';

	private static readonly ConfigEntry<string> AssemblyNamesToHookGenPatch = Config.Bind<string>("General", "MMHOOKAssemblyNames", "Assembly-CSharp.dll", $"Assembly names to make mmhooks for, separate entries with : {','} ");

	private static readonly ConfigEntry<bool> preciseHash = Config.Bind<bool>("General", "Preciser filehashing", false, "Hash file using contents instead of size. Minor perfomance impact.");

	private static bool skipHashing => !preciseHash.Value;

	public static IEnumerable<string> TargetDLLs { get; } = new string[0];


	public static void Initialize()
	{
		//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cf: Expected O, but got Unknown
		//IL_0237: Unknown result type (might be due to invalid IL or missing references)
		//IL_023e: Expected O, but got Unknown
		//IL_0278: Unknown result type (might be due to invalid IL or missing references)
		//IL_0282: Expected O, but got Unknown
		//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ce: Expected O, but got Unknown
		string[] array = AssemblyNamesToHookGenPatch.Value.Split(new char[1] { ',' });
		string text = Path.Combine(Paths.PluginPath, "MMHOOK");
		string[] array2 = array;
		foreach (string text2 in array2)
		{
			string text3 = "MMHOOK_" + text2;
			string text4 = Path.Combine(Paths.ManagedPath, text2);
			string text5 = Path.Combine(text, text3);
			bool flag = true;
			string[] files = Directory.GetFiles(Paths.PluginPath, text3, SearchOption.AllDirectories);
			foreach (string text6 in files)
			{
				if (Path.GetFileName(text6).Equals(text3))
				{
					text5 = text6;
					Logger.LogInfo((object)"Previous MMHOOK location found. Using that location to save instead.");
					flag = false;
					break;
				}
			}
			if (flag)
			{
				Directory.CreateDirectory(text);
			}
			FileInfo fileInfo = new FileInfo(text4);
			long length = fileInfo.Length;
			long num = 0L;
			if (File.Exists(text5))
			{
				try
				{
					AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text5);
					try
					{
						if (val.MainModule.GetType("BepHookGen.size" + length) != null)
						{
							if (skipHashing)
							{
								Logger.LogInfo((object)"Already ran for this version, reusing that file.");
								continue;
							}
							num = fileInfo.makeHash();
							if (val.MainModule.GetType("BepHookGen.content" + num) != null)
							{
								Logger.LogInfo((object)"Already ran for this version, reusing that file.");
								continue;
							}
						}
					}
					finally
					{
						((IDisposable)val)?.Dispose();
					}
				}
				catch (BadImageFormatException)
				{
					Logger.LogWarning((object)("Failed to read " + Path.GetFileName(text5) + ", probably corrupted, remaking one."));
				}
			}
			Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1");
			Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0");
			MonoModder val2 = new MonoModder
			{
				InputPath = text4,
				OutputPath = text5,
				ReadingMode = (ReadingMode)2
			};
			try
			{
				IAssemblyResolver assemblyResolver = val2.AssemblyResolver;
				IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
				if (obj != null)
				{
					((BaseAssemblyResolver)obj).AddSearchDirectory(Paths.BepInExAssemblyDirectory);
				}
				val2.Read();
				val2.MapDependencies();
				if (File.Exists(text5))
				{
					Logger.LogDebug((object)("Clearing " + text5));
					File.Delete(text5);
				}
				Logger.LogInfo((object)"Starting HookGenerator");
				HookGenerator val3 = new HookGenerator(val2, Path.GetFileName(text5));
				ModuleDefinition outputModule = val3.OutputModule;
				try
				{
					val3.Generate();
					outputModule.Types.Add(new TypeDefinition("BepHookGen", "size" + length, (TypeAttributes)1, outputModule.TypeSystem.Object));
					if (!skipHashing)
					{
						outputModule.Types.Add(new TypeDefinition("BepHookGen", "content" + ((num == 0L) ? fileInfo.makeHash() : num), (TypeAttributes)1, outputModule.TypeSystem.Object));
					}
					outputModule.Write(text5);
				}
				finally
				{
					((IDisposable)outputModule)?.Dispose();
				}
				Logger.LogInfo((object)"Done.");
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}
	}

	public static void Patch(AssemblyDefinition _)
	{
	}

	private static long makeHash(this FileInfo fileInfo)
	{
		FileStream inputStream = fileInfo.OpenRead();
		byte[] value = null;
		using (MD5 mD = new MD5CryptoServiceProvider())
		{
			value = mD.ComputeHash(inputStream);
		}
		long num = BitConverter.ToInt64(value, 0);
		if (num == 0L)
		{
			return 1L;
		}
		return num;
	}
}

pachers/BepInEx.MonoMod.HookGenPatcher/MonoMod.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.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Mdb;
using Mono.Cecil.Pdb;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.InlineRT;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2021 0x0ade")]
[assembly: AssemblyDescription("General purpose .NET assembly modding \"basework\". This package contains the core IL patcher and relinker.")]
[assembly: AssemblyFileVersion("21.8.5.1")]
[assembly: AssemblyInformationalVersion("21.08.05.01")]
[assembly: AssemblyProduct("MonoMod")]
[assembly: AssemblyTitle("MonoMod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("21.8.5.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace MonoMod
{
	[MonoMod__SafeToCopy__]
	public class MonoModAdded : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModConstructor : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModCustomAttributeAttribute : Attribute
	{
		public MonoModCustomAttributeAttribute(string h)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModCustomMethodAttributeAttribute : Attribute
	{
		public MonoModCustomMethodAttributeAttribute(string h)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModEnumReplace : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModForceCall : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModForceCallvirt : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	[Obsolete("Use MonoModLinkFrom or RuntimeDetour / HookGen instead.")]
	public class MonoModHook : Attribute
	{
		public string FindableID;

		public Type Type;

		public MonoModHook(string findableID)
		{
			FindableID = findableID;
		}

		public MonoModHook(Type type)
		{
			Type = type;
			FindableID = type.FullName;
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModIfFlag : Attribute
	{
		public MonoModIfFlag(string key)
		{
		}

		public MonoModIfFlag(string key, bool fallback)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModIgnore : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	public class MonoModLinkFrom : Attribute
	{
		public string FindableID;

		public Type Type;

		public MonoModLinkFrom(string findableID)
		{
			FindableID = findableID;
		}

		public MonoModLinkFrom(Type type)
		{
			Type = type;
			FindableID = type.FullName;
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModLinkTo : Attribute
	{
		public MonoModLinkTo(string t)
		{
		}

		public MonoModLinkTo(Type t)
		{
		}

		public MonoModLinkTo(string t, string n)
		{
		}

		public MonoModLinkTo(Type t, string n)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModNoNew : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOnPlatform : Attribute
	{
		public MonoModOnPlatform(params Platform[] p)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOriginal : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOriginalName : Attribute
	{
		public MonoModOriginalName(string n)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModPatch : Attribute
	{
		public MonoModPatch(string name)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModPublic : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModRemove : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModReplace : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModTargetModule : Attribute
	{
		public MonoModTargetModule(string name)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	internal class MonoMod__SafeToCopy__ : Attribute
	{
	}
	public delegate bool MethodParser(MonoModder modder, MethodBody body, Instruction instr, ref int instri);
	public delegate void MethodRewriter(MonoModder modder, MethodDefinition method);
	public delegate void MethodBodyRewriter(MonoModder modder, MethodBody body, Instruction instr, int instri);
	public delegate ModuleDefinition MissingDependencyResolver(MonoModder modder, ModuleDefinition main, string name, string fullName);
	public delegate void PostProcessor(MonoModder modder);
	public delegate void ModReadEventHandler(MonoModder modder, ModuleDefinition mod);
	public class RelinkMapEntry
	{
		public string Type;

		public string FindableID;

		public RelinkMapEntry()
		{
		}

		public RelinkMapEntry(string type, string findableID)
		{
			Type = type;
			FindableID = findableID;
		}
	}
	public enum DebugSymbolFormat
	{
		Auto,
		MDB,
		PDB
	}
	public class MonoModder : IDisposable
	{
		public static readonly bool IsMono = (object)Type.GetType("Mono.Runtime") != null;

		public static readonly Version Version = typeof(MonoModder).Assembly.GetName().Version;

		public Dictionary<string, object> SharedData = new Dictionary<string, object>();

		public Dictionary<string, object> RelinkMap = new Dictionary<string, object>();

		public Dictionary<string, ModuleDefinition> RelinkModuleMap = new Dictionary<string, ModuleDefinition>();

		public HashSet<string> SkipList = new HashSet<string>(EqualityComparer<string>.Default);

		public Dictionary<string, IMetadataTokenProvider> RelinkMapCache = new Dictionary<string, IMetadataTokenProvider>();

		public Dictionary<string, TypeReference> RelinkModuleMapCache = new Dictionary<string, TypeReference>();

		public Dictionary<string, OpCode> ForceCallMap = new Dictionary<string, OpCode>();

		public ModReadEventHandler OnReadMod;

		public PostProcessor PostProcessors;

		public Dictionary<string, Action<object, object[]>> CustomAttributeHandlers = new Dictionary<string, Action<object, object[]>> { 
		{
			"MonoMod.MonoModPublic",
			delegate
			{
			}
		} };

		public Dictionary<string, Action<object, object[]>> CustomMethodAttributeHandlers = new Dictionary<string, Action<object, object[]>>();

		public MissingDependencyResolver MissingDependencyResolver;

		public MethodParser MethodParser;

		public MethodRewriter MethodRewriter;

		public MethodBodyRewriter MethodBodyRewriter;

		public Stream Input;

		public string InputPath;

		public Stream Output;

		public string OutputPath;

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

		public ModuleDefinition Module;

		public Dictionary<ModuleDefinition, List<ModuleDefinition>> DependencyMap = new Dictionary<ModuleDefinition, List<ModuleDefinition>>();

		public Dictionary<string, ModuleDefinition> DependencyCache = new Dictionary<string, ModuleDefinition>();

		public Func<ICustomAttributeProvider, TypeReference, bool> ShouldCleanupAttrib;

		public bool LogVerboseEnabled;

		public bool CleanupEnabled;

		public bool PublicEverything;

		public List<ModuleReference> Mods = new List<ModuleReference>();

		public bool Strict;

		public bool MissingDependencyThrow;

		public bool RemovePatchReferences;

		public bool PreventInline;

		public bool? UpgradeMSCORLIB;

		public ReadingMode ReadingMode = (ReadingMode)1;

		public DebugSymbolFormat DebugSymbolOutputFormat;

		public int CurrentRID;

		protected IAssemblyResolver _assemblyResolver;

		protected ReaderParameters _readerParameters;

		protected WriterParameters _writerParameters;

		public bool GACEnabled;

		private string[] _GACPathsNone = new string[0];

		protected string[] _GACPaths;

		protected MethodDefinition _mmOriginalCtor;

		protected MethodDefinition _mmOriginalNameCtor;

		protected MethodDefinition _mmAddedCtor;

		protected MethodDefinition _mmPatchCtor;

		public virtual IAssemblyResolver AssemblyResolver
		{
			get
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Expected O, but got Unknown
				if (_assemblyResolver == null)
				{
					DefaultAssemblyResolver val = new DefaultAssemblyResolver();
					foreach (string dependencyDir in DependencyDirs)
					{
						((BaseAssemblyResolver)val).AddSearchDirectory(dependencyDir);
					}
					_assemblyResolver = (IAssemblyResolver)(object)val;
				}
				return _assemblyResolver;
			}
			set
			{
				_assemblyResolver = value;
			}
		}

		public virtual ReaderParameters ReaderParameters
		{
			get
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_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)
				//IL_002c: Expected O, but got Unknown
				if (_readerParameters == null)
				{
					_readerParameters = new ReaderParameters(ReadingMode)
					{
						AssemblyResolver = AssemblyResolver,
						ReadSymbols = true
					};
				}
				return _readerParameters;
			}
			set
			{
				_readerParameters = value;
			}
		}

		public virtual WriterParameters WriterParameters
		{
			get
			{
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0056: Unknown result type (might be due to invalid IL or missing references)
				//IL_005c: Expected O, but got Unknown
				//IL_0067: Expected O, but got Unknown
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Expected O, but got Unknown
				if (_writerParameters == null)
				{
					bool flag = DebugSymbolOutputFormat == DebugSymbolFormat.PDB;
					bool flag2 = DebugSymbolOutputFormat == DebugSymbolFormat.MDB;
					if (DebugSymbolOutputFormat == DebugSymbolFormat.Auto)
					{
						if ((PlatformHelper.Current & 0x25) == 37)
						{
							flag = true;
						}
						else
						{
							flag2 = true;
						}
					}
					WriterParameters val = new WriterParameters
					{
						WriteSymbols = true
					};
					object symbolWriterProvider;
					if (!flag)
					{
						if (!flag2)
						{
							symbolWriterProvider = null;
						}
						else
						{
							ISymbolWriterProvider val2 = (ISymbolWriterProvider)new MdbWriterProvider();
							symbolWriterProvider = val2;
						}
					}
					else
					{
						ISymbolWriterProvider val2 = (ISymbolWriterProvider)new NativePdbWriterProvider();
						symbolWriterProvider = val2;
					}
					val.SymbolWriterProvider = (ISymbolWriterProvider)symbolWriterProvider;
					_writerParameters = val;
				}
				return _writerParameters;
			}
			set
			{
				_writerParameters = value;
			}
		}

		public string[] GACPaths
		{
			get
			{
				if (!GACEnabled)
				{
					return _GACPathsNone;
				}
				if (_GACPaths != null)
				{
					return _GACPaths;
				}
				if (!IsMono)
				{
					string environmentVariable = Environment.GetEnvironmentVariable("windir");
					if (string.IsNullOrEmpty(environmentVariable))
					{
						return _GACPaths = _GACPathsNone;
					}
					environmentVariable = Path.Combine(environmentVariable, "Microsoft.NET");
					environmentVariable = Path.Combine(environmentVariable, "assembly");
					_GACPaths = new string[3]
					{
						Path.Combine(environmentVariable, "GAC_32"),
						Path.Combine(environmentVariable, "GAC_64"),
						Path.Combine(environmentVariable, "GAC_MSIL")
					};
				}
				else
				{
					List<string> list = new List<string>();
					string text = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName)), "gac");
					if (Directory.Exists(text))
					{
						list.Add(text);
					}
					string environmentVariable2 = Environment.GetEnvironmentVariable("MONO_GAC_PREFIX");
					if (!string.IsNullOrEmpty(environmentVariable2))
					{
						string[] array = environmentVariable2.Split(new char[1] { Path.PathSeparator });
						foreach (string text2 in array)
						{
							if (!string.IsNullOrEmpty(text2))
							{
								string path = text2;
								path = Path.Combine(path, "lib");
								path = Path.Combine(path, "mono");
								path = Path.Combine(path, "gac");
								if (Directory.Exists(path) && !list.Contains(path))
								{
									list.Add(path);
								}
							}
						}
					}
					_GACPaths = list.ToArray();
				}
				return _GACPaths;
			}
			set
			{
				GACEnabled = true;
				_GACPaths = value;
			}
		}

		public MonoModder()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			MethodParser = DefaultParser;
			MissingDependencyResolver = DefaultMissingDependencyResolver;
			PostProcessors = (PostProcessor)Delegate.Combine(PostProcessors, new PostProcessor(DefaultPostProcessor));
			string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DEPDIRS");
			if (!string.IsNullOrEmpty(environmentVariable))
			{
				foreach (string item in from dir in environmentVariable.Split(new char[1] { Path.PathSeparator })
					select dir.Trim())
				{
					IAssemblyResolver assemblyResolver = AssemblyResolver;
					IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
					if (obj != null)
					{
						((BaseAssemblyResolver)obj).AddSearchDirectory(item);
					}
					DependencyDirs.Add(item);
				}
			}
			LogVerboseEnabled = Environment.GetEnvironmentVariable("MONOMOD_LOG_VERBOSE") == "1";
			CleanupEnabled = Environment.GetEnvironmentVariable("MONOMOD_CLEANUP") != "0";
			PublicEverything = Environment.GetEnvironmentVariable("MONOMOD_PUBLIC_EVERYTHING") == "1";
			PreventInline = Environment.GetEnvironmentVariable("MONOMOD_PREVENTINLINE") == "1";
			Strict = Environment.GetEnvironmentVariable("MONOMOD_STRICT") == "1";
			MissingDependencyThrow = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") != "0";
			RemovePatchReferences = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_REMOVE_PATCH") != "0";
			string environmentVariable2 = Environment.GetEnvironmentVariable("MONOMOD_DEBUG_FORMAT");
			if (environmentVariable2 != null)
			{
				environmentVariable2 = environmentVariable2.ToLowerInvariant();
				if (environmentVariable2 == "pdb")
				{
					DebugSymbolOutputFormat = DebugSymbolFormat.PDB;
				}
				else if (environmentVariable2 == "mdb")
				{
					DebugSymbolOutputFormat = DebugSymbolFormat.MDB;
				}
			}
			string environmentVariable3 = Environment.GetEnvironmentVariable("MONOMOD_MSCORLIB_UPGRADE");
			UpgradeMSCORLIB = (string.IsNullOrEmpty(environmentVariable3) ? null : new bool?(environmentVariable3 != "0"));
			GACEnabled = Environment.GetEnvironmentVariable("MONOMOD_GAC_ENABLED") != "0";
			MonoModRulesManager.Register(this);
		}

		public virtual void ClearCaches(bool all = false, bool shareable = false, bool moduleSpecific = false)
		{
			if (all || shareable)
			{
				foreach (KeyValuePair<string, ModuleDefinition> item in DependencyCache)
				{
					item.Value.Dispose();
				}
				DependencyCache.Clear();
			}
			if (all || moduleSpecific)
			{
				RelinkMapCache.Clear();
				RelinkModuleMapCache.Clear();
			}
		}

		public virtual void Dispose()
		{
			//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)
			ClearCaches(all: true);
			ModuleDefinition module = Module;
			if (module != null)
			{
				module.Dispose();
			}
			Module = null;
			((IDisposable)AssemblyResolver)?.Dispose();
			AssemblyResolver = null;
			foreach (ModuleDefinition mod in Mods)
			{
				if ((int)mod != 0)
				{
					mod.Dispose();
				}
			}
			foreach (List<ModuleDefinition> value in DependencyMap.Values)
			{
				foreach (ModuleDefinition item in value)
				{
					if (item != null)
					{
						item.Dispose();
					}
				}
			}
			DependencyMap.Clear();
			Input?.Dispose();
			Output?.Dispose();
		}

		public virtual void Log(object value)
		{
			Log(value.ToString());
		}

		public virtual void Log(string text)
		{
			Console.Write("[MonoMod] ");
			Console.WriteLine(text);
		}

		public virtual void LogVerbose(object value)
		{
			if (LogVerboseEnabled)
			{
				Log(value);
			}
		}

		public virtual void LogVerbose(string text)
		{
			if (LogVerboseEnabled)
			{
				Log(text);
			}
		}

		private static ModuleDefinition _ReadModule(Stream input, ReaderParameters args)
		{
			if (args.ReadSymbols)
			{
				try
				{
					return ModuleDefinition.ReadModule(input, args);
				}
				catch
				{
					args.ReadSymbols = false;
					input.Seek(0L, SeekOrigin.Begin);
				}
			}
			return ModuleDefinition.ReadModule(input, args);
		}

		private static ModuleDefinition _ReadModule(string input, ReaderParameters args)
		{
			if (args.ReadSymbols)
			{
				try
				{
					return ModuleDefinition.ReadModule(input, args);
				}
				catch
				{
					args.ReadSymbols = false;
				}
			}
			return ModuleDefinition.ReadModule(input, args);
		}

		public virtual void Read()
		{
			if (Module != null)
			{
				return;
			}
			if (Input != null)
			{
				Log("Reading input stream into module.");
				Module = _ReadModule(Input, GenReaderParameters(mainModule: true));
			}
			else if (InputPath != null)
			{
				Log("Reading input file into module.");
				IAssemblyResolver assemblyResolver = AssemblyResolver;
				IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
				if (obj != null)
				{
					((BaseAssemblyResolver)obj).AddSearchDirectory(Path.GetDirectoryName(InputPath));
				}
				DependencyDirs.Add(Path.GetDirectoryName(InputPath));
				Module = _ReadModule(InputPath, GenReaderParameters(mainModule: true, InputPath));
			}
			string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_MODS");
			if (string.IsNullOrEmpty(environmentVariable))
			{
				return;
			}
			foreach (string item in from path in environmentVariable.Split(new char[1] { Path.PathSeparator })
				select path.Trim())
			{
				ReadMod(item);
			}
		}

		public virtual void MapDependencies()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			foreach (ModuleDefinition mod in Mods)
			{
				ModuleDefinition main = mod;
				MapDependencies(main);
			}
			MapDependencies(Module);
		}

		public virtual void MapDependencies(ModuleDefinition main)
		{
			//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)
			if (DependencyMap.ContainsKey(main))
			{
				return;
			}
			DependencyMap[main] = new List<ModuleDefinition>();
			Enumerator<AssemblyNameReference> enumerator = main.AssemblyReferences.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					AssemblyNameReference current = enumerator.Current;
					MapDependency(main, current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void MapDependency(ModuleDefinition main, AssemblyNameReference depRef)
		{
			MapDependency(main, depRef.Name, depRef.FullName, depRef);
		}

		public virtual void MapDependency(ModuleDefinition main, string name, string fullName = null, AssemblyNameReference depRef = null)
		{
			if (!DependencyMap.TryGetValue(main, out var value))
			{
				value = (DependencyMap[main] = new List<ModuleDefinition>());
			}
			if (fullName != null && (DependencyCache.TryGetValue(fullName, out var value2) || DependencyCache.TryGetValue(fullName + " [RT:" + main.RuntimeVersion + "]", out value2)))
			{
				LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) from cache");
				value.Add(value2);
				MapDependencies(value2);
				return;
			}
			if (DependencyCache.TryGetValue(name, out value2) || DependencyCache.TryGetValue(name + " [RT:" + main.RuntimeVersion + "]", out value2))
			{
				LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " (" + name + ") from cache");
				value.Add(value2);
				MapDependencies(value2);
				return;
			}
			string text = Path.GetExtension(name).ToLowerInvariant();
			bool flag = text == "pdb" || text == "mdb";
			string text2 = null;
			foreach (string dependencyDir in DependencyDirs)
			{
				text2 = Path.Combine(dependencyDir, name + ".dll");
				if (!File.Exists(text2))
				{
					text2 = Path.Combine(dependencyDir, name + ".exe");
				}
				if (!File.Exists(text2) && !flag)
				{
					text2 = Path.Combine(dependencyDir, name);
				}
				if (File.Exists(text2))
				{
					break;
				}
				text2 = null;
			}
			if (text2 == null && depRef != null)
			{
				try
				{
					AssemblyDefinition obj = AssemblyResolver.Resolve(depRef);
					value2 = ((obj != null) ? obj.MainModule : null);
				}
				catch
				{
				}
				if (value2 != null)
				{
					text2 = value2.FileName;
				}
			}
			if (text2 == null)
			{
				string[] gACPaths = GACPaths;
				for (int i = 0; i < gACPaths.Length; i++)
				{
					text2 = Path.Combine(gACPaths[i], name);
					if (Directory.Exists(text2))
					{
						string[] directories = Directory.GetDirectories(text2);
						int num = 0;
						int num2 = 0;
						for (int j = 0; j < directories.Length; j++)
						{
							string text3 = directories[j];
							if (text3.StartsWith(text2))
							{
								text3 = text3.Substring(text2.Length + 1);
							}
							Match match = Regex.Match(text3, "\\d+");
							if (match.Success)
							{
								int num3 = int.Parse(match.Value);
								if (num3 > num)
								{
									num = num3;
									num2 = j;
								}
							}
						}
						text2 = Path.Combine(directories[num2], name + ".dll");
						break;
					}
					text2 = null;
				}
			}
			if (text2 == null)
			{
				try
				{
					AssemblyDefinition obj3 = AssemblyResolver.Resolve(AssemblyNameReference.Parse(fullName ?? name));
					value2 = ((obj3 != null) ? obj3.MainModule : null);
				}
				catch
				{
				}
				if (value2 != null)
				{
					text2 = value2.FileName;
				}
			}
			if (value2 == null)
			{
				if (text2 != null && File.Exists(text2))
				{
					value2 = _ReadModule(text2, GenReaderParameters(mainModule: false, text2));
				}
				else if ((value2 = MissingDependencyResolver?.Invoke(this, main, name, fullName)) == null)
				{
					return;
				}
			}
			LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) loaded");
			value.Add(value2);
			if (fullName == null)
			{
				fullName = value2.Assembly.FullName;
			}
			DependencyCache[fullName] = value2;
			DependencyCache[name] = value2;
			MapDependencies(value2);
		}

		public virtual ModuleDefinition DefaultMissingDependencyResolver(MonoModder mod, ModuleDefinition main, string name, string fullName)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if (MissingDependencyThrow && Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") == "0")
			{
				Log("[MissingDependencyResolver] [WARNING] Use MMILRT.Modder.MissingDependencyThrow instead of setting the env var MONOMOD_DEPENDENCY_MISSING_THROW");
				MissingDependencyThrow = false;
			}
			if (MissingDependencyThrow || Strict)
			{
				throw new RelinkTargetNotFoundException("MonoMod cannot map dependency " + ((ModuleReference)main).Name + " -> ((" + fullName + "), (" + name + ")) - not found", (IMetadataTokenProvider)(object)main, (IMetadataTokenProvider)null);
			}
			return null;
		}

		public virtual void Write(Stream output = null, string outputPath = null)
		{
			output = output ?? Output;
			outputPath = outputPath ?? OutputPath;
			PatchRefsInType(PatchWasHere());
			if (output != null)
			{
				Log("[Write] Writing modded module into output stream.");
				Module.Write(output, WriterParameters);
			}
			else
			{
				Log("[Write] Writing modded module into output file.");
				Module.Write(outputPath, WriterParameters);
			}
		}

		public virtual ReaderParameters GenReaderParameters(bool mainModule, string path = null)
		{
			//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_0013: Expected O, but got Unknown
			ReaderParameters readerParameters = ReaderParameters;
			ReaderParameters val = new ReaderParameters(readerParameters.ReadingMode);
			val.AssemblyResolver = readerParameters.AssemblyResolver;
			val.MetadataResolver = readerParameters.MetadataResolver;
			val.InMemory = readerParameters.InMemory;
			val.MetadataImporterProvider = readerParameters.MetadataImporterProvider;
			val.ReflectionImporterProvider = readerParameters.ReflectionImporterProvider;
			val.ThrowIfSymbolsAreNotMatching = readerParameters.ThrowIfSymbolsAreNotMatching;
			val.ApplyWindowsRuntimeProjections = readerParameters.ApplyWindowsRuntimeProjections;
			val.SymbolStream = readerParameters.SymbolStream;
			val.SymbolReaderProvider = readerParameters.SymbolReaderProvider;
			val.ReadSymbols = readerParameters.ReadSymbols;
			if (path != null && !File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
			{
				val.ReadSymbols = false;
			}
			return val;
		}

		public virtual void ReadMod(string path)
		{
			if (Directory.Exists(path))
			{
				Log("[ReadMod] Loading mod dir: " + path);
				string text = ((ModuleReference)Module).Name.Substring(0, ((ModuleReference)Module).Name.Length - 3);
				string value = text.Replace(" ", "");
				if (!DependencyDirs.Contains(path))
				{
					IAssemblyResolver assemblyResolver = AssemblyResolver;
					IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
					if (obj != null)
					{
						((BaseAssemblyResolver)obj).AddSearchDirectory(path);
					}
					DependencyDirs.Add(path);
				}
				string[] files = Directory.GetFiles(path);
				foreach (string text2 in files)
				{
					if ((Path.GetFileName(text2).StartsWith(text) || Path.GetFileName(text2).StartsWith(value)) && text2.ToLower().EndsWith(".mm.dll"))
					{
						ReadMod(text2);
					}
				}
				return;
			}
			Log("[ReadMod] Loading mod: " + path);
			ModuleDefinition val = _ReadModule(path, GenReaderParameters(mainModule: false, path));
			string directoryName = Path.GetDirectoryName(path);
			if (!DependencyDirs.Contains(directoryName))
			{
				IAssemblyResolver assemblyResolver2 = AssemblyResolver;
				IAssemblyResolver obj2 = ((assemblyResolver2 is BaseAssemblyResolver) ? assemblyResolver2 : null);
				if (obj2 != null)
				{
					((BaseAssemblyResolver)obj2).AddSearchDirectory(directoryName);
				}
				DependencyDirs.Add(directoryName);
			}
			Mods.Add((ModuleReference)(object)val);
			OnReadMod?.Invoke(this, val);
		}

		public virtual void ReadMod(Stream stream)
		{
			Log($"[ReadMod] Loading mod: stream#{(uint)stream.GetHashCode()}");
			ModuleDefinition val = _ReadModule(stream, GenReaderParameters(mainModule: false));
			Mods.Add((ModuleReference)(object)val);
			OnReadMod?.Invoke(this, val);
		}

		public virtual void ParseRules(ModuleDefinition mod)
		{
			//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)
			TypeDefinition type = mod.GetType("MonoMod.MonoModRules");
			Type rulesTypeMMILRT = null;
			if (type != null)
			{
				rulesTypeMMILRT = this.ExecuteRules(type);
				mod.Types.Remove(type);
			}
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					ParseRulesInType(current, rulesTypeMMILRT);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void ParseRulesInType(TypeDefinition type, Type rulesTypeMMILRT = null)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_0377: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_0431: Unknown result type (might be due to invalid IL or missing references)
			//IL_0436: Unknown result type (might be due to invalid IL or missing references)
			Extensions.GetPatchFullName((MemberReference)(object)type);
			if (!MatchingConditionals((ICustomAttributeProvider)(object)type, Module))
			{
				return;
			}
			CustomAttribute customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomAttributeAttribute");
			CustomAttributeArgument val;
			if (customAttribute != null)
			{
				val = customAttribute.ConstructorArguments[0];
				MethodInfo method2 = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value);
				CustomAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
				{
					method2.Invoke(self, args);
				};
			}
			customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomMethodAttributeAttribute");
			if (customAttribute != null)
			{
				val = customAttribute.ConstructorArguments[0];
				MethodInfo method = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value);
				ParameterInfo[] parameters = method.GetParameters();
				if (parameters.Length == 2 && Extensions.IsCompatible(parameters[0].ParameterType, typeof(ILContext)))
				{
					CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
					{
						//IL_0024: Unknown result type (might be due to invalid IL or missing references)
						//IL_002e: Expected O, but got Unknown
						//IL_0029: Unknown result type (might be due to invalid IL or missing references)
						//IL_0033: Expected O, but got Unknown
						//IL_0040: Unknown result type (might be due to invalid IL or missing references)
						//IL_004a: Expected O, but got Unknown
						ILContext il = new ILContext((MethodDefinition)args[0]);
						il.Invoke((Manipulator)delegate
						{
							method.Invoke(self, new object[2]
							{
								il,
								args[1]
							});
						});
						if (il.IsReadOnly)
						{
							il.Dispose();
						}
					};
				}
				else
				{
					CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
					{
						method.Invoke(self, args);
					};
				}
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModHook"))
			{
				ParseLinkFrom((MemberReference)(object)type, val2);
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
			{
				ParseLinkFrom((MemberReference)(object)type, val2);
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
			{
				ParseLinkTo((MemberReference)(object)type, val2);
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore"))
			{
				return;
			}
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current, val2);
						}
						if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCall"))
						{
							ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Call;
						}
						else if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCallvirt"))
						{
							ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Callvirt;
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<FieldDefinition> enumerator2 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					FieldDefinition current2 = enumerator2.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current2, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current2, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current2, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current2, val2);
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<PropertyDefinition> enumerator3 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					PropertyDefinition current3 = enumerator3.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current3, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current3, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current3, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current3, val2);
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<TypeDefinition> enumerator4 = type.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					TypeDefinition current4 = enumerator4.Current;
					ParseRulesInType(current4, rulesTypeMMILRT);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
		}

		public virtual void ParseLinkFrom(MemberReference target, CustomAttribute hook)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			CustomAttributeArgument val = hook.ConstructorArguments[0];
			string key = (string)((CustomAttributeArgument)(ref val)).Value;
			object value;
			if (target is TypeReference)
			{
				value = Extensions.GetPatchFullName((MemberReference)(TypeReference)target);
			}
			else if (target is MethodReference)
			{
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(MethodReference)target).DeclaringType), Extensions.GetID((MethodReference)target, (string)null, (string)null, false, false));
			}
			else if (target is FieldReference)
			{
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(FieldReference)target).DeclaringType), ((MemberReference)(FieldReference)target).Name);
			}
			else
			{
				if (!(target is PropertyReference))
				{
					return;
				}
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(PropertyReference)target).DeclaringType), ((MemberReference)(PropertyReference)target).Name);
			}
			RelinkMap[key] = value;
		}

		public virtual void ParseLinkTo(MemberReference from, CustomAttribute hook)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			MemberReference obj = ((from is MethodReference) ? from : null);
			string key = ((obj != null) ? Extensions.GetID((MethodReference)(object)obj, (string)null, (string)null, true, false) : null) ?? Extensions.GetPatchFullName(from);
			CustomAttributeArgument val;
			if (hook.ConstructorArguments.Count == 1)
			{
				Dictionary<string, object> relinkMap = RelinkMap;
				val = hook.ConstructorArguments[0];
				relinkMap[key] = (string)((CustomAttributeArgument)(ref val)).Value;
			}
			else
			{
				Dictionary<string, object> relinkMap2 = RelinkMap;
				val = hook.ConstructorArguments[0];
				string type = (string)((CustomAttributeArgument)(ref val)).Value;
				val = hook.ConstructorArguments[1];
				relinkMap2[key] = new RelinkMapEntry(type, (string)((CustomAttributeArgument)(ref val)).Value);
			}
		}

		public virtual void RunCustomAttributeHandlers(ICustomAttributeProvider cap)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			if (!cap.HasCustomAttributes)
			{
				return;
			}
			CustomAttribute[] array = cap.CustomAttributes.ToArray();
			foreach (CustomAttribute val in array)
			{
				if (CustomAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out var value))
				{
					value?.Invoke(null, new object[2] { cap, val });
				}
				if (cap is MethodReference && CustomMethodAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out value))
				{
					value?.Invoke(null, new object[2]
					{
						(object)(MethodDefinition)cap,
						val
					});
				}
			}
		}

		public virtual void AutoPatch()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			Log("[AutoPatch] Parsing rules in loaded mods");
			foreach (ModuleDefinition mod4 in Mods)
			{
				ModuleDefinition mod = mod4;
				ParseRules(mod);
			}
			Log("[AutoPatch] PrePatch pass");
			foreach (ModuleDefinition mod5 in Mods)
			{
				ModuleDefinition mod2 = mod5;
				PrePatchModule(mod2);
			}
			Log("[AutoPatch] Patch pass");
			foreach (ModuleDefinition mod6 in Mods)
			{
				ModuleDefinition mod3 = mod6;
				PatchModule(mod3);
			}
			Log("[AutoPatch] PatchRefs pass");
			PatchRefs();
			if (PostProcessors != null)
			{
				Delegate[] invocationList = PostProcessors.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					Log($"[PostProcessor] PostProcessor pass #{i + 1}");
					((PostProcessor)invocationList[i])?.Invoke(this);
				}
			}
		}

		public virtual IMetadataTokenProvider Relinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			//IL_0027: 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)
			try
			{
				return PostRelinker(MainRelinker(mtp, context) ?? mtp, context) ?? throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context);
			}
			catch (Exception ex)
			{
				throw new RelinkFailedException((string)null, ex, mtp, (IMetadataTokenProvider)(object)context);
			}
		}

		public virtual IMetadataTokenProvider MainRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			TypeReference val = (TypeReference)(object)((mtp is TypeReference) ? mtp : null);
			if (val != null)
			{
				if (((MemberReference)val).Module == Module)
				{
					return (IMetadataTokenProvider)(object)val;
				}
				if (((MemberReference)val).Module != null && !Mods.Contains((ModuleReference)(object)((MemberReference)val).Module))
				{
					return (IMetadataTokenProvider)(object)Module.ImportReference(val);
				}
				val = (TypeReference)(((object)Extensions.SafeResolve(val)) ?? ((object)val));
				TypeReference val2 = FindTypeDeep(Extensions.GetPatchFullName((MemberReference)(object)val));
				if (val2 == null)
				{
					if (RelinkMap.ContainsKey(((MemberReference)val).FullName))
					{
						return null;
					}
					throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context);
				}
				return (IMetadataTokenProvider)(object)Module.ImportReference(val2);
			}
			if (mtp is FieldReference || mtp is MethodReference || mtp is PropertyReference || mtp is EventReference)
			{
				return Extensions.ImportReference(Module, mtp);
			}
			throw new InvalidOperationException($"MonoMod default relinker can't handle metadata token providers of the type {((object)mtp).GetType()}");
		}

		public virtual IMetadataTokenProvider PostRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			return ResolveRelinkTarget(mtp) ?? mtp;
		}

		public virtual IMetadataTokenProvider ResolveRelinkTarget(IMetadataTokenProvider mtp, bool relink = true, bool relinkModule = true)
		{
			//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_002f: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Expected O, but got Unknown
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Expected O, but got Unknown
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			string text = null;
			string text2;
			if (mtp is TypeReference)
			{
				text2 = ((MemberReference)(TypeReference)mtp).FullName;
			}
			else if (mtp is MethodReference)
			{
				text2 = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, false);
				text = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, true);
			}
			else if (mtp is FieldReference)
			{
				text2 = ((MemberReference)(FieldReference)mtp).FullName;
			}
			else
			{
				if (!(mtp is PropertyReference))
				{
					return null;
				}
				text2 = ((MemberReference)(PropertyReference)mtp).FullName;
			}
			if (RelinkMapCache.TryGetValue(text2, out var value))
			{
				return value;
			}
			if (relink && (RelinkMap.TryGetValue(text2, out var value2) || (text != null && RelinkMap.TryGetValue(text, out value2))))
			{
				if (value2 is IMetadataTokenProvider)
				{
					return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2);
				}
				if (value2 is RelinkMapEntry)
				{
					string type = ((RelinkMapEntry)value2).Type;
					string findableID = ((RelinkMapEntry)value2).FindableID;
					TypeReference obj = FindTypeDeep(type);
					TypeDefinition val2 = ((obj != null) ? Extensions.SafeResolve(obj) : null);
					if (val2 == null)
					{
						return RelinkMapCache[text2] = ResolveRelinkTarget(mtp, relink: false, relinkModule);
					}
					value2 = Extensions.FindMethod(val2, findableID, true) ?? ((object)Extensions.FindField(val2, findableID)) ?? ((object)(Extensions.FindProperty(val2, findableID) ?? null));
					if (value2 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} ({1}, {2}) (remap: {3})", "MonoMod relinker failed finding", type, findableID, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2);
				}
				if (value2 is string && mtp is TypeReference)
				{
					IMetadataTokenProvider val5 = (IMetadataTokenProvider)(object)FindTypeDeep((string)value2);
					if (val5 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", value2, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					value2 = Extensions.ImportReference(Module, ResolveRelinkTarget(val5, relink: false, relinkModule) ?? val5);
				}
				if (value2 is IMetadataTokenProvider)
				{
					Dictionary<string, IMetadataTokenProvider> relinkMapCache = RelinkMapCache;
					string key = text2;
					IMetadataTokenProvider val6 = (IMetadataTokenProvider)value2;
					IMetadataTokenProvider result = val6;
					relinkMapCache[key] = val6;
					return result;
				}
				throw new InvalidOperationException($"MonoMod doesn't support RelinkMap value of type {value2.GetType()} (remap: {mtp})");
			}
			if (relinkModule && mtp is TypeReference)
			{
				if (RelinkModuleMapCache.TryGetValue(text2, out var value3))
				{
					return (IMetadataTokenProvider)(object)value3;
				}
				value3 = (TypeReference)mtp;
				if (RelinkModuleMap.TryGetValue(value3.Scope.Name, out var value4))
				{
					TypeReference type2 = (TypeReference)(object)value4.GetType(((MemberReference)value3).FullName);
					if (type2 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", ((MemberReference)value3).FullName, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					return (IMetadataTokenProvider)(object)(RelinkModuleMapCache[text2] = Module.ImportReference(type2));
				}
				return (IMetadataTokenProvider)(object)Module.ImportReference(value3);
			}
			return null;
		}

		public virtual bool DefaultParser(MonoModder mod, MethodBody body, Instruction instr, ref int instri)
		{
			return true;
		}

		public virtual TypeReference FindType(string name)
		{
			return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, false);
		}

		public virtual TypeReference FindType(string name, bool runtimeName)
		{
			return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, runtimeName);
		}

		protected virtual TypeReference FindType(ModuleDefinition main, string fullName, Stack<ModuleDefinition> crawled)
		{
			TypeReference type;
			if ((type = main.GetType(fullName, false)) != null)
			{
				return type;
			}
			if (fullName.StartsWith("<PrivateImplementationDetails>/"))
			{
				return null;
			}
			if (crawled.Contains(main))
			{
				return null;
			}
			crawled.Push(main);
			foreach (ModuleDefinition item in DependencyMap[main])
			{
				if ((!RemovePatchReferences || !((AssemblyNameReference)item.Assembly.Name).Name.EndsWith(".mm")) && (type = FindType(item, fullName, crawled)) != null)
				{
					return type;
				}
			}
			return null;
		}

		public virtual TypeReference FindTypeDeep(string name)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			TypeReference val = FindType(name, runtimeName: false);
			if (val != null)
			{
				return val;
			}
			Stack<ModuleDefinition> crawled = new Stack<ModuleDefinition>();
			val = null;
			foreach (ModuleDefinition mod in Mods)
			{
				ModuleDefinition key = mod;
				foreach (ModuleDefinition item in DependencyMap[key])
				{
					if ((val = FindType(item, name, crawled)) != null)
					{
						IMetadataScope scope = val.Scope;
						AssemblyNameReference dllRef = (AssemblyNameReference)(object)((scope is AssemblyNameReference) ? scope : null);
						if (dllRef != null && !((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference n) => n.Name == dllRef.Name))
						{
							Module.AssemblyReferences.Add(dllRef);
						}
						return Module.ImportReference(val);
					}
				}
			}
			return null;
		}

		public virtual void PrePatchModule(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: 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_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PrePatchType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<ModuleReference> enumerator2 = mod.ModuleReferences.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					ModuleReference current2 = enumerator2.Current;
					if (!Module.ModuleReferences.Contains(current2))
					{
						Module.ModuleReferences.Add(current2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<Resource> enumerator3 = mod.Resources.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					Resource current3 = enumerator3.Current;
					if (current3 is EmbeddedResource)
					{
						Module.Resources.Add((Resource)new EmbeddedResource(current3.Name.StartsWith(((AssemblyNameReference)mod.Assembly.Name).Name) ? (((AssemblyNameReference)Module.Assembly.Name).Name + current3.Name.Substring(((AssemblyNameReference)mod.Assembly.Name).Name.Length)) : current3.Name, current3.Attributes, ((EmbeddedResource)current3).GetResourceData()));
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
		}

		public virtual void PrePatchType(TypeDefinition type, bool forceAdd = false)
		{
			//IL_0102: 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_0113: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Expected O, but got Unknown
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Expected O, but got Unknown
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type);
			if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module) || (((MemberReference)type).FullName == "MonoMod.MonoModRules" && !forceAdd))
			{
				return;
			}
			TypeReference val = (forceAdd ? null : Module.GetType(patchFullName, false));
			TypeDefinition val2 = ((val != null) ? Extensions.SafeResolve(val) : null);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModReplace") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove"))
			{
				if (val2 != null)
				{
					if (val2.DeclaringType == null)
					{
						Module.Types.Remove(val2);
					}
					else
					{
						val2.DeclaringType.NestedTypes.Remove(val2);
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			else if (val != null)
			{
				PrePatchNested(type);
				return;
			}
			LogVerbose("[PrePatchType] Adding " + patchFullName + " to the target module.");
			TypeDefinition val3 = new TypeDefinition(((TypeReference)type).Namespace, ((MemberReference)type).Name, type.Attributes, type.BaseType);
			Enumerator<GenericParameter> enumerator = ((TypeReference)type).GenericParameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					GenericParameter current = enumerator.Current;
					((TypeReference)val3).GenericParameters.Add(Extensions.Clone(current));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<InterfaceImplementation> enumerator2 = type.Interfaces.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					InterfaceImplementation current2 = enumerator2.Current;
					val3.Interfaces.Add(current2);
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			val3.ClassSize = type.ClassSize;
			if (type.DeclaringType != null)
			{
				val3.DeclaringType = Extensions.Relink((TypeReference)(object)type.DeclaringType, new Relinker(Relinker), (IGenericParameterProvider)(object)val3).Resolve();
				val3.DeclaringType.NestedTypes.Add(val3);
			}
			else
			{
				Module.Types.Add(val3);
			}
			val3.PackingSize = type.PackingSize;
			Extensions.AddRange<SecurityDeclaration>(val3.SecurityDeclarations, (IEnumerable<SecurityDeclaration>)type.SecurityDeclarations);
			val3.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
			val = (TypeReference)(object)val3;
			PrePatchNested(type);
		}

		protected virtual void PrePatchNested(TypeDefinition type)
		{
			for (int i = 0; i < type.NestedTypes.Count; i++)
			{
				PrePatchType(type.NestedTypes[i]);
			}
		}

		public virtual void PatchModule(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					if ((((TypeReference)current).Namespace == "MonoMod" || ((TypeReference)current).Namespace.StartsWith("MonoMod.")) && ((MemberReference)current.BaseType).FullName == "System.Attribute")
					{
						PatchType(current);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current2 = enumerator.Current;
					if ((!(((TypeReference)current2).Namespace == "MonoMod") && !((TypeReference)current2).Namespace.StartsWith("MonoMod.")) || !(((MemberReference)current2.BaseType).FullName == "System.Attribute"))
					{
						PatchType(current2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchType(TypeDefinition type)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: 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_02b7: Unknown result type (might be due to invalid IL or missing references)
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type);
			TypeReference type2 = Module.GetType(patchFullName, false);
			if (type2 == null)
			{
				return;
			}
			TypeDefinition val = ((type2 != null) ? Extensions.SafeResolve(type2) : null);
			Enumerator<CustomAttribute> enumerator;
			if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module))
			{
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore") && val != null)
				{
					enumerator = type.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				PatchNested(type);
				return;
			}
			if (patchFullName == ((MemberReference)type).FullName)
			{
				LogVerbose("[PatchType] Patching type " + patchFullName);
			}
			else
			{
				LogVerbose("[PatchType] Patching type " + patchFullName + " (prefixed: " + ((MemberReference)type).FullName + ")");
			}
			enumerator = type.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current2 = enumerator.Current;
					if (!Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)val, ((MemberReference)current2.AttributeType).FullName))
					{
						val.CustomAttributes.Add(Extensions.Clone(current2));
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			HashSet<MethodDefinition> hashSet = new HashSet<MethodDefinition>();
			Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					PropertyDefinition current3 = enumerator2.Current;
					PatchProperty(val, current3, hashSet);
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			HashSet<MethodDefinition> hashSet2 = new HashSet<MethodDefinition>();
			Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					EventDefinition current4 = enumerator3.Current;
					PatchEvent(val, current4, hashSet2);
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodDefinition current5 = enumerator4.Current;
					if (!hashSet.Contains(current5) && !hashSet2.Contains(current5))
					{
						PatchMethod(val, current5);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModEnumReplace"))
			{
				int num = 0;
				while (num < val.Fields.Count)
				{
					if (((MemberReference)val.Fields[num]).Name == "value__")
					{
						num++;
					}
					else
					{
						val.Fields.RemoveAt(num);
					}
				}
			}
			Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator5.MoveNext())
				{
					FieldDefinition current6 = enumerator5.Current;
					PatchField(val, current6);
				}
			}
			finally
			{
				((IDisposable)enumerator5).Dispose();
			}
			PatchNested(type);
		}

		protected virtual void PatchNested(TypeDefinition type)
		{
			for (int i = 0; i < type.NestedTypes.Count; i++)
			{
				PatchType(type.NestedTypes[i]);
			}
		}

		public virtual void PatchProperty(TypeDefinition targetType, PropertyDefinition prop, HashSet<MethodDefinition> propMethods = null)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: 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_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Expected O, but got Unknown
			//IL_022b: Expected O, but got Unknown
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Expected O, but got Unknown
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: 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_02b3: Expected O, but got Unknown
			//IL_02b5: Expected O, but got Unknown
			//IL_0363: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			if (!MatchingConditionals((ICustomAttributeProvider)(object)prop, Module))
			{
				return;
			}
			((MemberReference)prop).Name = Extensions.GetPatchName((MemberReference)(object)prop);
			PropertyDefinition val = Extensions.FindProperty(targetType, ((MemberReference)prop).Name);
			string text = "<" + ((MemberReference)prop).Name + ">__BackingField";
			FieldDefinition val2 = Extensions.FindField(prop.DeclaringType, text);
			FieldDefinition val3 = Extensions.FindField(targetType, text);
			Enumerator<CustomAttribute> enumerator;
			Enumerator<MethodDefinition> enumerator2;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModIgnore"))
			{
				if (val != null)
				{
					enumerator = prop.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (val2 != null)
				{
					val2.DeclaringType.Fields.Remove(val2);
				}
				if (prop.GetMethod != null)
				{
					propMethods?.Add(prop.GetMethod);
				}
				if (prop.SetMethod != null)
				{
					propMethods?.Add(prop.SetMethod);
				}
				enumerator2 = prop.OtherMethods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						propMethods?.Add(current2);
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModReplace"))
			{
				if (val != null)
				{
					targetType.Properties.Remove(val);
					if (val3 != null)
					{
						targetType.Fields.Remove(val3);
					}
					if (val.GetMethod != null)
					{
						targetType.Methods.Remove(val.GetMethod);
					}
					if (val.SetMethod != null)
					{
						targetType.Methods.Remove(val.SetMethod);
					}
					enumerator2 = val.OtherMethods.GetEnumerator();
					try
					{
						while (enumerator2.MoveNext())
						{
							MethodDefinition current3 = enumerator2.Current;
							targetType.Methods.Remove(current3);
						}
					}
					finally
					{
						((IDisposable)enumerator2).Dispose();
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			if (val == null)
			{
				PropertyDefinition val4 = new PropertyDefinition(((MemberReference)prop).Name, prop.Attributes, ((PropertyReference)prop).PropertyType);
				val = val4;
				PropertyDefinition val5 = val4;
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				Enumerator<ParameterDefinition> enumerator3 = ((PropertyReference)prop).Parameters.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						ParameterDefinition current4 = enumerator3.Current;
						((PropertyReference)val5).Parameters.Add(Extensions.Clone(current4));
					}
				}
				finally
				{
					((IDisposable)enumerator3).Dispose();
				}
				val5.DeclaringType = targetType;
				targetType.Properties.Add(val5);
				if (val2 != null)
				{
					FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType);
					val3 = val6;
					FieldDefinition val7 = val6;
					targetType.Fields.Add(val7);
				}
			}
			enumerator = prop.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current5 = enumerator.Current;
					val.CustomAttributes.Add(Extensions.Clone(current5));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodDefinition getMethod = prop.GetMethod;
			MethodDefinition getMethod2;
			if (getMethod != null && (getMethod2 = PatchMethod(targetType, getMethod)) != null)
			{
				val.GetMethod = getMethod2;
				propMethods?.Add(getMethod);
			}
			MethodDefinition setMethod = prop.SetMethod;
			if (setMethod != null && (getMethod2 = PatchMethod(targetType, setMethod)) != null)
			{
				val.SetMethod = getMethod2;
				propMethods?.Add(setMethod);
			}
			enumerator2 = prop.OtherMethods.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					MethodDefinition current6 = enumerator2.Current;
					if ((getMethod2 = PatchMethod(targetType, current6)) != null)
					{
						val.OtherMethods.Add(getMethod2);
						propMethods?.Add(current6);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
		}

		public virtual void PatchEvent(TypeDefinition targetType, EventDefinition srcEvent, HashSet<MethodDefinition> propMethods = null)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Expected O, but got Unknown
			//IL_0252: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			//IL_0283: 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_0295: Expected O, but got Unknown
			//IL_0117: 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_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			((MemberReference)srcEvent).Name = Extensions.GetPatchName((MemberReference)(object)srcEvent);
			EventDefinition val = Extensions.FindEvent(targetType, ((MemberReference)srcEvent).Name);
			string text = "<" + ((MemberReference)srcEvent).Name + ">__BackingField";
			FieldDefinition val2 = Extensions.FindField(srcEvent.DeclaringType, text);
			FieldDefinition val3 = Extensions.FindField(targetType, text);
			Enumerator<CustomAttribute> enumerator;
			Enumerator<MethodDefinition> enumerator2;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModIgnore"))
			{
				if (val != null)
				{
					enumerator = srcEvent.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (val2 != null)
				{
					val2.DeclaringType.Fields.Remove(val2);
				}
				if (srcEvent.AddMethod != null)
				{
					propMethods?.Add(srcEvent.AddMethod);
				}
				if (srcEvent.RemoveMethod != null)
				{
					propMethods?.Add(srcEvent.RemoveMethod);
				}
				if (srcEvent.InvokeMethod != null)
				{
					propMethods?.Add(srcEvent.InvokeMethod);
				}
				enumerator2 = srcEvent.OtherMethods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						propMethods?.Add(current2);
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModReplace"))
			{
				if (val != null)
				{
					targetType.Events.Remove(val);
					if (val3 != null)
					{
						targetType.Fields.Remove(val3);
					}
					if (val.AddMethod != null)
					{
						targetType.Methods.Remove(val.AddMethod);
					}
					if (val.RemoveMethod != null)
					{
						targetType.Methods.Remove(val.RemoveMethod);
					}
					if (val.InvokeMethod != null)
					{
						targetType.Methods.Remove(val.InvokeMethod);
					}
					if (val.OtherMethods != null)
					{
						enumerator2 = val.OtherMethods.GetEnumerator();
						try
						{
							while (enumerator2.MoveNext())
							{
								MethodDefinition current3 = enumerator2.Current;
								targetType.Methods.Remove(current3);
							}
						}
						finally
						{
							((IDisposable)enumerator2).Dispose();
						}
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			if (val == null)
			{
				EventDefinition val4 = new EventDefinition(((MemberReference)srcEvent).Name, srcEvent.Attributes, ((EventReference)srcEvent).EventType);
				val = val4;
				EventDefinition val5 = val4;
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				val5.DeclaringType = targetType;
				targetType.Events.Add(val5);
				if (val2 != null)
				{
					FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType);
					targetType.Fields.Add(val6);
				}
			}
			enumerator = srcEvent.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current4 = enumerator.Current;
					val.CustomAttributes.Add(Extensions.Clone(current4));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodDefinition addMethod = srcEvent.AddMethod;
			MethodDefinition addMethod2;
			if (addMethod != null && (addMethod2 = PatchMethod(targetType, addMethod)) != null)
			{
				val.AddMethod = addMethod2;
				propMethods?.Add(addMethod);
			}
			MethodDefinition removeMethod = srcEvent.RemoveMethod;
			if (removeMethod != null && (addMethod2 = PatchMethod(targetType, removeMethod)) != null)
			{
				val.RemoveMethod = addMethod2;
				propMethods?.Add(removeMethod);
			}
			MethodDefinition invokeMethod = srcEvent.InvokeMethod;
			if (invokeMethod != null && (addMethod2 = PatchMethod(targetType, invokeMethod)) != null)
			{
				val.InvokeMethod = addMethod2;
				propMethods?.Add(invokeMethod);
			}
			enumerator2 = srcEvent.OtherMethods.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					MethodDefinition current5 = enumerator2.Current;
					if ((addMethod2 = PatchMethod(targetType, current5)) != null)
					{
						val.OtherMethods.Add(addMethod2);
						propMethods?.Add(current5);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
		}

		public virtual void PatchField(TypeDefinition targetType, FieldDefinition field)
		{
			//IL_0174: 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_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Expected O, but got Unknown
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)field.DeclaringType);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModNoNew") || SkipList.Contains(patchFullName + "::" + ((MemberReference)field).Name) || !MatchingConditionals((ICustomAttributeProvider)(object)field, Module))
			{
				return;
			}
			((MemberReference)field).Name = Extensions.GetPatchName((MemberReference)(object)field);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModReplace"))
			{
				FieldDefinition val = Extensions.FindField(targetType, ((MemberReference)field).Name);
				if (val != null)
				{
					targetType.Fields.Remove(val);
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			FieldDefinition val2 = Extensions.FindField(targetType, ((MemberReference)field).Name);
			Enumerator<CustomAttribute> enumerator;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModIgnore") && val2 != null)
			{
				enumerator = field.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
						{
							val2.CustomAttributes.Add(Extensions.Clone(current));
						}
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			}
			if (val2 == null)
			{
				val2 = new FieldDefinition(((MemberReference)field).Name, field.Attributes, ((FieldReference)field).FieldType);
				val2.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				val2.InitialValue = field.InitialValue;
				if (field.HasConstant)
				{
					val2.Constant = field.Constant;
				}
				targetType.Fields.Add(val2);
			}
			enumerator = field.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current2 = enumerator.Current;
					val2.CustomAttributes.Add(Extensions.Clone(current2));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual MethodDefinition PatchMethod(TypeDefinition targetType, MethodDefinition method)
		{
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: 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_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_049f: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bb: Expected O, but got Unknown
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0504: Unknown result type (might be due to invalid IL or missing references)
			//IL_0511: Unknown result type (might be due to invalid IL or missing references)
			//IL_0564: Unknown result type (might be due to invalid IL or missing references)
			//IL_0569: Unknown result type (might be due to invalid IL or missing references)
			//IL_0453: Unknown result type (might be due to invalid IL or missing references)
			//IL_0458: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Expected O, but got Unknown
			//IL_05a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_069a: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a1: Expected O, but got Unknown
			//IL_06be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0630: Unknown result type (might be due to invalid IL or missing references)
			//IL_0635: Unknown result type (might be due to invalid IL or missing references)
			//IL_0676: Unknown result type (might be due to invalid IL or missing references)
			//IL_0680: Expected O, but got Unknown
			if (((MemberReference)method).Name.StartsWith("orig_") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginal"))
			{
				return null;
			}
			if (!AllowedSpecialName(method, targetType) || !MatchingConditionals((ICustomAttributeProvider)(object)method, Module))
			{
				return null;
			}
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)targetType);
			if (SkipList.Contains(Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false)))
			{
				return null;
			}
			((MemberReference)method).Name = Extensions.GetPatchName((MemberReference)(object)method);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor"))
			{
				if (!method.IsSpecialName && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginalName"))
				{
					CustomAttribute val = new CustomAttribute(GetMonoModOriginalNameCtor());
					val.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)("orig_" + ((MemberReference)method).Name)));
					method.CustomAttributes.Add(val);
				}
				((MemberReference)method).Name = (method.IsStatic ? ".cctor" : ".ctor");
				method.IsSpecialName = true;
				method.IsRuntimeSpecialName = true;
			}
			MethodDefinition val2 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false), true);
			MethodDefinition obj = method;
			string text = patchFullName;
			MethodDefinition val3 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)obj, method.GetOriginalName(), text, true, false), true);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModIgnore"))
			{
				if (val2 != null)
				{
					Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val2.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				return null;
			}
			if (val2 == null && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModNoNew"))
			{
				return null;
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModRemove"))
			{
				if (val2 != null)
				{
					targetType.Methods.Remove(val2);
				}
				return null;
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModReplace"))
			{
				if (val2 != null)
				{
					val2.CustomAttributes.Clear();
					val2.Attributes = method.Attributes;
					val2.IsPInvokeImpl = method.IsPInvokeImpl;
					val2.ImplAttributes = method.ImplAttributes;
				}
			}
			else if (val2 != null && val3 == null)
			{
				val3 = Extensions.Clone(val2, (MethodDefinition)null);
				((MemberReference)val3).Name = method.GetOriginalName();
				val3.Attributes = (MethodAttributes)(val2.Attributes & 0xF7FF & 0xEFFF);
				((MemberReference)val3).MetadataToken = GetMetadataToken((TokenType)100663296);
				val3.IsVirtual = false;
				val3.Overrides.Clear();
				Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodReference current2 = enumerator2.Current;
						val3.Overrides.Add(current2);
					}
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
				val3.CustomAttributes.Add(new CustomAttribute(GetMonoModOriginalCtor()));
				MethodDefinition val4 = Extensions.FindMethod(method.DeclaringType, Extensions.GetID((MethodReference)(object)method, method.GetOriginalName(), (string)null, true, false), true);
				if (val4 != null)
				{
					Enumerator<CustomAttribute> enumerator = val4.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current3 = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName))
							{
								val3.CustomAttributes.Add(Extensions.Clone(current3));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				targetType.Methods.Add(val3);
			}
			if (val3 != null && method.IsConstructor && method.IsStatic && method.HasBody && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor"))
			{
				Collection<Instruction> instructions = method.Body.Instructions;
				ILProcessor iLProcessor = method.Body.GetILProcessor();
				iLProcessor.InsertBefore(instructions[instructions.Count - 1], iLProcessor.Create(OpCodes.Call, (MethodReference)(object)val3));
			}
			if (val2 != null)
			{
				val2.Body = Extensions.Clone(method.Body, val2);
				val2.IsManaged = method.IsManaged;
				val2.IsIL = method.IsIL;
				val2.IsNative = method.IsNative;
				val2.PInvokeInfo = method.PInvokeInfo;
				val2.IsPreserveSig = method.IsPreserveSig;
				val2.IsInternalCall = method.IsInternalCall;
				val2.IsPInvokeImpl = method.IsPInvokeImpl;
				Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current4 = enumerator.Current;
						val2.CustomAttributes.Add(Extensions.Clone(current4));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				method = val2;
			}
			else
			{
				MethodDefinition val5 = new MethodDefinition(((MemberReference)method).Name, method.Attributes, Module.TypeSystem.Void);
				((MemberReference)val5).MetadataToken = GetMetadataToken((TokenType)100663296);
				((MethodReference)val5).CallingConvention = ((MethodReference)method).CallingConvention;
				((MethodReference)val5).ExplicitThis = ((MethodReference)method).ExplicitThis;
				((MethodReference)val5).MethodReturnType = ((MethodReference)method).MethodReturnType;
				val5.Attributes = method.Attributes;
				val5.ImplAttributes = method.ImplAttributes;
				val5.SemanticsAttributes = method.SemanticsAttributes;
				val5.DeclaringType = targetType;
				((MethodReference)val5).ReturnType = ((MethodReference)method).ReturnType;
				val5.Body = Extensions.Clone(method.Body, val5);
				val5.PInvokeInfo = method.PInvokeInfo;
				val5.IsPInvokeImpl = method.IsPInvokeImpl;
				Enumerator<GenericParameter> enumerator3 = ((MethodReference)method).GenericParameters.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						GenericParameter current5 = enumerator3.Current;
						((MethodReference)val5).GenericParameters.Add(Extensions.Clone(current5));
					}
				}
				finally
				{
					((IDisposable)enumerator3).Dispose();
				}
				Enumerator<ParameterDefinition> enumerator4 = ((MethodReference)method).Parameters.GetEnumerator();
				try
				{
					while (enumerator4.MoveNext())
					{
						ParameterDefinition current6 = enumerator4.Current;
						((MethodReference)val5).Parameters.Add(Extensions.Clone(current6));
					}
				}
				finally
				{
					((IDisposable)enumerator4).Dispose();
				}
				Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current7 = enumerator.Current;
						val5.CustomAttributes.Add(Extensions.Clone(current7));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodReference current8 = enumerator2.Current;
						val5.Overrides.Add(current8);
					}
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				targetType.Methods.Add(val5);
				method = val5;
			}
			if (val3 != null)
			{
				CustomAttribute val6 = new CustomAttribute(GetMonoModOriginalNameCtor());
				val6.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)((MemberReference)val3).Name));
				method.CustomAttributes.Add(val6);
			}
			return method;
		}

		public virtual void PatchRefs()
		{
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			if (!UpgradeMSCORLIB.HasValue)
			{
				Version fckUnity = new Version(2, 0, 5, 0);
				UpgradeMSCORLIB = ((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference x) => x.Version == fckUnity);
			}
			if (UpgradeMSCORLIB.Value)
			{
				List<AssemblyNameReference> list = new List<AssemblyNameReference>();
				for (int i = 0; i < Module.AssemblyReferences.Count; i++)
				{
					AssemblyNameReference val = Module.AssemblyReferences[i];
					if (val.Name == "mscorlib")
					{
						list.Add(val);
					}
				}
				if (list.Count > 1)
				{
					AssemblyNameReference val2 = list.OrderByDescending((AssemblyNameReference x) => x.Version).First();
					if (DependencyCache.TryGetValue(val2.FullName, out var value))
					{
						for (int j = 0; j < Module.AssemblyReferences.Count; j++)
						{
							AssemblyNameReference val3 = Module.AssemblyReferences[j];
							if (val3.Name == "mscorlib" && val2.Version > val3.Version)
							{
								LogVerbose("[PatchRefs] Removing and relinking duplicate mscorlib: " + val3.Version);
								RelinkModuleMap[val3.FullName] = value;
								Module.AssemblyReferences.RemoveAt(j);
								j--;
							}
						}
					}
				}
			}
			Enumerator<TypeDefinition> enumerator = Module.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PatchRefsInType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchRefs(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PatchRefsInType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchRefsInType(TypeDefinition type)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Expected O, but got Unknown
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Expected O, but got Unknown
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Expected O, but got Unknown
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Expected O, but got Unknown
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Expected O, but got Unknown
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0308: Expected O, but got Unknown
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Expected O, but got Unknown
			LogVerbose($"[VERBOSE] [PatchRefsInType] Patching refs in {type}");
			if (type.BaseType != null)
			{
				type.BaseType = Extensions.Relink(type.BaseType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			for (int i = 0; i < ((TypeReference)type).GenericParameters.Count; i++)
			{
				((TypeReference)type).GenericParameters[i] = Extensions.Relink(((TypeReference)type).GenericParameters[i], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			for (int j = 0; j < type.Interfaces.Count; j++)
			{
				InterfaceImplementation obj = type.Interfaces[j];
				InterfaceImplementation val = new InterfaceImplementation(Extensions.Relink(obj.InterfaceType, new Relinker(Relinker), (IGenericParameterProvider)(object)type));
				Enumerator<CustomAttribute> enumerator = obj.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						val.CustomAttributes.Add(Extensions.Relink(current, new Relinker(Relinker), (IGenericParameterProvider)(object)type));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				type.Interfaces[j] = val;
			}
			for (int k = 0; k < type.CustomAttributes.Count; k++)
			{
				type.CustomAttributes[k] = Extensions.Relink(type.CustomAttributes[k], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					PropertyDefinition current2 = enumerator2.Current;
					((PropertyReference)current2).PropertyType = Extensions.Relink(((PropertyReference)current2).PropertyType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int l = 0; l < current2.CustomAttributes.Count; l++)
					{
						current2.CustomAttributes[l] = Extensions.Relink(current2.CustomAttributes[l], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					EventDefinition current3 = enumerator3.Current;
					((EventReference)current3).EventType = Extensions.Relink(((EventReference)current3).EventType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int m = 0; m < current3.CustomAttributes.Count; m++)
					{
						current3.CustomAttributes[m] = Extensions.Relink(current3.CustomAttributes[m], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodDefinition current4 = enumerator4.Current;
					PatchRefsInMethod(current4);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator5.MoveNext())
				{
					FieldDefinition current5 = enumerator5.Current;
					((FieldReference)current5).FieldType = Extensions.Relink(((FieldReference)current5).FieldType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int n = 0; n < current5.CustomAttributes.Count; n++)
					{
						current5.CustomAttributes[n] = Extensions.Relink(current5.CustomAttributes[n], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator5).Dispose();
			}
			for (int num = 0; num < type.NestedTypes.Count; num++)
			{
				PatchRefsInType(type.NestedTypes[num]);
			}
		}

		public virtual void PatchRefsInMethod(MethodDefinition method)
		{
			//IL_0030: Unknown result t

pachers/BepInEx.MonoMod.HookGenPatcher/MonoMod.RuntimeDetour.HookGen.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2021 0x0ade")]
[assembly: AssemblyDescription("Auto-generate hook helper .dlls, hook arbitrary methods via events: On.Namespace.Type.Method += YourHandlerHere;")]
[assembly: AssemblyFileVersion("21.8.5.1")]
[assembly: AssemblyInformationalVersion("21.08.05.01")]
[assembly: AssemblyProduct("MonoMod.RuntimeDetour.HookGen")]
[assembly: AssemblyTitle("MonoMod.RuntimeDetour.HookGen")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("21.8.5.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace MonoMod
{
	internal static class MMDbgLog
	{
		public static readonly string Tag;

		public static TextWriter Writer;

		public static bool Debugging;

		static MMDbgLog()
		{
			Tag = typeof(MMDbgLog).Assembly.GetName().Name;
			if (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1" || (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG")?.ToLowerInvariant()?.Contains(Tag.ToLowerInvariant())).GetValueOrDefault())
			{
				Start();
			}
		}

		public static void WaitForDebugger()
		{
			if (!Debugging)
			{
				Debugging = true;
				Debugger.Launch();
				Thread.Sleep(6000);
				Debugger.Break();
			}
		}

		public static void Start()
		{
			if (Writer != null)
			{
				return;
			}
			string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH");
			if (text == "-")
			{
				Writer = Console.Out;
				return;
			}
			if (string.IsNullOrEmpty(text))
			{
				text = "mmdbglog.txt";
			}
			text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text));
			try
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
			catch
			{
			}
			try
			{
				string directoryName = Path.GetDirectoryName(text);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8);
			}
			catch
			{
			}
		}

		public static void Log(string str)
		{
			TextWriter writer = Writer;
			if (writer != null)
			{
				writer.WriteLine(str);
				writer.Flush();
			}
		}

		public static T Log<T>(string str, T value)
		{
			TextWriter writer = Writer;
			if (writer == null)
			{
				return value;
			}
			writer.WriteLine(string.Format(str, value));
			writer.Flush();
			return value;
		}
	}
}
namespace MonoMod.RuntimeDetour.HookGen
{
	public class HookGenerator
	{
		private const string ObsoleteMessageBackCompat = "This method only exists for backwards-compatibility purposes.";

		private static readonly Regex NameVerifyRegex;

		private static readonly Dictionary<Type, string> ReflTypeNameMap;

		private static readonly Dictionary<string, string> TypeNameMap;

		public MonoModder Modder;

		public ModuleDefinition OutputModule;

		public string Namespace;

		public string NamespaceIL;

		public bool HookOrig;

		public bool HookPrivate;

		public string HookExtName;

		public ModuleDefinition module_RuntimeDetour;

		public ModuleDefinition module_Utils;

		public TypeReference t_MulticastDelegate;

		public TypeReference t_IAsyncResult;

		public TypeReference t_AsyncCallback;

		public TypeReference t_MethodBase;

		public TypeReference t_RuntimeMethodHandle;

		public TypeReference t_EditorBrowsableState;

		public MethodReference m_Object_ctor;

		public MethodReference m_ObsoleteAttribute_ctor;

		public MethodReference m_EditorBrowsableAttribute_ctor;

		public MethodReference m_GetMethodFromHandle;

		public MethodReference m_Add;

		public MethodReference m_Remove;

		public MethodReference m_Modify;

		public MethodReference m_Unmodify;

		public TypeReference t_ILManipulator;

		static HookGenerator()
		{
			NameVerifyRegex = new Regex("[^a-zA-Z]");
			ReflTypeNameMap = new Dictionary<Type, string>
			{
				{
					typeof(string),
					"string"
				},
				{
					typeof(object),
					"object"
				},
				{
					typeof(bool),
					"bool"
				},
				{
					typeof(byte),
					"byte"
				},
				{
					typeof(char),
					"char"
				},
				{
					typeof(decimal),
					"decimal"
				},
				{
					typeof(double),
					"double"
				},
				{
					typeof(short),
					"short"
				},
				{
					typeof(int),
					"int"
				},
				{
					typeof(long),
					"long"
				},
				{
					typeof(sbyte),
					"sbyte"
				},
				{
					typeof(float),
					"float"
				},
				{
					typeof(ushort),
					"ushort"
				},
				{
					typeof(uint),
					"uint"
				},
				{
					typeof(ulong),
					"ulong"
				},
				{
					typeof(void),
					"void"
				}
			};
			TypeNameMap = new Dictionary<string, string>();
			foreach (KeyValuePair<Type, string> item in ReflTypeNameMap)
			{
				TypeNameMap[item.Key.FullName] = item.Value;
			}
		}

		public HookGenerator(MonoModder modder, string name)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Expected O, but got Unknown
			//IL_0326: Expected O, but got Unknown
			Modder = modder;
			OutputModule = ModuleDefinition.CreateModule(name, new ModuleParameters
			{
				Architecture = modder.Module.Architecture,
				AssemblyResolver = modder.Module.AssemblyResolver,
				Kind = (ModuleKind)0,
				Runtime = modder.Module.Runtime
			});
			modder.MapDependencies();
			Extensions.AddRange<AssemblyNameReference>(OutputModule.AssemblyReferences, (IEnumerable<AssemblyNameReference>)modder.Module.AssemblyReferences);
			modder.DependencyMap[OutputModule] = new List<ModuleDefinition>(modder.DependencyMap[modder.Module]);
			Namespace = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE");
			if (string.IsNullOrEmpty(Namespace))
			{
				Namespace = "On";
			}
			NamespaceIL = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL");
			if (string.IsNullOrEmpty(NamespaceIL))
			{
				NamespaceIL = "IL";
			}
			HookOrig = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG") == "1";
			HookPrivate = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE") == "1";
			modder.MapDependency(modder.Module, "MonoMod.RuntimeDetour", (string)null, (AssemblyNameReference)null);
			if (!modder.DependencyCache.TryGetValue("MonoMod.RuntimeDetour", out module_RuntimeDetour))
			{
				throw new FileNotFoundException("MonoMod.RuntimeDetour not found!");
			}
			modder.MapDependency(modder.Module, "MonoMod.Utils", (string)null, (AssemblyNameReference)null);
			if (!modder.DependencyCache.TryGetValue("MonoMod.Utils", out module_Utils))
			{
				throw new FileNotFoundException("MonoMod.Utils not found!");
			}
			t_MulticastDelegate = OutputModule.ImportReference(modder.FindType("System.MulticastDelegate"));
			t_IAsyncResult = OutputModule.ImportReference(modder.FindType("System.IAsyncResult"));
			t_AsyncCallback = OutputModule.ImportReference(modder.FindType("System.AsyncCallback"));
			t_MethodBase = OutputModule.ImportReference(modder.FindType("System.Reflection.MethodBase"));
			t_RuntimeMethodHandle = OutputModule.ImportReference(modder.FindType("System.RuntimeMethodHandle"));
			t_EditorBrowsableState = OutputModule.ImportReference(modder.FindType("System.ComponentModel.EditorBrowsableState"));
			TypeDefinition type = module_RuntimeDetour.GetType("MonoMod.RuntimeDetour.HookGen.HookEndpointManager");
			t_ILManipulator = OutputModule.ImportReference((TypeReference)(object)module_Utils.GetType("MonoMod.Cil.ILContext/Manipulator"));
			m_Object_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.Object").Resolve(), "System.Void .ctor()", true));
			m_ObsoleteAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ObsoleteAttribute").Resolve(), "System.Void .ctor(System.String,System.Boolean)", true));
			m_EditorBrowsableAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ComponentModel.EditorBrowsableAttribute").Resolve(), "System.Void .ctor(System.ComponentModel.EditorBrowsableState)", true));
			ModuleDefinition outputModule = OutputModule;
			MethodReference val = new MethodReference("GetMethodFromHandle", t_MethodBase, t_MethodBase);
			val.Parameters.Add(new ParameterDefinition(t_RuntimeMethodHandle));
			m_GetMethodFromHandle = outputModule.ImportReference(val);
			m_Add = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Add", true));
			m_Remove = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Remove", true));
			m_Modify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Modify", true));
			m_Unmodify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Unmodify", true));
		}

		public void Generate()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = Modder.Module.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					GenerateFor(current, out var hookType, out var hookILType);
					if (hookType != null && hookILType != null && !((TypeReference)hookType).IsNested)
					{
						OutputModule.Types.Add(hookType);
						OutputModule.Types.Add(hookILType);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public void GenerateFor(TypeDefinition type, out TypeDefinition hookType, out TypeDefinition hookILType)
		{
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			//IL_0141: 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_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			hookType = (hookILType = null);
			if (((TypeReference)type).HasGenericParameters || type.IsRuntimeSpecialName || ((MemberReference)type).Name.StartsWith("<") || (!HookPrivate && type.IsNotPublic))
			{
				return;
			}
			Modder.LogVerbose("[HookGen] Generating for type " + ((MemberReference)type).FullName);
			hookType = new TypeDefinition(((TypeReference)type).IsNested ? null : (Namespace + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object);
			hookILType = new TypeDefinition(((TypeReference)type).IsNested ? null : (NamespaceIL + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object);
			bool flag = false;
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					flag |= GenerateFor(hookType, hookILType, current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<TypeDefinition> enumerator2 = type.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					TypeDefinition current2 = enumerator2.Current;
					GenerateFor(current2, out var hookType2, out var hookILType2);
					if (hookType2 != null && hookILType2 != null)
					{
						flag = true;
						hookType.NestedTypes.Add(hookType2);
						hookILType.NestedTypes.Add(hookILType2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			if (!flag)
			{
				hookType = (hookILType = null);
			}
		}

		public bool GenerateFor(TypeDefinition hookType, TypeDefinition hookILType, MethodDefinition method)
		{
			//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Expected O, but got Unknown
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Expected O, but got Unknown
			//IL_0380: Unknown result type (might be due to invalid IL or missing references)
			//IL_0387: Expected O, but got Unknown
			//IL_0392: Unknown result type (might be due to invalid IL or missing references)
			//IL_039c: Expected O, but got Unknown
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03aa: Expected O, but got Unknown
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ec: Expected O, but got Unknown
			//IL_03fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0407: Unknown result type (might be due to invalid IL or missing references)
			//IL_0443: Unknown result type (might be due to invalid IL or missing references)
			//IL_044a: Expected O, but got Unknown
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			//IL_045f: Expected O, but got Unknown
			//IL_0463: Unknown result type (might be due to invalid IL or missing references)
			//IL_046d: Expected O, but got Unknown
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0487: Unknown result type (might be due to invalid IL or missing references)
			//IL_0498: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04af: Expected O, but got Unknown
			//IL_04be: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0501: Expected O, but got Unknown
			//IL_0533: Unknown result type (might be due to invalid IL or missing references)
			//IL_053a: Expected O, but got Unknown
			//IL_0549: Unknown result type (might be due to invalid IL or missing references)
			//IL_0553: Expected O, but got Unknown
			//IL_0557: Unknown result type (might be due to invalid IL or missing references)
			//IL_0561: Expected O, but got Unknown
			//IL_056e: Unknown result type (might be due to invalid IL or missing references)
			//IL_057b: Unknown result type (might be due to invalid IL or missing references)
			//IL_058c: Unknown result type (might be due to invalid IL or missing references)
			//IL_059c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a3: Expected O, but got Unknown
			//IL_05b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0601: Expected O, but got Unknown
			//IL_0610: Unknown result type (might be due to invalid IL or missing references)
			//IL_061a: Expected O, but got Unknown
			//IL_061e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0628: Expected O, but got Unknown
			//IL_0635: Unknown result type (might be due to invalid IL or missing references)
			//IL_0642: Unknown result type (might be due to invalid IL or missing references)
			//IL_0653: Unknown result type (might be due to invalid IL or missing references)
			//IL_0663: Unknown result type (might be due to invalid IL or missing references)
			//IL_066a: Expected O, but got Unknown
			//IL_0679: Unknown result type (might be due to invalid IL or missing references)
			//IL_0685: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c0: Expected O, but got Unknown
			if (((MethodReference)method).HasGenericParameters || method.IsAbstract || (method.IsSpecialName && !method.IsConstructor))
			{
				return false;
			}
			if (!HookOrig && ((MemberReference)method).Name.StartsWith("orig_"))
			{
				return false;
			}
			if (!HookPrivate && method.IsPrivate)
			{
				return false;
			}
			string name = GetFriendlyName((MethodReference)(object)method);
			bool flag = true;
			if (((MethodReference)method).Parameters.Count == 0)
			{
				flag = false;
			}
			IEnumerable<MethodDefinition> source = null;
			if (flag)
			{
				source = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name && other != method);
				if (source.Count() == 0)
				{
					flag = false;
				}
			}
			if (flag)
			{
				StringBuilder stringBuilder = new StringBuilder();
				for (int parami = 0; parami < ((MethodReference)method).Parameters.Count; parami++)
				{
					ParameterDefinition param = ((MethodReference)method).Parameters[parami];
					if (!TypeNameMap.TryGetValue(((MemberReference)((ParameterReference)param).ParameterType).FullName, out var typeName))
					{
						typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: false);
					}
					if (source.Any(delegate(MethodDefinition other)
					{
						ParameterDefinition val11 = ((IEnumerable<ParameterDefinition>)((MethodReference)other).Parameters).ElementAtOrDefault(parami);
						return val11 != null && GetFriendlyName(((ParameterReference)val11).ParameterType, full: false) == typeName && ((ParameterReference)val11).ParameterType.Namespace != ((ParameterReference)param).ParameterType.Namespace;
					}))
					{
						typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: true);
					}
					stringBuilder.Append("_");
					stringBuilder.Append(typeName.Replace(".", "").Replace("`", ""));
				}
				name += stringBuilder.ToString();
			}
			if (Extensions.FindEvent(hookType, name) != null)
			{
				int num = 1;
				string text;
				while (Extensions.FindEvent(hookType, text = name + "_" + num) != null)
				{
					num++;
				}
				name = text;
			}
			TypeDefinition val = GenerateDelegateFor(method);
			((MemberReference)val).Name = "orig_" + name;
			val.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
			hookType.NestedTypes.Add(val);
			TypeDefinition val2 = GenerateDelegateFor(method);
			((MemberReference)val2).Name = "hook_" + name;
			((MethodReference)Extensions.FindMethod(val2, "Invoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val));
			((MethodReference)Extensions.FindMethod(val2, "BeginInvoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val));
			val2.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
			hookType.NestedTypes.Add(val2);
			MethodReference val3 = OutputModule.ImportReference((MethodReference)(object)method);
			MethodDefinition val4 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val4).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2));
			val4.Body = new MethodBody(val4);
			ILProcessor iLProcessor = val4.Body.GetILProcessor();
			iLProcessor.Emit(OpCodes.Ldtoken, val3);
			iLProcessor.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor.Emit(OpCodes.Ldarg_0);
			GenericInstanceMethod val5 = new GenericInstanceMethod(m_Add);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor.Emit(OpCodes.Ret);
			hookType.Methods.Add(val4);
			MethodDefinition val6 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val6).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2));
			val6.Body = new MethodBody(val6);
			ILProcessor iLProcessor2 = val6.Body.GetILProcessor();
			iLProcessor2.Emit(OpCodes.Ldtoken, val3);
			iLProcessor2.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor2.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Remove);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor2.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor2.Emit(OpCodes.Ret);
			hookType.Methods.Add(val6);
			EventDefinition val7 = new EventDefinition(name, (EventAttributes)0, (TypeReference)(object)val2)
			{
				AddMethod = val4,
				RemoveMethod = val6
			};
			hookType.Events.Add(val7);
			MethodDefinition val8 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val8).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator));
			val8.Body = new MethodBody(val8);
			ILProcessor iLProcessor3 = val8.Body.GetILProcessor();
			iLProcessor3.Emit(OpCodes.Ldtoken, val3);
			iLProcessor3.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor3.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Modify);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor3.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor3.Emit(OpCodes.Ret);
			hookILType.Methods.Add(val8);
			MethodDefinition val9 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val9).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator));
			val9.Body = new MethodBody(val9);
			ILProcessor iLProcessor4 = val9.Body.GetILProcessor();
			iLProcessor4.Emit(OpCodes.Ldtoken, val3);
			iLProcessor4.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor4.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Unmodify);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor4.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor4.Emit(OpCodes.Ret);
			hookILType.Methods.Add(val9);
			EventDefinition val10 = new EventDefinition(name, (EventAttributes)0, t_ILManipulator)
			{
				AddMethod = val8,
				RemoveMethod = val9
			};
			hookILType.Events.Add(val10);
			return true;
		}

		public TypeDefinition GenerateDelegateFor(MethodDefinition method)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Expected O, but got Unknown
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Expected O, but got Unknown
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Expected O, but got Unknown
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Expected O, but got Unknown
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Expected O, but got Unknown
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Expected O, but got Unknown
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Expected O, but got Unknown
			//IL_0279: 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_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Expected O, but got Unknown
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: Expected O, but got Unknown
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Expected O, but got Unknown
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Expected O, but got Unknown
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Expected O, but got Unknown
			//IL_0367: Unknown result type (might be due to invalid IL or missing references)
			//IL_0371: Expected O, but got Unknown
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Expected O, but got Unknown
			string name = GetFriendlyName((MethodReference)(object)method);
			int num = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name).ToList().IndexOf(method);
			if (num != 0)
			{
				string suffix = num.ToString();
				do
				{
					name = name + "_" + suffix;
				}
				while (((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Any((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name + suffix));
			}
			name = "d_" + name;
			TypeDefinition val = new TypeDefinition((string)null, (string)null, (TypeAttributes)258, t_MulticastDelegate);
			MethodDefinition val2 = new MethodDefinition(".ctor", (MethodAttributes)6278, OutputModule.TypeSystem.Void)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.Object));
			((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.IntPtr));
			val2.Body = new MethodBody(val2);
			val.Methods.Add(val2);
			MethodDefinition val3 = new MethodDefinition("Invoke", (MethodAttributes)454, ImportVisible(((MethodReference)method).ReturnType))
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			if (!method.IsStatic)
			{
				TypeReference val4 = ImportVisible((TypeReference)(object)method.DeclaringType);
				if (((TypeReference)method.DeclaringType).IsValueType)
				{
					val4 = (TypeReference)new ByReferenceType(val4);
				}
				((MethodReference)val3).Parameters.Add(new ParameterDefinition("self", (ParameterAttributes)0, val4));
			}
			Enumerator<ParameterDefinition> enumerator = ((MethodReference)method).Parameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ParameterDefinition current = enumerator.Current;
					((MethodReference)val3).Parameters.Add(new ParameterDefinition(((ParameterReference)current).Name, (ParameterAttributes)(current.Attributes & 0xFFEF & 0xEFFF), ImportVisible(((ParameterReference)current).ParameterType)));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			val3.Body = new MethodBody(val3);
			val.Methods.Add(val3);
			MethodDefinition val5 = new MethodDefinition("BeginInvoke", (MethodAttributes)454, t_IAsyncResult)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			enumerator = ((MethodReference)val3).Parameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ParameterDefinition current2 = enumerator.Current;
					((MethodReference)val5).Parameters.Add(new ParameterDefinition(((ParameterReference)current2).Name, current2.Attributes, ((ParameterReference)current2).ParameterType));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			((MethodReference)val5).Parameters.Add(new ParameterDefinition("callback", (ParameterAttributes)0, t_AsyncCallback));
			((MethodReference)val5).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, OutputModule.TypeSystem.Object));
			val5.Body = new MethodBody(val5);
			val.Methods.Add(val5);
			MethodDefinition val6 = new MethodDefinition("EndInvoke", (MethodAttributes)454, OutputModule.TypeSystem.Object)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			((MethodReference)val6).Parameters.Add(new ParameterDefinition("result", (ParameterAttributes)0, t_IAsyncResult));
			val6.Body = new MethodBody(val6);
			val.Methods.Add(val6);
			return val;
		}

		private string GetFriendlyName(MethodReference method)
		{
			string text = ((MemberReference)method).Name;
			if (text.StartsWith("."))
			{
				text = text.Substring(1);
			}
			return text.Replace('.', '_');
		}

		private string GetFriendlyName(TypeReference type, bool full)
		{
			if (type is TypeSpecification)
			{
				StringBuilder stringBuilder = new StringBuilder();
				BuildFriendlyName(stringBuilder, type, full);
				return stringBuilder.ToString();
			}
			if (!full)
			{
				return ((MemberReference)type).Name;
			}
			return ((MemberReference)type).FullName;
		}

		private void BuildFriendlyName(StringBuilder builder, TypeReference type, bool full)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (!(type is TypeSpecification))
			{
				builder.Append((full ? ((MemberReference)type).FullName : ((MemberReference)type).Name).Replace("_", ""));
				return;
			}
			if (type.IsByReference)
			{
				builder.Append("ref");
			}
			else if (type.IsPointer)
			{
				builder.Append("ptr");
			}
			BuildFriendlyName(builder, ((TypeSpecification)type).ElementType, full);
			if (type.IsArray)
			{
				builder.Append("Array");
			}
		}

		private bool IsPublic(TypeDefinition typeDef)
		{
			if (typeDef != null && (typeDef.IsNestedPublic || typeDef.IsPublic))
			{
				return !typeDef.IsNotPublic;
			}
			return false;
		}

		private bool HasPublicArgs(GenericInstanceType typeGen)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeReference> enumerator = typeGen.GenericArguments.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeReference current = enumerator.Current;
					if (current.IsGenericParameter)
					{
						return false;
					}
					GenericInstanceType val = (GenericInstanceType)(object)((current is GenericInstanceType) ? current : null);
					if (val != null && !HasPublicArgs(val))
					{
						return false;
					}
					if (!IsPublic(Extensions.SafeResolve(current)))
					{
						return false;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return true;
		}

		private TypeReference ImportVisible(TypeReference typeRef)
		{
			for (TypeDefinition val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null); val != null; val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null))
			{
				GenericInstanceType val2 = (GenericInstanceType)(object)((typeRef is GenericInstanceType) ? typeRef : null);
				if (val2 == null || HasPublicArgs(val2))
				{
					TypeDefinition val3 = val;
					while (true)
					{
						if (val3 != null)
						{
							if (IsPublic(val3) && (val3 == val || !((TypeReference)val3).HasGenericParameters))
							{
								val3 = val3.DeclaringType;
								continue;
							}
							if (!val.IsEnum)
							{
								break;
							}
							typeRef = ((FieldReference)Extensions.FindField(val, "value__")).FieldType;
						}
						try
						{
							return OutputModule.ImportReference(typeRef);
						}
						catch
						{
							return OutputModule.TypeSystem.Object;
						}
					}
				}
				typeRef = val.BaseType;
			}
			return OutputModule.TypeSystem.Object;
		}

		private CustomAttribute GenerateObsolete(string message, bool error)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			CustomAttribute val = new CustomAttribute(m_ObsoleteAttribute_ctor);
			val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.String, (object)message));
			val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.Boolean, (object)error));
			return val;
		}

		private CustomAttribute GenerateEditorBrowsable(EditorBrowsableState state)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			CustomAttribute val = new CustomAttribute(m_EditorBrowsableAttribute_ctor);
			val.ConstructorArguments.Add(new CustomAttributeArgument(t_EditorBrowsableState, (object)state));
			return val;
		}
	}
	internal class Program
	{
		private static void Main(string[] args)
		{
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: 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_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Expected O, but got Unknown
			Console.WriteLine("MonoMod.RuntimeDetour.HookGen " + typeof(Program).Assembly.GetName().Version);
			Console.WriteLine("using MonoMod " + typeof(MonoModder).Assembly.GetName().Version);
			Console.WriteLine("using MonoMod.RuntimeDetour " + typeof(Detour).Assembly.GetName().Version);
			if (args.Length == 0)
			{
				Console.WriteLine("No valid arguments (assembly path) passed.");
				if (Debugger.IsAttached)
				{
					Console.ReadKey();
				}
				return;
			}
			int num = 0;
			for (int i = 0; i < args.Length; i++)
			{
				if (args[i] == "--namespace" && i + 2 < args.Length)
				{
					i++;
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE", args[i]);
					continue;
				}
				if (args[i] == "--namespace-il" && i + 2 < args.Length)
				{
					i++;
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL", args[i]);
					continue;
				}
				if (args[i] == "--orig")
				{
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG", "1");
					continue;
				}
				if (args[i] == "--private")
				{
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1");
					continue;
				}
				num = i;
				break;
			}
			if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW")))
			{
				Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0");
			}
			if (num >= args.Length)
			{
				Console.WriteLine("No assembly path passed.");
				if (Debugger.IsAttached)
				{
					Console.ReadKey();
				}
				return;
			}
			string text = args[num];
			string text2 = ((args.Length != 1 && num != args.Length - 1) ? args[^1] : null);
			text2 = text2 ?? Path.Combine(Path.GetDirectoryName(text), "MMHOOK_" + Path.ChangeExtension(Path.GetFileName(text), "dll"));
			MonoModder val = new MonoModder
			{
				InputPath = text,
				OutputPath = text2,
				ReadingMode = (ReadingMode)2
			};
			try
			{
				val.Read();
				val.MapDependencies();
				if (File.Exists(text2))
				{
					val.Log("[HookGen] Clearing " + text2);
					File.Delete(text2);
				}
				val.Log("[HookGen] Starting HookGenerator");
				HookGenerator hookGenerator = new HookGenerator(val, Path.GetFileName(text2));
				ModuleDefinition outputModule = hookGenerator.OutputModule;
				try
				{
					hookGenerator.Generate();
					outputModule.Write(text2);
				}
				finally
				{
					((IDisposable)outputModule)?.Dispose();
				}
				val.Log("[HookGen] Done.");
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			if (Debugger.IsAttached)
			{
				Console.ReadKey();
			}
		}
	}
}

plugins/CoilHeadStare.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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using TDP.CoilHeadStare.Patch;
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("CoilHeadStare")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CoilHeadStare")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9d96f0c2-6393-4d02-99d7-34538a0dad5c")]
[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 TDP.CoilHeadStare
{
	[BepInPlugin("TDP.CoilHeadStare", "CoilHeadStare", "1.0.6")]
	public class ModBase : BaseUnityPlugin
	{
		private const string modGUID = "TDP.CoilHeadStare";

		private const string modName = "CoilHeadStare";

		private const string modVersion = "1.0.6";

		private Harmony harmony;

		internal static ModBase instance;

		internal ManualLogSource mls;

		public static ConfigEntry<float> config_timeUntilStare;

		public static ConfigEntry<float> config_maxStareDistance;

		public static ConfigEntry<float> config_turnHeadSpeed;

		public static ConfigEntry<bool> config_shovelReact;

		private void Awake()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			if ((Object)(object)instance == (Object)null)
			{
				instance = this;
			}
			else
			{
				Object.Destroy((Object)(object)this);
			}
			ConfigFile();
			harmony = new Harmony("TDP.CoilHeadStare");
			harmony.PatchAll(typeof(CoilHeadPatch));
			mls = Logger.CreateLogSource("TDP.CoilHeadStare");
			mls.LogInfo((object)"CoilHeadStare 1.0.6 loaded.");
		}

		private void ConfigFile()
		{
			config_timeUntilStare = ((BaseUnityPlugin)this).Config.Bind<float>("CoilHeadStare", "Time Until Stare", 8f, "Time between moving and looking at closest player (in seconds)");
			config_maxStareDistance = ((BaseUnityPlugin)this).Config.Bind<float>("CoilHeadStare", "Max Stare Distance", 6f, "Coilhead will only stare at players closer than this (for reference: coilhead's height is ca. 4)");
			config_turnHeadSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("CoilHeadStare", "Head Turn Speed", 0.3f, "The speed at which the head turns towards the player");
			config_shovelReact = ((BaseUnityPlugin)this).Config.Bind<bool>("CoilHeadStare", "Head Bounce on Shovel Hit", true, "Should the coilhead spring wobble when hit with a shovel (or with anything else)");
			Stare.timeUntilStare = config_timeUntilStare.Value;
			Stare.maxStareDistance = config_maxStareDistance.Value;
			Stare.turnHeadSpeed = config_turnHeadSpeed.Value;
			CoilHeadPatch.shovelReact = config_shovelReact.Value;
		}
	}
}
namespace TDP.CoilHeadStare.Patch
{
	internal class CoilHeadPatch
	{
		public static bool shovelReact;

		[HarmonyPatch(typeof(EnemyAI), "Start")]
		[HarmonyPostfix]
		[HarmonyPriority(200)]
		private static void StartPostFix(EnemyAI __instance)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			if (__instance is SpringManAI)
			{
				Debug.Log((object)"CoilHead found. Adding stare script.");
				Stare stare = ((Component)__instance).gameObject.AddComponent<Stare>();
				stare.Initialize((SpringManAI)__instance);
			}
		}

		[HarmonyPatch(typeof(EnemyAI), "HitEnemy")]
		[HarmonyPrefix]
		public static void HitEnemyPreFix(EnemyAI __instance)
		{
			if (shovelReact)
			{
				__instance.creatureAnimator.SetTrigger("springBoing");
			}
		}
	}
	public class Stare : MonoBehaviour
	{
		private SpringManAI coilHeadInstance;

		public static float timeUntilStare;

		public static float maxStareDistance;

		public static float turnHeadSpeed;

		private Transform head;

		private float timeSinceMoving;

		private bool isTurningHead;

		private PlayerControllerB stareTarget;

		public void Initialize(SpringManAI instance)
		{
			Debug.Log((object)"Initializing Stare on Coil Head.");
			coilHeadInstance = instance;
			if ((Object)(object)coilHeadInstance == (Object)null)
			{
				Debug.LogError((object)"Coil Head instance missing. Harmony Patch failed?");
			}
			head = FindChildren(((Component)coilHeadInstance).transform, "springBone.002").Last();
			if ((Object)(object)head != (Object)null)
			{
				head = head.GetChild(head.childCount - 1);
			}
			if ((Object)(object)head == (Object)null)
			{
				Debug.LogError((object)"CoilHeadStare could not find head transform. Destroying script. (Coil Head should be unaffected by this)");
				Object.Destroy((Object)(object)this);
			}
			else
			{
				Debug.Log((object)("CoilHeadStare found head transform: " + ((Object)head).name));
			}
		}

		private List<Transform> FindChildren(Transform parent, string name)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			List<Transform> list = new List<Transform>();
			foreach (Transform item in parent)
			{
				Transform val = item;
				if (((Object)val).name == name)
				{
					list.Add(val);
				}
				else
				{
					list.AddRange(FindChildren(val, name));
				}
			}
			return list;
		}

		private void Start()
		{
			Debug.Log((object)"Coil Head stare initialization successful. \nNote: If a reskin is being used and the head does not turn it is most likely incompatible.");
		}

		private void Update()
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: 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_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0181: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)coilHeadInstance == (Object)null)
			{
				return;
			}
			if ((Object)(object)head == (Object)null)
			{
				Debug.LogError((object)"CoilHeadStare head transform missing. Destroying script.");
				Object.Destroy((Object)(object)this);
				return;
			}
			if (!isTurningHead)
			{
				stareTarget = ((EnemyAI)coilHeadInstance).GetClosestPlayer(false, false, false);
			}
			if (!((Object)(object)stareTarget == (Object)null))
			{
				Vector3 val = ((Component)stareTarget.gameplayCamera).transform.position - head.position;
				float num = Vector3.Distance(head.position, ((Component)((EnemyAI)coilHeadInstance).GetClosestPlayer(false, false, false)).transform.position);
				if ((double)((EnemyAI)coilHeadInstance).creatureAnimator.GetFloat("walkSpeed") > 0.01 || num > maxStareDistance || Vector3.Angle(head.forward, val) < 5f)
				{
					timeSinceMoving = 0f;
				}
				else
				{
					timeSinceMoving += Time.deltaTime;
				}
				if (timeSinceMoving > timeUntilStare)
				{
					isTurningHead = true;
				}
				else
				{
					isTurningHead = false;
				}
				if (isTurningHead)
				{
					head.forward = Vector3.RotateTowards(head.forward, val, turnHeadSpeed * Time.deltaTime, 0f);
				}
			}
		}
	}
}

plugins/CorporateRestructure.dll

Decompiled 7 months ago
using System;
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 BepInEx.Configuration;
using CorporateRestructure.Component;
using CorporateRestructure.Patch;
using GameNetcodeStuff;
using HarmonyLib;
using TMPro;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("CorporateRestructure")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CorporateRestructure")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("91760104-3647-46D9-988A-6D5B72EA80C6")]
[assembly: AssemblyFileVersion("1.0.6")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.6.0")]
namespace CorporateRestructure
{
	[BepInPlugin("jamil.corporate_restructure", "Corporate Restructure", "1.0.6")]
	public class CorporateRestructure : BaseUnityPlugin
	{
		private readonly Harmony _harmony = new Harmony("jamil.corporate_restructure");

		public static ConfigFile config;

		public static CorporateRestructure Instance { get; private set; }

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Corporate Restructure -> loading");
				Instance = this;
				config = ((BaseUnityPlugin)this).Config;
				CorporateConfig.Initialize();
				Instance.Patch();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Corporate Restructure -> complete");
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Corporate Restructure -> Awoke a second time?");
			}
		}

		private void Patch()
		{
			Instance._harmony.PatchAll(typeof(MonitorPatch));
			Instance._harmony.PatchAll(typeof(WeatherPatch));
		}
	}
	public class CorporateConfig
	{
		public const string Guid = "jamil.corporate_restructure";

		public const string Name = "Corporate Restructure";

		public const string Version = "1.0.6";

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

		public static void Initialize()
		{
			HideWeather = CorporateRestructure.config.Bind<bool>("General", "HideWeather", false, "Disables Weather from the navigation screen, and Terminal");
		}
	}
}
namespace CorporateRestructure.Patch
{
	internal class DevPatch
	{
	}
	internal class MonitorPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "Start")]
		private static void Initialize()
		{
			InitializeMonitorCluster();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "ReviveDeadPlayers")]
		private static void PlayerHasRevivedServerRpc()
		{
			LootMonitor.UpdateMonitor();
			CreditMonitor.UpdateMonitor();
			DayMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HUDManager), "ApplyPenalty")]
		private static void ApplyPenalty()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(DepositItemsDesk), "SellAndDisplayItemProfits")]
		private static void SellLoot()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(TimeOfDay), "SyncNewProfitQuotaClientRpc")]
		private static void OvertimeBonus()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")]
		private static void RefreshLootForClientOnStart()
		{
			LootMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		private static void OnPlayerConenct()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(TimeOfDay), "MoveTimeOfDay")]
		private static void RefreshClock()
		{
			TimeMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")]
		private static void RefreshLootOnPickupClient(bool grabValidated, NetworkObjectReference grabbedObject)
		{
			NetworkObject val = default(NetworkObject);
			if (((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null))
			{
				GrabbableObject componentInChildren = ((Component)val).gameObject.GetComponentInChildren<GrabbableObject>();
				if (componentInChildren.isInShipRoom | componentInChildren.isInElevator)
				{
					LootMonitor.UpdateMonitor();
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ThrowObjectClientRpc")]
		private static void RefreshLootOnThrowClient(bool droppedInElevator, bool droppedInShipRoom, Vector3 targetFloorPosition, NetworkObjectReference grabbedObject)
		{
			if (droppedInShipRoom || droppedInElevator)
			{
				LootMonitor.UpdateMonitor();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "ChangeLevelClientRpc")]
		private static void SwitchPlanets()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Terminal), "SyncGroupCreditsClientRpc")]
		private static void RefreshMoney()
		{
			CreditMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "EndOfGameClientRpc")]
		private static void RefreshDay()
		{
			DayMonitor.UpdateMonitor();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "StartGame")]
		private static void StartGame()
		{
			DayMonitor.UpdateMonitor();
		}

		private static void InitializeMonitorCluster()
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected O, but got Unknown
			//IL_0155: 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_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: 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_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Expected O, but got Unknown
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: 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_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Expected O, but got Unknown
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Unknown result type (might be due to invalid IL or missing references)
			//IL_0337: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			//IL_038d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0392: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)/MainContainer" ?? "");
			GameObject val2 = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)/MainContainer" + "/HeaderText");
			Object.Destroy((Object)(object)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)/MainContainer" + "/BG"));
			GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)/MainContainer" + "/HeaderText (1)");
			Object.Destroy((Object)(object)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)/MainContainer" + "/BG (1)"));
			GameObject val3 = new GameObject("lootMonitor");
			val3.transform.parent = val.transform;
			val3.transform.position = val.transform.position;
			val3.transform.localPosition = val.transform.localPosition;
			val3.transform.localScale = Vector3.one;
			val3.transform.rotation = Quaternion.Euler(Vector3.zero);
			GameObject obj = Object.Instantiate<GameObject>(val2, val3.transform);
			((Object)obj).name = "lootMonitorText";
			obj.transform.localPosition = new Vector3(-95f, 450f, 220f);
			obj.transform.rotation = Quaternion.Euler(new Vector3(-20f, 90f, 0f));
			obj.AddComponent<LootMonitor>();
			GameObject val4 = new GameObject("timeMonitor");
			val4.transform.parent = val.transform;
			val4.transform.position = val.transform.position;
			val4.transform.localPosition = val.transform.localPosition;
			val4.transform.localScale = Vector3.one;
			val4.transform.rotation = Quaternion.Euler(Vector3.zero);
			GameObject obj2 = Object.Instantiate<GameObject>(val2, val4.transform);
			((Object)obj2).name = "timeMonitorText";
			obj2.transform.localPosition = new Vector3(-95f, 450f, -250f);
			obj2.transform.rotation = Quaternion.Euler(new Vector3(-20f, 90f, 0f));
			obj2.AddComponent<TimeMonitor>();
			GameObject val5 = new GameObject("creditMonitor");
			val5.transform.parent = val.transform;
			val5.transform.position = val.transform.position;
			val5.transform.localPosition = val.transform.localPosition;
			val5.transform.localScale = Vector3.one;
			val5.transform.rotation = Quaternion.Euler(Vector3.zero);
			GameObject obj3 = Object.Instantiate<GameObject>(val2, val5.transform);
			((Object)obj3).name = "creditMonitorText";
			obj3.transform.localPosition = new Vector3(-198f, 450f, -750f);
			obj3.transform.rotation = Quaternion.Euler(new Vector3(-20f, 117f, 0f));
			obj3.AddComponent<CreditMonitor>();
			GameObject val6 = new GameObject("dayMonitor");
			val6.transform.parent = val.transform;
			val6.transform.position = val.transform.position;
			val6.transform.localPosition = val.transform.localPosition;
			val6.transform.localScale = Vector3.one;
			val6.transform.rotation = Quaternion.Euler(Vector3.zero);
			GameObject obj4 = Object.Instantiate<GameObject>(val2, val6.transform);
			((Object)obj4).name = "dayMonitorText";
			obj4.transform.localPosition = new Vector3(-413f, 450f, -1185f);
			obj4.transform.rotation = Quaternion.Euler(new Vector3(-21f, 117f, 0f));
			obj4.AddComponent<DayMonitor>();
		}
	}
	internal class WeatherPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "SetMapScreenInfoToCurrentLevel")]
		private static void ColorWeather(ref TextMeshProUGUI ___screenLevelDescription, ref SelectableLevel ___currentLevel)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("Orbiting: " + ___currentLevel.PlanetName + "\n");
			stringBuilder.Append("Weather: " + FormatWeather(___currentLevel.currentWeather) + "\n");
			stringBuilder.Append(___currentLevel.LevelDescription ?? "");
			((TMP_Text)___screenLevelDescription).text = stringBuilder.ToString();
		}

		private static string FormatWeather(LevelWeatherType currentWeather)
		{
			//IL_0023: 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_0047: Expected I4, but got Unknown
			string text = "FFFFFF";
			if (CorporateConfig.HideWeather.Value)
			{
				return "<color=#" + text + ">UNKNOWN</color>";
			}
			switch (currentWeather - -1)
			{
			case 0:
			case 1:
				text = "69FF6B";
				break;
			case 2:
			case 4:
				text = "FFDC00";
				break;
			case 3:
			case 5:
				text = "FF9300";
				break;
			case 6:
				text = "FF0000";
				break;
			}
			return "<color=#" + text + ">" + ((object)(LevelWeatherType)(ref currentWeather)).ToString() + "</color>";
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Terminal), "TextPostProcess")]
		private static string HideWeatherConditions(string __result)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (CorporateConfig.HideWeather.Value)
			{
				foreach (LevelWeatherType value in Enum.GetValues(typeof(LevelWeatherType)))
				{
					LevelWeatherType val = value;
					__result = __result.Replace("(" + ((object)(LevelWeatherType)(ref val)).ToString() + ")", "");
				}
			}
			return __result;
		}
	}
}
namespace CorporateRestructure.Component
{
	public class DayMonitor : MonoBehaviour
	{
		private static StartOfRound _startOfRound;

		private static TextMeshProUGUI _textMesh;

		private static EndOfGameStats _stats;

		public void Start()
		{
			_startOfRound = StartOfRound.Instance;
			_textMesh = ((Component)this).GetComponent<TextMeshProUGUI>();
			_stats = _startOfRound.gameStats;
			if (!((NetworkBehaviour)_startOfRound).IsHost)
			{
				((TMP_Text)_textMesh).text = "DAY:\n?";
			}
			else
			{
				UpdateMonitor();
			}
		}

		public static void UpdateMonitor()
		{
			((TMP_Text)_textMesh).text = $"DAY:\n{_stats.daysSpent}";
		}
	}
	public class LootMonitor : MonoBehaviour
	{
		private static LootMonitor _lootMonitor;

		private static TextMeshProUGUI _textMesh;

		private static GameObject _ship;

		public void Start()
		{
			_lootMonitor = this;
			_textMesh = ((Component)this).GetComponent<TextMeshProUGUI>();
			((TMP_Text)_textMesh).text = "LOOT:\n$NaN";
			_ship = GameObject.Find("/Environment/HangarShip");
			UpdateMonitor();
		}

		public static void UpdateMonitor()
		{
			float num = Calculate();
			((TMP_Text)_textMesh).text = $"LOOT:\n${num}";
		}

		private static float Calculate()
		{
			return (from x in _ship.GetComponentsInChildren<GrabbableObject>()
				where x.itemProperties.isScrap && !x.isPocketed && !x.isHeld
				select x).Sum((GrabbableObject x) => x.scrapValue);
		}
	}
	public class CreditMonitor : MonoBehaviour
	{
		private static Terminal _terminal;

		private static TextMeshProUGUI _textMesh;

		public void Start()
		{
			_terminal = Object.FindObjectOfType<Terminal>();
			_textMesh = ((Component)this).GetComponent<TextMeshProUGUI>();
			UpdateMonitor();
		}

		public static void UpdateMonitor()
		{
			((TMP_Text)_textMesh).text = $"CREDITS:\n${_terminal.groupCredits}";
		}
	}
	public class TimeMonitor : MonoBehaviour
	{
		private static TextMeshProUGUI _textMesh;

		private static TextMeshProUGUI _timeMesh;

		public void Start()
		{
			_textMesh = ((Component)this).GetComponent<TextMeshProUGUI>();
			_timeMesh = GameObject.Find("Systems/UI/Canvas/IngamePlayerHUD/ProfitQuota/Container/Box/TimeNumber").GetComponent<TextMeshProUGUI>();
			((TMP_Text)_textMesh).text = "TIME:\n7:30\nAM";
		}

		public static void UpdateMonitor()
		{
			((TMP_Text)_textMesh).text = "TIME:\n" + ((TMP_Text)_timeMesh).text;
		}
	}
}

plugins/DiscountAlert.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using DiscountAlert;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("DiscountAlert")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("A template for Lethal Company")]
[assembly: AssemblyFileVersion("2.3.0.0")]
[assembly: AssemblyInformationalVersion("2.3.0.0")]
[assembly: AssemblyProduct("DiscountAlert")]
[assembly: AssemblyTitle("DiscountAlert")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.3.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
[HarmonyPatch(typeof(StartMatchLever))]
public class StartMatchLever_Patches
{
	private static string priceUpColor = Plugin.Instance.PRICE_UP_COLOR;

	private static string priceDownColor = Plugin.Instance.PRICE_DOWN_COLOR;

	private static string noDiscountColor = Plugin.Instance.NO_DISCOUNT_COLOR;

	private static string noDiscountText = Plugin.Instance.noDiscountText.Value;

	private static string titleColor = Plugin.Instance.TITLE_COLOR;

	private static string titleText = Plugin.Instance.titleText.Value;

	private static int delayAfterLeverIsPulled = Plugin.Instance.delayAfterLeverIsPulled.Value;

	private static bool colorsEnabled = Plugin.Instance.colorsEnabled.Value;

	private static bool alertEnabledWhenNoDiscounts = Plugin.Instance.alertEnabledWhenNoDiscounts.Value;

	public static bool playerAlerted = false;

	public static int counter = 0;

	[HarmonyPatch("PlayLeverPullEffectsClientRpc")]
	[HarmonyPostfix]
	public static void PlayLeverPullEffectsClientRpcPatch()
	{
		playerAlerted = false;
		counter++;
		if (StartOfRound.Instance.inShipPhase && !playerAlerted && counter == 1)
		{
			playerAlerted = true;
			((MonoBehaviour)HUDManager.Instance).StartCoroutine(DisplayAlert());
		}
		else if (counter > 1)
		{
			counter = 0;
		}
	}

	private static IEnumerator DisplayAlert()
	{
		yield return (object)new WaitForSeconds((float)delayAfterLeverIsPulled);
		Debug.Log((object)"Displaying alert");
		StringBuilder discount_list = new StringBuilder();
		for (int i = 0; i < HUDManager.Instance.terminalScript.buyableItemsList.Length; i++)
		{
			if (HUDManager.Instance.terminalScript.itemSalesPercentages[i] != 100)
			{
				if (HUDManager.Instance.terminalScript.itemSalesPercentages[i] < 0)
				{
					discount_list.Append("\n" + ((priceUpColor != null) ? ("<color=" + priceUpColor + ">* ") : "* ") + HUDManager.Instance.terminalScript.buyableItemsList[i].itemName + $" ${(float)HUDManager.Instance.terminalScript.buyableItemsList[i].creditsWorth * (1f - (float)HUDManager.Instance.terminalScript.itemSalesPercentages[i] / 100f)} " + string.Format("({0}% UP!){1}", Math.Abs(HUDManager.Instance.terminalScript.itemSalesPercentages[i]), (priceUpColor != null) ? "</color>" : ""));
				}
				else if (HUDManager.Instance.terminalScript.itemSalesPercentages[i] > 0)
				{
					discount_list.Append("\n" + ((priceDownColor != null) ? ("<color=" + priceDownColor + ">* ") : "* ") + HUDManager.Instance.terminalScript.buyableItemsList[i].itemName + $" ${(float)HUDManager.Instance.terminalScript.buyableItemsList[i].creditsWorth * (float)HUDManager.Instance.terminalScript.itemSalesPercentages[i] / 100f} " + string.Format("({0}% OFF!){1}", 100 - HUDManager.Instance.terminalScript.itemSalesPercentages[i], (priceDownColor != null) ? "</color>" : ""));
				}
			}
		}
		if ((!(discount_list.ToString() == "") && discount_list != null) || alertEnabledWhenNoDiscounts)
		{
			if ((discount_list.ToString() == "" || discount_list == null) && alertEnabledWhenNoDiscounts)
			{
				discount_list.Append(((noDiscountColor != null) ? ("<color=" + noDiscountColor + "> ") : " ") + noDiscountText + ((noDiscountColor != null) ? "</color>" : ""));
			}
			HUDManager.Instance.DisplayTip(((titleColor != null) ? ("<color=" + titleColor + "> ") : " ") + titleText + ((titleColor != null) ? "</color>" : ""), discount_list.ToString(), false, false, "LC_Tip1");
		}
	}
}
namespace DiscountAlert
{
	[BepInPlugin("discount.alert", "DiscountAlert", "2.3.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "discount.alert";

		private const string modName = "DiscountAlert";

		private const string modVersion = "2.3.0.0";

		public ConfigEntry<string> priceUpColor;

		public ConfigEntry<string> priceDownColor;

		public ConfigEntry<string> noDiscountColor;

		public ConfigEntry<string> noDiscountText;

		public ConfigEntry<string> titleColor;

		public ConfigEntry<string> titleText;

		public ConfigEntry<int> delayAfterLeverIsPulled;

		public ConfigEntry<bool> colorsEnabled;

		public ConfigEntry<bool> alertEnabledWhenNoDiscounts;

		public string PRICE_UP_COLOR;

		public string PRICE_DOWN_COLOR;

		public string NO_DISCOUNT_COLOR;

		public string TITLE_COLOR;

		private readonly Harmony harmony = new Harmony("discount.alert");

		public static Plugin? Instance;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			priceUpColor = ((BaseUnityPlugin)this).Config.Bind<string>("Colors", "PriceUpColor", "#990000", "Text color when the price goes up (currently only possible with other mods)");
			priceDownColor = ((BaseUnityPlugin)this).Config.Bind<string>("Colors", "PriceDownColor", "#008000", "Text color when the price goes down");
			delayAfterLeverIsPulled = ((BaseUnityPlugin)this).Config.Bind<int>("Alert", "DelayAfterLeverIsPulled", 4, "Number of seconds to wait after the \"Land ship\" or \"Start Game\" lever is pulled before showing the alert.");
			colorsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Alert", "ColorsEnabled", true, "Enable or disable text colors");
			noDiscountColor = ((BaseUnityPlugin)this).Config.Bind<string>("Colors", "NoDiscountColor", "", "Text color when there are no discounts");
			titleColor = ((BaseUnityPlugin)this).Config.Bind<string>("Colors", "TitleColor", "", "Text color for the alert's title");
			titleText = ((BaseUnityPlugin)this).Config.Bind<string>("Alert", "TitleText", "Today's discounts", "Alert title text");
			noDiscountText = ((BaseUnityPlugin)this).Config.Bind<string>("Alert", "NoDiscountText", "None :( \n Check back tomorrow!", "Alert text when there are no discounts");
			alertEnabledWhenNoDiscounts = ((BaseUnityPlugin)this).Config.Bind<bool>("Alert", "AlertEnabledWhenNoDiscounts", true, "Show alert when there are no discounts");
			if (!IsValidHexCode(priceUpColor.Value))
			{
				PRICE_UP_COLOR = null;
			}
			else
			{
				PRICE_UP_COLOR = priceUpColor.Value;
			}
			if (!IsValidHexCode(priceDownColor.Value))
			{
				PRICE_DOWN_COLOR = null;
			}
			else
			{
				PRICE_DOWN_COLOR = priceDownColor.Value;
			}
			if (!IsValidHexCode(noDiscountColor.Value))
			{
				NO_DISCOUNT_COLOR = null;
			}
			else
			{
				NO_DISCOUNT_COLOR = noDiscountColor.Value;
			}
			if (!IsValidHexCode(titleColor.Value))
			{
				TITLE_COLOR = null;
			}
			else
			{
				TITLE_COLOR = titleColor.Value;
			}
			if (!colorsEnabled.Value)
			{
				PRICE_UP_COLOR = null;
				PRICE_DOWN_COLOR = null;
				NO_DISCOUNT_COLOR = null;
				TITLE_COLOR = null;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin discount.alert is loaded!");
			harmony.PatchAll();
		}

		public static bool IsValidHexCode(string hexCode)
		{
			string pattern = "^#?([0-9A-Fa-f]{3}){1,2}$";
			return Regex.IsMatch(hexCode, pattern);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}

plugins/DontTouchMe.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 BepInEx;
using GameNetcodeStuff;
using HarmonyLib;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("DontTouchMe")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DontTouchMe")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("2b5c0b79-7fa5-44d5-a3d7-384bed3474cb")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace DontTouchMe;

public class Assets
{
	public static AssetBundle MainAssetBundle;

	public static EnemyType EnemyType;

	public static TerminalNode EnemyNode;

	public static TerminalKeyword EnemyKeyword;

	public static AudioClip AudioMasked1;

	public static AudioClip AudioMasked2;

	internal static Stream GetEmbededResource(string name)
	{
		return Assembly.GetExecutingAssembly().GetManifestResourceStream("DontTouchMe." + name);
	}

	public static void Init()
	{
		Stream embededResource = GetEmbededResource("dtm.bundle");
		MainAssetBundle = AssetBundle.LoadFromStream(embededResource);
		EnemyType = MainAssetBundle.LoadAsset<EnemyType>("Assets/Mods/DontTouchMe/Resources/DTMEnemy.asset");
		EnemyNode = MainAssetBundle.LoadAsset<TerminalNode>("Assets/Mods/DontTouchMe/Resources/DTMNode.asset");
		EnemyKeyword = MainAssetBundle.LoadAsset<TerminalKeyword>("Assets/Mods/DontTouchMe/Resources/DTMKeyword.asset");
		AudioMasked1 = MainAssetBundle.LoadAsset<AudioClip>("Assets/Mods/DontTouchMe/Resources/dtm_masked_laugh1.wav");
		AudioMasked2 = MainAssetBundle.LoadAsset<AudioClip>("Assets/Mods/DontTouchMe/Resources/dtm_masked_laugh2.wav");
	}
}
public class DTMEntityAI : EnemyAI
{
	public static List<DTMEntityAI> Instances = new List<DTMEntityAI>();

	[Header("DTM Specific")]
	public InteractTrigger[] Triggers;

	public GameObject Music;

	public AudioSource VoiceA;

	public AudioSource VoiceB;

	private float AttackTime;

	private bool IsAttacking;

	private bool HasAttacked;

	private bool AttemptedMurder;

	public MaskedPlayerEnemy MaskedEnemy;

	private float StaringTimestamp;

	[Header("Disguise")]
	public GameObject MainModel;

	public GameObject Disguise;

	private int DisguiseID;

	private float ScreenShakeTime;

	private const float KillWindowMin = 2.3f;

	private const float KillWindowMax = 3.5f;

	private float KillWindowStart = 2.8f;

	private const string ButtonTouchParam = "Touched";

	private const string ButtonPressParam = "Press";

	private Coroutine ExplodePlayerCoroutine;

	public static int Count => Instances.Count;

	public static DTMEntityAI GetClosest(Vector3 pos)
	{
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		DTMEntityAI dTMEntityAI = null;
		if (Instances.Count == 0)
		{
			return dTMEntityAI;
		}
		if (Instances.Count == 1)
		{
			return Instances[0];
		}
		float num = float.MaxValue;
		foreach (DTMEntityAI instance in Instances)
		{
			if ((Object)(object)instance == (Object)null)
			{
				Instances.RemoveAll((DTMEntityAI v) => (Object)(object)v == (Object)null);
				dTMEntityAI = GetClosest(pos);
				break;
			}
			float num2 = Vector3.Distance(((Component)instance).transform.position, pos);
			if ((Object)(object)dTMEntityAI == (Object)null || num2 < num)
			{
				dTMEntityAI = instance;
				num = num2;
			}
		}
		return dTMEntityAI;
	}

	public void SetTrigger(bool interactable)
	{
		InteractTrigger[] triggers = Triggers;
		foreach (InteractTrigger val in triggers)
		{
			val.interactable = interactable;
		}
	}

	public bool CanBeShocked()
	{
		if (!IsAttacking)
		{
			return !HasAttacked;
		}
		return false;
	}

	public override void OnDestroy()
	{
		((EnemyAI)this).OnDestroy();
		Instances.Remove(this);
	}

	public override void Start()
	{
		//IL_00ee: 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_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_010e: Expected O, but got Unknown
		Instances.Add(this);
		base.skinnedMeshRenderers = ((Component)this).gameObject.GetComponentsInChildren<SkinnedMeshRenderer>(true);
		base.meshRenderers = ((Component)this).gameObject.GetComponentsInChildren<MeshRenderer>(true);
		base.thisNetworkObject = ((Component)this).gameObject.GetComponentInChildren<NetworkObject>(true);
		base.thisEnemyIndex = RoundManager.Instance.numberOfEnemiesInScene;
		RoundManager instance = RoundManager.Instance;
		instance.numberOfEnemiesInScene++;
		base.isOutside = Plugin.SpawnOutsideChance > 0 && Random.Range(0, 100) < Plugin.SpawnOutsideChance;
		if (base.isOutside)
		{
			base.allAINodes = GameObject.FindGameObjectsWithTag("OutsideAINode");
			if ((Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null)
			{
				((EnemyAI)this).EnableEnemyMesh(!StartOfRound.Instance.hangarDoorsClosed || !GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom, false);
			}
		}
		else
		{
			base.allAINodes = GameObject.FindGameObjectsWithTag("AINode");
		}
		base.serverPosition = ((Component)this).transform.position;
		base.updatePositionThreshold = 0f;
		base.path1 = new NavMeshPath();
		base.openDoorSpeedMultiplier = base.enemyType.doorSpeedMultiplier;
		ResetInteraction(changeLocation: true);
		Debug.Log((object)"DON'T TOUCH ME | DON'T TOUCH ME | DON'T TOUCH ME | DON'T TOUCH ME | DON'T TOUCH ME | DON'T TOUCH ME");
		Debug.Log((object)("Spawned Outside: " + base.isOutside));
	}

	private void ResetInteraction(bool changeLocation)
	{
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		MaskedEnemy = null;
		base.targetPlayer = null;
		IsAttacking = false;
		HasAttacked = false;
		AttemptedMurder = false;
		SetTrigger(interactable: true);
		Music.SetActive(false);
		((Component)VoiceA).gameObject.SetActive(false);
		base.creatureAnimator.ResetTrigger("Touched");
		base.creatureAnimator.ResetTrigger("Press");
		if (changeLocation)
		{
			if (((NetworkBehaviour)this).IsOwner)
			{
				Vector3 position = base.allAINodes[Random.Range(0, base.allAINodes.Length)].transform.position;
				position = RoundManager.Instance.GetNavMeshPosition(position, RoundManager.Instance.navHit, 1f, -1);
				((Component)this).transform.position = position;
				((Component)this).transform.rotation = Quaternion.Euler(0f, Random.Range(-180f, 180f), 0f);
				DisguiseID = ((Random.Range(0, 100) < Plugin.DisguiseAsItemChance) ? Random.Range(1, Disguise.transform.childCount) : (-1));
				Debug.Log((object)"[DTM] Trying to sync position with other players.");
				SyncSpawnOnServer();
			}
			else
			{
				base.isClientCalculatingAI = false;
			}
		}
	}

	public override void Update()
	{
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_037e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0389: Unknown result type (might be due to invalid IL or missing references)
		//IL_038e: 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_0397: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c9: 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_01e5: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)MaskedEnemy != (Object)null)
		{
			if (((NetworkBehaviour)MaskedEnemy).IsOwner && !((EnemyAI)MaskedEnemy).isEnemyDead && ((EnemyAI)MaskedEnemy).moveTowardsDestination && Vector3.Distance(((EnemyAI)MaskedEnemy).destination, ((Component)this).transform.position) < 1.5f && Object.op_Implicit((Object)(object)base.targetPlayer) && ((EnemyAI)MaskedEnemy).isOutside == !base.targetPlayer.isInsideFactory && !base.targetPlayer.isPlayerDead && ((EnemyAI)MaskedEnemy).currentBehaviourState != null)
			{
				float num = Vector3.Distance(((Component)MaskedEnemy).transform.position, ((Component)this).transform.position);
				switch (((EnemyAI)MaskedEnemy).currentBehaviourState.name)
				{
				case "FoundDTM":
					if (!(num > 1.5f))
					{
						Debug.Log((object)"[MASK] Start staring.");
						StaringTimestamp = Time.time + Random.Range(1f, 4f);
						MaskedEnemy.LookAtPlayerServerRpc((int)base.targetPlayer.playerClientId);
						((EnemyAI)MaskedEnemy).SetDestinationToPosition(((Component)MaskedEnemy).transform.position, false);
						((EnemyAI)MaskedEnemy).SwitchToBehaviourState(((EnemyAI)MaskedEnemy).currentBehaviourStateIndex + 1);
					}
					break;
				case "StareDTM":
					if (!(Time.time < StaringTimestamp))
					{
						Debug.Log((object)"[MASK] Look at the button.");
						StaringTimestamp = Time.time + Random.Range(1f, 2f);
						MaskedEnemy.StopLookingAtTransformServerRpc();
						MaskedEnemy.LookAtPositionServerRpc(((Component)this).transform.position, 10f);
						((EnemyAI)MaskedEnemy).SwitchToBehaviourState(((EnemyAI)MaskedEnemy).currentBehaviourStateIndex + 1);
					}
					break;
				case "PressDTM":
					if (!(Time.time < StaringTimestamp))
					{
						Debug.Log((object)"[MASK] Pressing the button.");
						OnTouched(base.targetPlayer);
						MaskedEnemy.StopLookingAtTransformServerRpc();
						((EnemyAI)MaskedEnemy).SwitchToBehaviourState(0);
						MaskedEnemy = null;
						base.targetPlayer = null;
					}
					break;
				}
			}
			else
			{
				Debug.Log((object)"[MASK] Lost interest.");
				MaskedEnemy.StopLookingAtTransformServerRpc();
				((EnemyAI)MaskedEnemy).SwitchToBehaviourState(0);
				MaskedEnemy = null;
				base.targetPlayer = null;
			}
		}
		if (!IsAttacking)
		{
			return;
		}
		if (Object.op_Implicit((Object)(object)MaskedEnemy))
		{
			MaskedEnemy = null;
			base.targetPlayer = null;
		}
		float num2 = Time.time - AttackTime;
		PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
		bool flag = ((EnemyAI)this).PlayerIsTargetable(localPlayerController, false, false) || (localPlayerController.hasBegunSpectating && Object.op_Implicit((Object)(object)localPlayerController.spectatedPlayerScript) && ((EnemyAI)this).PlayerIsTargetable(localPlayerController.spectatedPlayerScript, false, false));
		if (flag && ScreenShakeTime < Time.time)
		{
			HUDManager.Instance.ShakeCamera((ScreenShakeType)3);
			ScreenShakeTime = Time.time + 0.1f;
		}
		AudioSource voiceA = VoiceA;
		bool flag3 = (VoiceB.mute = flag);
		voiceA.mute = !flag3;
		if (num2 > KillWindowStart && num2 < 4.4f)
		{
			if (localPlayerController.isPlayerControlled && !localPlayerController.isPlayerDead && flag)
			{
				Vector3 val = ((Component)localPlayerController).transform.position - ((Component)this).transform.position;
				Vector3 val2 = ((Vector3)(ref val)).normalized * Random.Range(15f, 30f);
				val2.y = Random.Range(10f, 15f);
				localPlayerController.KillPlayer(val2, true, (CauseOfDeath)3, 0);
				ExplodePlayerServerRpc((int)localPlayerController.playerClientId);
			}
			if (Plugin.IncludeMonstersOnKill && ((NetworkBehaviour)this).IsServer && !AttemptedMurder)
			{
				foreach (EnemyAI spawnedEnemy in RoundManager.Instance.SpawnedEnemies)
				{
					if (Object.op_Implicit((Object)(object)spawnedEnemy) && spawnedEnemy.isOutside == base.isOutside && (Object)(object)((Component)spawnedEnemy).gameObject != (Object)(object)((Component)this).gameObject && spawnedEnemy.thisNetworkObject.IsSpawned && (Plugin.IncludeUnkillableMonsters || spawnedEnemy.enemyType.canDie))
					{
						Debug.Log((object)("[DTM] Killing " + ((Object)spawnedEnemy).name));
						spawnedEnemy.thisNetworkObject.Despawn(true);
					}
				}
				AttemptedMurder = true;
			}
		}
		if (num2 >= 5f)
		{
			if (Plugin.DestroyEntityAfterTouch)
			{
				IsAttacking = false;
				HasAttacked = true;
				((EnemyAI)this).KillEnemy(true);
			}
			else
			{
				ResetInteraction(Plugin.ChangeLocationAfterTouch);
			}
		}
	}

	private IEnumerator ExplodePlayerEffect(int clientId)
	{
		PlayerControllerB killedPlayer = StartOfRound.Instance.allPlayerScripts[clientId];
		float startTime = Time.realtimeSinceStartup;
		yield return (object)new WaitUntil((Func<bool>)(() => Time.realtimeSinceStartup - startTime > 1f || (Object)(object)killedPlayer.deadBody != (Object)null));
		Transform transform = ((Component)killedPlayer).transform;
		if ((Object)(object)killedPlayer.deadBody != (Object)null)
		{
			transform = ((Component)killedPlayer.deadBody).transform;
		}
		Object.Instantiate<GameObject>(StartOfRound.Instance.explosionPrefab, transform.position + Vector3.up * 0.5f, Quaternion.Euler(-90f, 0f, 0f), RoundManager.Instance.mapPropsContainer.transform).SetActive(true);
		base.inSpecialAnimation = false;
	}

	[ClientRpc]
	private void ExplodePlayerClientRpc(int clientId)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
		{
			ClientRpcParams val = default(ClientRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3906254083u, val, (RpcDelivery)0);
			BytePacker.WriteValueBitPacked(val2, clientId);
			((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3906254083u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
		{
			if (ExplodePlayerCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(ExplodePlayerCoroutine);
			}
			ExplodePlayerCoroutine = ((MonoBehaviour)this).StartCoroutine(ExplodePlayerEffect(clientId));
		}
	}

	[ServerRpc(RequireOwnership = false)]
	private void ExplodePlayerServerRpc(int clientId)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(877622320u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, clientId);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 877622320u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ExplodePlayerClientRpc(clientId);
			}
		}
	}

	private void UpdateDisguise()
	{
		MainModel.SetActive(DisguiseID < 1);
		Disguise.SetActive(!MainModel.activeSelf);
		if (Disguise.activeSelf)
		{
			Transform transform = Disguise.transform;
			for (int i = 1; i < transform.childCount; i++)
			{
				((Component)transform.GetChild(i)).gameObject.SetActive(i == DisguiseID);
			}
		}
	}

	private void SyncSpawnOnServer()
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: 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_001b: 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)
		base.serverPosition = ((Component)this).transform.position;
		if (((NetworkBehaviour)this).IsOwner)
		{
			SpawnClientRpc(base.serverPosition, ((Component)this).transform.eulerAngles.y, DisguiseID);
		}
		else
		{
			SpawnServerRpc(base.serverPosition, ((Component)this).transform.eulerAngles.y, DisguiseID);
		}
	}

	[ClientRpc]
	public void SpawnClientRpc(Vector3 newPos, float yRot, int disguise)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: 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)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3860255087u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe(ref newPos);
				((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref yRot, default(ForPrimitives));
				BytePacker.WriteValueBitPacked(val2, disguise);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3860255087u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				DisguiseID = disguise;
				((Component)this).transform.position = newPos;
				((Component)this).transform.rotation = Quaternion.Euler(0f, yRot, 0f);
				Music.SetActive(Plugin.PlayMusic && DisguiseID < 1);
				UpdateDisguise();
			}
		}
	}

	[ServerRpc]
	public void SpawnServerRpc(Vector3 newPos, float yRot, int disguise)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Invalid comparison between Unknown and I4
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Invalid comparison between Unknown and I4
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
		{
			if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
				return;
			}
			ServerRpcParams val = default(ServerRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2003288437u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe(ref newPos);
			((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref yRot, default(ForPrimitives));
			BytePacker.WriteValueBitPacked(val2, disguise);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2003288437u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			SpawnClientRpc(newPos, yRot, disguise);
		}
	}

	public void OnTouched(PlayerControllerB player)
	{
		//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)
		if (!IsAttacking && !((Object)(object)player == (Object)null))
		{
			int num = ((DisguiseID > 0) ? 80 : 20);
			if (Random.Range(0, 100) > num)
			{
				StartAttack(!player.isInsideFactory);
			}
			else if (Random.Range(0, 100) < 10)
			{
				player.JumpToFearLevel(1f, true);
			}
			else
			{
				player.DamagePlayer(999, true, true, (CauseOfDeath)0, Random.Range(1, 3), false, default(Vector3));
			}
		}
	}

	public void StartAttack(bool outside)
	{
		Debug.Log((object)"[DTM] Starting attack");
		if (((NetworkBehaviour)this).IsOwner)
		{
			AttackClientRpc(outside);
		}
		else
		{
			AttackServerRpc(outside);
		}
	}

	[ClientRpc]
	public void AttackClientRpc(bool outside)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
		{
			ClientRpcParams val = default(ClientRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3888608358u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref outside, default(ForPrimitives));
			((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3888608358u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
		{
			Debug.Log((object)"[DTM] Attempting attack on client");
			if (!IsAttacking && !HasAttacked)
			{
				AttackTime = Time.time;
				ScreenShakeTime = 0f;
				KillWindowStart = Random.Range(2.3f, 3.5f);
				DisguiseID = -1;
				Disguise.SetActive(false);
				MainModel.SetActive(true);
				Music.SetActive(false);
				((Component)VoiceA).gameObject.SetActive(true);
				base.isOutside = outside;
				SetTrigger(interactable: false);
				IsAttacking = true;
				base.creatureAnimator.SetTrigger("Touched");
			}
		}
	}

	[ServerRpc(RequireOwnership = false)]
	public void AttackServerRpc(bool outside)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2283008872u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref outside, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2283008872u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				Debug.Log((object)"[DTM] Attempting attack from server");
				AttackClientRpc(outside);
			}
		}
	}

	public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
	{
		Debug.Log((object)("[DTM] Hit by enemy: " + (object)playerWhoHit));
		OnTouched(playerWhoHit);
	}

	public override void SetEnemyStunned(bool setToStunned, float setToStunTime = 1f, PlayerControllerB setStunnedByPlayer = null)
	{
		if (setToStunned)
		{
			OnTouched(setStunnedByPlayer);
		}
	}

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

	[RuntimeInitializeOnLoadMethod]
	internal static void InitializeRPCS_DTMEntityAI()
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Expected O, but got Unknown
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Expected O, but got Unknown
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Expected O, but got Unknown
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Expected O, but got Unknown
		NetworkManager.__rpc_func_table.Add(3906254083u, new RpcReceiveHandler(__rpc_handler_3906254083));
		NetworkManager.__rpc_func_table.Add(877622320u, new RpcReceiveHandler(__rpc_handler_877622320));
		NetworkManager.__rpc_func_table.Add(3860255087u, new RpcReceiveHandler(__rpc_handler_3860255087));
		NetworkManager.__rpc_func_table.Add(2003288437u, new RpcReceiveHandler(__rpc_handler_2003288437));
		NetworkManager.__rpc_func_table.Add(3888608358u, new RpcReceiveHandler(__rpc_handler_3888608358));
		NetworkManager.__rpc_func_table.Add(2283008872u, new RpcReceiveHandler(__rpc_handler_2283008872));
	}

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

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

	private static void __rpc_handler_3860255087(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: 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_0069: 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)
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			Vector3 newPos = default(Vector3);
			((FastBufferReader)(ref reader)).ReadValueSafe(ref newPos);
			float yRot = default(float);
			((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref yRot, default(ForPrimitives));
			int disguise = default(int);
			ByteUnpacker.ReadValueBitPacked(reader, ref disguise);
			target.__rpc_exec_stage = (__RpcExecStage)2;
			((DTMEntityAI)(object)target).SpawnClientRpc(newPos, yRot, disguise);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}
	}

	private static void __rpc_handler_2003288437(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: 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_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Invalid comparison between Unknown and I4
		NetworkManager networkManager = target.NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
		{
			if ((int)networkManager.LogLevel <= 1)
			{
				Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
			}
			return;
		}
		Vector3 newPos = default(Vector3);
		((FastBufferReader)(ref reader)).ReadValueSafe(ref newPos);
		float yRot = default(float);
		((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref yRot, default(ForPrimitives));
		int disguise = default(int);
		ByteUnpacker.ReadValueBitPacked(reader, ref disguise);
		target.__rpc_exec_stage = (__RpcExecStage)1;
		((DTMEntityAI)(object)target).SpawnServerRpc(newPos, yRot, disguise);
		target.__rpc_exec_stage = (__RpcExecStage)0;
	}

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

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

	protected internal override string __getTypeName()
	{
		return "DTMEntityAI";
	}
}
public class DTMHitBox : MonoBehaviour, IHittable, IShockableWithGun
{
	public DTMEntityAI mainScript;

	bool IHittable.Hit(int force, Vector3 hitDirection, PlayerControllerB playerWhoHit, bool playHitSFX)
	{
		((EnemyAI)mainScript).SetEnemyStunned(true, 1f, playerWhoHit);
		return true;
	}

	bool IShockableWithGun.CanBeShocked()
	{
		return mainScript.CanBeShocked();
	}

	Vector3 IShockableWithGun.GetShockablePosition()
	{
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)((EnemyAI)mainScript).eye != (Object)null)
		{
			return ((EnemyAI)mainScript).eye.position;
		}
		return ((Component)this).transform.position + Vector3.up * 1f;
	}

	float IShockableWithGun.GetDifficultyMultiplier()
	{
		return ((EnemyAI)mainScript).enemyType.stunGameDifficultyMultiplier;
	}

	void IShockableWithGun.ShockWithGun(PlayerControllerB shockedByPlayer)
	{
		((EnemyAI)mainScript).SetEnemyStunned(true, 0.25f, shockedByPlayer);
		DTMEntityAI dTMEntityAI = mainScript;
		((EnemyAI)dTMEntityAI).stunnedIndefinitely = ((EnemyAI)dTMEntityAI).stunnedIndefinitely + 1;
	}

	Transform IShockableWithGun.GetShockableTransform()
	{
		return ((Component)this).transform;
	}

	NetworkObject IShockableWithGun.GetNetworkObject()
	{
		return ((NetworkBehaviour)mainScript).NetworkObject;
	}

	void IShockableWithGun.StopShockingWithGun()
	{
	}
}
[HarmonyPatch(typeof(MaskedPlayerEnemy))]
internal class MaskedEnemyPatch
{
	public const float InteractProximity = 1.5f;

	public const float DetectProximity = 10f;

	public const float StaringTimeMin = 1f;

	public const float StaringTimeMax = 4f;

	private static EnemyBehaviourState[] BehaviourStates;

	public const string BehaviourStateFound = "FoundDTM";

	public const string BehaviourStateStare = "StareDTM";

	public const string BehaviourStatePress = "PressDTM";

	[HarmonyPatch("Start")]
	[HarmonyPostfix]
	private static void StartPatch(ref MaskedPlayerEnemy __instance)
	{
		//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_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Expected O, but got Unknown
		//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_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Expected O, but got Unknown
		if (BehaviourStates == null)
		{
			BehaviourStates = (EnemyBehaviourState[])(object)new EnemyBehaviourState[3]
			{
				new EnemyBehaviourState
				{
					name = "FoundDTM",
					playOneShotVoice = ((Object)(object)Assets.AudioMasked1 != (Object)null),
					VoiceClip = Assets.AudioMasked1
				},
				new EnemyBehaviourState
				{
					name = "StareDTM",
					VoiceClip = null,
					playOneShotVoice = false
				},
				new EnemyBehaviourState
				{
					name = "PressDTM",
					playOneShotVoice = ((Object)(object)Assets.AudioMasked2 != (Object)null),
					VoiceClip = Assets.AudioMasked2
				}
			};
		}
		EnemyBehaviourState[] enemyBehaviourStates = ((EnemyAI)__instance).enemyBehaviourStates;
		int num = enemyBehaviourStates.Length;
		EnemyBehaviourState[] array = (EnemyBehaviourState[])(object)new EnemyBehaviourState[num + BehaviourStates.Length];
		for (int i = 0; i < array.Length; i++)
		{
			array[i] = ((i < num) ? enemyBehaviourStates[i] : BehaviourStates[i % num]);
		}
		((EnemyAI)__instance).enemyBehaviourStates = array;
	}

	[HarmonyPatch("DoAIInterval")]
	[HarmonyPostfix]
	private static void DoAIIntervalPatch(ref MaskedPlayerEnemy __instance)
	{
		//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_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: 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_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Expected O, but got Unknown
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: 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_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: Unknown result type (might be due to invalid IL or missing references)
		if (DTMEntityAI.Count <= 0 || ((EnemyAI)__instance).currentBehaviourStateIndex != 1)
		{
			return;
		}
		Vector3 position = ((Component)__instance).transform.position;
		DTMEntityAI closest = DTMEntityAI.GetClosest(position);
		if ((Object)(object)closest == (Object)null || !closest.CanBeShocked() || (Object)(object)closest.MaskedEnemy != (Object)null)
		{
			return;
		}
		Vector3 position2 = ((Component)closest).transform.position;
		float num = Vector3.Distance(position, position2);
		PlayerControllerB targetPlayer = ((EnemyAI)__instance).targetPlayer;
		if ((Object)(object)targetPlayer != (Object)null && ((EnemyAI)__instance).movingTowardsTargetPlayer && num < 10f && !((EnemyAI)__instance).PathIsIntersectedByLineOfSight(position2, false, true))
		{
			((EnemyAI)__instance).path1 = new NavMeshPath();
			if (((EnemyAI)__instance).agent.CalculatePath(position2, ((EnemyAI)__instance).path1) && !(Vector3.Distance(((EnemyAI)__instance).path1.corners[((EnemyAI)__instance).path1.corners.Length - 1], RoundManager.Instance.GetNavMeshPosition(position2, RoundManager.Instance.navHit, 2.7f, -1)) > 1.55f) && ((EnemyAI)__instance).SetDestinationToPosition(position2, true))
			{
				__instance.StopLookingAtTransformServerRpc();
				((EnemyAI)__instance).SwitchToBehaviourState(Array.IndexOf(((EnemyAI)__instance).enemyBehaviourStates, BehaviourStates[0]));
				closest.MaskedEnemy = __instance;
				((EnemyAI)closest).targetPlayer = targetPlayer;
			}
		}
	}
}
[BepInPlugin("Kittenji.DontTouchMe", "Don't Touch Me", "1.2.1")]
public class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPatch()
		{
			((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().AddNetworkPrefab(Assets.EnemyType.enemyPrefab);
			Debug.Log((object)"[DTM] Added network prefab");
		}
	}

	[HarmonyPatch(typeof(Terminal))]
	internal class TerminalPatch
	{
		private static Random TerminalRandom = new Random();

		private static FieldInfo InteractTriggerField = AccessTools.Field(typeof(Terminal), "terminalTrigger");

		private static InteractTrigger m_Trigger;

		private static bool HandlingSpecialEvent;

		private static InteractTrigger GetTrigger(Terminal __instance)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			if ((Object)(object)m_Trigger == (Object)null)
			{
				m_Trigger = (InteractTrigger)InteractTriggerField.GetValue(__instance);
			}
			return m_Trigger;
		}

		private static void PerformRandomTPOnPlayer(PlayerControllerB localPlayer, int index, bool redirected = false)
		{
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: 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_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: 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_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: 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_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			if (localPlayer.isPlayerDead)
			{
				return;
			}
			bool flag;
			Vector3 val;
			switch (index)
			{
			default:
				return;
			case 0:
			case 1:
			{
				flag = index == 0;
				GameObject[] array = (flag ? RoundManager.Instance.insideAINodes : RoundManager.Instance.outsideAINodes);
				if (array.Length != 0)
				{
					val = array[Random.Range(0, array.Length)].transform.position;
					val = RoundManager.Instance.GetRandomNavMeshPositionInRadiusSpherical(val, 10f, default(NavMeshHit));
					Debug.LogWarning((object)"Where am I anyway?");
					break;
				}
				return;
			}
			case 2:
			{
				Turret[] array2 = Object.FindObjectsOfType<Turret>(false);
				if (array2 == null || array2.Length == 0)
				{
					PerformRandomTPOnPlayer(localPlayer, redirected ? Random.Range(0, 2) : 3, redirected: true);
					return;
				}
				Turret val3 = array2[Random.Range(0, array2.Length)];
				if ((Object)(object)val3 == (Object)null)
				{
					return;
				}
				val = ((Component)val3).transform.position;
				flag = val.y < -80f;
				val = RoundManager.Instance.GetRandomNavMeshPositionInRadiusSpherical(val, 2f, default(NavMeshHit));
				Debug.LogError((object)"Run Forest, RUN!!!");
				break;
			}
			case 3:
			{
				Landmine[] array3 = Object.FindObjectsOfType<Landmine>(false);
				if (array3 == null || array3.Length == 0)
				{
					PerformRandomTPOnPlayer(localPlayer, redirected ? Random.Range(0, 2) : 2, redirected: true);
					return;
				}
				Landmine val4 = array3[Random.Range(0, array3.Length)];
				if ((Object)(object)val4 == (Object)null)
				{
					return;
				}
				val = ((Component)val4).transform.position;
				flag = val.y < -80f;
				val = RoundManager.Instance.GetRandomNavMeshPositionInRadiusSpherical(val, 2f, default(NavMeshHit));
				Debug.LogError((object)"WAIT, DON'T MOVE!!!... Or do... I'm a programmer, not a land mine inspector.");
				break;
			}
			case 4:
			{
				List<EnemyAI> spawnedEnemies = RoundManager.Instance.SpawnedEnemies;
				if (spawnedEnemies == null || spawnedEnemies.Count == 0)
				{
					PerformRandomTPOnPlayer(localPlayer, Random.Range(0, 2), redirected: true);
					return;
				}
				EnemyAI val2 = spawnedEnemies[Random.Range(0, spawnedEnemies.Count)];
				val = ((Component)val2).transform.position;
				flag = val.y < -80f;
				val = RoundManager.Instance.GetRandomNavMeshPositionInRadiusSpherical(val, 8f, default(NavMeshHit));
				Debug.LogError((object)"OH NO!, that is horrible!!!............ anyway..");
				break;
			}
			case 5:
				val = ((Component)localPlayer).transform.position + Vector3.up * 100f;
				flag = false;
				Debug.LogError((object)"Fly like a bird... wait, why are you falling?");
				break;
			}
			if (!localPlayer.isPlayerDead)
			{
				localPlayer.DropAllHeldItems(true, false);
				localPlayer.isInElevator = false;
				localPlayer.isInHangarShipRoom = false;
				localPlayer.isInsideFactory = flag;
				localPlayer.averageVelocity = 0f;
				localPlayer.velocityLastFrame = Vector3.zero;
				localPlayer.TeleportPlayer(val, false, 0f, false, true);
				HUDManager.Instance.ShakeCamera((ScreenShakeType)1);
			}
		}

		private static IEnumerator SpecialEvent(Terminal __instance, int index)
		{
			HandlingSpecialEvent = true;
			PlayerControllerB localPlayer = GameNetworkManager.Instance.localPlayerController;
			InteractTrigger trigger = GetTrigger(__instance);
			if (!Object.op_Implicit((Object)(object)trigger))
			{
				HandlingSpecialEvent = false;
				yield break;
			}
			yield return (object)new WaitForSeconds(0.35f);
			switch (index)
			{
			case 1:
				__instance.QuitTerminal();
				if (Random.Range(0, 100) < 34)
				{
					while (trigger.currentCooldownValue > 0f)
					{
						yield return null;
					}
					localPlayer.DropAllHeldItems(true, false);
					Debug.LogError((object)"Haha, butter fingers!");
				}
				else
				{
					Debug.LogWarning((object)"GET OUT!");
				}
				break;
			case 2:
				__instance.QuitTerminal();
				while (trigger.currentCooldownValue > 0f)
				{
					yield return null;
				}
				if (!StartOfRound.Instance.inShipPhase)
				{
					index = RoundManager.Instance.GetRandomWeightedIndex(Terminal_Weights_TP, (Random)null);
					PerformRandomTPOnPlayer(localPlayer, index);
				}
				break;
			case 3:
			{
				__instance.QuitTerminal();
				while (trigger.currentCooldownValue > 0f)
				{
					yield return null;
				}
				for (int i = 0; i < localPlayer.ItemSlots.Length; i++)
				{
					GrabbableObject val = localPlayer.ItemSlots[i];
					if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val.itemProperties) && val.itemProperties.requiresBattery)
					{
						val.insertedBattery = new Battery(true, 0f);
					}
				}
				Debug.LogError((object)"This mod is not sponsored by DURACELL");
				break;
			}
			case 4:
			{
				__instance.QuitTerminal();
				while (trigger.currentCooldownValue > 0f)
				{
					yield return null;
				}
				if (StartOfRound.Instance.inShipPhase)
				{
					break;
				}
				GameObject[] outsideAINodes = RoundManager.Instance.outsideAINodes;
				if (outsideAINodes.Length != 0)
				{
					int num = Random.Range(1, 5);
					for (int j = 0; j < num; j++)
					{
						RoundManager.Instance.SpawnEnemyOnServer(Vector3.zero, Random.Range(-180f, 180f), -3);
					}
					Debug.LogError((object)("OOPS! Have fun with " + ((num > 1) ? "those" : "that") + "..."));
				}
				break;
			}
			case 5:
				__instance.QuitTerminal();
				while (trigger.currentCooldownValue > 0f)
				{
					yield return null;
				}
				if (!StartOfRound.Instance.inShipPhase && localPlayer.health > 5)
				{
					localPlayer.DamagePlayer(localPlayer.health - 5, true, true, (CauseOfDeath)0, 0, false, default(Vector3));
					Debug.LogError((object)"Ouch, that must hurt.");
				}
				break;
			case 6:
				__instance.QuitTerminal();
				while (trigger.currentCooldownValue > 0f)
				{
					yield return null;
				}
				if (!StartOfRound.Instance.inShipPhase)
				{
					localPlayer.KillPlayer(Vector3.up, true, (CauseOfDeath)0, 0);
					Debug.LogError((object)"Curiosity killed the cat, in this case... you");
				}
				break;
			}
			HandlingSpecialEvent = false;
		}

		[HarmonyPatch("RunTerminalEvents")]
		[HarmonyPostfix]
		private static void RunTerminalEventsPatch(ref Terminal __instance, TerminalNode node)
		{
			if (node.terminalEvent == "dontReadMe")
			{
				Debug.Log((object)"Don't read me, please.");
				int randomWeightedIndex = RoundManager.Instance.GetRandomWeightedIndex(Terminal_Weights, TerminalRandom);
				if (!HandlingSpecialEvent)
				{
					((MonoBehaviour)__instance).StartCoroutine(SpecialEvent(__instance, randomWeightedIndex));
				}
			}
		}

		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void StartPatch(ref Terminal __instance)
		{
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			Debug.Log((object)"[DTM] Adding terminal entries");
			TerminalNode terminalNode = Assets.EnemyNode;
			TerminalKeyword val = __instance.terminalNodes.allKeywords.First((TerminalKeyword k) => k.word == "info");
			if (!__instance.enemyFiles.Any((TerminalNode x) => x.creatureName == terminalNode.creatureName))
			{
				TerminalKeyword keyword = Assets.EnemyKeyword;
				keyword.defaultVerb = val;
				List<TerminalKeyword> list = __instance.terminalNodes.allKeywords.ToList();
				if (!list.Any((TerminalKeyword x) => x.word == keyword.word))
				{
					list.Add(keyword);
					__instance.terminalNodes.allKeywords = list.ToArray();
				}
				List<CompatibleNoun> list2 = val.compatibleNouns.ToList();
				if (!list2.Any((CompatibleNoun x) => x.noun.word == keyword.word))
				{
					list2.Add(new CompatibleNoun
					{
						noun = keyword,
						result = terminalNode
					});
				}
				val.compatibleNouns = list2.ToArray();
				terminalNode.creatureFileID = __instance.enemyFiles.Count;
				__instance.enemyFiles.Add(terminalNode);
				Assets.EnemyType.enemyPrefab.GetComponentInChildren<ScanNodeProperties>().creatureScanID = terminalNode.creatureFileID;
				Debug.Log((object)"[DTM] Done adding entries.");
			}
		}
	}

	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void AwakePatch(ref StartOfRound __instance)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			EnemyType enemyDef = Assets.EnemyType;
			SelectableLevel[] levels = __instance.levels;
			foreach (SelectableLevel val in levels)
			{
				if (val.Enemies.Count >= 2 && !val.Enemies.Any((SpawnableEnemyWithRarity e) => (Object)(object)e.enemyType == (Object)(object)enemyDef))
				{
					Debug.Log((object)("[DTM] Adding entity to level: " + val.PlanetName));
					val.Enemies.Add(new SpawnableEnemyWithRarity
					{
						enemyType = enemyDef,
						rarity = SpawnRarity
					});
				}
			}
		}
	}

	private const string modGUID = "Kittenji.DontTouchMe";

	private readonly Harmony harmony = new Harmony("Kittenji.DontTouchMe");

	public static bool PlayMusic = true;

	public static bool IncludeMonstersOnKill = true;

	public static bool IncludeUnkillableMonsters = true;

	public static bool DestroyMonstersOnKill = true;

	public static int SpawnRarity = 24;

	public static int SpawnOutsideChance = 2;

	public static bool ChangeLocationAfterTouch = true;

	public static bool DestroyEntityAfterTouch = true;

	public static int DisguiseAsItemChance = 40;

	private const int Terminal_Weight_None = 5;

	private const int Terminal_Weight_Quit = 50;

	private const int Terminal_Weight_TP = 15;

	private const int Terminal_Weight_Battery = 14;

	private const int Terminal_Weight_Punish = 14;

	private const int Terminal_Weight_Break = 3;

	private const int Terminal_Weight_Kill = 1;

	private const int Terminal_Weight_TP_Inside = 36;

	private const int Terminal_Weight_TP_Outside = 36;

	private const int Terminal_Weight_TP_Turret = 18;

	private const int Terminal_Weight_TP_Landmine = 6;

	private const int Terminal_Weight_TP_Monster = 3;

	private const int Terminal_Weight_TP_Sky = 1;

	private const int Terminal_Punish_Min = 1;

	private const int Terminal_Punish_Max = 5;

	private static readonly int[] Terminal_Weights = new int[7] { 5, 50, 15, 14, 14, 3, 1 };

	private static readonly int[] Terminal_Weights_TP = new int[6] { 36, 36, 18, 6, 3, 1 };

	private void Awake()
	{
		SpawnRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Spawning", "Spawn Rarity", 24, "Spawn rarity. Lower value means lower chance to spawn. (default = 24)").Value;
		SpawnOutsideChance = ((BaseUnityPlugin)this).Config.Bind<int>("Spawning", "Spawn Rarity Outside", 2, "Random chance percentage for this entity to spawn outside. (default = 2)").Value;
		DisguiseAsItemChance = ((BaseUnityPlugin)this).Config.Bind<int>("Spawning", "Disguise As Item Chance", 45, "Random chance percentage for this entity to disguise itself as an item. (default = 45)").Value;
		ChangeLocationAfterTouch = ((BaseUnityPlugin)this).Config.Bind<bool>("Interaction", "Changes Location", true, "If 'true' the entity will change it's position to a random location after the animation. (default = true)").Value;
		DestroyEntityAfterTouch = ((BaseUnityPlugin)this).Config.Bind<bool>("Interaction", "Destroy After Touch", false, "If 'true' the entity will hide for the rest of the round after touch. It will teleport to a different location. (default = false)").Value;
		IncludeMonstersOnKill = ((BaseUnityPlugin)this).Config.Bind<bool>("Interaction", "Include Monsters On Kill", true, "If 'true' the entity will not pick favorites and will try killing monsters in the facility as well. (default = true)").Value;
		DestroyMonstersOnKill = ((BaseUnityPlugin)this).Config.Bind<bool>("Interaction", "Destroy Monsters On Kill", true, "If 'true' monsters will directly despawn to prevent lag and other potential issues. (default = true)").Value;
		IncludeUnkillableMonsters = ((BaseUnityPlugin)this).Config.Bind<bool>("Interaction", "Include Unkillable Monsters", true, "If 'true' the entity will also kill unkillable monsters too. (default = true)").Value;
		PlayMusic = ((BaseUnityPlugin)this).Config.Bind<bool>("Audio", "Play Music", true, "If 'true' the entity will play ominous music (Lobotomy Corp OST - Neutral 01) that can be heard in the distance, getting more noticeable the closer you get to it. (default = true)").Value;
		SpawnRarity = Mathf.Min(100, Mathf.Max(1, SpawnRarity));
		SpawnOutsideChance = Mathf.Min(100, Mathf.Max(0, SpawnOutsideChance));
		DisguiseAsItemChance = Mathf.Min(100, Mathf.Max(0, DisguiseAsItemChance));
		((BaseUnityPlugin)this).Config.Save();
		Assets.Init();
		harmony.PatchAll();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Patched!");
		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);
				}
			}
		}
	}
}

plugins/EmployeeAssignments.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.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using PersonalAssignments.AssignmentLogic;
using PersonalAssignments.Components;
using PersonalAssignments.Data;
using PersonalAssignments.Network;
using PersonalAssignments.UI;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("EmployeeAssignments")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("PersonalAssignments")]
[assembly: AssemblyFileVersion("1.0.9.0")]
[assembly: AssemblyInformationalVersion("1.0.9")]
[assembly: AssemblyProduct("EmployeeAssignments")]
[assembly: AssemblyTitle("EmployeeAssignments")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.9.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 PersonalAssignments
{
	[BepInPlugin("EmployeeAssignments", "EmployeeAssignments", "1.0.9")]
	public class Plugin : BaseUnityPlugin
	{
		private static bool Initialized;

		public static ManualLogSource Log { get; private set; }

		private void Start()
		{
			Initialize();
		}

		private void OnDestroy()
		{
			Initialize();
		}

		private void Initialize()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			if (!Initialized)
			{
				Initialized = true;
				GameObject val = new GameObject("PersonalAssignmentManager");
				Object.DontDestroyOnLoad((Object)(object)val);
				PersonalAssignmentManager personalAssignmentManager = val.AddComponent<PersonalAssignmentManager>();
				personalAssignmentManager.Config = new PAConfig(((BaseUnityPlugin)this).Config);
				val.AddComponent<KillableEnemiesOutput>();
				val.AddComponent<UpdateChecker>();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin EmployeeAssignments is loaded!");
			}
		}
	}
	[Serializable]
	public enum AssignmentType
	{
		CollectScrapItem,
		KillMonster,
		RepairValve
	}
	[Serializable]
	public struct Assignment
	{
		public string Name;

		public string UID;

		public byte ID;

		public string BodyText;

		public string ShortText;

		public string TargetText;

		public string FailureReason;

		public int CashReward;

		public int XPReward;

		public AssignmentType Type;

		public ulong PlayerId;

		public ulong[] TargetIds;

		public int TargetsComplete;

		public Vector3 FixedTargetPosition;
	}
	public static class Assignments
	{
		public static readonly Assignment[] All = new Assignment[3]
		{
			new Assignment
			{
				Name = "SCRAP RETRIEVAL",
				UID = "collect_scrap",
				BodyText = "YOU MUST COLLECT THE FOLLOWING SCRAP ITEM: [{0}] IT WILL BE MARKED AS [ASSIGNMENT TARGET]",
				ShortText = "FIND THE [{0}] MARKED 'ASSIGNMENT TARGET'",
				FailureReason = "ANOTHER EMPLOYEE COLLECTED THE ITEM",
				CashReward = 100,
				XPReward = 0,
				Type = AssignmentType.CollectScrapItem,
				TargetIds = new ulong[1]
			},
			new Assignment
			{
				Name = "HUNT & KILL",
				UID = "hunt_kill",
				BodyText = "YOU MUST HUNT AND KILL THE FOLLOWING ENEMY: [{0}] IT WILL BE MARKED AS [ASSIGNMENT TARGET]",
				ShortText = "FIND AND KILL THE [{0}]",
				FailureReason = "THE ENEMY WAS NOT KILLED",
				CashReward = 200,
				XPReward = 0,
				Type = AssignmentType.KillMonster,
				TargetIds = new ulong[1]
			},
			new Assignment
			{
				Name = "REPAIR VALVE",
				UID = "repair_valve",
				BodyText = "YOU MUST FIND AND REPAIR THE BROKEN VALVE",
				ShortText = "FIND AND REPAIR THE BROKEN VALVE",
				TargetText = "BROKEN VALVE",
				FailureReason = "THE BROKEN VALVE WAS NOT FIXED",
				CashReward = 100,
				XPReward = 0,
				Type = AssignmentType.RepairValve,
				TargetIds = new ulong[1]
			}
		};

		public static Assignment GetAssignment(string guid)
		{
			Assignment[] all = All;
			for (int i = 0; i < all.Length; i++)
			{
				Assignment result = all[i];
				if (result.UID == guid)
				{
					return result;
				}
			}
			return default(Assignment);
		}
	}
	public class PersonalAssignmentManager : MonoBehaviour
	{
		private readonly List<IAssignmentLogic> _assignmentLogic = new List<IAssignmentLogic>();

		private NetworkUtils _networkUtils;

		private AssignmentUI _assignmentUI;

		private PAContext _context;

		private GameContext _gameContext;

		private int _maxAssignedPlayers = 20;

		private int _minAssignedPlayers = 1;

		public PAConfig Config;

		private Coroutine _lootValueSyncRoutine;

		private WaitForSecondsRealtime _rewardValueSyncDelay = new WaitForSecondsRealtime(1f);

		private void Log(string log)
		{
			Plugin.Log.LogInfo((object)log);
		}

		public void Awake()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			_context = new PAContext();
			_assignmentUI = new GameObject("UI").AddComponent<AssignmentUI>();
			((Component)_assignmentUI).transform.SetParent(((Component)this).transform);
			_networkUtils = ((Component)this).gameObject.AddComponent<NetworkUtils>();
			NetworkUtils networkUtils = _networkUtils;
			networkUtils.OnNetworkData = (Action<string, byte[]>)Delegate.Combine(networkUtils.OnNetworkData, new Action<string, byte[]>(OnNetworkData));
			NetworkUtils networkUtils2 = _networkUtils;
			networkUtils2.OnDisconnect = (Action)Delegate.Combine(networkUtils2.OnDisconnect, new Action(OnDisconnect));
			_gameContext = new GameContext();
			GameStateSync gameStateSync = ((Component)this).gameObject.AddComponent<GameStateSync>();
			gameStateSync.Inject(_gameContext, _networkUtils);
			GameContext gameContext = _gameContext;
			gameContext.GameStateChanged = (Action<GameStateEnum>)Delegate.Combine(gameContext.GameStateChanged, new Action<GameStateEnum>(GameStateChanged));
			InstallAssignmentLogic();
		}

		private void InstallAssignmentLogic()
		{
			_assignmentLogic.Add(new CollectScrapLogic(_context));
			_assignmentLogic.Add(new HuntAndKillLogic(_context));
			_assignmentLogic.Add(new RepairValveLogic(_context));
		}

		public void Start()
		{
			_maxAssignedPlayers = Config.MaxAssignedPlayers.Value;
			_minAssignedPlayers = Config.MinAssignedPlayers.Value;
			_context.AssignAllPlayers = Config.AssignAllPlayers.Value;
			_context.AllPlayersComplete = Config.AllPlayersCanComplete.Value;
			Assignments.All[0].CashReward = Config.ScrapRetrievalReward.Value;
			Assignments.All[2].CashReward = Config.BrokenValveReward.Value;
			_context.ParseStringArray(ref _context.EnemyWhitelist, Config.HuntAndKillWhitelist);
			_context.ParseStringArray(ref _context.AssignmentWhitelist, Config.AssignmentWhiteList);
			_context.ParseIntArray(ref _context.AssignmentWeights, Config.AssignmentWeights);
			_context.ParseIntArray(ref _context.EnemyWeights, Config.HuntAndKillWeights);
			_context.ParseIntArray(ref _context.EnemyRewards, Config.HuntAndKillRewards);
		}

		private void OnDisconnect()
		{
			HandleResetEvent();
		}

		private void SendNetworkEvent<T>(T netEvent) where T : IPAEvent
		{
			string s = JsonUtility.ToJson((object)netEvent);
			byte[] bytes = Encoding.UTF8.GetBytes(s);
			_networkUtils.SendToAll(netEvent.TAG, bytes);
		}

		private void OnNetworkData(string tag, byte[] data)
		{
			if (tag.StartsWith("PA-"))
			{
				string @string = Encoding.UTF8.GetString(data);
				Log("Incoming data " + tag + " " + @string);
				switch (tag)
				{
				case "PA-Reset":
					HandleResetEvent();
					break;
				case "PA-Allocation":
				{
					AssignmentEvent assignmentEvent2 = JsonUtility.FromJson<AssignmentEvent>(@string);
					HandleAllocationEvent(assignmentEvent2);
					break;
				}
				case "PA-Complete":
				{
					CompleteEvent assignmentEvent = JsonUtility.FromJson<CompleteEvent>(@string);
					HandleCompleteEvent(assignmentEvent);
					break;
				}
				case "PA-Failed":
				{
					FailedEvent failedEvent = JsonUtility.FromJson<FailedEvent>(@string);
					HandleFailedEvent(failedEvent);
					break;
				}
				}
			}
		}

		private void HandleResetEvent()
		{
			_context.AssignmentsGenerated = false;
			_context.CurrentAssignment = null;
			_context.ActiveAssignments.Clear();
			_context.CompletedAssignments.Clear();
			_assignmentUI.ClearAssignment();
		}

		private void HandleAllocationEvent(AssignmentEvent assignmentEvent)
		{
			Assignment assignment = Assignments.GetAssignment(assignmentEvent.AssignmentUID);
			assignment.PlayerId = assignmentEvent.PlayerId;
			assignment.TargetIds = assignmentEvent.TargetIds;
			assignment.CashReward = assignmentEvent.RewardValue;
			assignment.TargetText = assignmentEvent.TargetName;
			assignment.ID = assignmentEvent.AssignmentID;
			bool flag = assignment.PlayerId == NetworkManager.Singleton.LocalClientId;
			bool flag2 = _assignmentLogic[(int)assignment.Type].HandleAllocationEvent(ref assignment, flag);
			if (flag && flag2)
			{
				_context.CurrentAssignment = assignment;
				ShowAssignment(_context.CurrentAssignment.Value);
			}
			else
			{
				Log($"Assignment not assigned to local player: (ForLocalPlayer){flag} | (SetupComplete){flag2}");
			}
		}

		private void HandleCompleteEvent(CompleteEvent assignmentEvent)
		{
			Assignment assignment = Assignments.GetAssignment(assignmentEvent.AssignmentUID);
			assignment.CashReward = assignmentEvent.RewardValue;
			assignment.TargetIds = assignmentEvent.TargetIds;
			assignment.PlayerId = assignmentEvent.PlayerId;
			assignment.ID = assignmentEvent.AssignmentID;
			bool flag = _context.CurrentAssignment.HasValue && _context.CurrentAssignment.Value.ID == assignmentEvent.AssignmentID && assignment.PlayerId == NetworkManager.Singleton.LocalClientId;
			_assignmentLogic[(int)assignment.Type].CompleteAssignment(ref assignment, flag);
			if (flag)
			{
				CompleteAssignment();
			}
		}

		private void HandleFailedEvent(FailedEvent failedEvent)
		{
			if (_context.CurrentAssignment.HasValue && _context.CurrentAssignment.Value.ID == failedEvent.AssignmentID && failedEvent.PlayerId == NetworkManager.Singleton.LocalClientId)
			{
				FailAssignment(failedEvent.Reason);
			}
		}

		private void GameStateChanged(GameStateEnum state)
		{
			switch (state)
			{
			case GameStateEnum.MainMenu:
				HandleResetEvent();
				break;
			case GameStateEnum.Orbit:
				ShipTookOff();
				break;
			case GameStateEnum.CompanyHQ:
				HandleResetEvent();
				break;
			case GameStateEnum.Level:
				LandedOnMoon();
				if (NetworkManager.Singleton.IsHost)
				{
					GenerateAssignments();
				}
				break;
			}
		}

		public void LandedOnMoon()
		{
		}

		public void ShipTookOff()
		{
			ClearAllAssignments();
		}

		private void ClearAllAssignments()
		{
			SendNetworkEvent(default(ResetEvent));
		}

		public void Update()
		{
			if (_gameContext.GameState != GameStateEnum.Level)
			{
				return;
			}
			if (_context.CurrentAssignment.HasValue)
			{
				_assignmentUI.SetAssignment(_context.CurrentAssignment.Value);
			}
			if (NetworkManager.Singleton.IsHost)
			{
				if (_context.ActiveAssignments.Count > 0)
				{
					CheckCompleted();
				}
				if (_lootValueSyncRoutine == null && _context.SyncedRewardValues.Count > 0)
				{
					_lootValueSyncRoutine = ((MonoBehaviour)this).StartCoroutine(SyncLootValues());
				}
			}
		}

		private IEnumerator SyncLootValues()
		{
			yield return _rewardValueSyncDelay;
			for (int i = _context.SyncedRewardValues.Count - 1; i >= 0; i--)
			{
				if ((Object)(object)_context.SyncedRewardValues[i].Item1 == (Object)null)
				{
					_context.SyncedRewardValues.RemoveAt(i);
				}
			}
			if (_context.SyncedRewardValues.Count > 0)
			{
				List<NetworkObjectReference> references = new List<NetworkObjectReference>();
				List<int> values = new List<int>();
				foreach (var item in _context.SyncedRewardValues)
				{
					references.Add(NetworkObjectReference.op_Implicit(item.Item1));
					values.Add(item.Item2);
				}
				RoundManager.Instance.SyncScrapValuesClientRpc(references.ToArray(), values.ToArray());
			}
			_lootValueSyncRoutine = null;
		}

		private void GenerateAssignments()
		{
			int num = 0;
			_context.CompletedAssignments.Clear();
			_context.ActiveAssignments.Clear();
			_context.ExcludeTargetIds.Clear();
			IReadOnlyList<ulong> connectedClientsIds = NetworkManager.Singleton.ConnectedClientsIds;
			int num2 = Mathf.Max(_minAssignedPlayers, Mathf.Min(_maxAssignedPlayers, RoundManager.Instance.playersManager.connectedPlayersAmount / 2));
			List<int> list = new List<int>();
			for (int i = 0; i < connectedClientsIds.Count; i++)
			{
				list.Add(i);
			}
			num2 = Mathf.Min(num2, list.Count);
			if (_context.AssignAllPlayers)
			{
				num2 = list.Count;
			}
			Log($"Starting assignment generation for {num2} players");
			byte b = 0;
			for (int j = 0; j < num2; j++)
			{
				b++;
				int index = Random.Range(0, list.Count);
				int index2 = list[index];
				int num3 = Utils.WeightedRandom(_context.AssignmentWeights);
				Assignment assignment = Assignments.GetAssignment(_context.AssignmentWhitelist[num3]);
				if (!string.IsNullOrEmpty(assignment.UID))
				{
					assignment.PlayerId = connectedClientsIds[index2];
					assignment.ID = b;
					bool flag = _assignmentLogic[(int)assignment.Type].ServerSetupAssignment(ref assignment);
					if (!flag && num < 5)
					{
						j--;
						Log($"trying to find another assignment {connectedClientsIds[index2]}");
						num++;
					}
					else if (flag)
					{
						Log($"created assignment for player {connectedClientsIds[index2]}");
						AssignmentEvent assignmentEvent = default(AssignmentEvent);
						assignmentEvent.PlayerId = connectedClientsIds[index2];
						assignmentEvent.AssignmentUID = _context.AssignmentWhitelist[num3];
						assignmentEvent.TargetIds = assignment.TargetIds;
						assignmentEvent.RewardValue = assignment.CashReward;
						assignmentEvent.TargetName = assignment.TargetText;
						assignmentEvent.AssignmentID = b;
						AssignmentEvent netEvent = assignmentEvent;
						SendNetworkEvent(netEvent);
						_context.ActiveAssignments.Add(assignment);
						list.RemoveAt(index);
					}
				}
			}
			_context.AssignmentsGenerated = true;
			Log("Finishing assignment generation");
		}

		private void CheckCompleted()
		{
			bool wasPressedThisFrame = ((ButtonControl)Keyboard.current.oKey).wasPressedThisFrame;
			bool wasPressedThisFrame2 = ((ButtonControl)Keyboard.current.pKey).wasPressedThisFrame;
			for (int num = _context.ActiveAssignments.Count - 1; num >= 0; num--)
			{
				Assignment assignment = _context.ActiveAssignments[num];
				AssignmentState assignmentState = _assignmentLogic[(int)assignment.Type].CheckCompletion(ref assignment);
				if (assignmentState != 0)
				{
					_context.ActiveAssignments.RemoveAt(num);
					_context.CompletedAssignments.Add(assignment);
				}
				switch (assignmentState)
				{
				case AssignmentState.Complete:
					SendNetworkEvent(new CompleteEvent
					{
						PlayerId = assignment.PlayerId,
						AssignmentUID = assignment.UID,
						TargetIds = assignment.TargetIds,
						RewardValue = assignment.CashReward,
						AssignmentID = assignment.ID
					});
					break;
				case AssignmentState.Failed:
					SendNetworkEvent(new FailedEvent
					{
						PlayerId = assignment.PlayerId,
						Reason = assignment.FailureReason,
						AssignmentID = assignment.ID
					});
					break;
				}
			}
		}

		private void ShowAssignment(Assignment assignment)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			if (!((Object)(object)HUDManager.Instance == (Object)null))
			{
				DialogueSegment[] array = (DialogueSegment[])(object)new DialogueSegment[1]
				{
					new DialogueSegment
					{
						speakerText = "ASSIGNMENT:" + assignment.Name,
						bodyText = "YOU HAVE BEEN SELECTED BY THE COMPANY FOR ASSIGNMENT, " + string.Format(assignment.BodyText, assignment.TargetText),
						waitTime = 10f
					}
				};
				_assignmentUI.SetAssignment(assignment);
				HUDManager.Instance.ReadDialogue(array);
			}
		}

		private void CompleteAssignment()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			if (_context.CurrentAssignment.HasValue)
			{
				DialogueSegment[] array = (DialogueSegment[])(object)new DialogueSegment[1]
				{
					new DialogueSegment
					{
						speakerText = "ASSIGNMENT COMPLETE",
						bodyText = "YOU HAVE COMPLETED THE ASSIGNMENT, WELL DONE. THE COMPANY VALUES YOUR LOYALTY",
						waitTime = 5f
					}
				};
				_assignmentUI.ClearAssignment();
				HUDManager.Instance.ReadDialogue(array);
				_context.CurrentAssignment = null;
			}
		}

		private void FailAssignment(string reason)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_004f: Expected O, but got Unknown
			if (_context.CurrentAssignment.HasValue)
			{
				DialogueSegment[] array = (DialogueSegment[])(object)new DialogueSegment[1]
				{
					new DialogueSegment
					{
						speakerText = "ASSIGNMENT FAILED",
						bodyText = "YOU FAILED TO COMPLETE THE ASSIGNMENT. REASON: " + reason,
						waitTime = 5f
					}
				};
				_assignmentUI.ClearAssignment();
				HUDManager.Instance.ReadDialogue(array);
				_context.CurrentAssignment = null;
			}
		}
	}
	public static class Utils
	{
		private const float EASE_IN_OUT_MAGIC1 = 1.7f;

		private const float EASE_IN_OUT_MAGIC2 = 2.5500002f;

		public static float EaseInOutBack(float x)
		{
			return (x < 0.5f) ? (MathF.Pow(2f * x, 2f) * (7.1000004f * x - 2.5500002f) / 2f) : ((MathF.Pow(2f * x - 2f, 2f) * (3.5500002f * (x * 2f - 2f) + 2.5500002f) + 2f) / 2f);
		}

		public static int WeightedRandom(int[] weights)
		{
			int num = 0;
			for (int i = 0; i < weights.Length; i++)
			{
				num += weights[i];
			}
			int num2 = Random.Range(0, num);
			int num3 = 0;
			for (int j = 0; j < weights.Length; j++)
			{
				num3 += weights[j];
				if (num3 >= num2)
				{
					return j;
				}
			}
			return 0;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "EmployeeAssignments";

		public const string PLUGIN_NAME = "EmployeeAssignments";

		public const string PLUGIN_VERSION = "1.0.9";
	}
}
namespace PersonalAssignments.UI
{
	public class AssignmentUI : MonoBehaviour
	{
		private enum State
		{
			Showing,
			Shown,
			Hiding,
			Hidden
		}

		private readonly Color NONE_TEXT_COLOR = new Color(1f, 0.8277124f, 0.5235849f, 0.3254902f);

		private readonly Color BG_COLOR = new Color(1f, 0.6916346f, 0.259434f, 1f);

		private readonly Color TITLE_COLOR = new Color(1f, 0.9356132f, 0.8160377f, 1f);

		private readonly Color TEXT_COLOR = new Color(0.3584906f, 0.2703371f, 0f, 1f);

		private const float SHOW_SPEED = 1f;

		private const float HIDE_SPEED = 2f;

		private readonly Vector2 SHOW_POSITION = new Vector2(-50f, -350f);

		private readonly Vector2 HIDE_POSITION = new Vector2(500f, -350f);

		private Canvas _canvas;

		private GameObject _noneText;

		private RectTransform _assignment;

		private Text _assignmentTitle;

		private Text _assignmentText;

		private Font _font;

		private QuickMenuManager _menuManager;

		private State _state;

		private float _animationProgress;

		public Assignment? _activeAssignment;

		private void Awake()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: 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_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Expected O, but got Unknown
			//IL_0147: 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_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: 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_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0335: Unknown result type (might be due to invalid IL or missing references)
			//IL_0342: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_0370: Unknown result type (might be due to invalid IL or missing references)
			//IL_0381: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0419: Unknown result type (might be due to invalid IL or missing references)
			//IL_0430: Unknown result type (might be due to invalid IL or missing references)
			//IL_043d: 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)
			//IL_046b: Unknown result type (might be due to invalid IL or missing references)
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			_state = State.Hidden;
			((Component)this).gameObject.layer = 5;
			_font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
			_canvas = new GameObject("Canvas").AddComponent<Canvas>();
			((Component)_canvas).transform.SetParent(((Component)this).transform);
			_canvas.sortingOrder = -100;
			_canvas.renderMode = (RenderMode)0;
			RectTransform component = ((Component)_canvas).GetComponent<RectTransform>();
			component.sizeDelta = new Vector2(1920f, 1080f);
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.zero;
			component.pivot = Vector2.zero / 2f;
			CanvasScaler val = ((Component)_canvas).gameObject.AddComponent<CanvasScaler>();
			val.uiScaleMode = (ScaleMode)1;
			val.screenMatchMode = (ScreenMatchMode)2;
			val.referenceResolution = new Vector2(1920f, 1080f);
			_noneText = new GameObject("NoneText");
			Text val2 = _noneText.AddComponent<Text>();
			val2.fontSize = 20;
			val2.font = _font;
			val2.fontStyle = (FontStyle)1;
			val2.text = "NO ASSIGNMENT ACTIVE";
			((Graphic)val2).color = NONE_TEXT_COLOR;
			val2.alignment = (TextAnchor)4;
			RectTransform component2 = _noneText.GetComponent<RectTransform>();
			((Transform)component2).SetParent((Transform)(object)component);
			component2.pivot = Vector2.one;
			component2.anchorMin = Vector2.one;
			component2.anchorMax = Vector2.one;
			component2.anchoredPosition = new Vector2(-70f, -360f);
			component2.sizeDelta = new Vector2(310f, 50f);
			CanvasGroup val3 = new GameObject("AssignmentPanel").AddComponent<CanvasGroup>();
			val3.alpha = 0.5f;
			Image val4 = ((Component)val3).gameObject.AddComponent<Image>();
			((Graphic)val4).color = BG_COLOR;
			_assignment = ((Component)val3).gameObject.GetComponent<RectTransform>();
			((Transform)_assignment).SetParent((Transform)(object)component);
			_assignment.pivot = Vector2.one;
			_assignment.anchorMin = Vector2.one;
			_assignment.anchorMax = Vector2.one;
			_assignment.anchoredPosition = new Vector2(-50f, -350f);
			_assignment.sizeDelta = new Vector2(350f, 80f);
			_assignmentTitle = new GameObject("Title").AddComponent<Text>();
			_assignmentTitle.font = _font;
			_assignmentTitle.fontSize = 20;
			_assignmentTitle.fontStyle = (FontStyle)1;
			_assignmentTitle.text = "NO ASSIGNMENT ACTIVE";
			((Graphic)_assignmentTitle).color = TITLE_COLOR;
			_assignmentTitle.alignment = (TextAnchor)0;
			RectTransform component3 = ((Component)_assignmentTitle).gameObject.GetComponent<RectTransform>();
			((Transform)component3).SetParent((Transform)(object)_assignment);
			component3.pivot = new Vector2(0.5f, 1f);
			component3.anchorMin = new Vector2(0f, 1f);
			component3.anchorMax = Vector2.one;
			component3.anchoredPosition = new Vector2(0f, -10f);
			component3.sizeDelta = new Vector2(-40f, 100f);
			_assignmentText = new GameObject("Text").AddComponent<Text>();
			_assignmentText.font = _font;
			_assignmentText.fontSize = 16;
			_assignmentText.fontStyle = (FontStyle)1;
			_assignmentText.text = "NO ASSIGNMENT ACTIVE";
			((Graphic)_assignmentText).color = TEXT_COLOR;
			_assignmentText.alignment = (TextAnchor)6;
			RectTransform component4 = ((Component)_assignmentText).gameObject.GetComponent<RectTransform>();
			((Transform)component4).SetParent((Transform)(object)_assignment);
			component4.pivot = new Vector2(0.5f, 0.5f);
			component4.anchorMin = new Vector2(0f, 0f);
			component4.anchorMax = Vector2.one;
			component4.anchoredPosition = new Vector2(0f, -10f);
			component4.sizeDelta = new Vector2(-40f, -40f);
		}

		public void SetAssignment(Assignment assignment)
		{
			if (_state == State.Hidden || _state == State.Hiding)
			{
				ChangeState(State.Showing);
				_activeAssignment = assignment;
				_assignmentTitle.text = assignment.Name;
				_assignmentText.text = string.Format(assignment.ShortText, assignment.TargetText);
			}
		}

		public void ClearAssignment(bool force = false)
		{
			if (force || _state == State.Shown || _state == State.Showing)
			{
				ChangeState(State.Hiding);
				_activeAssignment = null;
			}
		}

		private void ChangeState(State state)
		{
			_state = state;
			_animationProgress = 0f;
		}

		private void PanelAnimation()
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			if (_state == State.Shown || _state == State.Hidden)
			{
				return;
			}
			if (_animationProgress >= 1f)
			{
				_state++;
				return;
			}
			float num = 1f;
			if (_state == State.Hiding)
			{
				num = 2f;
			}
			_animationProgress += num * Time.deltaTime;
			float num2 = _animationProgress;
			if (_state == State.Hiding)
			{
				num2 = 1f - num2;
			}
			_assignment.anchoredPosition = Vector2.Lerp(HIDE_POSITION, SHOW_POSITION, Utils.EaseInOutBack(num2));
		}

		private void Update()
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			PanelAnimation();
			bool flag = (Object)(object)GameNetworkManager.Instance?.localPlayerController != (Object)null && !GameNetworkManager.Instance.localPlayerController.isPlayerDead;
			if ((Object)(object)_menuManager == (Object)null)
			{
				flag = false;
				_menuManager = Object.FindAnyObjectByType<QuickMenuManager>();
			}
			else
			{
				flag &= !_menuManager.isMenuOpen;
			}
			if (_activeAssignment.HasValue && _activeAssignment.Value.FixedTargetPosition != Vector3.zero)
			{
				float num = Vector3.Distance(_activeAssignment.Value.FixedTargetPosition, ((Component)GameNetworkManager.Instance.localPlayerController).transform.position);
				_assignmentText.text = string.Format(_activeAssignment.Value.ShortText, _activeAssignment.Value.TargetText) + $" {(int)num}m";
			}
			((Component)_assignment).gameObject.SetActive(_state != State.Hidden);
			_noneText.SetActive(!_activeAssignment.HasValue);
			((Behaviour)_canvas).enabled = flag;
		}
	}
}
namespace PersonalAssignments.Network
{
	[Serializable]
	public struct NetworkMessage
	{
		public string MessageTag;

		public ulong TargetId;

		public Hash128 Checksum;

		public byte[] Data;
	}
	public class NetworkUtils : MonoBehaviour
	{
		public Action<string, byte[]> OnNetworkData;

		public Action OnDisconnect;

		public Action OnConnect;

		private bool _initialized;

		private bool _connected;

		public bool IsConnected => _connected;

		private void Initialize()
		{
			if (!((Object)(object)NetworkManager.Singleton == (Object)null) && NetworkManager.Singleton.CustomMessagingManager != null)
			{
				_initialized = true;
				Debug.Log((object)"[Network Transport] Initialized");
			}
		}

		private void UnInitialize()
		{
			if (_connected)
			{
				Disconnected();
			}
			_initialized = false;
		}

		private void Connected()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			NetworkManager.Singleton.CustomMessagingManager.OnUnnamedMessage += new UnnamedMessageDelegate(OnMessageEvent);
			OnConnect?.Invoke();
			_connected = true;
			Debug.Log((object)"[Network Transport] Connected");
		}

		private void Disconnected()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			NetworkManager singleton = NetworkManager.Singleton;
			if (((singleton != null) ? singleton.CustomMessagingManager : null) != null)
			{
				NetworkManager.Singleton.CustomMessagingManager.OnUnnamedMessage -= new UnnamedMessageDelegate(OnMessageEvent);
			}
			OnDisconnect?.Invoke();
			_connected = false;
			Debug.Log((object)"[Network Transport] Disconnected");
		}

		public void Update()
		{
			if (!_initialized)
			{
				Initialize();
			}
			else if ((Object)(object)NetworkManager.Singleton == (Object)null)
			{
				UnInitialize();
			}
			else if (!_connected && NetworkManager.Singleton.IsConnectedClient)
			{
				Connected();
			}
			else if (_connected && !NetworkManager.Singleton.IsConnectedClient)
			{
				Disconnected();
			}
		}

		private void OnMessageEvent(ulong clientId, FastBufferReader reader)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			Hash128 val = default(Hash128);
			string text = "";
			NetworkMessage networkMessage = default(NetworkMessage);
			try
			{
				((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
				Debug.Log((object)$"[Network Transport] Incoming message from {clientId} {text}");
				networkMessage = JsonUtility.FromJson<NetworkMessage>(text);
				val = Hash128.Compute<byte>(networkMessage.Data);
			}
			catch (Exception ex)
			{
				Debug.LogException(ex);
			}
			if (!(val == default(Hash128)) && ((Hash128)(ref val)).CompareTo(val) == 0)
			{
				OnNetworkData?.Invoke(networkMessage.MessageTag, networkMessage.Data);
			}
		}

		public void SendToAll(string tag, byte[] data)
		{
			if (!_initialized)
			{
				return;
			}
			foreach (var (num2, val2) in NetworkManager.Singleton.ConnectedClients)
			{
				SendTo(val2.ClientId, tag, data);
			}
		}

		public void SendTo(ulong clientId, string tag, byte[] data)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_00a2: Unknown result type (might be due to invalid IL or missing references)
			if (!_initialized)
			{
				return;
			}
			NetworkMessage networkMessage = default(NetworkMessage);
			networkMessage.MessageTag = tag;
			networkMessage.TargetId = clientId;
			networkMessage.Data = data;
			networkMessage.Checksum = Hash128.Compute<byte>(data);
			NetworkMessage networkMessage2 = networkMessage;
			string text = JsonUtility.ToJson((object)networkMessage2);
			byte[] bytes = Encoding.UTF8.GetBytes(text);
			int writeSize = FastBufferWriter.GetWriteSize(text, false);
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(writeSize + 1, (Allocator)2, -1);
			FastBufferWriter val2 = val;
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe(text, false);
				Debug.Log((object)$"[Network Transport] Sending message to {clientId} {text}");
				NetworkManager.Singleton.CustomMessagingManager.SendUnnamedMessage(clientId, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val2)).Dispose();
			}
		}
	}
}
namespace PersonalAssignments.Data
{
	public interface IPAEvent
	{
		string TAG { get; }
	}
	[Serializable]
	public struct AssignmentEvent : IPAEvent
	{
		public byte AssignmentID;

		public ulong PlayerId;

		public string AssignmentUID;

		public int RewardValue;

		public ulong[] TargetIds;

		public string TargetName;

		public string TAG => "PA-Allocation";
	}
	[Serializable]
	public struct CompleteEvent : IPAEvent
	{
		public byte AssignmentID;

		public ulong PlayerId;

		public string AssignmentUID;

		public int RewardValue;

		public ulong[] TargetIds;

		public string TAG => "PA-Complete";
	}
	[Serializable]
	public struct FailedEvent : IPAEvent
	{
		public byte AssignmentID;

		public ulong PlayerId;

		public string Reason;

		public string TAG => "PA-Failed";
	}
	[Serializable]
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	public struct ResetEvent : IPAEvent
	{
		public string TAG => "PA-Reset";
	}
	public class GameContext
	{
		private GameStateEnum _gameState;

		public Action<GameStateEnum> GameStateChanged;

		public GameStateEnum GameState
		{
			get
			{
				return _gameState;
			}
			set
			{
				if (value != _gameState)
				{
					_gameState = value;
					GameStateChanged?.Invoke(value);
				}
			}
		}
	}
	public enum GameStateEnum
	{
		MainMenu,
		Orbit,
		CompanyHQ,
		Level
	}
	public class PAConfig
	{
		public readonly ConfigEntry<int> MaxAssignedPlayers;

		public readonly ConfigEntry<int> MinAssignedPlayers;

		public readonly ConfigEntry<bool> AssignAllPlayers;

		public readonly ConfigEntry<int> ScrapRetrievalReward;

		public readonly ConfigEntry<string> HuntAndKillWhitelist;

		public readonly ConfigEntry<string> HuntAndKillWeights;

		public readonly ConfigEntry<string> HuntAndKillRewards;

		public readonly ConfigEntry<int> BrokenValveReward;

		public readonly ConfigEntry<bool> AllPlayersCanComplete;

		public readonly ConfigEntry<string> AssignmentWhiteList;

		public readonly ConfigEntry<string> AssignmentWeights;

		public PAConfig(ConfigFile configFile)
		{
			MaxAssignedPlayers = configFile.Bind<int>("0_HostOnly.0_General", "MaxAssignedPlayers", 10, "The maximum number of players that can be assigned each round.");
			MinAssignedPlayers = configFile.Bind<int>("0_HostOnly.0_General", "MinAssignedPlayers", 1, "The minimum number of players that can be assigned each round.");
			AssignAllPlayers = configFile.Bind<bool>("0_HostOnly.0_General", "AssignAllPlayers", false, "When this is true all connected players will always get an assignment  each time you land.");
			AllPlayersCanComplete = configFile.Bind<bool>("0_HostOnly.0_General", "AllPlayersCanComplete", false, "All players can complete someone elses assignment and it will not fail for the owner");
			AssignmentWhiteList = configFile.Bind<string>("0_HostOnly.0_General", "AssignmentWhiteList", "collect_scrap,hunt_kill,repair_valve", "All allowed Assignments");
			AssignmentWeights = configFile.Bind<string>("0_HostOnly.0_General", "AssignmentWeights", "50,25,25", "Weights for allowed assignments");
			ScrapRetrievalReward = configFile.Bind<int>("0_HostOnly.1_ScrapRetrieval", "AssignmentReward", 100, "The reward for completing a Scrap Retrieval Assignment");
			HuntAndKillWhitelist = configFile.Bind<string>("0_HostOnly.2_HuntAndKill", "EnemyWhitelist", "Centipede,Bunker Spider,Hoarding bug,Crawler", "The EnemyNames that are allowed to spawn");
			HuntAndKillRewards = configFile.Bind<string>("0_HostOnly.2_HuntAndKill", "EnemyRewards", "100,200,100,200", "The reward for completing a Hunt And KillReward Assignment for each enemy in the whitelist");
			HuntAndKillWeights = configFile.Bind<string>("0_HostOnly.2_HuntAndKill", "EnemyWeights", "50,25,50,25", "Spawn Weights for each enemy in the whitelist");
			BrokenValveReward = configFile.Bind<int>("0_HostOnly.3_BrokenValve", "AssignmentReward", 100, "The reward for completing a Broken Valve Assignment");
		}
	}
	public class PAContext
	{
		public bool AssignmentsGenerated;

		public readonly List<Assignment> ActiveAssignments = new List<Assignment>();

		public readonly List<Assignment> CompletedAssignments = new List<Assignment>();

		public readonly List<ulong> ExcludeTargetIds = new List<ulong>();

		public readonly List<(NetworkObject, int)> SyncedRewardValues = new List<(NetworkObject, int)>();

		public string[] EnemyWhitelist = new string[0];

		public int[] EnemyWeights = new int[0];

		public int[] EnemyRewards = new int[0];

		public string[] AssignmentWhitelist = new string[0];

		public int[] AssignmentWeights = new int[0];

		public Assignment? CurrentAssignment;

		public bool AssignAllPlayers;

		public bool AllPlayersComplete;

		public void ParseStringArray(ref string[] array, ConfigEntry<string> data)
		{
			string[] array2 = GetConfigValue(data).Split(',', StringSplitOptions.RemoveEmptyEntries);
			array = new string[array2.Length];
			for (int i = 0; i < array2.Length; i++)
			{
				array[i] = array2[i].TrimEnd(',').TrimStart(',');
			}
		}

		public void ParseIntArray(ref int[] array, ConfigEntry<string> data)
		{
			string[] array2 = GetConfigValue(data).Split(',', StringSplitOptions.RemoveEmptyEntries);
			array = new int[array2.Length];
			for (int i = 0; i < array2.Length; i++)
			{
				string s = array2[i].TrimEnd(',').TrimStart(',');
				if (int.TryParse(s, out var result))
				{
					array[i] = result;
				}
				else
				{
					array[i] = 0;
				}
			}
		}

		private string GetConfigValue(ConfigEntry<string> data)
		{
			string text = data.Value;
			if (string.IsNullOrWhiteSpace(text))
			{
				text = (string)((ConfigEntryBase)data).DefaultValue;
			}
			return text;
		}
	}
	public static class PAEventTags
	{
		public const string PREFIX = "PA-";

		public const string RESET = "PA-Reset";

		public const string ALLOCATION = "PA-Allocation";

		public const string COMPLETE = "PA-Complete";

		public const string FAILED = "PA-Failed";
	}
}
namespace PersonalAssignments.Components
{
	public class GameStateSync : MonoBehaviour
	{
		private const string COMPANY_BUILDING_SCENE = "CompanyBuilding";

		private GameContext _gameContext;

		private NetworkUtils _networkUtils;

		private bool _hasLanded;

		public void Inject(GameContext gameContext, NetworkUtils networkUtils)
		{
			_gameContext = gameContext;
			_networkUtils = networkUtils;
		}

		public void Update()
		{
			if (!_networkUtils.IsConnected || (Object)(object)StartOfRound.Instance == (Object)null)
			{
				_gameContext.GameState = GameStateEnum.MainMenu;
			}
			else if (StartOfRound.Instance.inShipPhase && _hasLanded)
			{
				_hasLanded = false;
				_gameContext.GameState = GameStateEnum.Orbit;
			}
			else if (StartOfRound.Instance.shipHasLanded && !_hasLanded)
			{
				_hasLanded = true;
				Debug.Log((object)("Landed on moon : " + RoundManager.Instance.currentLevel.sceneName));
				if (RoundManager.Instance.currentLevel.sceneName == "CompanyBuilding")
				{
					_gameContext.GameState = GameStateEnum.CompanyHQ;
				}
				else
				{
					_gameContext.GameState = GameStateEnum.Level;
				}
			}
		}
	}
	public class KillableEnemiesOutput : MonoBehaviour
	{
		private const string OUTPUT_PATH = "/../BepInEx/config2/KillableEnemies.md";

		private const string OUTPUT_PREFIX = "#KILLABLE ENEMIES LIST\r\nCopy the names from this list into the enemy assignment whilelist config entry to allow them to spawn.\r\nNote that some enemies would normally be spawnable on certain maps only, I'm not sure how well some\r\nenemies will handle being spawned on those maps but they should work I would have thought.";

		public void Update()
		{
			if (!((Object)(object)StartOfRound.Instance == (Object)null))
			{
				OutputList();
				Object.Destroy((Object)(object)this);
			}
		}

		private void OutputList()
		{
			List<string> list = new List<string>();
			string text = "#KILLABLE ENEMIES LIST\r\nCopy the names from this list into the enemy assignment whilelist config entry to allow them to spawn.\r\nNote that some enemies would normally be spawnable on certain maps only, I'm not sure how well some\r\nenemies will handle being spawned on those maps but they should work I would have thought.";
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				foreach (SpawnableEnemyWithRarity enemy in val.Enemies)
				{
					if (!list.Contains(enemy.enemyType.enemyName) && enemy.enemyType.canDie)
					{
						list.Add(enemy.enemyType.enemyName);
						text = text + "\n" + enemy.enemyType.enemyName;
					}
				}
			}
			try
			{
				FileStream fileStream = File.OpenWrite(Application.dataPath + "/../BepInEx/config2/KillableEnemies.md");
				using (StreamWriter streamWriter = new StreamWriter(fileStream))
				{
					streamWriter.Write(text);
				}
				fileStream.Close();
			}
			catch (Exception ex)
			{
				Debug.Log((object)ex);
			}
		}
	}
	public class UpdateChecker : MonoBehaviour
	{
		public const string EXPECTED_VERSION = "1.1.0";

		public const int MAINMENU_BUILDINDEX = 2;

		public const string THUNDERSTORE_URL = "https://thunderstore.io/package/download/amnsoft/EmployeeAssignments/";

		private UnityWebRequestAsyncOperation _webRequest;

		public bool IsLatestVersion { get; private set; }

		private void Awake()
		{
			SceneManager.sceneLoaded += OnSceneLoaded;
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode sceneMode)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			if (((Scene)(ref scene)).buildIndex == 2)
			{
				UnityWebRequest val = new UnityWebRequest("https://thunderstore.io/package/download/amnsoft/EmployeeAssignments/" + "1.1.0");
				_webRequest = val.SendWebRequest();
				((AsyncOperation)_webRequest).completed += OnComplete;
				SceneManager.sceneLoaded -= OnSceneLoaded;
			}
		}

		private void OnComplete(AsyncOperation obj)
		{
			IsLatestVersion = _webRequest.webRequest.responseCode == 404;
			if (!IsLatestVersion)
			{
				MenuManager val = Object.FindObjectOfType<MenuManager>();
				((TMP_Text)val.menuNotificationText).SetText("Employee Assignments mod is out of date, new version is atleast 1.1.0. Please update the mod.", true);
				((TMP_Text)val.menuNotificationButtonText).SetText("[ CLOSE ]", true);
				val.menuNotification.SetActive(true);
			}
			_webRequest = null;
		}
	}
}
namespace PersonalAssignments.AssignmentLogic
{
	public class CollectScrapLogic : IAssignmentLogic
	{
		private readonly PAContext _context;

		public CollectScrapLogic(PAContext context)
		{
			_context = context;
		}

		public bool ServerSetupAssignment(ref Assignment assignment)
		{
			GrabbableObject[] array = Object.FindObjectsByType<GrabbableObject>((FindObjectsSortMode)0);
			for (int i = 0; i < array.Length; i++)
			{
				if (!_context.ExcludeTargetIds.Contains(((NetworkBehaviour)array[i]).NetworkObjectId) && !array[i].scrapPersistedThroughRounds && array[i].itemProperties.isScrap)
				{
					assignment.TargetIds[0] = ((NetworkBehaviour)array[i]).NetworkObjectId;
					assignment.TargetText = array[i].itemProperties.itemName.ToUpper();
					_context.ExcludeTargetIds.Add(((NetworkBehaviour)array[i]).NetworkObjectId);
					return true;
				}
			}
			return false;
		}

		public bool HandleAllocationEvent(ref Assignment assignment, bool localPlayer)
		{
			if (!localPlayer)
			{
				return false;
			}
			GrabbableObject[] array = Object.FindObjectsByType<GrabbableObject>((FindObjectsSortMode)0);
			for (int i = 0; i < array.Length; i++)
			{
				if (((NetworkBehaviour)array[i]).NetworkObjectId == assignment.TargetIds[0])
				{
					assignment.TargetText = array[i].itemProperties.itemName.ToUpper();
					ScanNodeProperties componentInChildren = ((Component)array[i]).gameObject.GetComponentInChildren<ScanNodeProperties>();
					if ((Object)(object)componentInChildren == (Object)null)
					{
						Debug.LogError((object)("Scan node is missing for item!: " + ((Object)((Component)array[i]).gameObject).name));
						return false;
					}
					componentInChildren.headerText = "ASSIGNMENT TARGET";
					componentInChildren.subText = "Value : ???";
					break;
				}
			}
			return true;
		}

		public AssignmentState CheckCompletion(ref Assignment assignment)
		{
			foreach (GrabbableObject item in RoundManager.Instance.scrapCollectedThisRound)
			{
				if (item.isInShipRoom && ((NetworkBehaviour)item).NetworkObjectId == assignment.TargetIds[0])
				{
					if (_context.AllPlayersComplete || ((NetworkBehaviour)item).OwnerClientId == assignment.PlayerId)
					{
						return AssignmentState.Complete;
					}
					return AssignmentState.Failed;
				}
			}
			return AssignmentState.InProgress;
		}

		public void CompleteAssignment(ref Assignment assignment, bool localPlayer)
		{
			if (((NetworkBehaviour)RoundManager.Instance).NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(assignment.TargetIds[0], out var value))
			{
				GrabbableObject component = ((Component)value).gameObject.GetComponent<GrabbableObject>();
				component.SetScrapValue(assignment.CashReward + component.scrapValue);
				ScanNodeProperties componentInChildren = ((Component)component).gameObject.GetComponentInChildren<ScanNodeProperties>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					componentInChildren.headerText = component.itemProperties.itemName;
				}
				if (NetworkManager.Singleton.IsHost)
				{
					_context.SyncedRewardValues.Add((((NetworkBehaviour)component).NetworkObject, component.scrapValue));
				}
			}
		}
	}
	public class HuntAndKillLogic : IAssignmentLogic
	{
		private const float MAX_SPAWNDISTANCE = 20f;

		private const float MAX_PLAYERDISTANCE = 10f;

		private const string REWARD = "Gold bar";

		private readonly PAContext _context;

		public HuntAndKillLogic(PAContext context)
		{
			_context = context;
		}

		public bool ServerSetupAssignment(ref Assignment assignment)
		{
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_0335: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)RoundManager.Instance == (Object)null)
			{
				return false;
			}
			int num = Utils.WeightedRandom(_context.EnemyWeights);
			string text = _context.EnemyWhitelist[num];
			assignment.CashReward = _context.EnemyRewards[num];
			bool flag = false;
			for (int i = 0; i < RoundManager.Instance.SpawnedEnemies.Count; i++)
			{
				EnemyAI val = RoundManager.Instance.SpawnedEnemies[i];
				if (!(val.enemyType.enemyName != text) && ((NetworkBehaviour)val).IsSpawned && !val.isEnemyDead && !_context.ExcludeTargetIds.Contains(((NetworkBehaviour)val).NetworkObjectId))
				{
					assignment.TargetIds[0] = ((NetworkBehaviour)val).NetworkObjectId;
					assignment.TargetText = val.enemyType.enemyName.ToUpper();
					_context.ExcludeTargetIds.Add(((NetworkBehaviour)val).NetworkObjectId);
					flag = true;
					ScanNodeProperties componentInChildren = ((Component)val).gameObject.GetComponentInChildren<ScanNodeProperties>();
					componentInChildren.headerText = "ASSIGNMENT TARGET";
					break;
				}
			}
			if (!flag)
			{
				SpawnableEnemyWithRarity val2 = null;
				num = 0;
				for (int j = 0; j < RoundManager.Instance.currentLevel.Enemies.Count; j++)
				{
					if (RoundManager.Instance.currentLevel.Enemies[j].enemyType.enemyName == text)
					{
						val2 = RoundManager.Instance.currentLevel.Enemies[j];
						num = j;
						break;
					}
				}
				if (val2 == null)
				{
					return false;
				}
				Vector3 val3 = Vector3.zero;
				EntranceTeleport[] array = Object.FindObjectsOfType<EntranceTeleport>();
				for (int k = 0; k < array.Length; k++)
				{
					if (!array[k].isEntranceToBuilding && array[k].entranceId == 0)
					{
						val3 = ((Component)array[k]).transform.position;
					}
				}
				List<(EnemyVent, float)> list = new List<(EnemyVent, float)>();
				EnemyVent[] allEnemyVents = RoundManager.Instance.allEnemyVents;
				foreach (EnemyVent val4 in allEnemyVents)
				{
					list.Add((val4, Vector3.Distance(val4.floorNode.position, val3)));
				}
				list = list.OrderByDescending<(EnemyVent, float), float>(((EnemyVent vent, float distance) a) => a.distance).ToList();
				bool flag2 = false;
				int num2 = 0;
				Vector3 val5 = Vector3.zero;
				NavMeshHit val6 = default(NavMeshHit);
				while (!flag2 && num2 < 5)
				{
					EnemyVent item = list[Random.Range(0, list.Count / 2)].Item1;
					flag2 = NavMesh.SamplePosition(item.floorNode.position, ref val6, 20f, -1);
					val5 = ((NavMeshHit)(ref val6)).position;
					num2++;
				}
				if (!flag2)
				{
					return false;
				}
				RoundManager.Instance.SpawnEnemyOnServer(val5, 0f, num);
				ulong[] targetIds = assignment.TargetIds;
				List<EnemyAI> spawnedEnemies = RoundManager.Instance.SpawnedEnemies;
				targetIds[0] = ((NetworkBehaviour)spawnedEnemies[spawnedEnemies.Count - 1]).NetworkObjectId;
				List<EnemyAI> spawnedEnemies2 = RoundManager.Instance.SpawnedEnemies;
				assignment.TargetText = spawnedEnemies2[spawnedEnemies2.Count - 1].enemyType.enemyName.ToUpper();
				_context.ExcludeTargetIds.Add(assignment.TargetIds[0]);
				List<EnemyAI> spawnedEnemies3 = RoundManager.Instance.SpawnedEnemies;
				ScanNodeProperties componentInChildren2 = ((Component)spawnedEnemies3[spawnedEnemies3.Count - 1]).gameObject.GetComponentInChildren<ScanNodeProperties>();
				componentInChildren2.headerText = "ASSIGNMENT TARGET";
			}
			return true;
		}

		public bool HandleAllocationEvent(ref Assignment assignment, bool localPlayer)
		{
			foreach (EnemyAI spawnedEnemy in RoundManager.Instance.SpawnedEnemies)
			{
				if (((NetworkBehaviour)spawnedEnemy).NetworkObjectId == assignment.TargetIds[0])
				{
					assignment.TargetText = spawnedEnemy.enemyType.enemyName.ToUpper();
					ScanNodeProperties componentInChildren = ((Component)spawnedEnemy).gameObject.GetComponentInChildren<ScanNodeProperties>();
					componentInChildren.headerText = "ASSIGNMENT TARGET";
					return true;
				}
			}
			return true;
		}

		public AssignmentState CheckCompletion(ref Assignment assignment)
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			foreach (EnemyAI spawnedEnemy in RoundManager.Instance.SpawnedEnemies)
			{
				if (((NetworkBehaviour)spawnedEnemy).NetworkObjectId != assignment.TargetIds[0] || !spawnedEnemy.isEnemyDead)
				{
					continue;
				}
				float num = float.MaxValue;
				foreach (NetworkClient connectedClients in NetworkManager.Singleton.ConnectedClientsList)
				{
					float num2 = Vector3.Distance(((Component)connectedClients.PlayerObject).transform.position, ((Component)spawnedEnemy.agent).transform.position);
					if (num2 < num)
					{
						num = num2;
					}
				}
				if (num < 10f)
				{
					return AssignmentState.Complete;
				}
				return AssignmentState.Failed;
			}
			return AssignmentState.InProgress;
		}

		public void CompleteAssignment(ref Assignment assignment, bool localPlayer)
		{
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsHost)
			{
				return;
			}
			foreach (EnemyAI spawnedEnemy in RoundManager.Instance.SpawnedEnemies)
			{
				if (((NetworkBehaviour)spawnedEnemy).NetworkObjectId == assignment.TargetIds[0])
				{
					GameObject val = (from a in StartOfRound.Instance.allItemsList.itemsList?.Where((Item a) => a.itemName == "Gold bar")
						select a.spawnPrefab).First();
					GameObject val2 = Object.Instantiate<GameObject>(val, spawnedEnemy.serverPosition, Quaternion.identity, RoundManager.Instance.spawnedScrapContainer);
					GrabbableObject component = val2.GetComponent<GrabbableObject>();
					((Component)component).transform.rotation = Quaternion.Euler(component.itemProperties.restingRotation);
					component.fallTime = 0f;
					component.SetScrapValue(assignment.CashReward);
					NetworkObject component2 = val2.GetComponent<NetworkObject>();
					component2.Spawn(false);
					_context.SyncedRewardValues.Add((component2, assignment.CashReward));
					break;
				}
			}
		}
	}
	public interface IAssignmentLogic
	{
		bool ServerSetupAssignment(ref Assignment assignment);

		bool HandleAllocationEvent(ref Assignment assignment, bool localPlayer);

		AssignmentState CheckCompletion(ref Assignment assignment);

		void CompleteAssignment(ref Assignment assignment, bool localPlayer);
	}
	public enum AssignmentState
	{
		InProgress,
		Complete,
		Failed
	}
	public class RepairValveLogic : IAssignmentLogic
	{
		private readonly PAContext _context;

		public RepairValveLogic(PAContext context)
		{
			_context = context;
		}

		public bool ServerSetupAssignment(ref Assignment assignment)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			SteamValveHazard[] array = Object.FindObjectsByType<SteamValveHazard>((FindObjectsSortMode)0);
			if (array.Length == 0)
			{
				return false;
			}
			Vector3 val = RoundManager.FindMainEntrancePosition(false, false);
			float num = 0f;
			int num2 = 0;
			for (int i = 0; i < array.Length; i++)
			{
				float num3 = Vector3.Distance(val, ((Component)array[i]).transform.position);
				if (num3 > num && num3 > 80f)
				{
					num2 = i;
					num = num3;
				}
			}
			if (!_context.ExcludeTargetIds.Contains(((NetworkBehaviour)array[num2]).NetworkObjectId) && ((NetworkBehaviour)array[num2]).IsSpawned)
			{
				assignment.TargetIds[0] = ((NetworkBehaviour)array[num2]).NetworkObjectId;
				_context.ExcludeTargetIds.Add(((NetworkBehaviour)array[num2]).NetworkObjectId);
				array[num2].valveCrackTime = 0.001f;
				array[num2].valveBurstTime = 0.01f;
				array[num2].triggerScript.interactable = true;
				assignment.FixedTargetPosition = ((Component)array[num2]).gameObject.transform.position;
				return true;
			}
			return false;
		}

		public bool HandleAllocationEvent(ref Assignment assignment, bool localPlayer)
		{
			return true;
		}

		public AssignmentState CheckCompletion(ref Assignment assignment)
		{
			SteamValveHazard[] array = Object.FindObjectsOfType<SteamValveHazard>();
			SteamValveHazard[] array2 = array;
			foreach (SteamValveHazard val in array2)
			{
				if (((NetworkBehaviour)val).NetworkObjectId == assignment.TargetIds[0] && !val.triggerScript.interactable)
				{
					if (_context.AllPlayersComplete || ((NetworkBehaviour)val.triggerScript).OwnerClientId == assignment.PlayerId)
					{
						return AssignmentState.Complete;
					}
					return AssignmentState.Failed;
				}
			}
			return AssignmentState.InProgress;
		}

		public void CompleteAssignment(ref Assignment assignment, bool localPlayer)
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsHost)
			{
				return;
			}
			SteamValveHazard[] array = Object.FindObjectsOfType<SteamValveHazard>();
			SteamValveHazard[] array2 = array;
			foreach (SteamValveHazard val in array2)
			{
				if (((NetworkBehaviour)val).NetworkObjectId == assignment.TargetIds[0])
				{
					GameObject val2 = (from a in StartOfRound.Instance.allItemsList.itemsList?.Where((Item a) => a.itemName == "Gold bar")
						select a.spawnPrefab).First();
					GameObject val3 = Object.Instantiate<GameObject>(val2, ((Component)val).gameObject.transform.position, Quaternion.identity, RoundManager.Instance.spawnedScrapContainer);
					GrabbableObject component = val3.GetComponent<GrabbableObject>();
					((Component)component).transform.rotation = Quaternion.Euler(component.itemProperties.restingRotation);
					component.fallTime = 0f;
					component.SetScrapValue(assignment.CashReward);
					NetworkObject component2 = val3.GetComponent<NetworkObject>();
					component2.Spawn(false);
					_context.SyncedRewardValues.Add((component2, assignment.CashReward));
					break;
				}
			}
		}
	}
}

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

plugins/HookGun.dll

Decompiled 7 months ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using HookGun.Patches;
using LethalLib.Modules;
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("HookGun")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HookGun")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("56cd2431-e59f-4623-8b05-4f3a954ed7df")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HookGun
{
	[BepInPlugin("com.BLKNeko.HookGun", "HookGun", "1.3.4.1")]
	public class HookGunPlugin : BaseUnityPlugin
	{
		public class HookGunScript : GrabbableObject
		{
			private AudioSource audioSource;

			private RoundManager roundManager;

			private MeshRenderer HookGO;

			public LayerMask whatIsGrappleable = LayerMask.op_Implicit(234918656);

			public LayerMask whatIsGrappleableToPull = LayerMask.op_Implicit(1048640);

			public LineRenderer lr;

			public float maxGrappleDistance = 60f;

			public float grappleDelayTime = 1f;

			public float overshootYAxis = 1.5f;

			public float HookSpeed = 48f;

			public float OkDistance = 1f;

			public float HookmaxTimer = 6f;

			public float HookTimer = 0f;

			public float smoothTime = 1.3f;

			public static bool grappling;

			public static bool pulling;

			public static bool shoudFall;

			public static bool DisableJump;

			public static bool DisableFall;

			private bool grapplingSlowY = false;

			private bool JumpNoDmg = true;

			public static bool isJumping;

			public static bool NoDmg;

			private Vector3 grapplePoint = Vector3.zero;

			private Vector3 targetPosition = Vector3.zero;

			private Vector3 forces = Vector3.zero;

			private Vector3 forcesP = Vector3.zero;

			private GameObject pullingGameObject;

			private RaycastHit hit;

			public void Awake()
			{
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0047: Expected O, but got Unknown
				audioSource = ((Component)this).GetComponent<AudioSource>();
				roundManager = Object.FindObjectOfType<RoundManager>();
				base.grabbable = true;
				base.grabbableToEnemies = true;
				base.useCooldown = itemCooldown.Value;
				base.insertedBattery = new Battery(false, 1f);
				base.mainObjectRenderer = ((Component)this).GetComponent<MeshRenderer>();
			}

			public override void Update()
			{
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0093: Unknown result type (might be due to invalid IL or missing references)
				//IL_0098: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
				//IL_0125: Unknown result type (might be due to invalid IL or missing references)
				//IL_012a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0136: Unknown result type (might be due to invalid IL or missing references)
				//IL_013b: Unknown result type (might be due to invalid IL or missing references)
				//IL_015a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0161: Unknown result type (might be due to invalid IL or missing references)
				//IL_0166: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
				//IL_020a: Unknown result type (might be due to invalid IL or missing references)
				//IL_020f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0236: Unknown result type (might be due to invalid IL or missing references)
				//IL_023b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0262: 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_03a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_03ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_03b8: 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_0406: Unknown result type (might be due to invalid IL or missing references)
				//IL_040b: Unknown result type (might be due to invalid IL or missing references)
				//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
				//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
				//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
				((GrabbableObject)this).Update();
				if (!base.isHeld)
				{
					return;
				}
				if (base.currentUseCooldown <= 0f && base.insertedBattery.charge > 0f)
				{
					((Component)((Component)this).gameObject.transform.Find("HookMesh")).gameObject.active = true;
				}
				else
				{
					((Component)((Component)this).gameObject.transform.Find("HookMesh")).gameObject.active = false;
				}
				if (pulling)
				{
					_ = targetPosition;
					if (targetPosition != Vector3.zero && !base.playerHeldBy.isPlayerDead)
					{
						((Component)pullingGameObject.GetComponent<GrabbableObject>()).transform.position = ((Component)base.playerHeldBy).transform.position + new Vector3(0.2f, 0.8f, 0.2f);
						pullingGameObject.GetComponent<GrabbableObject>().FallToGround(false);
						HookTimer = 0f;
						HookSpeed = 0f;
						forcesP = Vector3.zero;
						pulling = false;
						targetPosition = Vector3.zero;
						((MonoBehaviour)this).Invoke("backToNormal", 0.5f);
					}
				}
				if (!grappling)
				{
					return;
				}
				_ = targetPosition;
				if (!(targetPosition != Vector3.zero) || base.playerHeldBy.isPlayerDead)
				{
					return;
				}
				if (!base.playerHeldBy.isInsideFactory)
				{
					NoDmg = true;
				}
				if (HookTimer >= HookmaxTimer)
				{
					((MonoBehaviour)this).Invoke("backToNormal", 1f);
					((MonoBehaviour)this).Invoke("enableDamage", 4f);
					HookTimer = 0f;
					HookSpeed = 0f;
					forces = Vector3.zero;
					grappling = false;
					targetPosition = Vector3.zero;
					base.playerHeldBy.ResetFallGravity();
					base.playerHeldBy.averageVelocity = 0f;
					base.playerHeldBy.externalForces = Vector3.zero;
				}
				else
				{
					HookTimer += Time.fixedDeltaTime;
				}
				if (Vector3.Distance(((Component)base.playerHeldBy).transform.position, targetPosition) >= OkDistance)
				{
					if (base.playerHeldBy.isInsideFactory)
					{
						HookSpeed = 38f;
					}
					else
					{
						HookSpeed = 45f;
					}
					forces = Vector3.Normalize(targetPosition - ((Component)base.playerHeldBy).transform.position) * HookSpeed;
					if (base.playerHeldBy.isInsideFactory)
					{
						forces.y *= 2f;
					}
					else
					{
						forces.y *= 1.5f;
					}
					base.playerHeldBy.externalForces.x += forces.x;
					base.playerHeldBy.externalForces.z += forces.z;
					base.playerHeldBy.externalForces.y += forces.y;
				}
				else
				{
					HookTimer = 0f;
					HookSpeed = 0f;
					forces = Vector3.zero;
					grappling = false;
					targetPosition = Vector3.zero;
					((MonoBehaviour)this).Invoke("backToNormal", 2f);
					((MonoBehaviour)this).Invoke("enableDamage", 8f);
					base.playerHeldBy.ResetFallGravity();
					base.playerHeldBy.averageVelocity = 0f;
					base.playerHeldBy.externalForces = Vector3.zero;
				}
			}

			public override void ItemActivate(bool used, bool buttonDown = true)
			{
				((GrabbableObject)this).ItemActivate(used, buttonDown);
				if (base.playerHeldBy.isInsideFactory)
				{
					OkDistance = 2f;
					HookmaxTimer = 4f;
				}
				else
				{
					OkDistance = 1f;
					HookmaxTimer = 6f;
				}
				if (base.insertedBattery.charge >= energyCost.Value)
				{
					Battery insertedBattery = base.insertedBattery;
					insertedBattery.charge -= energyCost.Value;
					if (base.insertedBattery.charge < energyCost.Value)
					{
						base.insertedBattery.charge = 0f;
					}
					audioSource.PlayOneShot(Assets.ShootSFX);
					StartGrapple();
				}
				else
				{
					audioSource.PlayOneShot(Assets.NoAmmoSFX);
				}
			}

			private void StartGrapple()
			{
				//IL_002e: 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_0055: 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_0157: Unknown result type (might be due to invalid IL or missing references)
				//IL_0169: Unknown result type (might be due to invalid IL or missing references)
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_0085: Unknown result type (might be due to invalid IL or missing references)
				//IL_0092: Unknown result type (might be due to invalid IL or missing references)
				//IL_0097: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00be: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cd: 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_00d9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00de: Unknown result type (might be due to invalid IL or missing references)
				//IL_00df: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
				//IL_0189: Unknown result type (might be due to invalid IL or missing references)
				//IL_018e: 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_01a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
				//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
				//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
				//IL_0200: Unknown result type (might be due to invalid IL or missing references)
				//IL_0204: Unknown result type (might be due to invalid IL or missing references)
				//IL_0217: Unknown result type (might be due to invalid IL or missing references)
				//IL_0219: Unknown result type (might be due to invalid IL or missing references)
				LineRenderer component = ((Component)Object.Instantiate<HookGunScript>(this, ((Component)this).gameObject.transform.GetChild(0))).GetComponent<LineRenderer>();
				if (Physics.Raycast(((Component)base.playerHeldBy.gameplayCamera).transform.position, ((Component)base.playerHeldBy.gameplayCamera).transform.forward, ref hit, maxGrappleDistance, LayerMask.op_Implicit(whatIsGrappleableToPull)))
				{
					grapplePoint = ((RaycastHit)(ref hit)).point;
					SpawnTrail(component, ((RaycastHit)(ref hit)).point);
					targetPosition = grapplePoint;
					Vector3 position = ((Component)base.playerHeldBy).transform.position;
					Vector3 val = position - ((RaycastHit)(ref hit)).point;
					((Vector3)(ref val)).Normalize();
					val *= 1f;
					position = ((RaycastHit)(ref hit)).point + val;
					position.y *= 1.1f;
					targetPosition = position;
					pulling = true;
					pullingGameObject = ((Component)((RaycastHit)(ref hit)).transform).gameObject;
					audioSource.PlayOneShot(Assets.HitSFX);
				}
				else if (Physics.Raycast(((Component)base.playerHeldBy.gameplayCamera).transform.position, ((Component)base.playerHeldBy.gameplayCamera).transform.forward, ref hit, maxGrappleDistance, LayerMask.op_Implicit(whatIsGrappleable)))
				{
					grapplePoint = ((RaycastHit)(ref hit)).point;
					SpawnTrail(component, ((RaycastHit)(ref hit)).point);
					targetPosition = grapplePoint;
					Vector3 position2 = ((Component)base.playerHeldBy).transform.position;
					Vector3 val2 = position2 - ((RaycastHit)(ref hit)).point;
					((Vector3)(ref val2)).Normalize();
					val2 *= 1f;
					position2 = ((RaycastHit)(ref hit)).point + val2;
					position2.y *= 1.1f;
					targetPosition = position2;
					grappling = true;
					audioSource.PlayOneShot(Assets.HitSFX);
				}
				else
				{
					audioSource.PlayOneShot(Assets.MissSFX);
					((Component)component).gameObject.AddComponent<LineRendererFadeOut>();
					Battery insertedBattery = base.insertedBattery;
					insertedBattery.charge += energyCost.Value;
				}
			}

			private void SpawnTrail(LineRenderer Trail, Vector3 HitPoint)
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				Trail.SetPositions((Vector3[])(object)new Vector3[2]
				{
					((Component)this).gameObject.transform.GetChild(0).position,
					HitPoint
				});
				((Component)Trail).gameObject.AddComponent<LineRendererFadeOut>();
			}

			private void backToNormal()
			{
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				HookSpeed = 0f;
				HookTimer = 0f;
				forces = Vector3.zero;
				grappling = false;
				targetPosition = Vector3.zero;
				base.playerHeldBy.ResetFallGravity();
				base.playerHeldBy.averageVelocity = 0f;
				base.playerHeldBy.externalForces = Vector3.zero;
			}

			private void enableDamage()
			{
				NoDmg = false;
			}
		}

		public class LineRendererFadeOut : MonoBehaviour
		{
			public LineRenderer lineRenderer;

			public float fadeDuration = 1f;

			public float destroyDelay = 0.5f;

			private float elapsed = 0f;

			private bool isFading = true;

			private void Start()
			{
				lineRenderer = ((Component)this).GetComponent<LineRenderer>();
			}

			private void Update()
			{
				//IL_00c4: 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_00ee: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
				//IL_0058: 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_0082: 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)
				if (isFading)
				{
					if (elapsed < fadeDuration)
					{
						float num = Mathf.Lerp(1f, 0f, elapsed / fadeDuration);
						((Renderer)lineRenderer).material.color = new Color(((Renderer)lineRenderer).material.color.r, ((Renderer)lineRenderer).material.color.g, ((Renderer)lineRenderer).material.color.b, num);
						elapsed += Time.deltaTime;
					}
					else
					{
						((Renderer)lineRenderer).material.color = new Color(((Renderer)lineRenderer).material.color.r, ((Renderer)lineRenderer).material.color.g, ((Renderer)lineRenderer).material.color.b, 0f);
						isFading = false;
						Object.Destroy((Object)(object)((Component)this).gameObject, destroyDelay);
					}
				}
			}
		}

		private class Assets
		{
			internal static AssetBundle mainAssetBundle;

			private const string assetbundleName = "hookgunitem";

			private static string[] assetNames = new string[0];

			public static Item HGItem;

			public static Sprite HGSprite;

			public static AudioClip ShootSFX;

			public static AudioClip HitSFX;

			public static AudioClip MissSFX;

			public static AudioClip NoAmmoSFX;

			public static Mesh HGMesh;

			public static Mesh HOMesh;

			internal static void LoadAssetBundle()
			{
				if ((Object)(object)mainAssetBundle == (Object)null)
				{
					using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("HookGun.hookgunitem");
					mainAssetBundle = AssetBundle.LoadFromStream(stream);
				}
				assetNames = mainAssetBundle.GetAllAssetNames();
			}

			internal static void PopulateAssets()
			{
				if (!Object.op_Implicit((Object)(object)mainAssetBundle))
				{
					Debug.LogError((object)"There is no AssetBundle to load assets from.");
					return;
				}
				HGSprite = mainAssetBundle.LoadAsset<Sprite>("HGSprite");
				ShootSFX = mainAssetBundle.LoadAsset<AudioClip>("ShootSFX");
				HitSFX = mainAssetBundle.LoadAsset<AudioClip>("HitSFX");
				MissSFX = mainAssetBundle.LoadAsset<AudioClip>("MissSFX");
				NoAmmoSFX = mainAssetBundle.LoadAsset<AudioClip>("NoAmmoSFX");
				HGItem = mainAssetBundle.LoadAsset<Item>("HookGunItem");
			}
		}

		private const string MODUID = "com.BLKNeko.HookGun";

		private const string MODNAME = "HookGun";

		private const string MODVERSION = "1.3.4.1";

		private readonly Harmony harmony = new Harmony("com.BLKNeko.HookGun");

		private static HookGunPlugin Instance;

		internal ManualLogSource mls;

		public static ConfigEntry<int> itemPrice { get; set; }

		public static ConfigEntry<float> itemCooldown { get; set; }

		public static ConfigEntry<float> energyCost { get; set; }

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("com.BLKNeko.HookGun");
			harmony.PatchAll(typeof(HookGunPlugin));
			harmony.PatchAll(typeof(AllowDeathPatch));
			harmony.PatchAll();
			Assets.LoadAssetBundle();
			Assets.PopulateAssets();
			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);
					}
				}
			}
			itemPrice = ((BaseUnityPlugin)this).Config.Bind<int>("ItemPrice", "Price", 25, "This is the item price, my default is 25, [INTEGER 1,2,30...]");
			itemCooldown = ((BaseUnityPlugin)this).Config.Bind<float>("ItemCooldown", "Cooldown", 2f, "This is the item cooldown, my default is 2, [FLOAT 0.5,1.8,18.9,...]");
			energyCost = ((BaseUnityPlugin)this).Config.Bind<float>("EnergyCost", "Cost", 0.05f, "This is the item energy cost of activation, my default is 0.05, the MAX energy is 1f so 0.05 give you 20 sucessfull activations [FLOAT 0.01,0.1,1 -- DON'T USE MORE THAN 1]");
			Item hGItem = Assets.HGItem;
			HookGunScript hookGunScript = hGItem.spawnPrefab.AddComponent<HookGunScript>();
			((GrabbableObject)hookGunScript).itemProperties = hGItem;
			Items.RegisterShopItem(hGItem, itemPrice.Value);
			NetworkPrefabs.RegisterNetworkPrefab(hGItem.spawnPrefab);
		}
	}
}
namespace HookGun.Patches
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	public class AllowDeathPatch
	{
		[HarmonyPatch("AllowPlayerDeath")]
		[HarmonyPrefix]
		private static bool ChangeAllowDeath()
		{
			if (HookGunPlugin.HookGunScript.NoDmg)
			{
				return false;
			}
			return true;
		}
	}
}

plugins/LC_API.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.BundleAPI;
using LC_API.ClientAPI;
using LC_API.Comp;
using LC_API.Data;
using LC_API.Exceptions;
using LC_API.Extensions;
using LC_API.GameInterfaceAPI;
using LC_API.GameInterfaceAPI.Events;
using LC_API.GameInterfaceAPI.Events.Cache;
using LC_API.GameInterfaceAPI.Events.EventArgs.Player;
using LC_API.GameInterfaceAPI.Events.Handlers;
using LC_API.GameInterfaceAPI.Features;
using LC_API.ManualPatches;
using LC_API.Networking;
using LC_API.ServerAPI;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("")]
[assembly: AssemblyCompany("2018")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Utilities for plugin devs")]
[assembly: AssemblyFileVersion("3.4.5.0")]
[assembly: AssemblyInformationalVersion("3.4.5+ae2de74676f4f0d6440c82067f4c1a22389fe27b")]
[assembly: AssemblyProduct("Lethal Company API")]
[assembly: AssemblyTitle("LC_API")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("3.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

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

		private const string SIG_SEND_MODS = "LC_APISendMods";

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

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

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

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

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

		private ConfigEntry<bool> configOverrideModServer;

		private ConfigEntry<bool> configLegacyAssetLoading;

		private ConfigEntry<bool> configDisableBundleLoader;

		internal static ConfigEntry<bool> configVanillaSupport;

		internal static Harmony Harmony;

		internal static Plugin Instance { get; private set; }

		public static bool Initialized { get; private set; }

		private void Awake()
		{
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Expected O, but got Unknown
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Expected O, but got Unknown
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Expected O, but got Unknown
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Expected O, but got Unknown
			//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d2: Expected O, but got Unknown
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Expected O, but got Unknown
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: Expected O, but got Unknown
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_031a: Expected O, but got Unknown
			Instance = this;
			configOverrideModServer = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Force modded server browser", false, "Should the API force you into the modded server browser?");
			configLegacyAssetLoading = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Legacy asset bundle loading", false, "Should the BundleLoader use legacy asset loading? Turning this on may help with loading assets from older plugins.");
			configDisableBundleLoader = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Disable BundleLoader", false, "Should the BundleLoader be turned off? Enable this if you are having problems with mods that load assets using a different method from LC_API's BundleLoader.");
			configVanillaSupport = ((BaseUnityPlugin)this).Config.Bind<bool>("Compatibility", "Vanilla Compatibility", false, "Allows you to join vanilla servers, but disables many networking-related things and could cause mods to not work properly.");
			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();
			}
			if (configVanillaSupport.Value)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API is starting with VANILLA SUPPORT ENABLED.");
			}
			Harmony = new Harmony("ModAPI");
			MethodInfo methodInfo = AccessTools.Method(typeof(GameNetworkManager), "SteamMatchmaking_OnLobbyCreated", (Type[])null, (Type[])null);
			AccessTools.Method(typeof(GameNetworkManager), "LobbyDataIsJoinable", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(ServerPatch), "OnLobbyCreate", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(MenuManager), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(ServerPatch), "CacheMenuManager", (Type[])null, (Type[])null);
			AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(typeof(HUDManager), "SubmitChat_performed", (Type[])null, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.Method(typeof(CommandHandler.SubmitChatPatch), "Transpiler", (Type[])null, (Type[])null);
			MethodInfo methodInfo7 = AccessTools.Method(typeof(GameNetworkManager), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo8 = AccessTools.Method(typeof(ServerPatch), "GameNetworkManagerAwake", (Type[])null, (Type[])null);
			MethodInfo methodInfo9 = AccessTools.Method(typeof(NetworkManager), "StartClient", (Type[])null, (Type[])null);
			MethodInfo methodInfo10 = AccessTools.Method(typeof(NetworkManager), "StartHost", (Type[])null, (Type[])null);
			MethodInfo methodInfo11 = AccessTools.Method(typeof(NetworkManager), "Shutdown", (Type[])null, (Type[])null);
			MethodInfo methodInfo12 = AccessTools.Method(typeof(RegisterPatch), "Postfix", (Type[])null, (Type[])null);
			MethodInfo methodInfo13 = AccessTools.Method(typeof(UnregisterPatch), "Postfix", (Type[])null, (Type[])null);
			Harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo7, new HarmonyMethod(methodInfo8), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo9, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo10, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo11, (HarmonyMethod)null, new HarmonyMethod(methodInfo13), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Network.Init();
			Events.Patch(Harmony);
		}

		internal void Start()
		{
			Initialize();
		}

		internal void OnDestroy()
		{
			Initialize();
		}

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

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

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

		public const string PLUGIN_NAME = "Lethal Company API";

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

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

		public static int GameVersion { get; internal set; }

		public static bool ModdedOnly => moddedOnly;

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

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

			public readonly T Value;

			public Data(string signature, T value)
			{
				Signature = signature;
				Value = value;
			}
		}

		private const string StringMessageRegistrationName = "LCAPI_NET_LEGACY_STRING";

		private const string ListStringMessageRegistrationName = "LCAPI_NET_LEGACY_LISTSTRING";

		private const string IntMessageRegistrationName = "LCAPI_NET_LEGACY_INT";

		private const string FloatMessageRegistrationName = "LCAPI_NET_LEGACY_FLOAT";

		private const string Vector3MessageRegistrationName = "LCAPI_NET_LEGACY_VECTOR3";

		private const string SyncVarMessageRegistrationName = "LCAPI_NET_LEGACY_SYNCVAR_SET";

		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! ( / )");
			}
			else
			{
				Network.Broadcast("LCAPI_NET_LEGACY_STRING", new Data<string>(signature, data));
			}
		}

		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";
			}
			Network.Broadcast("LCAPI_NET_LEGACY_LISTSTRING", new Data<string>(signature, text));
		}

		public static void Broadcast(int data, string signature)
		{
			Network.Broadcast("LCAPI_NET_LEGACY_INT", new Data<int>(signature, data));
		}

		public static void Broadcast(float data, string signature)
		{
			Network.Broadcast("LCAPI_NET_LEGACY_FLOAT", new Data<float>(signature, data));
		}

		public static void Broadcast(Vector3 data, string signature)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			Network.Broadcast("LCAPI_NET_LEGACY_VECTOR3", new Data<Vector3>(signature, data));
		}

		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_LEGACY_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_LEGACY_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 "";
		}

		internal static void InitializeLegacyNetworking()
		{
			GetListString = (Action<List<string>, string>)Delegate.Combine(GetListString, new Action<List<string>, string>(LCAPI_NET_SYNCVAR_SET));
			Network.RegisterMessage("LCAPI_NET_LEGACY_STRING", relayToSelf: false, delegate(ulong senderId, Data<string> data)
			{
				GetString(data.Value, data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_LISTSTRING", relayToSelf: false, delegate(ulong senderId, Data<string> data)
			{
				GetListString(data.Value.Split('\n').ToList(), data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_INT", relayToSelf: false, delegate(ulong senderId, Data<int> data)
			{
				GetInt(data.Value, data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_FLOAT", relayToSelf: false, delegate(ulong senderId, Data<float> data)
			{
				GetFloat(data.Value, data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_VECTOR3", relayToSelf: false, delegate(ulong senderId, Data<Vector3> data)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				GetVector3(data.Value, data.Signature);
			});
		}
	}
}
namespace LC_API.Networking
{
	public static class Network
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static HandleNamedMessageDelegate <>9__35_2;

			public static Events.CustomEventHandler <>9__35_0;

			public static Events.CustomEventHandler <>9__35_1;

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

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

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

		internal const string MESSAGE_RELAY_UNIQUE_NAME = "LC_API_RELAY_MESSAGE";

		private static MethodInfo _registerInfo = null;

		private static MethodInfo _registerInfoGeneric = null;

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


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


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

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

		public static event Events.CustomEventHandler RegisterNetworkMessages;

		internal static event Events.CustomEventHandler UnregisterNetworkMessages;

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

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

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

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

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

		internal static void UnregisterAllMessages()
		{
			foreach (string key in NetworkMessageFinalizers.Keys)
			{
				UnregisterMessage(key, andRemoveHandler: false);
			}
		}

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

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

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

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

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

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

		public static void UnregisterMessage(string uniqueName, bool andRemoveHandler = true)
		{
			if ((!andRemoveHandler && NetworkMessageFinalizers.ContainsKey(uniqueName)) || (andRemoveHandler && NetworkMessageFinalizers.Remove(uniqueName)))
			{
				NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler(uniqueName);
			}
		}

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

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

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

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

		public bool RelayToSelf { get; }

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

		internal abstract bool RelayToSelf { get; }

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

		internal override bool RelayToSelf { get; }

		internal Action<ulong> OnReceived { get; }

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

		public void Send()
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater());
				return;
			}
			byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId).ToBytes();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
				if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)4);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)4);
				}
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

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

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

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

		internal override bool RelayToSelf { get; }

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

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

		public void Send(T obj)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater(obj));
				return;
			}
			byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId, obj.ToBytes()).ToBytes();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
				if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)4);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)4);
				}
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

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

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

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

		public ulong Sender { get; set; }

		public byte[] Message { get; set; }

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

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

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

		public float x { get; set; }

		public float y { get; set; }

		[JsonIgnore]
		public Vector2 vector2
		{
			get
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				if (!v2.HasValue)
				{
					v2 = new Vector2(x, y);
				}
				return v2.Value;
			}
		}

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

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

		public static implicit operator Vector2S(Vector2 vector2)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return new Vector2S(vector2.x, vector2.y);
		}
	}
	public struct Vector2IntS
	{
		private Vector2Int? v2;

		public int x { get; set; }

		public int y { get; set; }

		[JsonIgnore]
		public Vector2Int vector2
		{
			get
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				if (!v2.HasValue)
				{
					v2 = new Vector2Int(x, y);
				}
				return v2.Value;
			}
		}

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

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

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

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		[JsonIgnore]
		public Vector3 vector3
		{
			get
			{
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				if (!v3.HasValue)
				{
					v3 = new Vector3(x, y, z);
				}
				return v3.Value;
			}
		}

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

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

		public static implicit operator Vector3S(Vector3 vector3)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3S(vector3.x, vector3.y, vector3.z);
		}
	}
	public struct Vector3IntS
	{
		private Vector3Int? v3;

		public int x { get; set; }

		public int y { get; set; }

		public int z { get; set; }

		[JsonIgnore]
		public Vector3Int vector3
		{
			get
			{
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				if (!v3.HasValue)
				{
					v3 = new Vector3Int(x, y, z);
				}
				return v3.Value;
			}
		}

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

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

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

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public float w { get; set; }

		[JsonIgnore]
		public Vector4 Vector4
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!v4.HasValue)
				{
					v4 = new Vector4(x, y, z, w);
				}
				return v4.Value;
			}
		}

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

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

		public static implicit operator Vector4S(Vector4 vector4)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector4S(vector4.x, vector4.y, vector4.z, vector4.w);
		}
	}
	public struct QuaternionS
	{
		private Quaternion? q;

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public float w { get; set; }

		[JsonIgnore]
		public Quaternion Quaternion
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!q.HasValue)
				{
					q = new Quaternion(x, y, z, w);
				}
				return q.Value;
			}
		}

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

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

		public static implicit operator QuaternionS(Quaternion quaternion)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new QuaternionS(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
		}
	}
	public struct ColorS
	{
		private Color? c;

		public float r { get; set; }

		public float g { get; set; }

		public float b { get; set; }

		public float a { get; set; }

		[JsonIgnore]
		public Color Color
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!c.HasValue)
				{
					c = new Color(r, g, b, a);
				}
				return c.Value;
			}
		}

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

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

		public static implicit operator ColorS(Color color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new ColorS(color.r, color.g, color.b, color.a);
		}
	}
	public struct Color32S
	{
		private Color32? c;

		public byte r { get; set; }

		public byte g { get; set; }

		public byte b { get; set; }

		public byte a { get; set; }

		[JsonIgnore]
		public Color32 Color
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!c.HasValue)
				{
					c = new Color32(r, g, b, a);
				}
				return c.Value;
			}
		}

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

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

		public static implicit operator Color32S(Color32 color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Color32S(color.r, color.g, color.b, color.a);
		}
	}
	public struct RayS
	{
		private Ray? r;

		public Vector3S origin { get; set; }

		public Vector3S direction { get; set; }

		[JsonIgnore]
		public Ray Ray
		{
			get
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				if (!r.HasValue)
				{
					r = new Ray((Vector3)origin, (Vector3)direction);
				}
				return r.Value;
			}
		}

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

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

		public static implicit operator RayS(Ray ray)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			return new RayS(((Ray)(ref ray)).origin, ((Ray)(ref ray)).direction);
		}
	}
	public struct Ray2DS
	{
		private Ray2D? r;

		public Vector2S origin { get; set; }

		public Vector2S direction { get; set; }

		[JsonIgnore]
		public Ray2D Ray
		{
			get
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				if (!r.HasValue)
				{
					r = new Ray2D((Vector2)origin, (Vector2)direction);
				}
				return r.Value;
			}
		}

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

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

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

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

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

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

		public static int AlivePlayerCount { get; private set; }

		public static ShipState ShipState { get; private set; }

		public static event Action PlayerDied;

		public static event Action LandOnMoon;

		public static event Action WentIntoOrbit;

		public static event Action ShipStartedLeaving;

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

		static GameState()
		{
			GameState.PlayerDied = NothingAction;
			GameState.LandOnMoon = NothingAction;
			GameState.WentIntoOrbit = NothingAction;
			GameState.ShipStartedLeaving = NothingAction;
		}
	}
	[Obsolete("Use Player::QueueTip instead.")]
	public class GameTips
	{
		private static List<string> tipHeaders = new List<string>();

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

		private static float lastMessageTime;

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

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

		internal static GameObject ItemNetworkPrefab { get; set; }

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


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

		public GrabbableObject GrabbableObject { get; private set; }

		public Item ItemProperties => GrabbableObject.itemProperties;

		public ScanNodeProperties ScanNodeProperties { get; set; }

		public bool IsHeld => GrabbableObject.isHeld;

		public bool IsTwoHanded => ItemProperties.twoHanded;

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

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

		public Vector3 Position
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return ((Component)GrabbableObject).transform.position;
			}
			set
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set item position on client.");
				}
				GrabbableObject.startFallingPosition = value;
				GrabbableObject.targetFloorPosition = value;
				((Component)GrabbableObject).transform.position = value;
				SetItemPositionClientRpc(value);
			}
		}

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

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

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

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

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

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

		[ClientRpc]
		private void SetItemPositionClientRpc(Vector3 pos)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(949135576u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref pos);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 949135576u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					GrabbableObject.startFallingPosition = pos;
					GrabbableObject.targetFloorPosition = pos;
					((Component)GrabbableObject).transform.position = pos;
				}
			}
		}

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

		[ClientRpc]
		private void SetItemRotationClientRpc(Quaternion rotation)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1528367091u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref rotation);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1528367091u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Rotation = rotation;
				}
			}
		}

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

		[ClientRpc]
		private void SetItemScaleClientRpc(Vector3 scale)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2688253945u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref scale);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2688253945u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Scale = scale;
				}
			}
		}

		[ClientRpc]
		private void SetIsScrapClientRpc(bool isScrap)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(4227417717u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref isScrap, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4227417717u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					CloneProperties();
					ItemProperties.isScrap = isScrap;
				}
			}
		}

		[ClientRpc]
		private void SetScrapValueClientRpc(int scrapValue)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3866863385u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, scrapValue);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3866863385u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					GrabbableObject.SetScrapValue(scrapValue);
				}
			}
		}

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

		[ClientRpc]
		private void RemoveFromHolderClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1050513218u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1050513218u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && IsHeld)
				{
					Holder.Inventory.RemoveItem(this);
				}
			}
		}

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

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

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

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

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

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

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

		[ClientRpc]
		private void InitializeScrapClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1334565671u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1334565671u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			MeshFilter val3 = default(MeshFilter);
			if (((Component)GrabbableObject).gameObject.TryGetComponent<MeshFilter>(ref val3) && ItemProperties.meshVariants != null && ItemProperties.meshVariants.Length != 0)
			{
				if (RoundManager.Instance.ScrapValuesRandom != null)
				{
					val3.mesh = ItemProperties.meshVariants[RoundManager.Instance.ScrapValuesRandom.Next(ItemProperties.meshVariants.Length)];
				}
				else
				{
					val3.mesh = ItemProperties.meshVariants[0];
				}
			}
			MeshRenderer val4 = default(MeshRenderer);
			if (((Component)GrabbableObject).gameObject.TryGetComponent<MeshRenderer>(ref val4) && ItemProperties.materialVariants != null && ItemProperties.materialVariants.Length != 0)
			{
				if (RoundManager.Instance.ScrapValuesRandom != null)
				{
					((Renderer)val4).sharedMaterial = ItemProperties.materialVariants[RoundManager.Instance.ScrapValuesRandom.Next(ItemProperties.materialVariants.Length)];
				}
				else
				{
					((Renderer)val4).sharedMaterial = ItemProperties.materialVariants[0];
				}
			}
		}

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

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

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

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

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

		public static Item GetOrAdd(GrabbableObject grabbableObject)
		{
			if (Dictionary.TryGetValue(grabbableObject, out var value))
			{
				return value;
			}
			return ((Component)grabbableObject).gameObject.AddComponent<Item>();
		}

		public static Item Get(GrabbableObject grabbableObject)
		{
			if (Dictionary.TryGetValue(grabbableObject, out var value))
			{
				return value;
			}
			return null;
		}

		public static bool TryGet(GrabbableObject grabbableObject, out Item item)
		{
			return Dictionary.TryGetValue(grabbableObject, out item);
		}

		public static Item Get(ulong netId)
		{
			return List.FirstOrDefault((Item i) => ((NetworkBehaviour)i).NetworkObjectId == netId);
		}

		public static bool TryGet(ulong netId, out Item item)
		{
			item = Get(netId);
			return (Object)(object)item != (Object)null;
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_Item()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(66243798u, new RpcReceiveHandler(__rpc_handler_66243798));
			NetworkManager.__rpc_func_table.Add(949135576u, new RpcReceiveHandler(__rpc_handler_949135576));
			NetworkManager.__rpc_func_table.Add(1528367091u, new RpcReceiveHandler(__rpc_handler_1528367091));
			NetworkManager.__rpc_func_table.Add(2688253945u, new RpcReceiveHandler(__rpc_handler_2688253945));
			NetworkManager.__rpc_func_table.Add(4227417717u, new RpcReceiveHandler(__rpc_handler_4227417717));
			NetworkManager.__rpc_func_table.Add(3866863385u, new RpcReceiveHandler(__rpc_handler_3866863385));
			NetworkManager.__rpc_func_table.Add(1050513218u, new RpcReceiveHandler(__rpc_handler_1050513218));
			NetworkManager.__rpc_func_table.Add(1334565671u, new RpcReceiveHandler(__rpc_handler_1334565671));
		}

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

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

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

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

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

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

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

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

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

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

			public int CurrentSlot
			{
				get
				{
					return Player.PlayerController.currentItemSlot;
				}
				set
				{
					//IL_0011: Unknown result type (might be due to invalid IL or missing references)
					//IL_0017: Unknown result type (might be due to invalid IL or missing references)
					if (Player.IsLocalPlayer)
					{
						SetSlotServerRpc(value);
					}
					else if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
					{
						SetSlotClientRpc(value);
					}
				}
			}

			[ServerRpc(RequireOwnership = false)]
			private void SetSlotServerRpc(int slot, ServerRpcParams serverRpcParams = default(ServerRpcParams))
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
					{
						FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1475903090u, serverRpcParams, (RpcDelivery)0);
						BytePacker.WriteValueBitPacked(val, slot);
						((NetworkBehaviour)this).__endSendServerRpc(ref val, 1475903090u, serverRpcParams, (RpcDelivery)0);
					}
					if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && serverRpcParams.Receive.SenderClientId == Player.ClientId)
					{
						SetSlotClientRpc(slot);
					}
				}
			}

			[ClientRpc]
			private void SetSlotClientRpc(int slot)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
					{
						ClientRpcParams val = default(ClientRpcParams);
						FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2977994897u, val, (RpcDelivery)0);
						BytePacker.WriteValueBitPacked(val2, slot);
						((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2977994897u, val, (RpcDelivery)0);
					}
					if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
					{
						Player.PlayerController.SwitchToItemSlot(slot, (GrabbableObject)null);
					}
				}
			}

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

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

			public bool TryAddItem(Item item, bool switchTo = true)
			{
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to add item from client.");
				}
				if (TryGetFirstEmptySlot(out var slot))
				{
					if (item.IsTwoHanded && !Player.HasFreeHands)
					{
						return false;
					}
					if (item.IsHeld)
					{
						item.RemoveFromHolder();
					}
					((NetworkBehaviour)item).NetworkObject.ChangeOwnership(Player.ClientId);
					if (item.IsTwoHanded)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (switchTo && Player.HasFreeHands)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (Player.PlayerController.currentItemSlot == slot)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else
					{
						SetItemInSlotClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					return true;
				}
				return false;
			}

			public bool TryAddItemToSlot(Item item, int slot, bool switchTo = true)
			{
				//IL_007a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to add item from client.");
				}
				if (slot < Player.PlayerController.ItemSlots.Length && (Object)(object)Player.PlayerController.ItemSlots[slot] == (Object)null)
				{
					if (item.IsTwoHanded && !Player.HasFreeHands)
					{
						return false;
					}
		

plugins/LCOffice.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.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using LCOffice.Patches;
using LethalLevelLoader;
using LethalLib.Modules;
using LethalNetworkAPI;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Animations.Rigging;
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: AssemblyTitle("LcOffice")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LcOffice")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("8ee335db-0cbe-470c-8fbc-69263f01b35a")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[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 LCOffice
{
	[BepInPlugin("Piggy.LCOffice", "LCOffice", "1.0.3")]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "Piggy.LCOffice";

		private const string modName = "LCOffice";

		private const string modVersion = "1.0.3";

		private readonly Harmony harmony = new Harmony("Piggy.LCOffice");

		private static Plugin Instance;

		public static ManualLogSource mls;

		public static AssetBundle Bundle;

		public static AudioClip ElevatorOpen;

		public static AudioClip ElevatorClose;

		public static AudioClip ElevatorUp;

		public static AudioClip ElevatorDown;

		public static AudioClip stanleyVoiceline1;

		public static AudioClip bossaLullaby;

		public static AudioClip shopTheme;

		public static AudioClip saferoomTheme;

		public static AudioClip cootieTheme;

		public static AudioClip garageDoorSlam;

		public static AudioClip garageSlide;

		public static AudioClip floorOpen;

		public static AudioClip floorClose;

		public static AudioClip footstep1;

		public static AudioClip footstep2;

		public static AudioClip footstep3;

		public static AudioClip footstep4;

		public static AudioClip dogEatItem;

		public static AudioClip bigGrowl;

		public static AudioClip enragedScream;

		public static AudioClip dogSprint;

		public static AudioClip ripPlayerApart;

		public static AudioClip cry1;

		public static AudioClip dogHowl;

		public static AudioClip stomachGrowl;

		public static AudioClip eatenExplode;

		public static AudioClip dogSneeze;

		public static GameObject shrimpPrefab;

		public static GameObject storagePrefab;

		public static GameObject socketPrefab;

		public static GameObject socketInteractPrefab;

		public static EnemyType shrimpEnemy;

		public static ExtendedDungeonFlow officeExtendedDungeonFlow;

		public static DungeonFlow officeDungeonFlow;

		public static TerminalNode shrimpTerminalNode;

		public static TerminalKeyword shrimpTerminalKeyword;

		public static string PluginDirectory;

		private ConfigEntry<bool> configGuaranteedOffice;

		private ConfigEntry<int> configOfficeRarity;

		private ConfigEntry<string> configMoons;

		private ConfigEntry<string> shrimpSpawnWeight;

		private ConfigEntry<int> shrimpModdedSpawnWeight;

		public static bool setKorean;

		private void Awake()
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Expected O, but got Unknown
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Expected O, but got Unknown
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Expected O, but got Unknown
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Expected O, but got Unknown
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Expected O, but got Unknown
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Expected O, but got Unknown
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			//IL_034d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Expected O, but got Unknown
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c2: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			configOfficeRarity = ((BaseUnityPlugin)this).Config.Bind<int>("General", "OfficeRarity", 50, new ConfigDescription("How rare it is for the office to be chosen. Higher values increases the chance of spawning the office.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 300), Array.Empty<object>()));
			configGuaranteedOffice = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "OfficeGuaranteed", false, new ConfigDescription("If enabled, the office will be effectively guaranteed to spawn. Only recommended for debugging/sightseeing purposes.", (AcceptableValueBase)null, Array.Empty<object>()));
			configMoons = ((BaseUnityPlugin)this).Config.Bind<string>("General", "OfficeMoonsList", "free", new ConfigDescription("The moon(s) that the office can spawn on, in the form of a comma separated list of selectable level names (e.g. \"TitanLevel,RendLevel,DineLevel\")\nNOTE: These must be the internal data names of the levels (all vanilla moons are \"MoonnameLevel\", for modded moon support you will have to find their name if it doesn't follow the convention).\nThe following strings: \"all\", \"vanilla\", \"modded\", \"paid\", \"free\", \"none\" are dynamic presets which add the dungeon to that specified group (string must only contain one of these, or a manual moon name list).\nDefault dungeon generation size is balanced around the dungeon scale multiplier of Titan (2.35), moons with significantly different dungeon size multipliers (see Lethal Company wiki for values) may result in dungeons that are extremely small/large.", (AcceptableValueBase)null, Array.Empty<object>()));
			shrimpSpawnWeight = ((BaseUnityPlugin)this).Config.Bind<string>("Spawn", "ShrimpSpawnWeight", "2,4,5,3,6,8,8,10", new ConfigDescription("Set the shrimp spawn weight for each moon. In this order:\n(experimentation, assurance, vow, march, offense, rend, dine, titan).", (AcceptableValueBase)null, Array.Empty<object>()));
			shrimpModdedSpawnWeight = ((BaseUnityPlugin)this).Config.Bind<int>("Spawn", "ShrimpModdedMoonSpawnWeight", 5, new ConfigDescription("Set the shrimp spawn weight for modded moon. ", (AcceptableValueBase)null, Array.Empty<object>()));
			setKorean = ((BaseUnityPlugin)this).Config.Bind<bool>("Translation", "Enable Korean", false, "Set language to Korean.").Value;
			PluginDirectory = ((BaseUnityPlugin)this).Info.Location;
			mls = Logger.CreateLogSource("Piggy.LCOffice");
			mls.LogInfo((object)"LC_Office is loaded!");
			Bundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "lcoffice"));
			officeDungeonFlow = Bundle.LoadAsset<DungeonFlow>("OfficeDungeonFlow.asset");
			officeExtendedDungeonFlow = ScriptableObject.CreateInstance<ExtendedDungeonFlow>();
			officeExtendedDungeonFlow.contentSourceName = "LC_Office";
			officeExtendedDungeonFlow.dungeonFlow = officeDungeonFlow;
			officeExtendedDungeonFlow.dungeonDefaultRarity = 0;
			int num = (configGuaranteedOffice.Value ? 99999 : configOfficeRarity.Value);
			if (configMoons.Value.ToLower() == "all")
			{
				officeExtendedDungeonFlow.manualContentSourceNameReferenceList.Add(new StringWithRarity("Lethal Company", num));
				officeExtendedDungeonFlow.manualContentSourceNameReferenceList.Add(new StringWithRarity("Custom", num));
			}
			else if (configMoons.Value.ToLower() == "vanilla")
			{
				officeExtendedDungeonFlow.manualContentSourceNameReferenceList.Add(new StringWithRarity("Lethal Company", num));
			}
			else if (configMoons.Value.ToLower() == "modded")
			{
				officeExtendedDungeonFlow.dynamicLevelTagsList.Add(new StringWithRarity("Custom", num));
			}
			else if (configMoons.Value.ToLower() == "paid")
			{
				officeExtendedDungeonFlow.dynamicRoutePricesList.Add(new Vector2WithRarity(new Vector2(1f, 9999f), num));
			}
			else if (configMoons.Value.ToLower() == "free")
			{
				officeExtendedDungeonFlow.dynamicRoutePricesList.Add(new Vector2WithRarity(new Vector2(0f, 0f), num));
			}
			else if (!(configMoons.Value.ToLower() == "none"))
			{
				string[] array = configMoons.Value.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
				StringWithRarity[] array2 = (StringWithRarity[])(object)new StringWithRarity[array.Length];
				for (int i = 0; i < array.Length; i++)
				{
					array2[i] = new StringWithRarity(array[i], num);
				}
				officeExtendedDungeonFlow.manualPlanetNameReferenceList = array2.ToList();
			}
			officeExtendedDungeonFlow.dungeonSizeMax = 0.1f;
			officeExtendedDungeonFlow.dungeonSizeLerpPercentage = 0f;
			AssetBundleLoader.RegisterExtendedDungeonFlow(officeExtendedDungeonFlow);
			shrimpPrefab = Bundle.LoadAsset<GameObject>("Shrimp.prefab");
			shrimpPrefab.AddComponent<ShrimpAI>();
			shrimpEnemy = Bundle.LoadAsset<EnemyType>("ShrimpEnemy.asset");
			storagePrefab = Bundle.LoadAsset<GameObject>("DepositPlace.prefab");
			socketPrefab = Bundle.LoadAsset<GameObject>("ElevatorSocket.prefab");
			socketInteractPrefab = Bundle.LoadAsset<GameObject>("LungPlacement.prefab");
			GameObject val = Bundle.LoadAsset<GameObject>("OfficeStartRoom.prefab");
			val.AddComponent<ElevatorSystem>();
			bossaLullaby = Bundle.LoadAsset<AudioClip>("bossa_lullaby_refiltered.ogg");
			shopTheme = Bundle.LoadAsset<AudioClip>("shop_refiltered.ogg");
			saferoomTheme = Bundle.LoadAsset<AudioClip>("saferoom_refiltered.ogg");
			ElevatorOpen = Bundle.LoadAsset<AudioClip>("ElevatorOpen.ogg");
			ElevatorClose = Bundle.LoadAsset<AudioClip>("ElevatorClose.ogg");
			ElevatorDown = Bundle.LoadAsset<AudioClip>("ElevatorDown.ogg");
			ElevatorUp = Bundle.LoadAsset<AudioClip>("ElevatorUp.ogg");
			garageDoorSlam = Bundle.LoadAsset<AudioClip>("GarageDoorSlam.ogg");
			garageSlide = Bundle.LoadAsset<AudioClip>("GarageDoorSlide1.ogg");
			floorOpen = Bundle.LoadAsset<AudioClip>("FloorOpen.ogg");
			floorClose = Bundle.LoadAsset<AudioClip>("FloorClosed.ogg");
			footstep1 = Bundle.LoadAsset<AudioClip>("Footstep1.ogg");
			footstep2 = Bundle.LoadAsset<AudioClip>("Footstep2.ogg");
			footstep3 = Bundle.LoadAsset<AudioClip>("Footstep3.ogg");
			footstep4 = Bundle.LoadAsset<AudioClip>("Footstep4.ogg");
			dogEatItem = Bundle.LoadAsset<AudioClip>("DogEatObject.ogg");
			bigGrowl = Bundle.LoadAsset<AudioClip>("BigGrowl.ogg");
			enragedScream = Bundle.LoadAsset<AudioClip>("DogRage.ogg");
			dogSprint = Bundle.LoadAsset<AudioClip>("DogSprint.ogg");
			ripPlayerApart = Bundle.LoadAsset<AudioClip>("RipPlayerApart.ogg");
			cry1 = Bundle.LoadAsset<AudioClip>("Cry1.ogg");
			dogHowl = Bundle.LoadAsset<AudioClip>("DogHowl.ogg");
			stomachGrowl = Bundle.LoadAsset<AudioClip>("StomachGrowl.ogg");
			eatenExplode = Bundle.LoadAsset<AudioClip>("eatenExplode.ogg");
			dogSneeze = Bundle.LoadAsset<AudioClip>("Sneeze.ogg");
			stanleyVoiceline1 = Bundle.LoadAsset<AudioClip>("stanley.ogg");
			shrimpTerminalNode = Bundle.LoadAsset<TerminalNode>("ShrimpFile.asset");
			shrimpTerminalKeyword = Bundle.LoadAsset<TerminalKeyword>("shrimpTK.asset");
			if (!setKorean)
			{
				shrimpTerminalNode.displayText = "Shrimp\r\n\r\nSigurd’s Danger Level: 60%\r\n\r\n\nScientific name: Canispiritus-Artemus\r\n\r\nShrimps are dog-like creatures, known to be the first tenant of the Upturned Inn. For the most part, he is relatively friendly to humans, following them around, curiously stalking them. Unfortunately, their passive temperament comes with a dangerously vicious hunger.\r\nDue to the nature of their biology, he has a much more unique stomach organ than most other creatures. The stomach lining is flexible, yet hardy, allowing a Shrimp to digest and absorb the nutrients from anything, biological or not, so long as it isn’t too large.\r\n\r\nHowever, this evolutionary adaptation was most likely a result of their naturally rapid metabolism. He uses nutrients so quickly that he needs to eat multiple meals a day to survive. The time between these meals are inconsistent, as the rate of caloric consumption is variable. This can range from hours to even minutes and causes the shrimp to behave monstrously if he has not eaten for a while.\r\n\r\nKnown to live in abandoned buildings, shrimp can often be seen in large abandoned factories or offices scavenging for scrap metal, to eat. That isn’t to say he can’t be found elsewhere. He is usually a lone hunters and expert trackers out of necessity.\r\n\r\nSigurd’s Note:\r\nIf this guy spots you, you’ll want to drop something you’re holding and let him eat it. It’s either you or that piece of scrap on you.\r\n\r\nit’s best to avoid letting him spot you. I swear… it’s almost like his eyes are staring into your soul.\r\nI never want to see one of these guys behind me again.\r\n\r\n\r\nIK: <i>Sir, don't be sad! Shrimp didn't hate you.\r\nhe was just... hungry.</i>\r\n\r\n";
				shrimpTerminalNode.creatureName = "Shrimp";
				shrimpTerminalKeyword.word = "shrimp";
			}
			else
			{
				shrimpTerminalNode.displayText = "쉬림프\r\n\r\n시구르드의 위험 수준: 60%\r\n\r\n\n학명: 카니스피리투스-아르테무스\r\n\r\n쉬림프는 개를 닮은 생명체로 Upturned Inn의 첫 번째 세입자로 알려져 있습니다. 평소에는 상대적으로 우호적이며, 호기심을 가지고 인간을 따라다닙니다. 불행하게도 그는 위험할 정도로 굉장한 식욕을 가지고 있습니다.\r\n생물학적 특성으로 인해, 그는 대부분의 다른 생물보다 훨씬 더 독특한 위장 기관을 가지고 있습니다. 위 내막은 유연하면서도 견고하기 때문에 어떤 물체라도 영양분을 소화하고 흡수할 수 있습니다.\r\n그러나 이러한 진화적 적응은 자연적으로 빠른 신진대사의 결과일 가능성이 높습니다. 그는 영양분을 너무 빨리 사용하기 때문에 생존하려면 하루에 여러 끼를 먹어야 합니다.\r\n칼로리 소비율이 다양하기 때문에 식사 사이의 시간이 일정하지 않습니다. 이는 몇 시간에서 몇 분까지 지속될 수 있으며, 쉬림프가 오랫동안 무언가를 먹지 않으면 매우 포악해지며 따라다니던 사람을 쫒습니다.\r\n\r\n버려진 건물에 사는 것으로 알려진 쉬림프는 버려진 공장이나 사무실에서 폐철물을 찾아다니는 것으로 발견할 수 있습니다. 그렇다고 다른 곳에서 그를 찾을 수 없다는 말은 아닙니다. 그는 일반적으로 고독한 사냥꾼이며, 때로는 전문적인 추적자가 되기도 합니다.\r\n\r\n시구르드의 노트: 이 녀석이 으르렁거리는 소리를 듣게 된다면, 먹이를 줄 수 있는 무언가를 가지고 있기를 바라세요. 아니면 당신이 이 녀석의 식사가 될 거예요.\r\n맹세컨대... 마치 당신의 영혼을 들여다보는 것 같아요. 다시는 내 뒤에서 이 녀석을 보고 싶지 않아요.\r\n\r\n\r\nIK: <i>손님, 슬퍼하지 마세요! 쉬림프는 당신을 싫어하지 않는답니다.\r\n걔는 그냥... 배고플 뿐이에요.</i>\r\n\r\n";
				shrimpTerminalNode.creatureName = "쉬림프";
				shrimpTerminalKeyword.word = "쉬림프";
			}
			NetworkPrefabs.RegisterNetworkPrefab(shrimpPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(storagePrefab);
			NetworkPrefabs.RegisterNetworkPrefab(socketInteractPrefab);
			int[] array3 = shrimpSpawnWeight.Value.Split(new char[1] { ',' }).Select(int.Parse).ToArray();
			Enemies.RegisterEnemy(shrimpEnemy, array3[0], (LevelTypes)4, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in ExperimentationLevel: " + array3[0]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[1], (LevelTypes)8, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in AssuranceLevel: " + array3[1]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[2], (LevelTypes)16, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in VowLevel: " + array3[2]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[3], (LevelTypes)64, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in MarchLevel: " + array3[3]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[4], (LevelTypes)32, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in OffenseLevel: " + array3[4]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[5], (LevelTypes)128, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in RendLevel: " + array3[5]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[6], (LevelTypes)256, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in DineLevel: " + array3[6]));
			Enemies.RegisterEnemy(shrimpEnemy, array3[7], (LevelTypes)512, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in TitanLevel: " + array3[7]));
			Enemies.RegisterEnemy(shrimpEnemy, shrimpModdedSpawnWeight.Value, (LevelTypes)1024, (SpawnType)0, shrimpTerminalNode, shrimpTerminalKeyword);
			mls.LogInfo((object)("Shrimp spawn chance in Modded Moons: " + shrimpModdedSpawnWeight.Value));
			((BaseUnityPlugin)this).Logger.LogInfo((object)"[LC_Office] Successfully loaded assets!");
			harmony.PatchAll(typeof(Plugin));
			harmony.PatchAll(typeof(PlayerControllerBPatch));
			harmony.PatchAll(typeof(GrabbableObjectPatch));
			harmony.PatchAll(typeof(TerminalPatch));
			harmony.PatchAll(typeof(StartOfRoundPatch));
			harmony.PatchAll(typeof(GameNetworkManagerPatch));
			harmony.PatchAll(typeof(PlaceLung));
			socketInteractPrefab.AddComponent<PlaceLung>();
		}
	}
}
namespace LCOffice.Patches
{
	public class PlaceLung : NetworkBehaviour
	{
		public static LethalNetworkVariable<bool> lungPlacedThisFrame = new LethalNetworkVariable<bool>("lungPlacedThisFrame");

		public static LethalNetworkVariable<bool> placeLungNetwork = new LethalNetworkVariable<bool>("placeLung");

		public static LethalNetworkVariable<ulong> lungPlacer = new LethalNetworkVariable<ulong>("Installer");

		[PublicNetworkVariable]
		public static LethalNetworkVariable<GameObject> placedLung = new LethalNetworkVariable<GameObject>("placedLung");

		public LethalClientEvent onLungPlace = new LethalClientEvent("onLungPlace", (Action)null, (Action<ulong>)null);

		public LethalClientMessage<bool> onLungPlaced = new LethalClientMessage<bool>("onLungPlaced", (Action<bool>)null, (Action<bool, ulong>)null);

		public LethalClientMessage<bool> onLungRemoved = new LethalClientMessage<bool>("onLungRemoved", (Action<bool>)null, (Action<bool, ulong>)null);

		public bool isPlaceCalled;

		public bool isOtherClientPlaceChecked;

		public bool isOtherClientRemoveChecked;

		public static bool lungPlaced;

		public static bool lungPlacedLocalFrame;

		public static bool emergencyPowerRequires;

		public static bool emergencyCheck;

		public bool isSetupEnd;

		public static ElevatorSystem elevatorSystem;

		public static Animator socketLED;

		public static AudioSource socketAudioSource;

		public static InteractTrigger socketInteractTrigger;

		public static Transform lungPos;

		public static Transform lungSocket;

		public static Transform lungParent;

		public static Animator lungParentAnimator;

		public static AudioSource elevatorMusic;

		public static AudioSource elevatorSound;

		public static Animator elevatorAnimator;

		public static List<InteractTrigger> upButtons = new List<InteractTrigger>();

		public static List<InteractTrigger> downButtons = new List<InteractTrigger>();

		public LungProp lungComponent;

		public bool isForceMoving;

		public BoxCollider boxCollider;

		public List<Light> elevatorLights = new List<Light>();

		private void Start()
		{
			lungPlacedThisFrame.Value = false;
			placeLungNetwork.Value = false;
			lungPlacer.Value = 0uL;
			placedLung.Value = null;
		}

		private void LateUpdate()
		{
			//IL_002a: 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_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03af: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: 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_015d: Unknown result type (might be due to invalid IL or missing references)
			if (!RoundMapSystem.Instance.isOffice)
			{
				return;
			}
			Setup();
			((Component)this).transform.position = lungPos.position;
			((Component)this).transform.rotation = lungPos.rotation;
			if (emergencyCheck && !emergencyPowerRequires && !lungPlaced && !ElevatorSystem.isElevatorDowned.Value)
			{
				elevatorSystem.ElevatorDownTrigger(StartOfRound.Instance.localPlayerController);
			}
			if (emergencyCheck && !emergencyPowerRequires)
			{
				ElevatorSystem.isElevatorClosed.Value = false;
				elevatorMusic.pitch = Mathf.Lerp(elevatorMusic.pitch, 0f, Time.deltaTime * 2.5f);
				AnimatorStateInfo currentAnimatorStateInfo = elevatorSystem.doorAnimator.GetCurrentAnimatorStateInfo(0);
				if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime > 1f && elevatorSystem.doorAnimator.GetBool("closed"))
				{
					currentAnimatorStateInfo = elevatorSystem.animator.GetCurrentAnimatorStateInfo(0);
					if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime > 1f && elevatorSystem.animator.GetBool("goDown") && ((Component)elevatorAnimator).gameObject.transform.localPosition.y <= -9.6998f)
					{
						emergencyPowerRequires = true;
						emergencyCheck = false;
					}
				}
			}
			if (lungPlaced)
			{
				lungComponent = placedLung.Value.GetComponent<LungProp>();
				boxCollider.size = new Vector3(0f, 0f, 0f);
				placedLung.Value.transform.SetParent(lungParent);
				placedLung.Value.transform.localPosition = new Vector3(0f, 0f, 0f);
				placedLung.Value.transform.localRotation = Quaternion.Euler(0f, 90f, 0f);
				if (lungPlacedLocalFrame && emergencyPowerRequires)
				{
					foreach (InteractTrigger upButton in upButtons)
					{
						((UnityEvent<PlayerControllerB>)(object)upButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorUpTrigger);
					}
					foreach (InteractTrigger downButton in downButtons)
					{
						((UnityEvent<PlayerControllerB>)(object)downButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorDownTrigger);
					}
					lungPlacedLocalFrame = false;
				}
			}
			else
			{
				if (emergencyPowerRequires)
				{
					foreach (InteractTrigger upButton2 in upButtons)
					{
						((UnityEventBase)upButton2.onInteract).RemoveAllListeners();
					}
					foreach (InteractTrigger downButton2 in downButtons)
					{
						((UnityEventBase)downButton2.onInteract).RemoveAllListeners();
					}
				}
				lungPlacedLocalFrame = true;
				boxCollider.size = new Vector3(2f, 1.6f, 2f);
				lungComponent = null;
			}
			CheckPlayerHoldingLung();
			if (lungPlaced)
			{
				RemoveLung();
			}
			if (lungPlacedThisFrame.Value)
			{
				LungPlacement();
			}
			if (isOtherClientPlaceChecked)
			{
				OnLungPlacedThisFrameOtherClient();
			}
			if (isOtherClientRemoveChecked)
			{
				RemoveLungOtherClient();
			}
			if (emergencyPowerRequires)
			{
				if (lungPlaced)
				{
					elevatorAnimator.SetFloat("speed", Mathf.Lerp(elevatorAnimator.GetFloat("speed"), 1f, Time.deltaTime * 3f));
					elevatorSystem.doorAnimator.SetFloat("speed", elevatorAnimator.GetFloat("speed"));
					elevatorSound.pitch = Mathf.Lerp(elevatorMusic.pitch, 1f, Time.deltaTime * 3f);
					elevatorMusic.pitch = Mathf.Lerp(elevatorMusic.pitch, 1f, Time.deltaTime * 3.5f);
				}
				else
				{
					elevatorAnimator.SetFloat("speed", Mathf.Lerp(elevatorAnimator.GetFloat("speed"), 0f, Time.deltaTime * 3f));
					elevatorSystem.doorAnimator.SetFloat("speed", elevatorAnimator.GetFloat("speed"));
					elevatorSound.pitch = Mathf.Lerp(elevatorMusic.pitch, 0f, Time.deltaTime * 3f);
					elevatorMusic.pitch = Mathf.Lerp(elevatorMusic.pitch, 0f, Time.deltaTime * 2.5f);
				}
			}
			else
			{
				elevatorAnimator.SetFloat("speed", Mathf.Lerp(elevatorAnimator.GetFloat("speed"), 1f, Time.deltaTime * 3f));
				elevatorSystem.doorAnimator.SetFloat("speed", elevatorAnimator.GetFloat("speed"));
				elevatorSound.pitch = Mathf.Lerp(elevatorMusic.pitch, 1f, Time.deltaTime * 3f);
				elevatorMusic.pitch = Mathf.Lerp(elevatorMusic.pitch, 1f, Time.deltaTime * 3.5f);
			}
		}

		private void Setup()
		{
			if (isSetupEnd)
			{
				return;
			}
			elevatorSystem = Object.FindObjectOfType<ElevatorSystem>();
			socketAudioSource = ((Component)this).GetComponent<AudioSource>();
			socketInteractTrigger = ((Component)this).GetComponent<InteractTrigger>();
			((UnityEvent<PlayerControllerB>)(object)socketInteractTrigger.onInteract).AddListener((UnityAction<PlayerControllerB>)PlaceApparatus);
			socketLED = GameObject.Find("SocketLED").GetComponent<Animator>();
			boxCollider = ((Component)this).GetComponent<BoxCollider>();
			lungPos = GameObject.Find("LungPos").transform;
			lungSocket = GameObject.Find("LungSocket").transform;
			elevatorMusic = GameObject.Find("ElevatorMusic").GetComponent<AudioSource>();
			elevatorSound = GameObject.Find("ElevatorSound").GetComponent<AudioSource>();
			elevatorAnimator = Object.FindObjectOfType<ElevatorSystem>().animator;
			elevatorLights.Add(GameObject.Find("ElevatorLight1").GetComponent<Light>());
			elevatorLights.Add(GameObject.Find("ElevatorLight2").GetComponent<Light>());
			lungParent = GameObject.Find("LungParent").transform;
			lungParentAnimator = ((Component)lungParent).GetComponent<Animator>();
			foreach (Animator panelAnimator in elevatorSystem.panelAnimators)
			{
				upButtons.Add(((Component)((Component)panelAnimator).transform.GetChild(1).GetChild(0)).GetComponent<InteractTrigger>());
				downButtons.Add(((Component)((Component)panelAnimator).transform.GetChild(2).GetChild(0)).GetComponent<InteractTrigger>());
			}
			lungPlacedThisFrame.Value = false;
			placeLungNetwork.Value = false;
			lungPlacer.Value = 0uL;
			placedLung.Value = null;
			isSetupEnd = true;
		}

		private void CheckPlayerHoldingLung()
		{
			if (StartOfRound.Instance.localPlayerController.isHoldingObject)
			{
				if ((Object)(object)((Component)StartOfRound.Instance.localPlayerController.currentlyGrabbingObject).GetComponent<LungProp>() != (Object)null)
				{
					socketInteractTrigger.interactable = true;
				}
				else
				{
					socketInteractTrigger.interactable = false;
				}
			}
			else
			{
				socketInteractTrigger.interactable = false;
			}
		}

		private void LungPlacement()
		{
			//IL_0197: 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_021f: Unknown result type (might be due to invalid IL or missing references)
			onLungPlaced.OnReceivedFromClient += OnLungPlacedThisFrame;
			Plugin.mls.LogInfo((object)"lungPlacedThisFrame.Value is true");
			if (isPlaceCalled)
			{
				return;
			}
			PlayerControllerB playerController = LethalNetworkExtensions.GetPlayerController(lungPlacer.Value);
			socketLED.SetBool("warning", false);
			Plugin.mls.LogInfo((object)"lungPlacedThisFrame is enabled");
			placedLung.Value = ((Component)playerController.currentlyGrabbingObject).gameObject;
			socketAudioSource.PlayOneShot(((Component)playerController.currentlyGrabbingObject).GetComponent<LungProp>().connectSFX);
			if (emergencyPowerRequires)
			{
				foreach (Light elevatorLight in elevatorLights)
				{
					((Behaviour)elevatorLight).enabled = true;
				}
				foreach (InteractTrigger upButton in upButtons)
				{
					((UnityEvent<PlayerControllerB>)(object)upButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorUpTrigger);
				}
				foreach (InteractTrigger downButton in downButtons)
				{
					((UnityEvent<PlayerControllerB>)(object)downButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorDownTrigger);
				}
			}
			playerController.DiscardHeldObject(true, ((NetworkBehaviour)this).NetworkObject, ((Component)this).transform.position, true);
			lungPlaced = true;
			lungComponent = placedLung.Value.GetComponent<LungProp>();
			placedLung.Value.transform.SetParent(lungParent);
			placedLung.Value.transform.localPosition = new Vector3(0f, 0f, 0f);
			placedLung.Value.transform.localRotation = Quaternion.Euler(0f, 90f, 0f);
			isPlaceCalled = true;
			lungParentAnimator.SetTrigger("LungPlaced");
			if (!LethalNetworkExtensions.GetPlayerController(lungPlacer.Value).isCameraDisabled)
			{
				onLungPlaced.SendAllClients(true, false, false);
			}
			lungPlacedThisFrame.Value = false;
		}

		private void OnLungPlacedThisFrame(bool value, ulong id)
		{
			if (isOtherClientPlaceChecked != value)
			{
				isOtherClientPlaceChecked = value;
			}
		}

		private void OnLungPlacedThisFrameOtherClient()
		{
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			if (isPlaceCalled)
			{
				return;
			}
			PlayerControllerB playerController = LethalNetworkExtensions.GetPlayerController(lungPlacer.Value);
			socketLED.SetBool("warning", false);
			Plugin.mls.LogInfo((object)"lungPlacedThisFrame is enabled");
			socketAudioSource.PlayOneShot(placedLung.Value.GetComponent<LungProp>().connectSFX);
			if (emergencyPowerRequires)
			{
				foreach (Light elevatorLight in elevatorLights)
				{
					((Behaviour)elevatorLight).enabled = true;
				}
				foreach (InteractTrigger upButton in upButtons)
				{
					((UnityEvent<PlayerControllerB>)(object)upButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorUpTrigger);
				}
				foreach (InteractTrigger downButton in downButtons)
				{
					((UnityEvent<PlayerControllerB>)(object)downButton.onInteract).AddListener((UnityAction<PlayerControllerB>)elevatorSystem.ElevatorDownTrigger);
				}
			}
			lungPlaced = true;
			lungComponent = placedLung.Value.GetComponent<LungProp>();
			placedLung.Value.transform.SetParent(lungParent);
			placedLung.Value.transform.localPosition = new Vector3(0f, 0f, 0f);
			placedLung.Value.transform.localRotation = Quaternion.Euler(0f, 90f, 0f);
			boxCollider.size = new Vector3(0f, 0f, 0f);
			lungPlacedThisFrame.Value = false;
			isPlaceCalled = true;
			lungParentAnimator.SetTrigger("LungPlaced");
			isOtherClientPlaceChecked = false;
		}

		private void PlaceApparatus(PlayerControllerB playerControllerB)
		{
			Plugin.mls.LogInfo((object)("PlaceApparatus triggered by " + ((Object)((Component)playerControllerB).gameObject).name));
			if ((Object)(object)((Component)playerControllerB.currentlyGrabbingObject).GetComponent<LungProp>() != (Object)null && playerControllerB.isHoldingObject)
			{
				Plugin.mls.LogInfo((object)(((Object)((Component)playerControllerB).gameObject).name + " is placed LungProp"));
				lungPlacedThisFrame.Value = true;
				lungPlacer.Value = playerControllerB.actualClientId;
			}
		}

		private void RemoveLung()
		{
			onLungRemoved.OnReceivedFromClient += OnLungRemovedThisFrame;
			if (!((GrabbableObject)lungComponent).isHeld)
			{
				return;
			}
			foreach (Light elevatorLight in elevatorLights)
			{
				((Behaviour)elevatorLight).enabled = false;
			}
			socketLED.SetBool("warning", true);
			if (emergencyPowerRequires)
			{
				foreach (InteractTrigger upButton in upButtons)
				{
					((UnityEventBase)upButton.onInteract).RemoveAllListeners();
				}
				foreach (InteractTrigger downButton in downButtons)
				{
					((UnityEventBase)downButton.onInteract).RemoveAllListeners();
				}
			}
			socketAudioSource.PlayOneShot(placedLung.Value.GetComponent<LungProp>().disconnectSFX);
			lungPlaced = false;
			isPlaceCalled = false;
			onLungRemoved.SendAllClients(true, false, false);
		}

		private void OnLungRemovedThisFrame(bool value, ulong id)
		{
			if (isOtherClientRemoveChecked != value)
			{
				isOtherClientRemoveChecked = value;
			}
		}

		private void RemoveLungOtherClient()
		{
			if (!lungPlaced || !((GrabbableObject)lungComponent).isHeld)
			{
				return;
			}
			foreach (Light elevatorLight in elevatorLights)
			{
				((Behaviour)elevatorLight).enabled = false;
			}
			socketLED.SetBool("warning", true);
			if (emergencyPowerRequires)
			{
				foreach (InteractTrigger upButton in upButtons)
				{
					((UnityEventBase)upButton.onInteract).RemoveAllListeners();
				}
				foreach (InteractTrigger downButton in downButtons)
				{
					((UnityEventBase)downButton.onInteract).RemoveAllListeners();
				}
			}
			socketAudioSource.PlayOneShot(placedLung.Value.GetComponent<LungProp>().disconnectSFX);
			lungPlaced = false;
			isPlaceCalled = false;
		}

		private IEnumerator LightFlickerOn()
		{
			using List<Light>.Enumerator enumerator = elevatorLights.GetEnumerator();
			if (enumerator.MoveNext())
			{
				Light elevatorLight = enumerator.Current;
				((Behaviour)elevatorLight).enabled = true;
				yield return (object)new WaitForSeconds(0.05f);
				((Behaviour)elevatorLight).enabled = false;
				yield return (object)new WaitForSeconds(0.05f);
				((Behaviour)elevatorLight).enabled = true;
				yield return (object)new WaitForSeconds(0.05f);
				((Behaviour)elevatorLight).enabled = false;
				yield return (object)new WaitForSeconds(0.05f);
				((Behaviour)elevatorLight).enabled = true;
				yield return (object)new WaitForSeconds(2f);
				yield break;
			}
		}

		[HarmonyPatch(typeof(LungProp))]
		[HarmonyPrefix]
		[HarmonyPatch("EquipItem")]
		private static void EquipItem_Patch(ref bool ___isLungDocked)
		{
			if (!___isLungDocked || !RoundMapSystem.Instance.isOffice)
			{
				return;
			}
			Animator component = GameObject.Find("SocketLED").GetComponent<Animator>();
			component.SetBool("on", true);
			ElevatorSystem elevatorSystem = Object.FindObjectOfType<ElevatorSystem>();
			PlaceLung placeLung = Object.FindObjectOfType<PlaceLung>();
			foreach (Animator panelAnimator in elevatorSystem.panelAnimators)
			{
				((UnityEventBase)((Component)((Component)panelAnimator).transform.GetChild(1).GetChild(0)).GetComponent<InteractTrigger>().onInteract).RemoveAllListeners();
				((UnityEventBase)((Component)((Component)panelAnimator).transform.GetChild(2).GetChild(0)).GetComponent<InteractTrigger>().onInteract).RemoveAllListeners();
				if (!lungPlaced)
				{
					((Behaviour)GameObject.Find("ElevatorLight1").GetComponent<Light>()).enabled = false;
					((Behaviour)GameObject.Find("ElevatorLight2").GetComponent<Light>()).enabled = false;
				}
				component.SetBool("warning", true);
				emergencyCheck = true;
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Disconnect")]
		private static void Disconnect_Prefix()
		{
		}
	}
	public class RoundMapSystem : NetworkBehaviour
	{
		public bool isOffice;

		public bool isChecked;

		public bool isDungeonOfficeChecked;

		public static RoundMapSystem Instance { get; private set; }

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

		private void LateUpdate()
		{
			if (!isChecked && !StartOfRound.Instance.inShipPhase && (!((Object)(object)GameObject.Find("IndustrialFan") == (Object)null) || !((Object)(object)GameObject.Find("ManorStartRoom") == (Object)null)))
			{
				if ((Object)(object)GameObject.Find("IndustrialFan") != (Object)null && (Object)(object)GameObject.Find("ElevatorScreenDoor") != (Object)null)
				{
					isOffice = true;
					Plugin.mls.LogInfo((object)"isOffice true");
				}
				else
				{
					isOffice = false;
					Plugin.mls.LogInfo((object)"isOffice false");
				}
				if (!isDungeonOfficeChecked)
				{
					((MonoBehaviour)this).StartCoroutine(CheckOfficeElevator());
				}
				isDungeonOfficeChecked = true;
			}
		}

		private IEnumerator CheckOfficeElevator()
		{
			yield return (object)new WaitForSeconds(2f);
			isChecked = true;
		}
	}
	public class ShrimpCollider : MonoBehaviour, IHittable
	{
		public ShrimpAI shrimpAI;

		private void Start()
		{
			shrimpAI = ((Component)((Component)this).transform.parent).GetComponent<ShrimpAI>();
		}

		bool IHittable.Hit(int force, Vector3 hitDirection, PlayerControllerB playerWhoHit, bool playHitSFX = false)
		{
			if (ShrimpAI.hungerValue.Value < 55f && shrimpAI.scaredBackingAway <= 0f)
			{
				ShrimpAI.isHitted.Value = true;
			}
			return true;
		}
	}
	public class ShrimpAI : EnemyAI
	{
		public float networkPosDistance;

		public Vector3 prevPosition;

		public float stuckDetectionTimer;

		public float prevPositionDistance;

		public AISearchRoutine roamMap = new AISearchRoutine();

		private Vector3 spawnPosition;

		public PlayerControllerB hittedPlayer;

		public static LethalNetworkVariable<bool> KillingPlayerBool = new LethalNetworkVariable<bool>("KillingPlayerBool");

		public static LethalNetworkVariable<int> SelectNode = new LethalNetworkVariable<int>("SelectNode");

		public static LethalNetworkVariable<float> shrimpVelocity = new LethalNetworkVariable<float>("shrimpVelocity");

		public static LethalNetworkVariable<float> hungerValue = new LethalNetworkVariable<float>("hungerValue");

		public static LethalNetworkVariable<bool> isHitted = new LethalNetworkVariable<bool>("isHitted");

		public static LethalNetworkVariable<Vector3> networkPosition = new LethalNetworkVariable<Vector3>("networkPosition");

		public static LethalNetworkVariable<Vector3> networkRotation = new LethalNetworkVariable<Vector3>("networkRotation");

		public static LethalNetworkVariable<PlayerControllerB> networkTargetPlayer = new LethalNetworkVariable<PlayerControllerB>("networkTargetPlayer");

		public bool isKillingPlayer;

		public bool isSeenPlayer;

		public bool isEnraging;

		public bool isAngered;

		public bool canBeMoved;

		public bool isRunning;

		public bool dogRandomWalk;

		public float footStepTime;

		public float randomVal;

		public bool isTargetAvailable;

		public float networkTargetPlayerDistance;

		public float nearestItemDistance;

		public bool isNearestItem;

		public List<GameObject> droppedItems = new List<GameObject>();

		public GameObject nearestDroppedItem;

		public Transform dogHead;

		public Ray lookRay;

		public Transform lookTarget;

		public BoxCollider[] allBoxCollider;

		public Transform IdleTarget;

		public bool isIdleTargetAvailable;

		public bool forceChangeTarget;

		public Rig lookRig;

		public Light lungLight;

		public bool ateLung;

		public bool isSatisfied;

		public float satisfyValue;

		public Transform leftEye;

		public Transform rightEye;

		public Transform shrimpEye;

		public Transform mouth;

		public GameObject shrimpKillTrigger;

		public Transform bittenObjectHolder;

		public float searchingForObjectTimer;

		private Vector3 scaleOfEyesNormally;

		public AudioSource mainAudio;

		public AudioSource voiceAudio;

		public AudioSource voice2Audio;

		public AudioSource dogMusic;

		public AudioSource sprintAudio;

		public Vector3 originalMouthScale;

		public float scaredBackingAway;

		public Ray backAwayRay;

		private RaycastHit hitInfo;

		private RaycastHit hitInfoB;

		public float followTimer;

		public EnemyBehaviourState roamingState;

		public EnemyBehaviourState followingPlayer;

		public EnemyBehaviourState enragedState;

		public List<EnemyBehaviourState> tempEnemyBehaviourStates;

		public List<SkinnedMeshRenderer> skinnedMeshRendererList;

		public List<MeshRenderer> meshRendererList;

		private void Awake()
		{
			base.agent = ((Component)this).GetComponent<NavMeshAgent>();
		}

		public override void Start()
		{
			//IL_00ad: 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_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Expected O, but got Unknown
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_029c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			//IL_0351: Expected O, but got Unknown
			KillingPlayerBool.Value = false;
			SelectNode.Value = 0;
			shrimpVelocity.Value = 0f;
			hungerValue.Value = 0f;
			isHitted.Value = false;
			networkTargetPlayer.Value = null;
			((Component)((Component)this).transform.GetChild(0)).GetComponent<EnemyAICollisionDetect>().mainScript = (EnemyAI)(object)this;
			base.enemyType = Plugin.shrimpEnemy;
			base.skinnedMeshRenderers = ((Component)this).gameObject.GetComponentsInChildren<SkinnedMeshRenderer>();
			base.meshRenderers = ((Component)this).gameObject.GetComponentsInChildren<MeshRenderer>();
			base.thisNetworkObject = ((Component)this).gameObject.GetComponentInChildren<NetworkObject>();
			base.serverPosition = ((Component)this).transform.position;
			base.thisEnemyIndex = RoundManager.Instance.numberOfEnemiesInScene;
			RoundManager instance = RoundManager.Instance;
			instance.numberOfEnemiesInScene++;
			base.allAINodes = GameObject.FindGameObjectsWithTag("AINode");
			base.path1 = new NavMeshPath();
			mouth = GameObject.Find("ShrimpMouth").transform;
			leftEye = GameObject.Find("ShrimpLeftEye").transform;
			rightEye = GameObject.Find("ShrimpRightEye").transform;
			shrimpKillTrigger = GameObject.Find("ShrimpKillTrigger");
			base.creatureAnimator = ((Component)((Component)this).transform.GetChild(0).GetChild(1)).gameObject.GetComponent<Animator>();
			base.creatureAnimator.SetTrigger("Walk");
			mainAudio = GameObject.Find("ShrimpMainAudio").GetComponent<AudioSource>();
			voiceAudio = GameObject.Find("ShrimpGrowlAudio").GetComponent<AudioSource>();
			voice2Audio = GameObject.Find("ShrimpAngerAudio").GetComponent<AudioSource>();
			lookRig = GameObject.Find("ShrimpLookAtPlayer").GetComponent<Rig>();
			lungLight = GameObject.Find("LungFlash").GetComponent<Light>();
			lungLight.intensity = 0f;
			AudioSource[] componentsInChildren = ((Component)((Component)this).transform).GetComponentsInChildren<AudioSource>();
			AudioSource[] array = componentsInChildren;
			foreach (AudioSource val in array)
			{
				val.outputAudioMixerGroup = GameObject.Find("StatusEffectAudio").GetComponent<AudioSource>().outputAudioMixerGroup;
			}
			lookTarget = GameObject.Find("Shrimp_Look_target").transform;
			dogHead = GameObject.Find("ShrimpLookPoint").transform;
			bittenObjectHolder = GameObject.Find("BittenObjectHolder").transform;
			shrimpEye = GameObject.Find("ShrimpEye").transform;
			scaleOfEyesNormally = leftEye.localScale;
			originalMouthScale = mouth.localScale;
			voice2Audio.clip = Plugin.dogSprint;
			voice2Audio.Play();
			base.creatureVoice = voice2Audio;
			base.creatureSFX = voice2Audio;
			base.eye = shrimpEye;
			SetupBehaviour();
			tempEnemyBehaviourStates.Add(roamingState);
			tempEnemyBehaviourStates.Add(followingPlayer);
			tempEnemyBehaviourStates.Add(enragedState);
			base.enemyBehaviourStates = tempEnemyBehaviourStates.ToArray();
			spawnPosition = ((Component)this).transform.position;
			roamMap = new AISearchRoutine();
			ItemElevatorCheck[] array2 = Object.FindObjectsOfType<ItemElevatorCheck>();
			ItemElevatorCheck[] array3 = array2;
			foreach (ItemElevatorCheck itemElevatorCheck in array3)
			{
				itemElevatorCheck.shrimpAI = this;
			}
			if (Plugin.setKorean)
			{
				((Component)((Component)this).transform.GetChild(1)).GetComponent<ScanNodeProperties>().headerText = "쉬림프";
			}
		}

		public IEnumerator stunnedTimer(PlayerControllerB playerWhoHit)
		{
			isHitted.Value = false;
			hittedPlayer = playerWhoHit;
			base.agent.speed = 0f;
			base.creatureAnimator.SetTrigger("Recoil");
			mainAudio.PlayOneShot(Plugin.cry1, 1f);
			yield return (object)new WaitForSeconds(0.5f);
			scaredBackingAway = 3f;
			yield return (object)new WaitForSeconds(2f);
			hittedPlayer = null;
		}

		private void StunTest()
		{
			//IL_0064: 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)
			if (scaredBackingAway > 0f)
			{
				if (((Behaviour)base.agent).enabled && ((NetworkBehaviour)this).IsOwner)
				{
					lookRig.weight = Mathf.Lerp(lookRig.weight, 0f, Time.deltaTime);
					base.agent.SetDestination(((EnemyAI)this).ChooseFarthestNodeFromPosition(((Component)this).transform.position, true, 0, false).position);
				}
				base.creatureAnimator.SetFloat("walkSpeed", -3.5f);
				scaredBackingAway -= Time.deltaTime;
			}
		}

		public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
		{
			((EnemyAI)this).HitEnemy(force, playerWhoHit, false);
			if (hungerValue.Value < 60f && scaredBackingAway <= 0f)
			{
				isHitted.Value = true;
			}
		}

		public void FootStepSound()
		{
			randomVal = Random.Range(0, 20);
			if (randomVal < 5f)
			{
				mainAudio.PlayOneShot(Plugin.footstep1, Random.Range(0.8f, 1f));
			}
			else if (randomVal < 10f)
			{
				mainAudio.PlayOneShot(Plugin.footstep2, Random.Range(0.8f, 1f));
			}
			else if (randomVal < 15f)
			{
				mainAudio.PlayOneShot(Plugin.footstep3, Random.Range(0.8f, 1f));
			}
			else if (randomVal < 20f)
			{
				mainAudio.PlayOneShot(Plugin.footstep4, Random.Range(0.8f, 1f));
			}
		}

		private IEnumerator DogSatisfied()
		{
			yield return (object)new WaitForSeconds(2f);
			canBeMoved = true;
			networkTargetPlayer.Value = null;
		}

		public override void Update()
		{
			//IL_0048: 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_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_032c: Unknown result type (might be due to invalid IL or missing references)
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0593: Unknown result type (might be due to invalid IL or missing references)
			//IL_059d: Unknown result type (might be due to invalid IL or missing references)
			//IL_053c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0552: Unknown result type (might be due to invalid IL or missing references)
			//IL_0557: Unknown result type (might be due to invalid IL or missing references)
			//IL_055b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0571: Unknown result type (might be due to invalid IL or missing references)
			//IL_0576: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0600: Unknown result type (might be due to invalid IL or missing references)
			//IL_0610: 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_0628: Unknown result type (might be due to invalid IL or missing references)
			//IL_062d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0631: Unknown result type (might be due to invalid IL or missing references)
			//IL_063b: Unknown result type (might be due to invalid IL or missing references)
			//IL_064b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0650: Unknown result type (might be due to invalid IL or missing references)
			//IL_0445: Unknown result type (might be due to invalid IL or missing references)
			//IL_044b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0450: Unknown result type (might be due to invalid IL or missing references)
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			//IL_0457: Unknown result type (might be due to invalid IL or missing references)
			//IL_045f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0464: Unknown result type (might be due to invalid IL or missing references)
			//IL_0468: Unknown result type (might be due to invalid IL or missing references)
			//IL_07c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_07c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_07d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0804: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_06dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0703: Unknown result type (might be due to invalid IL or missing references)
			//IL_0709: Unknown result type (might be due to invalid IL or missing references)
			//IL_0719: Unknown result type (might be due to invalid IL or missing references)
			//IL_074e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0754: Unknown result type (might be due to invalid IL or missing references)
			//IL_075e: Unknown result type (might be due to invalid IL or missing references)
			//IL_076e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0785: Unknown result type (might be due to invalid IL or missing references)
			//IL_078b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0795: Unknown result type (might be due to invalid IL or missing references)
			//IL_07a5: Unknown result type (might be due to invalid IL or missing references)
			if (!isSatisfied)
			{
				CheckPlayer();
			}
			if ((Object)(object)networkTargetPlayer.Value != (Object)null)
			{
				GameObject[] allPlayerObjects = StartOfRound.Instance.allPlayerObjects;
				foreach (GameObject val in allPlayerObjects)
				{
					float num = Vector3.Distance(((Component)this).transform.position, val.transform.position);
					if (num < float.PositiveInfinity && num > 80f)
					{
						networkTargetPlayer.Value = null;
					}
				}
			}
			base.targetPlayer = networkTargetPlayer.Value;
			SetByHunger();
			EatItem();
			CheckTargetAvailable();
			if (isHitted.Value)
			{
				((MonoBehaviour)this).StartCoroutine(stunnedTimer(base.targetPlayer));
			}
			if (((NetworkBehaviour)this).IsOwner)
			{
				((EnemyAI)this).SyncPositionToClients();
			}
			else
			{
				((EnemyAI)this).SetClientCalculatingAI(false);
			}
			if (ateLung)
			{
				lungLight.intensity = Mathf.Lerp(lungLight.intensity, 1500f, Time.deltaTime * 10f);
			}
			if (satisfyValue >= 21f && !isSatisfied)
			{
				canBeMoved = false;
				((MonoBehaviour)this).StartCoroutine(DogSatisfied());
				mainAudio.PlayOneShot(Plugin.dogSneeze);
				isSatisfied = true;
			}
			if (isSatisfied && satisfyValue > 0f)
			{
				satisfyValue -= Time.deltaTime;
				isSeenPlayer = false;
			}
			if (satisfyValue <= 0f && isSatisfied)
			{
				isSatisfied = false;
				satisfyValue = 0f;
			}
			if ((Object)(object)base.targetPlayer == (Object)null && !isNearestItem && (Object)(object)base.targetNode == (Object)null)
			{
				int num2 = Random.Range(1, base.allAINodes.Length);
				if (Vector3.Distance(((Component)this).transform.position, base.allAINodes[num2].transform.position) > 5f && SelectNode.Value != num2 && ((NetworkBehaviour)this).IsOwner && ((NetworkBehaviour)this).IsOwner)
				{
					SelectNode.Value = num2;
				}
			}
			if (stuckDetectionTimer > 3.5f)
			{
				int num3 = Random.Range(1, base.allAINodes.Length);
				if (Vector3.Distance(((Component)this).transform.position, base.allAINodes[num3].transform.position) > 5f && SelectNode.Value != num3)
				{
					if (((NetworkBehaviour)this).IsOwner)
					{
						SelectNode.Value = num3;
					}
					stuckDetectionTimer = 0f;
				}
				else if (Vector3.Distance(((Component)this).transform.position, base.allAINodes[num3].transform.position) > 5f)
				{
					stuckDetectionTimer = 0f;
				}
			}
			Vector3 velocity;
			if (((Object)(object)base.targetPlayer == (Object)null && !isNearestItem) || isSatisfied)
			{
				lookRig.weight = Mathf.Lerp(lookRig.weight, 0f, Time.deltaTime);
				if ((Object)(object)base.targetNode != (Object)null)
				{
					if (((Behaviour)base.agent).enabled && ((NetworkBehaviour)this).IsOwner)
					{
						base.agent.SetDestination(base.targetNode.position);
					}
					if (shrimpVelocity.Value < 0.5f)
					{
						stuckDetectionTimer += Time.deltaTime;
					}
					else
					{
						stuckDetectionTimer = 0f;
					}
					float num4 = 30f;
					Vector3 val2 = ((Component)this).transform.position - prevPosition;
					velocity = base.agent.velocity;
					float num5 = Vector3.Angle(val2, ((Vector3)(ref velocity)).normalized);
					if (num5 > num4)
					{
						Plugin.mls.LogInfo((object)("각도 차이가 " + num5 + "이며, " + num4 + " 이상 차이납니다."));
					}
					prevPosition = ((Component)this).transform.position;
				}
			}
			base.targetNode = base.allAINodes[SelectNode.Value].transform;
			if ((Object)(object)base.targetPlayer != (Object)null || isNearestItem)
			{
				dogRandomWalk = false;
				stuckDetectionTimer = 0f;
			}
			Quaternion rotation;
			if (((NetworkBehaviour)this).IsOwner)
			{
				networkPosition.Value = ((Component)this).transform.position;
				LethalNetworkVariable<Vector3> obj = networkRotation;
				rotation = ((Component)this).transform.rotation;
				obj.Value = ((Quaternion)(ref rotation)).eulerAngles;
				LethalNetworkVariable<float> obj2 = shrimpVelocity;
				velocity = base.agent.velocity;
				obj2.Value = ((Vector3)(ref velocity)).sqrMagnitude;
			}
			else
			{
				networkPosDistance = Vector3.Distance(((Component)this).transform.position, networkPosition.Value);
				if (networkPosDistance > 3f)
				{
					((Component)this).transform.position = networkPosition.Value;
					Plugin.mls.LogWarning((object)"Force the shrimp to change position.");
				}
				else
				{
					((Component)this).transform.position = Vector3.Lerp(((Component)this).transform.position, networkPosition.Value, Time.deltaTime * 10f);
				}
				Transform transform = ((Component)this).transform;
				rotation = ((Component)this).transform.rotation;
				transform.rotation = Quaternion.Euler(Vector3.Lerp(((Quaternion)(ref rotation)).eulerAngles, networkRotation.Value, Time.deltaTime * 10f));
				if (networkPosDistance > 15f)
				{
					Plugin.mls.LogFatal((object)"Shrimp spawned successfully, but its current position is VERY different from the network position. This error is usually caused by low network quality or high traffic on the server.");
				}
			}
			if ((Object)(object)base.targetPlayer != (Object)null)
			{
				isTargetAvailable = true;
			}
			if ((Object)(object)base.targetPlayer != (Object)null)
			{
				if (hungerValue.Value < 55f)
				{
					leftEye.localScale = Vector3.Lerp(leftEye.localScale, scaleOfEyesNormally, 20f * Time.deltaTime);
					rightEye.localScale = Vector3.Lerp(rightEye.localScale, scaleOfEyesNormally, 20f * Time.deltaTime);
				}
				else if (hungerValue.Value > 55f)
				{
					leftEye.localScale = Vector3.Lerp(leftEye.localScale, scaleOfEyesNormally * 0.4f, 20f * Time.deltaTime);
					rightEye.localScale = Vector3.Lerp(rightEye.localScale, scaleOfEyesNormally * 0.4f, 20f * Time.deltaTime);
				}
			}
			else
			{
				leftEye.localScale = Vector3.Lerp(leftEye.localScale, scaleOfEyesNormally, 20f * Time.deltaTime);
				rightEye.localScale = Vector3.Lerp(rightEye.localScale, scaleOfEyesNormally, 20f * Time.deltaTime);
			}
			base.creatureAnimator.SetBool("DogRandomWalk", dogRandomWalk);
			if (canBeMoved && !isRunning)
			{
				base.creatureAnimator.SetBool("Running", false);
				base.agent.speed = 5.5f;
				base.agent.acceleration = 7f;
				base.agent.angularSpeed = 150f;
			}
			else if (!canBeMoved && !isRunning)
			{
				base.creatureAnimator.SetBool("Running", false);
				base.agent.speed = 0f;
				base.agent.angularSpeed = 0f;
			}
			if (isRunning)
			{
				base.creatureAnimator.SetBool("Running", true);
				base.agent.speed = Mathf.Lerp(base.agent.speed, 15f, Time.deltaTime * 2f);
				base.agent.angularSpeed = 10000f;
				base.agent.acceleration = 50f;
			}
			StunTest();
		}

		private IEnumerator SyncRotation()
		{
			Transform transform = ((Component)this).transform;
			Quaternion rotation = ((Component)this).transform.rotation;
			transform.rotation = Quaternion.Euler(Vector3.Lerp(((Quaternion)(ref rotation)).eulerAngles, networkRotation.Value, Time.deltaTime * 10f));
			yield return (object)new WaitForSeconds(1f);
		}

		private float CalculateRotationDifference(Vector3 rotation1, Vector3 rotation2)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Quaternion val = Quaternion.Euler(rotation1);
			Quaternion val2 = Quaternion.Euler(rotation2);
			return Quaternion.Angle(val, val2);
		}

		private void CheckPlayer()
		{
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB val = ((EnemyAI)this).CheckLineOfSightForPlayer(40f, 40, -1);
			if ((Object)(object)val != (Object)null && (Object)(object)base.targetPlayer == (Object)null && !isKillingPlayer)
			{
				if (!isSeenPlayer)
				{
					mainAudio.PlayOneShot(Plugin.dogHowl);
					base.creatureAnimator.SetTrigger("Walk");
					isSeenPlayer = true;
				}
				networkTargetPlayer.Value = val;
			}
			if (droppedItems.Count > 0 && (Object)(object)nearestDroppedItem == (Object)null)
			{
				FindNearestItem();
			}
			footStepTime += Time.deltaTime * shrimpVelocity.Value / 8f;
			if ((double)footStepTime > 0.5)
			{
				FootStepSound();
				footStepTime = 0f;
			}
			base.creatureAnimator.SetFloat("walkSpeed", Mathf.Clamp(shrimpVelocity.Value / 5f, 0f, 3f));
			base.creatureAnimator.SetFloat("runSpeed", Mathf.Clamp(shrimpVelocity.Value / 2.7f, 3f, 4f));
			if ((Object)(object)base.targetPlayer != (Object)null)
			{
				if (!isNearestItem && scaredBackingAway <= 0f)
				{
					if (hungerValue.Value > 55f)
					{
						lookRay = new Ray(dogHead.position, ((Component)base.targetPlayer).transform.position - dogHead.position);
						lookTarget.position = Vector3.Lerp(lookTarget.position, ((Ray)(ref lookRay)).GetPoint(3f), 30f * Time.deltaTime);
					}
					else
					{
						lookTarget.position = Vector3.Lerp(lookTarget.position, ((Component)base.targetPlayer.lowerSpine).transform.position, 6f * Time.deltaTime);
					}
				}
				base.agent.autoBraking = true;
				lookRig.weight = Mathf.Lerp(lookRig.weight, 0.5f, Time.deltaTime);
				dogRandomWalk = false;
				if (!isSeenPlayer)
				{
					mainAudio.PlayOneShot(Plugin.dogHowl, 1f);
				}
				isSeenPlayer = true;
			}
			if (!isRunning && !isNearestItem)
			{
				base.agent.stoppingDistance = 4.5f;
				lookRig.weight = Mathf.Lerp(lookRig.weight, 0f, Time.deltaTime);
			}
			else
			{
				base.agent.stoppingDistance = 0.5f;
			}
			if (!isNearestItem)
			{
			}
		}

		private void SetByHunger()
		{
			//IL_0550: Unknown result type (might be due to invalid IL or missing references)
			//IL_0556: Unknown result type (might be due to invalid IL or missing references)
			//IL_0566: Unknown result type (might be due to invalid IL or missing references)
			//IL_0478: Unknown result type (might be due to invalid IL or missing references)
			//IL_048c: Unknown result type (might be due to invalid IL or missing references)
			//IL_049c: Unknown result type (might be due to invalid IL or missing references)
			if (hungerValue.Value < 66f)
			{
				if (isSeenPlayer && !isTargetAvailable && ((NetworkBehaviour)this).IsOwner)
				{
					LethalNetworkVariable<float> obj = hungerValue;
					obj.Value += Time.deltaTime * 0.09f;
				}
				else if (isSeenPlayer && isTargetAvailable && ((NetworkBehaviour)this).IsOwner)
				{
					LethalNetworkVariable<float> obj2 = hungerValue;
					obj2.Value += Time.deltaTime;
				}
			}
			if (hungerValue.Value > 55f && hungerValue.Value < 60f)
			{
				voiceAudio.pitch = Mathf.Lerp(voiceAudio.pitch, 1f, 45f * Time.deltaTime);
				voiceAudio.volume = Mathf.Lerp(voiceAudio.volume, 1f, 125f * Time.deltaTime);
				voiceAudio.loop = true;
				voiceAudio.clip = Plugin.stomachGrowl;
				if (!voiceAudio.isPlaying)
				{
					voiceAudio.Play();
				}
			}
			else if (hungerValue.Value < 63f && hungerValue.Value >= 60f && !isEnraging)
			{
				voiceAudio.pitch = Mathf.Lerp(voiceAudio.pitch, 0.8f, 45f * Time.deltaTime);
				voiceAudio.volume = Mathf.Lerp(voiceAudio.volume, 1f, 125f * Time.deltaTime);
				isEnraging = true;
				voiceAudio.clip = Plugin.bigGrowl;
				if (!voiceAudio.isPlaying)
				{
					voiceAudio.Play();
				}
			}
			else if (hungerValue.Value < 63f && hungerValue.Value > 60f && isEnraging)
			{
				voiceAudio.pitch = Mathf.Lerp(voiceAudio.pitch, 1f, 45f * Time.deltaTime);
				voiceAudio.volume = Mathf.Lerp(voiceAudio.volume, 1f, 125f * Time.deltaTime);
				if (!isNearestItem)
				{
					canBeMoved = false;
				}
			}
			else if (hungerValue.Value < 55f)
			{
				voiceAudio.pitch = Mathf.Lerp(voiceAudio.pitch, 0f, 45f * Time.deltaTime);
				voiceAudio.volume = Mathf.Lerp(voiceAudio.volume, 0f, 125f * Time.deltaTime);
			}
			else if (hungerValue.Value > 63f && !isAngered)
			{
				if (!isNearestItem && !isKillingPlayer && base.stunNormalizedTimer <= 0f)
				{
					canBeMoved = true;
				}
				voiceAudio.clip = Plugin.enragedScream;
				voiceAudio.Play();
				isEnraging = false;
				isAngered = true;
			}
			else if (hungerValue.Value > 65f)
			{
				base.openDoorSpeedMultiplier = 1.5f;
				isRunning = true;
				voice2Audio.volume = Mathf.Lerp(voice2Audio.volume, 1f, 125f * Time.deltaTime);
			}
			else if (hungerValue.Value > 63f)
			{
				voiceAudio.pitch = Mathf.Lerp(voiceAudio.pitch, 0.8f, 45f * Time.deltaTime);
				mouth.localScale = Vector3.Lerp(mouth.localScale, new Vector3(0.005590725f, 0.01034348f, 0.02495567f), 30f * Time.deltaTime);
			}
			if (hungerValue.Value < 60f)
			{
				isEnraging = false;
				isAngered = false;
				if (!isNearestItem && !isKillingPlayer && base.stunNormalizedTimer <= 0f)
				{
					canBeMoved = true;
				}
			}
			if (hungerValue.Value < 66f)
			{
				isRunning = false;
				base.openDoorSpeedMultiplier = 0.3f;
			}
			if (hungerValue.Value < 63f)
			{
				mouth.localScale = Vector3.Lerp(mouth.localScale, originalMouthScale, 20f * Time.deltaTime);
				voice2Audio.volume = Mathf.Lerp(voice2Audio.volume, 0f, 125f * Time.deltaTime);
				isRunning = false;
			}
			if (hungerValue.Value > 64f && networkTargetPlayerDistance < 3.5f && !isKillingPlayer && (Object)(object)base.targetPlayer != (Object)null && !base.targetPlayer.isCameraDisabled)
			{
				KillingPlayerBool.Value = true;
			}
			if (KillingPlayerBool.Value)
			{
				if (!base.targetPlayer.isCameraDisabled)
				{
					Plugin.mls.LogInfo((object)("Shrimp: (Owner) Killing " + ((Object)base.targetPlayer).name + "!"));
					((MonoBehaviour)this).StartCoroutine(KillPlayer(base.targetPlayer));
					KillingPlayerBool.Value = false;
				}
				else if (base.targetPlayer.isCameraDisabled)
				{
					Plugin.mls.LogInfo((object)("Shrimp: (Not Owner) Killing " + ((Object)base.targetPlayer).name + "!"));
					((MonoBehaviour)this).StartCoroutine(KillPlayerInOtherClient(base.targetPlayer));
					KillingPlayerBool.Value = false;
				}
			}
			if (isKillingPlayer)
			{
				canBeMoved = false;
			}
		}

		private void EatItem()
		{
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)nearestDroppedItem != (Object)null)
			{
				if (isNearestItem && !nearestDroppedItem.GetComponent<GrabbableObject>().isHeld)
				{
					if (hungerValue.Value < 55f)
					{
						lookRay = new Ray(dogHead.position, nearestDroppedItem.transform.position - dogHead.position);
						lookTarget.position = Vector3.Lerp(lookTarget.position, ((Ray)(ref lookRay)).GetPoint(1.8f), 6f * Time.deltaTime);
					}
					else
					{
						lookTarget.position = Vector3.Lerp(lookTarget.position, nearestDroppedItem.transform.position, 6f * Time.deltaTime);
					}
					if (((Behaviour)base.agent).enabled && ((NetworkBehaviour)this).IsOwner)
					{
						base.agent.SetDestination(nearestDroppedItem.transform.position);
					}
					nearestItemDistance = Vector3.Distance(((Component)this).transform.position, nearestDroppedItem.transform.position);
					if (nearestItemDistance < 1.35f)
					{
						canBeMoved = false;
						isRunning = false;
						nearestDroppedItem.transform.SetParent(((Component)this).transform, true);
						if ((Object)(object)nearestDroppedItem.GetComponent<LungProp>() != (Object)null)
						{
							satisfyValue += 30f;
							if (((NetworkBehaviour)this).IsOwner)
							{
								LethalNetworkVariable<float> obj = hungerValue;
								obj.Value -= 50f;
							}
							ateLung = true;
							((Behaviour)nearestDroppedItem.GetComponentInChildren<Light>()).enabled = false;
						}
						else if ((Object)(object)nearestDroppedItem.GetComponent<StunGrenadeItem>() != (Object)null)
						{
							StunGrenadeItem component = nearestDroppedItem.GetComponent<StunGrenadeItem>();
							component.hasExploded = true;
							((MonoBehaviour)this).StartCoroutine(EatenFlashbang());
						}
						base.creatureAnimator.SetTrigger("eat");
						mainAudio.PlayOneShot(Plugin.dogEatItem);
						isNearestItem = false;
						nearestItemDistance = 500f;
						if (nearestDroppedItem.GetComponent<GrabbableObject>().itemProperties.weight > 1f)
						{
							satisfyValue += Mathf.Clamp(nearestDroppedItem.GetComponent<GrabbableObject>().itemProperties.weight - 1f, 0f, 100f) * 150f;
							if (((NetworkBehaviour)this).IsOwner)
							{
								LethalNetworkVariable<float> obj2 = hungerValue;
								obj2.Value -= Mathf.Clamp(nearestDroppedItem.GetComponent<GrabbableObject>().itemProperties.weight - 1f, 0f, 100f) * 230f;
							}
						}
						else
						{
							satisfyValue += 6f;
							if (((NetworkBehaviour)this).IsOwner)
							{
								LethalNetworkVariable<float> obj3 = hungerValue;
								obj3.Value -= 12f;
							}
						}
						GrabbableObject component2 = nearestDroppedItem.GetComponent<GrabbableObject>();
						component2.grabbable = false;
						component2.grabbableToEnemies = false;
						component2.deactivated = true;
						if ((Object)(object)component2.radarIcon != (Object)null)
						{
							Object.Destroy((Object)(object)((Component)component2.radarIcon).gameObject);
						}
						MeshRenderer[] componentsInChildren = ((Component)component2).gameObject.GetComponentsInChildren<MeshRenderer>();
						for (int i = 0; i < componentsInChildren.Length; i++)
						{
							Object.Destroy((Object)(object)componentsInChildren[i]);
						}
						Collider[] componentsInChildren2 = ((Component)component2).gameObject.GetComponentsInChildren<Collider>();
						for (int j = 0; j < componentsInChildren2.Length; j++)
						{
							Object.Destroy((Object)(object)componentsInChildren2[j]);
						}
						droppedItems.Remove(nearestDroppedItem);
						nearestDroppedItem = null;
					}
					else if (!isKillingPlayer && base.stunNormalizedTimer <= 0f)
					{
						canBeMoved = true;
					}
				}
				else if ((Object)(object)base.targetPlayer != (Object)null && !isSatisfied)
				{
					nearestDroppedItem = null;
					nearestItemDistance = 3000f;
					isNearestItem = false;
				}
			}
			if (base.stunNormalizedTimer > 0f)
			{
				canBeMoved = false;
				base.creatureAnimator.SetBool("Stun", true);
			}
			else
			{
				base.creatureAnimator.SetBool("Stun", false);
			}
		}

		private void CheckTargetAvailable()
		{
			//IL_0076: 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_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			if ((networkTargetPlayerDistance <= 12f || Object.op_Implicit((Object)(object)((EnemyAI)this).CheckLineOfSightForPlayer(40f, 40, -1))) && !isNearestItem && !isKillingPlayer && scaredBackingAway <= 0f)
			{
				followTimer = 10f;
				canBeMoved = true;
			}
			if ((Object)(object)base.targetPlayer != (Object)null)
			{
				networkTargetPlayerDistance = Vector3.Distance(((Component)this).transform.position, ((Component)base.targetPlayer).transform.position);
			}
			else
			{
				networkTargetPlayerDistance = 3000f;
			}
			if ((followTimer > 0f || networkTargetPlayerDistance < 10f) && !isSatisfied)
			{
				if (isTargetAvailable && scaredBackingAway <= 0f && !isNearestItem && ((Behaviour)base.agent).enabled && ((NetworkBehaviour)this).IsOwner)
				{
					base.agent.SetDestination(((Component)base.targetPlayer).transform.position);
				}
				if ((Object)(object)nearestDroppedItem != (Object)null && nearestDroppedItem.GetComponent<GrabbableObject>().isHeld)
				{
					nearestDroppedItem.GetComponent<ItemElevatorCheck>().dogEatTimer = 5f;
					droppedItems.Remove(nearestDroppedItem);
					if (((Behaviour)base.agent).enabled && ((NetworkBehaviour)this).IsOwner)
					{
						base.agent.SetDestination(((Component)base.targetPlayer).transform.position);
					}
					nearestDroppedItem = null;
					nearestItemDistance = 3000f;
					isNearestItem = false;
				}
			}
			if ((((Object)(object)base.targetPlayer != (Object)null && networkTargetPlayerDistance > 12f) || !Object.op_Implicit((Object)(object)((EnemyAI)this).CheckLineOfSightForPlayer(40f, 30, -1))) && followTimer > 0f)
			{
				followTimer -= Time.deltaTime;
			}
			if ((Object)(object)base.targetPlayer == (Object)null)
			{
				followTimer = 10f;
			}
			if (followTimer <= 0f)
			{
				networkTargetPlayer.Value = null;
				base.targetPlayer = null;
				isTargetAvailable = false;
			}
		}

		private bool IsPlayerVisible(PlayerControllerB player)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = ((Component)player).transform.position - ((Component)this).transform.position;
			float num = Vector3.Angle(((Component)this).transform.forward, val);
			if (num < 35f && Physics.Raycast(((Component)this).transform.position, val, 120f, LayerMask.NameToLayer("Player")))
			{
				return true;
			}
			return false;
		}

		private void FindNearestItem()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			foreach (GameObject droppedItem in droppedItems)
			{
				float num = Vector3.Distance(((Component)this).transform.position, droppedItem.transform.position);
				if (num < float.PositiveInfinity && num < 30f)
				{
					nearestDroppedItem = droppedItem;
					isNearestItem = true;
					return;
				}
			}
			isNearestItem = false;
		}

		private IEnumerator EatenFlashbang()
		{
			yield return (object)new WaitForSeconds(2f);
			mainAudio.PlayOneShot(Plugin.eatenExplode);
		}

		private void KillPlayerTrigger(PlayerControllerB killPlayer)
		{
			if (!killPlayer.isCameraDisabled)
			{
				((MonoBehaviour)this).StartCoroutine(KillPlayer(killPlayer));
			}
			else
			{
				((MonoBehaviour)this).StartCoroutine(KillPlayerInOtherClient(killPlayer));
			}
		}

		private IEnumerator KillPlayer(PlayerControllerB killPlayer)
		{
			hungerValue.Value = 0f;
			Plugin.mls.LogInfo((object)("Shrimp: Killing " + ((Object)killPlayer).name + "!"));
			yield return (object)new WaitForSeconds(0.05f);
			isKillingPlayer = true;
			base.creatureAnimator.SetTrigger("RipObject");
			mainAudio.PlayOneShot(Plugin.ripPlayerApart);
			if ((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)(object)killPlayer)
			{
				killPlayer.KillPlayer(Vector3.zero, true, (CauseOfDeath)6, 0);
			}
			yield return (object)new WaitForSeconds(0.1f);
			if ((Object)(object)killPlayer.deadBody == (Object)null)
			{
				Debug.Log((object)"Shrimp: Player body was not spawned or found within 0.5 seconds.");
				killPlayer.inAnimationWithEnemy = null;
				isKillingPlayer = false;
				KillingPlayerBool.Value = false;
			}
			else
			{
				TakeBodyInMouth(killPlayer.deadBody);
				yield return (object)new WaitForSeconds(4.4f);
				base.creatureAnimator.SetTrigger("eat");
				mainAudio.PlayOneShot(Plugin.dogEatItem);
				((Component)killPlayer.deadBody).gameObject.SetActive(false);
				yield return (object)new WaitForSeconds(2f);
				isKillingPlayer = false;
			}
		}

		private IEnumerator KillPlayerInOtherClient(PlayerControllerB killPlayer)
		{
			Plugin.mls.LogInfo((object)("Shrimp: Killing " + ((Object)killPlayer).name + "!"));
			hungerValue.Value = 0f;
			yield return (object)new WaitForSeconds(0.05f);
			isKillingPlayer = true;
			base.creatureAnimator.SetTrigger("RipObject");
			mainAudio.PlayOneShot(Plugin.ripPlayerApart);
			yield return (object)new WaitForSeconds(0.1f);
			if ((Object)(object)killPlayer.deadBody == (Object)null)
			{
				Debug.Log((object)"Shrimp: Player body was not spawned or found within 0.5 seconds.");
				killPlayer.inAnimationWithEnemy = null;
				isKillingPlayer = false;
				KillingPlayerBool.Value = false;
			}
			else
			{
				TakeBodyInMouth(killPlayer.deadBody);
				yield return (object)new WaitForSeconds(4.4f);
				base.creatureAnimator.SetTrigger("eat");
				mainAudio.PlayOneShot(Plugin.dogEatItem);
				((Component)killPlayer.deadBody).gameObject.SetActive(false);
				yield return (object)new WaitForSeconds(2f);
				isKillingPlayer = false;
			}
		}

		private void TakeBodyInMouth(DeadBodyInfo body)
		{
			body.attachedTo = bittenObjectHolder;
			body.attachedLimb = body.bodyParts[5];
			body.matchPositionExactly = true;
		}

		private void SetupBehaviour()
		{
			roamingState.name = "Roaming";
			roamingState.boolValue = true;
			followingPlayer.name = "Following";
			followingPlayer.boolValue = true;
			enragedState.name = "Enraged";
			enragedState.boolValue = true;
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	internal class TerminalPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("Start")]
		private static void Start_Prefix(Terminal __instance, ref List<TerminalNode> ___enemyFiles)
		{
			___enemyFiles.Add(Plugin.shrimpTerminalNode);
			TerminalKeyword defaultVerb = __instance.terminalNodes.allKeywords.First((TerminalKeyword x) => x.word == "info");
			TerminalKeyword shrimpTerminalKeyword = Plugin.shrimpTerminalKeyword;
			shrimpTerminalKeyword.defaultVerb = defaultVerb;
		}
	}
	public class TrapRoomTrigger : NetworkBehaviour
	{
		public LethalClientMessage<bool> SendTrapFloorTrigger = new LethalClientMessage<bool>("SendTrapFloorTrigger", (Action<bool>)null, (Action<bool, ulong>)null);

		public LethalClientMessage<bool> SendTrapDeactivate = new LethalClientMessage<bool>("SendTrapDeactivate", (Action<bool>)null, (Action<bool, ulong>)null);

		public AudioSource floorAudioSource;

		public AudioSource floorAudioSource2;

		public AudioSource doorAudioSource;

		public Animator roomAnimator;

		public bool isPlayed;

		public bool isPlayedOnce;

		public bool isDeactivated;

		public PlayerControllerB[] players;

		public float Timer;

		private void SendTrapFloorTriggerSync(bool value, ulong id)
		{
			if (value && !isPlayed)
			{
				isPlayed = true;
			}
			else if (!value && isPlayed)
			{
				isPlayed = false;
			}
		}

		private void SendTrapDeactivateSync(bool value, ulong id)
		{
			if (value && !isDeactivated)
			{
				isDeactivated = true;
			}
			else if (!value && isDeactivated)
			{
				isDeactivated = false;
			}
		}

		private void Start()
		{
			SendTrapFloorTrigger.OnReceivedFromClient += SendTrapFloorTriggerSync;
			SendTrapDeactivate.OnReceivedFromClient += SendTrapDeactivateSync;
			roomAnimator = GameObject.Find("TrapDoorAnimator").GetComponent<Animator>();
			floorAudioSource = GameObject.Find("Floor1").GetComponent<AudioSource>();
			floorAudioSource2 = GameObject.Find("Floor2").GetComponent<AudioSource>();
			doorAudioSource = GameObject.Find("DoorSlam").GetComponent<AudioSource>();
			((UnityEvent<PlayerControllerB>)(object)GameObject.Find("TrapTrigger").GetComponent<InteractTrigger>().onInteract).AddListener((UnityAction<PlayerControllerB>)TriggerTrap);
			((UnityEvent<PlayerControllerB>)(object)GameObject.Find("IgnoreFallDamagePlayer").GetComponent<InteractTrigger>().onInteract).AddListener((UnityAction<PlayerControllerB>)IgnoreFallDamage);
			((UnityEvent<PlayerControllerB>)(object)((Component)this).GetComponent<TerminalAccessibleObject>().terminalCodeEvent).AddListener((UnityAction<PlayerControllerB>)DeactivateTrap);
		}

		private void Update()
		{
			if (isPlayed && !isPlayedOnce && !isDeactivated)
			{
				((MonoBehaviour)this).StartCoroutine(ActivateTrap());
				isPlayed = false;
				isPlayedOnce = true;
			}
			if (!isPlayed && isDeactivated && isPlayedOnce)
			{
				((MonoBehaviour)this).StartCoroutine(DeactivateTrapCoroutine());
				isDeactivated = false;
			}
		}

		public void TriggerTrap(PlayerControllerB playerControllerB)
		{
			SendTrapFloorTrigger.SendAllClients(true, true, false);
		}

		public void IgnoreFallDamage(PlayerControllerB playerControllerB)
		{
			playerControllerB.fallValue -= 5f;
		}

		public void DeactivateTrap(PlayerControllerB playerControllerB)
		{
			SendTrapDeactivate.SendAllClients(true, true, false);
		}

		private IEnumerator ActivateTrap()
		{
			roomAnimator.SetBool("open", true);
			doorAudioSource.PlayOneShot(Plugin.garageDoorSlam);
			yield return (object)new WaitForSeconds(3f);
			doorAudioSource.PlayOneShot(Plugin.floorOpen);
		}

		private IEnumerator DeactivateTrapCoroutine()
		{
			roomAnimator.SetBool("unlock", true);
			doorAudioSource.PlayOneShot(Plugin.floorClose);
			yield return (object)new WaitForSeconds(1f);
			doorAudioSource.PlayOneShot(Plugin.garageSlide);
		}
	}
	public class StanleyTrigger : MonoBehaviour
	{
		public AudioSource audioSource;

		public bool isPlayed;

		private void Start()
		{
			((UnityEvent<PlayerControllerB>)(object)GameObject.Find("Stanley").GetComponent<InteractTrigger>().onInteract).AddListener((UnityAction<PlayerControllerB>)TriggerStanley);
			audioSource = GameObject.Find("NarratorAudio").GetComponent<AudioSource>();
		}

		public void TriggerStanley(PlayerControllerB playerControllerB)
		{
			if (!isPlayed)
			{
				((MonoBehaviour)this).StartCoroutine(PlayVoice1());
				isPlayed = true;
			}
		}

		private IEnumerator PlayVoice1()
		{
			yield return (object)new WaitForSeconds(3f);
			audioSource.PlayOneShot(Plugin.stanleyVoiceline1);
		}
	}
	public class ElevatorMusic : MonoBehaviour
	{
		public AudioSource audioSource;

		public int currentMusic;

		public float musicPlayTimer;

		private void Start()
		{
			audioSource = ((Component)this).GetComponent<AudioSource>();
			audioSource.PlayOneShot(Plugin.bossaLullaby);
			musicPlayTimer = 0f;
			currentMusic = 1;
		}

		private void Update()
		{
			if (audioSource.isPlaying)
			{
				return;
			}
			musicPlayTimer += Time.deltaTime;
			if (musicPlayTimer > 0.5f)
			{
				if (currentMusic == 0)
				{
					audioSource.PlayOneShot(Plugin.bossaLullaby);
					musicPlayTimer = 0f;
					currentMusic++;
				}
				else if (currentMusic == 1)
				{
					audioSource.PlayOneShot(Plugin.shopTheme);
					musicPlayTimer = 0f;
					currentMusic++;
				}
				else if (currentMusic == 2)
				{
					audioSource.PlayOneShot(Plugin.saferoomTheme);
					musicPlayTimer = 0f;
					currentMusic = 0;
				}
			}
		}
	}
	public class ElevatorCollider : NetworkBehaviour
	{
		public Bounds checkBounds;

		public LethalClientMessage<bool> SendInElevator = new LethalClientMessage<bool>("SendInElevator", (Action<bool>)null, (Action<bool, ulong>)IsInElevatorSync);

		public List<GameObject> allPlayerColliders = new List<GameObject>();

		public Transform storageParent;

		public Transform lungPlacement;

		public Vector3 tempTargetFloorPosition;

		public Vector3 tempStartFallingPosition;

		private static void IsInElevatorSync(bool value, ulong id)
		{
			if (value)
			{
				((Component)LethalNetworkExtensions.GetPlayerController(id)).GetComponent<PlayerElevatorCheck>().wasInElevator = true;
				((Component)LethalNetworkExtensions.GetPlayerController(id)).GetComponent<PlayerElevatorCheck>().isInElevatorNotOwner = true;
			}
			else
			{
				((Component)LethalNetworkExtensions.GetPlayerController(id)).GetComponent<PlayerElevatorCheck>().isInElevatorNotOwner = false;
			}
		}

		private void Start()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			((Bounds)(ref checkBounds)).size = new Vector3(4.9f, 17f, 4.9f);
			GameObject[] allPlayerObjects = StartOfRound.Instance.allPlayerObjects;
			foreach (GameObject item in allPlayerObjects)
			{
				allPlayerColliders.Add(item);
			}
			lungPlacement = ((Component)Object.FindObjectOfType<PlaceLung>()).transform;
		}

		private void Update()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: 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_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			if (!RoundMapSystem.Instance.isOffice)
			{
				return;
			}
			((Bounds)(ref checkBounds)).center = ((Component)this).transform.position;
			foreach (GameObject allPlayerCollider in allPlayerColliders)
			{
				if (!((Object)(object)allPlayerCollider.GetComponent<Collider>() != (Object)null))
				{
					continue;
				}
				BoxCollider component = allPlayerCollider.GetComponent<BoxCollider>();
				if (((Bounds)(ref checkBounds)).Intersects(((Collider)component).bounds))
				{
					if (((Component)component).gameObject.tag == "Player")
					{
						PlayerControllerB component2 = ((Component)component).GetComponent<PlayerControllerB>();
						PlayerElevatorCheck component3 = ((Component)component).GetComponent<PlayerElevatorCheck>();
						if (!((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorB && !component2.isCameraDisabled)
						{
							((Component)component).transform.SetParent(((Component)this).transform.parent);
							SendInElevator.SendAllClients(true, true, false);
							component3.wasInElevator = true;
							component3.isInElevatorB = true;
						}
					}
					else if (((Component)component).gameObject.tag == "PhysicsProp")
					{
						if ((Object)(object)((Component)component).GetComponent<GrabbableObject>().playerHeldBy != (Object)null && ((Component)((Component)component).GetComponent<GrabbableObject>().playerHeldBy).GetComponent<PlayerElevatorCheck>().isInElevatorB)
						{
							tempTargetFloorPosition = ((Component)((Component)component).GetComponent<GrabbableObject>().playerHeldBy).transform.localPosition;
							tempStartFallingPosition = ((Component)((Component)component).GetComponent<GrabbableObject>()).transform.localPosition;
						}
						if (!((Component)component).GetComponent<ItemElevatorCheck>().isInElevatorB && ((Object)(object)((Component)component).transform.parent != (Object)(object)storageParent || (Object)(object)((Component)component).transform.parent != (Object)(object)lungPlacement))
						{
							((Component)component).transform.parent = ((Component)this).transform.parent;
							((Component)component).GetComponent<GrabbableObject>().targetFloorPosition = tempTargetFloorPosition;
							((Component)component).GetComponent<GrabbableObject>().startFallingPosition = tempStartFallingPosition;
							((Component)component).GetComponent<ItemElevatorCheck>().isInElevatorB = true;
						}
					}
					continue;
				}
				if (((Component)component).gameObject.tag == "Player")
				{
					if (((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorB)
					{
						((Component)component).transform.SetParent(StartOfRound.Instance.playersContainer, true);
						SendInElevator.SendAllClients(false, true, false);
						((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorB = false;
					}
					else if (((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorB && ((Component)component).GetComponent<PlayerControllerB>().isCameraDisabled && !((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorNotOwner)
					{
						((Component)component).transform.SetParent((Transform)null, true);
						((Component)component).GetComponent<PlayerElevatorCheck>().isInElevatorB = false;
					}
				}
				if ((Object)(object)allPlayerCollider.GetComponent<PlayerControllerB>() != (Object)null)
				{
					PlayerControllerB component4 = ((Component)component).GetComponent<PlayerControllerB>();
					PlayerElevatorCheck component5 = ((Component)component).GetComponent<PlayerElevatorCheck>();
					if (!component5.isInElevatorB && component4.isCameraDisabled && component5.isInElevatorNotOwner)
					{
						Plugin.mls.LogInfo((object)(component4.actualClientId + " is inside of elevator check!"));
						((Component)component).transform.SetParent(((Component)this).transform.parent, true);
						component5.isInElevatorB = true;
						component5.wasInElevator = true;
					}
					else if (component5.isInElevatorB && component4.isCameraDisabled && !component5.isInElevatorNotOwner)
					{
						Plugin.mls.LogInfo((object)(component4.actualClientId + " is outside of elevator check!"));
						((Component)component).transform.SetParent((Transform)null, true);
						component5.isInElevatorB = false;
					}
				}
			}
		}
	}
	public class ElevatorSystem : NetworkBehaviour
	{
		public static LethalNetworkVariable<bool> isElevatorDowned = new LethalNetworkVariable<bool>("isElevatorDowned");

		public static LethalNetworkVariable<bool> isElevatorClosed = new LethalNetworkVariable<bool>("isElevatorClosed");

		public float elevatorTimer;

		public static LethalNetworkVariable<bool> spawnShrimpBool = new LethalNetworkVariable<bool>("spawnShrimpBool");

		public Animator doorAnimator;

		public Animator elevatorScreenDoorAnimator;

		public Animator animator;

		public AudioSource audioSource;

		public List<Animator> panelAnimators;

		public List<Animator> buttonLightAnimators;

		public bool performanceCheck;

		public GameObject storageObject;

		public bool isSetupEnd;

		private void Start()
		{
			isElevatorDowned.Value = false;
			isElevatorClosed.Value = false;
			spawnShrimpBool.Value = false;
		}

		private void LateUpdate()
		{
			//IL_00bd: 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_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			if (!RoundMapSystem.Instance.isOffice)
			{
				return;
			}
			Setup();
			AnimatorStateInfo currentAnimatorStateInfo;
			if (isElevatorClosed.Value)
			{
				if (doorAnimator.GetBool("closed"))
				{
					audioSource.PlayOneShot(Plugin.ElevatorClose);
				}
				elevatorScreenDoorAnimator.SetBool("open", false);
				doorAnimator.SetBool("closed", false);
			}
			else
			{
				if (!doorAnimator.GetBool("closed"))
				{
					audioSource.PlayOneShot(Plugin.ElevatorOpen);
				}
				if (!isElevatorDowned.Value)
				{
					currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
					if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime > 0.4f)
					{
						currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
						if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime < 1f)
						{
							elevatorScreenDoorAnimator.SetBool("open", true);
						}
					}
				}
				doorAnimator.SetBool("closed", true);
			}
			if (isElevatorDowned.Value && !animator.GetBool("goDown"))
			{
				elevatorTimer += Time.deltaTime;
				foreach (Animator buttonLightAnimator in buttonLightAnimators)
				{
					buttonLightAnimator.SetBool("up", false);
				}
				if (elevatorTimer > 0f)
				{
					if (!isElevatorClosed.Value)
					{
						isElevatorClosed.Value = true;
					}
					if (elevatorTimer > 3f)
					{
						audioSource.PlayOneShot(Plugin.ElevatorDown);
						animator.SetBool("goDown", true);
						if (!isElevatorDowned.Value)
						{
							isElevatorDowned.Value = true;
						}
					}
				}
			}
			if (!isElevatorDowned.Value && animator.GetBool("goDown"))
			{
				foreach (Animator buttonLightAnimator2 in buttonLightAnimators)
				{
					buttonLightAnimator2.SetBool("up", true);
				}
				elevatorTimer += Time.deltaTime;
				if (elevatorTimer > 0f)
				{
					isElevatorClosed.Value = true;
					if (elevatorTimer > 3f)
					{
						audioSource.PlayOneShot(Plugin.ElevatorUp);
						animator.SetBool("goDown", false);
						if (!isElevatorDowned.Value)
						{
							isElevatorDowned.Value = false;
						}
					}
				}
			}
			if (!isElevatorClosed.Value)
			{
				return;
			}
			currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
			if (!(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime < 1f))
			{
				return;
			}
			currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
			if (!(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime >= 0.98f))
			{
				return;
			}
			foreach (Animator panelAnimator in panelAnimators)
			{
				if (Plugin.setKorean)
				{
					((Component)((Component)panelAnimator).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "대기 중";
				}
				else
				{
					((Component)((Component)panelAnimator).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "Idle";
				}
			}
			if (isElevatorClosed.Value)
			{
				isElevatorClosed.Value = false;
				elevatorTimer = 0f;
			}
		}

		private void Setup()
		{
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			if (isSetupEnd)
			{
				return;
			}
			animator = ((Component)((Component)this).transform.GetChild(0)).GetComponent<Animator>();
			audioSource = GameObject.Find("ElevatorSound").GetComponent<AudioSource>();
			doorAnimator = GameObject.Find("DoorBone").GetComponent<Animator>();
			elevatorScreenDoorAnimator = GameObject.Find("ElevatorScreenDoor").GetComponent<Animator>();
			Animator[] array = Object.FindObjectsOfType<Animator>();
			Animator[] array2 = array;
			foreach (Animator val in array2)
			{
				if (!(((Object)((Component)val).gameObject).name == "ElevatorPanel"))
				{
					continue;
				}
				((UnityEvent<PlayerControllerB>)(object)((Component)((Component)val).transform.GetChild(1).GetChild(0)).GetComponent<InteractTrigger>().onInteract).AddListener((UnityAction<PlayerControllerB>)ElevatorUpTrigger);
				((UnityEvent<PlayerControllerB>)(object)((Component)((Component)val).transform.GetChild(2).GetChild(0)).GetComponent<InteractTrigger>().onInteract).AddListener((UnityAction<PlayerControllerB>)ElevatorDownTrigger);
				((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>();
				((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().font = GameObject.Find("doorHydraulics").GetComponent<TMP_Text>().font;
				((Graphic)((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>()).material = ((Graphic)GameObject.Find("doorHydraulics").GetComponent<TMP_Text>()).material;
				((Graphic)((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>()).color = new Color(1f, 0.3444f, 0f, 1f);
				if (!PlaceLung.emergencyPowerRequires || PlaceLung.lungPlaced)
				{
					if (Plugin.setKorean)
					{
						((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "대기 중";
					}
					else
					{
						((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "Idle";
					}
				}
				else if (PlaceLung.emergencyPowerRequires && !PlaceLung.lungPlaced)
				{
					if (Plugin.setKorean)
					{
						((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "전력 없음";
					}
					else
					{
						((Component)((Component)val).transform.GetChild(3).GetChild(1)).GetComponent<TMP_Text>().text = "No Power";
					}
				}
				panelAnimators.Add(val);
			}
			Animator[] array3 = array;
			foreach (Animator val2 in array3)
			{
				if (((Object)((Component)val2).gameObject).name == "ButtonLights")
				{
					buttonLightAnimators.Add(val2);
				}
			}
			GameObject.Find("InsideCollider").gameObject.AddComponent<ElevatorCollider>();
			GameObject.Find("ElevatorMusic").AddComponent<ElevatorMusic>();
			ScanNodeProperties[] array4 = Object.FindObjectsOfType<ScanNodeProperties>();
			if (Plugin.setKorean)
			{
				ScanNodeProperties[] array5 = array4;
				foreach (ScanNodeProperties val3 in array5)
				{
					if (val3.headerText == "Elevator Controller")
					{
						val3.headerText = "엘리베이터 제어기";
					}
					if (val3.headerText == "Auxiliary power unit")
					{
						val3.headerText = "보조 동력 장치";
						val3.subText = "긴급 전력 공급기";
					}
				}
			}
			if (GameNetworkManager.Instance.isHostingGame)
			{
				GameObject val4 = Object.Instantiate<GameObject>(Plugin.socketInteractPrefab);
				val4.GetComponent<NetworkObject>().Spawn(false);
			}
			isElevatorDowned.Value = false;
			isElevatorClosed.Value = false;
			spawnShrimpBool.Value = false;
			isSetupEnd = true;
		}

		public void ElevatorUpTrigger(PlayerControllerB playerController)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			Plugin.mls.LogInfo((object)"pressed up button!");
			if (!isElevatorDowned.Value)
			{
				return;
			}
			AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
			if (!(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime >= 1f))
			{
				return;
			}
			foreach (Animator panelAnimator 

plugins/LCOuijaBoard.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.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using GameNetcodeStuff;
using HarmonyLib;
using LCOuijaBoard.Properties;
using LethalCompanyInputUtils;
using LethalLib.Modules;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("LCOuijaBoard")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LCOuijaBoard")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("1c1acc88-8f86-45d6-beb9-9b98f2302980")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace LCOuijaBoard
{
	[BepInPlugin("Electric.OuijaBoard", "OuijaBoard", "1.5.3")]
	public class Plugin : BaseUnityPlugin
	{
		private class UIHandler
		{
			public static GameObject inputObject;

			public static TMP_InputField input;

			public static bool registered;

			public static float lastError;

			public static TMP_InputField GetInput()
			{
				if (registered && (Object)(object)input != (Object)null)
				{
					return input;
				}
				inputObject = ((Component)OuijaTextUI.transform.GetChild(2)).gameObject;
				input = inputObject.GetComponent<TMP_InputField>();
				((UnityEvent<string>)(object)input.onSubmit).AddListener((UnityAction<string>)SubmitUI);
				((UnityEvent<string>)(object)input.onEndEdit).AddListener((UnityAction<string>)EndEditUI);
				registered = true;
				return input;
			}

			public static void hide()
			{
				OuijaTextUI.SetActive(false);
				Traverse.Create(typeof(LcInputActionApi)).Method("ReEnableFromRebind", Array.Empty<object>()).GetValue();
				input.text = "";
			}

			public static void ToggleUI(CallbackContext context)
			{
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if (!Object.op_Implicit((Object)(object)localPlayerController))
				{
					return;
				}
				Debug.Log((object)"Ouija Text UI Toggle Requested");
				if (!DEVDEBUG && ((Object)(object)localPlayerController == (Object)null || !localPlayerController.isPlayerDead))
				{
					Debug.Log((object)"Ouija Text UI Toggle Denied: Not Dead");
					return;
				}
				if ((Object)(object)OuijaTextUI == (Object)null)
				{
					Debug.LogError((object)"Ouija Text UI Toggle Denied: No UI");
					return;
				}
				bool flag = !OuijaTextUI.active;
				GetInput();
				Debug.Log((object)$"Ouija Text UI Toggle Accepted: New State is {flag}");
				if (!flag)
				{
					if (!input.isFocused || !OuijaTextUI.active)
					{
						OuijaTextUI.SetActive(false);
						Traverse.Create(typeof(LcInputActionApi)).Method("ReEnableFromRebind", Array.Empty<object>()).GetValue();
					}
				}
				else
				{
					Traverse.Create(typeof(LcInputActionApi)).Method("DisableForRebind", Array.Empty<object>()).GetValue();
					OuijaTextUI.SetActive(true);
					input.ActivateInputField();
					((Selectable)input).Select();
				}
			}

			public static void SubmitUI(string msg)
			{
				AttemptSend(msg);
			}

			public static void EndEditUI(string msg)
			{
				hide();
			}

			public static bool AttemptSend(string msg)
			{
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0041: Expected O, but got Unknown
				//IL_0079: Unknown result type (might be due to invalid IL or missing references)
				string[] value = msg.Split(new char[1] { ' ' }).ToArray();
				Object[] array = Object.FindObjectsOfType(typeof(GameObject));
				List<GameObject> list = new List<GameObject>();
				Object[] array2 = array;
				for (int i = 0; i < array2.Length; i++)
				{
					GameObject val = (GameObject)array2[i];
					if ((((Object)val).name == "OuijaBoardScrap(Clone)" || ((Object)val).name == "OuijaBoardStore(Clone)") && !((GrabbableObject)(PhysicsProp)val.GetComponent(typeof(PhysicsProp))).isHeld)
					{
						list.Add(val);
					}
				}
				if (list.Count > 0)
				{
					if (!StartOfRoundPatch.complete)
					{
						ShowError("Boards on cooldown");
						return false;
					}
					string text = string.Join("", value);
					if (Regex.Match(text, "([A-Za-z\\d ])+").Value.Length != text.Length)
					{
						ShowError("Invalid character(s)");
						return false;
					}
					text = text.Replace(" ", "");
					if (text.Length > 10)
					{
						ShowError("Too many characters");
						return false;
					}
					OuijaNetworker.Instance.WriteOut(text);
					return true;
				}
				ShowError("No valid boards");
				return false;
			}

			public static void ShowError(string msg)
			{
				if ((Object)(object)OuijaErrorUI != (Object)null)
				{
					Debug.Log((object)("Ouija Board showing erorr: " + msg));
					((Component)OuijaErrorUI.transform.GetChild(0)).GetComponent<TMP_Text>().text = msg;
					OuijaErrorUI.SetActive(true);
					lastError = Time.time;
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound))]
		public class StartOfRoundPatch
		{
			public static int writeIndex = 0;

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

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

			public static float timer = 0f;

			public static double amount = 0.0;

			public static bool complete = true;

			[HarmonyPatch("Update")]
			[HarmonyPostfix]
			private static void Update(ref StartOfRound __instance)
			{
				PlayerControllerB localPlayerController = __instance.localPlayerController;
				if (!Object.op_Implicit((Object)(object)localPlayerController))
				{
					return;
				}
				if (!DEVDEBUG && !localPlayerController.isPlayerDead && Object.op_Implicit((Object)(object)OuijaTextUI) && OuijaTextUI.active)
				{
					Debug.Log((object)"Ouija Text UI closed since player is not dead");
					OuijaTextUI.SetActive(false);
					Traverse.Create(typeof(LcInputActionApi)).Method("ReEnableFromRebind", Array.Empty<object>()).GetValue();
				}
				if (Object.op_Implicit((Object)(object)OuijaErrorUI) && OuijaErrorUI.active && Time.time - UIHandler.lastError > 2f)
				{
					Debug.Log((object)"Ouija Error UI closed");
					OuijaErrorUI.SetActive(false);
					Traverse.Create(typeof(LcInputActionApi)).Method("ReEnableFromRebind", Array.Empty<object>()).GetValue();
				}
				if (writeIndex < names.Count)
				{
					amount = Mathf.Clamp(timer / 1.2f, 0f, 1f);
					MoveUpdate(names[writeIndex]);
					timer += Time.deltaTime;
					if (timer >= 3f)
					{
						amount = 1.0;
						MoveUpdate(names[writeIndex]);
						timer = 0f;
						writeIndex++;
					}
				}
				else if (!complete)
				{
					if (timer < 5f)
					{
						timer += Time.deltaTime;
					}
					else
					{
						complete = true;
						timer = 0f;
						amount = 0.0;
					}
				}
				if ((Object)(object)OuijaTextUI != (Object)null)
				{
					((Component)OuijaTextUI.transform.GetChild(3)).gameObject.SetActive(!complete);
				}
			}

			public static void MoveUpdate(string name)
			{
				//IL_0051: 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_0148: Unknown result type (might be due to invalid IL or missing references)
				//IL_014d: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
				//IL_0233: Unknown result type (might be due to invalid IL or missing references)
				//IL_023f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0224: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
				//IL_009d: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a4: Expected O, but got Unknown
				int num = -1;
				bool flag = false;
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				foreach (GameObject board in boards)
				{
					if (!Object.op_Implicit((Object)(object)board) || ((GrabbableObject)(PhysicsProp)board.GetComponent(typeof(PhysicsProp))).isHeld)
					{
						continue;
					}
					flag = true;
					if (num == -1)
					{
						num = 0;
						foreach (Transform item in board.transform.GetChild(0).GetChild(3))
						{
							Transform val = item;
							GameObject gameObject = ((Component)val).gameObject;
							if (((Object)gameObject).name == name)
							{
								break;
							}
							num++;
						}
						if (num == -1)
						{
							amount = 0.0;
							writeIndex++;
							break;
						}
					}
					Vector3 localPosition = board.transform.GetChild(0).GetChild(3).GetChild(num)
						.localPosition;
					Vector3 localPosition2 = board.transform.GetChild(0).GetChild(4).localPosition;
					GameObject gameObject2 = ((Component)board.transform.GetChild(0).GetChild(2)).gameObject;
					if (amount == 0.0)
					{
						gameObject2.GetComponent<AudioSource>().Play();
						if (makesSound)
						{
							RoundManager.Instance.PlayAudibleNoise(board.transform.position, 8f, 0.3f, 0, false, 8925);
						}
					}
					Vector3 val2 = localPosition + new Vector3(0f, 0.166f, 0f);
					gameObject2.transform.localPosition = Vector3.Lerp(localPosition2, val2, (float)amount);
					if (amount == 1.0)
					{
						board.transform.GetChild(0).GetChild(4).localPosition = val2;
					}
					if (Vector3.Distance(((Component)localPlayerController).transform.position, board.transform.position) < 5f)
					{
						localPlayerController.insanityLevel += Time.deltaTime * 0.5f;
					}
				}
				if (!flag)
				{
					writeIndex = names.Count;
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB))]
		[HarmonyPriority(500)]
		public class PlayerPatch
		{
			[HarmonyPatch("Interact_performed")]
			[HarmonyPrefix]
			private static void InteractPrefixPatch(ref PlayerControllerB __instance, out bool __state)
			{
				__state = __instance.isPlayerDead;
				if (Object.op_Implicit((Object)(object)OuijaTextUI) && OuijaTextUI.active)
				{
					__instance.isPlayerDead = false;
				}
			}

			[HarmonyPatch("Interact_performed")]
			[HarmonyPostfix]
			private static void InteractPostfixPatch(ref PlayerControllerB __instance, bool __state)
			{
				__instance.isPlayerDead = __state;
			}
		}

		public class OuijaNetworker : NetworkBehaviour
		{
			public static OuijaNetworker Instance;

			private void Awake()
			{
				Instance = this;
			}

			public void WriteOut(string message)
			{
				if (((NetworkBehaviour)this).IsOwner)
				{
					WriteOutClientRpc(message);
				}
				else
				{
					WriteOutServerRpc(message);
				}
			}

			[ClientRpc]
			public void WriteOutClientRpc(string message)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d4: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_008e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_011c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0123: Expected O, but got Unknown
				//IL_015b: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3508306228u, val, (RpcDelivery)0);
					bool flag = message != null;
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
					if (flag)
					{
						((FastBufferWriter)(ref val2)).WriteValueSafe(message, false);
					}
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3508306228u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
				{
					return;
				}
				Object[] array = Object.FindObjectsOfType(typeof(GameObject));
				List<GameObject> list = new List<GameObject>();
				Object[] array2 = array;
				for (int i = 0; i < array2.Length; i++)
				{
					GameObject val3 = (GameObject)array2[i];
					if ((((Object)val3).name == "OuijaBoardScrap(Clone)" || ((Object)val3).name == "OuijaBoardStore(Clone)") && !((GrabbableObject)(PhysicsProp)val3.GetComponent(typeof(PhysicsProp))).isHeld)
					{
						list.Add(val3);
					}
				}
				List<string> list2 = new List<string>();
				switch (message)
				{
				case "yes":
				case "y":
					list2.Add("Yes");
					break;
				case "no":
				case "n":
					list2.Add("No");
					break;
				case "goodbye":
				case "bye":
					list2.Add("Goodbye");
					break;
				default:
					list2 = (from c in message.ToUpper().ToCharArray()
						select c.ToString()).ToList();
					break;
				}
				StartOfRoundPatch.amount = 0.0;
				StartOfRoundPatch.complete = false;
				StartOfRoundPatch.writeIndex = 0;
				StartOfRoundPatch.names = list2;
				StartOfRoundPatch.boards = list;
			}

			[ServerRpc(RequireOwnership = false)]
			public void WriteOutServerRpc(string message)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d4: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_008e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3320529116u, val, (RpcDelivery)0);
					bool flag = message != null;
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
					if (flag)
					{
						((FastBufferWriter)(ref val2)).WriteValueSafe(message, false);
					}
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3320529116u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					WriteOutClientRpc(message);
				}
			}

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

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

			private static void __rpc_handler_3508306228(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					bool flag = default(bool);
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
					string message = null;
					if (flag)
					{
						((FastBufferReader)(ref reader)).ReadValueSafe(ref message, false);
					}
					target.__rpc_exec_stage = (__RpcExecStage)2;
					((OuijaNetworker)(object)target).WriteOutClientRpc(message);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_3320529116(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					bool flag = default(bool);
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
					string message = null;
					if (flag)
					{
						((FastBufferReader)(ref reader)).ReadValueSafe(ref message, false);
					}
					target.__rpc_exec_stage = (__RpcExecStage)1;
					((OuijaNetworker)(object)target).WriteOutServerRpc(message);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

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

		[HarmonyPatch(typeof(RoundManager))]
		internal class RoundManagerPatch
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			private static void StartPatch(ref RoundManager __instance)
			{
				if (((NetworkBehaviour)__instance).IsServer && (Object)(object)OuijaNetworker.Instance == (Object)null)
				{
					GameObject val = Object.Instantiate<GameObject>(OuijaNetworkerPrefab);
					val.GetComponent<NetworkObject>().Spawn(true);
				}
				OuijaTextUI = Object.Instantiate<GameObject>(OuijaTextUIPrefab);
				OuijaTextUI.SetActive(false);
				Traverse.Create(typeof(LcInputActionApi)).Method("ReEnableFromRebind", Array.Empty<object>()).GetValue();
				OuijaErrorUI = Object.Instantiate<GameObject>(OuijaErrorUIPrefab);
				OuijaErrorUI.SetActive(false);
			}
		}

		private const string modGUID = "Electric.OuijaBoard";

		private const string modName = "OuijaBoard";

		private const string modVersion = "1.5.3";

		private readonly Harmony harmony = new Harmony("Electric.OuijaBoard");

		public static bool storeEnabled;

		public static int storeCost;

		public static bool scrapEnabled;

		public static int scrapRarity;

		public static bool makesSound;

		private static bool DEVDEBUG;

		public static GameObject OuijaNetworkerPrefab;

		public static GameObject OuijaTextUIPrefab;

		public static GameObject OuijaTextUI;

		public static GameObject OuijaErrorUIPrefab;

		public static GameObject OuijaErrorUI;

		private void Awake()
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			AssetBundle val = AssetBundle.LoadFromMemory(Resources.fullboard);
			OuijaNetworkerPrefab = val.LoadAsset<GameObject>("Assets/OuijaNetworker.prefab");
			OuijaNetworkerPrefab.AddComponent<OuijaNetworker>();
			OuijaTextUIPrefab = val.LoadAsset<GameObject>("Assets/OuijaTextUI.prefab");
			OuijaErrorUIPrefab = val.LoadAsset<GameObject>("Assets/OuijaErrorUI.prefab");
			GameObject val2 = val.LoadAsset<GameObject>("Assets/OuijaBoardStore.prefab");
			GameObject val3 = val.LoadAsset<GameObject>("Assets/OuijaBoardScrap.prefab");
			NetworkPrefabs.RegisterNetworkPrefab(OuijaNetworkerPrefab);
			NetworkPrefabs.RegisterNetworkPrefab(val2);
			NetworkPrefabs.RegisterNetworkPrefab(val3);
			InputAction val4 = new InputAction((string)null, (InputActionType)0, "<Keyboard>/#(" + ((BaseUnityPlugin)this).Config.Bind<string>("General", "Keybind", "o", "(Clientside) The key that will open the Ouija Board UI. Note: This will NOT change the tooltip on the item").Value + ")", (string)null, (string)null, (string)null);
			val4.performed += UIHandler.ToggleUI;
			val4.Enable();
			storeEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Store", "Enabled", true, "Allow Ouija Board to be bought in the store").Value;
			storeCost = ((BaseUnityPlugin)this).Config.Bind<int>("Store", "Cost", 100, "Cost of a Ouija Board in the store (Store must be enabled)").Value;
			scrapEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Scrap", "Enabled", false, "Allow the Ouija Board to spawn in the facility").Value;
			scrapRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "Rarity Weight", 20, "Chance for a Ouija Board to spawn as scrap").Value;
			if (storeCost < 0)
			{
				storeCost = 0;
			}
			if (scrapRarity < 0)
			{
				scrapRarity = 0;
			}
			makesSound = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Makes Sound", true, "Enables the Ouija Board's sliding to be heard by enemies").Value;
			Item val5 = val.LoadAsset<Item>("Assets/OuijaBoardStoreItem.asset");
			Item val6 = val.LoadAsset<Item>("Assets/OuijaBoardScrapItem.asset");
			if (storeEnabled)
			{
				Debug.Log((object)$"Ouija Board store enabled at {storeCost} credits");
				Items.RegisterShopItem(val5, storeCost);
			}
			if (scrapEnabled)
			{
				Debug.Log((object)$"Ouija Board scrap spawn enabled at {scrapRarity} rarity weight");
				val6.minValue = Mathf.Max(((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "Min Value", 60, "The minimum value of the Ouija Board (must be > 0)").Value, 1);
				val6.maxValue = Mathf.Max(((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "Max Value", 80, "The maximum value of the Ouija Board (must be > min value)").Value, val6.minValue);
				Items.RegisterScrap(val6, scrapRarity, (LevelTypes)(-1));
			}
			NetcodeWeaver();
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"OuijaBoard loaded!");
		}

		private static void NetcodeWeaver()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}
	}
}
namespace LCOuijaBoard.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					ResourceManager resourceManager = new ResourceManager("LCOuijaBoard.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[] fullboard
		{
			get
			{
				object @object = ResourceManager.GetObject("fullboard", resourceCulture);
				return (byte[])@object;
			}
		}

		internal Resources()
		{
		}
	}
}

plugins/LethalExpansion.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Adapters;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using LethalExpansion.Extenders;
using LethalExpansion.Patches;
using LethalExpansion.Patches.Monsters;
using LethalExpansion.Utils;
using LethalExpansion.Utils.HUD;
using LethalSDK.Component;
using LethalSDK.Editor;
using LethalSDK.ScriptableObjects;
using LethalSDK.Utils;
using TMPro;
using Unity.AI.Navigation;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Audio;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.ProBuilder;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Video;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Mono.Security")]
[assembly: IgnoresAccessChecksTo("Newtonsoft.Json")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AccessibilityModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AIModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AndroidJNIModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AnimationModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AssetBundleModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AudioModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ClothModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ClusterInputModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ClusterRendererModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ContentLoadModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.CoreModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.CrashReportingModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.DirectorModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine")]
[assembly: IgnoresAccessChecksTo("UnityEngine.DSPGraphModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.GameCenterModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.GIModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.GridModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.HotReloadModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ImageConversionModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.IMGUIModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.InputLegacyModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.InputModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.JSONSerializeModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.LocalizationModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ParticleSystemModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.PerformanceReportingModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.Physics2DModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.PhysicsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ProfilerModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.PropertiesModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.RuntimeInitializeOnLoadManagerInitializerModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ScreenCaptureModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SharedInternalsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SpriteMaskModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SpriteShapeModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.StreamingModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SubstanceModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SubsystemsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TerrainModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TerrainPhysicsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TextCoreFontEngineModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TextCoreTextEngineModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TextRenderingModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TilemapModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TLSModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UIElementsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UIModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UmbraModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityAnalyticsCommonModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityAnalyticsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityConnectModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityCurlModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityTestProtocolModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityWebRequestAssetBundleModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityWebRequestAudioModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityWebRequestModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityWebRequestTextureModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityWebRequestWWWModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.VehiclesModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.VFXModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.VideoModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.VirtualTexturingModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.VRModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.WindModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.XRModule")]
[assembly: AssemblyCompany("LethalExpansion")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+0d1e9935dad978282ca6d7387d33772b4ae32190")]
[assembly: AssemblyProduct("LethalExpansion")]
[assembly: AssemblyTitle("LethalExpansion")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
public class AutoScrollText : MonoBehaviour
{
	public TextMeshProUGUI textMeshPro;

	public float scrollSpeed = 15f;

	private Vector2 startPosition;

	private float textHeight;

	private bool startScrolling = false;

	private bool isWaitingToReset = false;

	private float displayHeight;

	private float fontSize;

	private void Start()
	{
		textMeshPro = ((Component)this).GetComponent<TextMeshProUGUI>();
		InitializeScrolling();
	}

	private void InitializeScrolling()
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)textMeshPro != (Object)null)
		{
			startPosition = ((TMP_Text)textMeshPro).rectTransform.anchoredPosition;
			textHeight = ((TMP_Text)textMeshPro).preferredHeight;
			displayHeight = ((TMP_Text)textMeshPro).rectTransform.sizeDelta.y;
			fontSize = ((TMP_Text)textMeshPro).fontSize;
		}
		((MonoBehaviour)this).StartCoroutine(WaitBeforeScrolling(5f));
	}

	private IEnumerator WaitBeforeScrolling(float waitTime)
	{
		yield return (object)new WaitForSeconds(waitTime);
		startScrolling = true;
	}

	private IEnumerator WaitBeforeResetting(float waitTime)
	{
		isWaitingToReset = true;
		yield return (object)new WaitForSeconds(waitTime);
		((TMP_Text)textMeshPro).rectTransform.anchoredPosition = startPosition;
		isWaitingToReset = false;
		((MonoBehaviour)this).StartCoroutine(WaitBeforeScrolling(5f));
	}

	private void Update()
	{
		//IL_0037: 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_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)textMeshPro != (Object)null && startScrolling && !isWaitingToReset)
		{
			RectTransform rectTransform = ((TMP_Text)textMeshPro).rectTransform;
			rectTransform.anchoredPosition += new Vector2(0f, scrollSpeed * Time.deltaTime);
			if (((TMP_Text)textMeshPro).rectTransform.anchoredPosition.y >= startPosition.y + textHeight - displayHeight - fontSize)
			{
				startScrolling = false;
				((MonoBehaviour)this).StartCoroutine(WaitBeforeResetting(5f));
			}
		}
	}

	public void ResetScrolling()
	{
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		((MonoBehaviour)this).StopAllCoroutines();
		if ((Object)(object)textMeshPro != (Object)null)
		{
			((TMP_Text)textMeshPro).rectTransform.anchoredPosition = startPosition;
		}
		isWaitingToReset = false;
		InitializeScrolling();
	}
}
public class TooltipHandler : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
{
	private string description;

	private string netinfo;

	public static RectTransform ModSettingsToolTipPanel;

	public static TMP_Text ModSettingsToolTipPanelDescription;

	public static TMP_Text ModSettingsToolTipPanelNetInfo;

	public int index;

	private float delay = 0.5f;

	private bool isPointerOver = false;

	public void OnPointerEnter(PointerEventData eventData)
	{
		isPointerOver = true;
		((MonoBehaviour)this).StartCoroutine(ShowTooltipAfterDelay());
	}

	public void OnPointerExit(PointerEventData eventData)
	{
		isPointerOver = false;
		((Component)ModSettingsToolTipPanel).gameObject.SetActive(false);
	}

	private IEnumerator ShowTooltipAfterDelay()
	{
		yield return (object)new WaitForSeconds(delay);
		if (isPointerOver)
		{
			ModSettingsToolTipPanel.anchoredPosition = new Vector2(-30f, ((Component)this).GetComponent<RectTransform>().anchoredPosition.y + -80f);
			description = ConfigManager.Instance.FindDescription(index);
			(bool, bool) info = ConfigManager.Instance.FindNetInfo(index);
			netinfo = "Network synchronization: " + (info.Item1 ? "Yes" : "No") + "\nMod required by clients: " + (info.Item2 ? "No" : "Yes");
			ModSettingsToolTipPanelDescription.text = description;
			ModSettingsToolTipPanelNetInfo.text = netinfo;
			((Component)ModSettingsToolTipPanel).gameObject.SetActive(true);
		}
	}
}
public class ConfigItem
{
	public string Key { get; set; }

	public Type type { get; set; }

	public object Value { get; set; }

	public object DefaultValue { get; set; }

	public string Tab { get; set; }

	public string Description { get; set; }

	public object MinValue { get; set; }

	public object MaxValue { get; set; }

	public bool Sync { get; set; }

	public bool Hidden { get; set; }

	public bool Optional { get; set; }

	public bool RequireRestart { get; set; }

	public ConfigItem(string key, object defaultValue, string tab, string description, object minValue = null, object maxValue = null, bool sync = true, bool optional = false, bool hidden = false, bool requireRestart = false)
	{
		Key = key;
		DefaultValue = defaultValue;
		type = defaultValue.GetType();
		Tab = tab;
		Description = description;
		if (minValue != null && maxValue != null)
		{
			if (minValue.GetType() == type && maxValue.GetType() == type)
			{
				MinValue = minValue;
				MaxValue = maxValue;
			}
		}
		else
		{
			MinValue = null;
			MaxValue = null;
		}
		Sync = sync;
		Optional = optional;
		Hidden = hidden;
		Value = DefaultValue;
		RequireRestart = requireRestart;
	}
}
namespace LethalExpansion
{
	[BepInPlugin("LethalExpansion", "LethalExpansion", "1.3.37")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class LethalExpansion : BaseUnityPlugin
	{
		private enum compatibility
		{
			unknown,
			perfect,
			good,
			medium,
			bad,
			critical
		}

		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<PluginInfo, bool> <>9__31_1;

			public static UnityAction <>9__31_0;

			public static Func<PluginInfo, bool> <>9__31_2;

			public static Func<AudioMixerGroup, bool> <>9__32_0;

			public static Func<GameObject, bool> <>9__32_1;

			public static Func<AudioMixerGroup, bool> <>9__32_2;

			public static Func<AudioMixerGroup, bool> <>9__32_3;

			public static Func<AudioMixerGroup, bool> <>9__32_4;

			public static Func<PluginInfo, bool> <>9__35_0;

			public static Func<PluginInfo, bool> <>9__35_1;

			public static Func<PluginInfo, bool> <>9__35_2;

			public static Func<PluginInfo, bool> <>9__35_3;

			public static Func<PluginInfo, bool> <>9__35_4;

			public static Func<PluginInfo, bool> <>9__35_5;

			internal bool <OnSceneLoaded>b__31_1(PluginInfo p)
			{
				return p.Metadata.GUID == "CoomfyDungeon";
			}

			internal void <OnSceneLoaded>b__31_0()
			{
				ConfigManager.Instance.SetItemValue("CoomfyDungeonCompatibility", value: true);
				ConfigManager.Instance.SetEntryValue("CoomfyDungeonCompatibility", value: true);
			}

			internal bool <OnSceneLoaded>b__31_2(PluginInfo p)
			{
				return p.Metadata.GUID == "BiggerLobby";
			}

			internal bool <LoadCustomMoon>b__32_0(AudioMixerGroup a)
			{
				return ((Object)a).name == "Master";
			}

			internal bool <LoadCustomMoon>b__32_1(GameObject o)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				Scene scene = o.scene;
				return ((Scene)(ref scene)).name != "InitSceneLaunchOptions";
			}

			internal bool <LoadCustomMoon>b__32_2(AudioMixerGroup a)
			{
				return ((Object)a).name == "Master";
			}

			internal bool <LoadCustomMoon>b__32_3(AudioMixerGroup a)
			{
				return ((Object)a).name == "Master";
			}

			internal bool <LoadCustomMoon>b__32_4(AudioMixerGroup a)
			{
				return ((Object)a).name == "Master";
			}

			internal bool <waitForSession>b__35_0(PluginInfo p)
			{
				return p.Metadata.GUID == "BrutalCompanyPlus";
			}

			internal bool <waitForSession>b__35_1(PluginInfo p)
			{
				return p.Metadata.GUID == "LethalAdjustments";
			}

			internal bool <waitForSession>b__35_2(PluginInfo p)
			{
				return p.Metadata.GUID == "CoomfyDungeon";
			}

			internal bool <waitForSession>b__35_3(PluginInfo p)
			{
				return p.Metadata.GUID == "299792458.MoreMoneyStart";
			}

			internal bool <waitForSession>b__35_4(PluginInfo p)
			{
				return p.Metadata.GUID == "ExtraDaysToDeadline";
			}

			internal bool <waitForSession>b__35_5(PluginInfo p)
			{
				return p.Metadata.GUID == "AdvancedCompany";
			}
		}

		private const string PluginGUID = "LethalExpansion";

		private const string PluginName = "LethalExpansion";

		private const string VersionString = "1.3.37";

		public static readonly Version ModVersion = new Version("1.3.37");

		public static readonly int[] CompatibleGameVersions = new int[4] { 45, 47, 48, 49 };

		private readonly Dictionary<string, compatibility> CompatibleMods = new Dictionary<string, compatibility>
		{
			{
				"com.sinai.unityexplorer",
				compatibility.medium
			},
			{
				"HDLethalCompany",
				compatibility.good
			},
			{
				"LC_API",
				compatibility.good
			},
			{
				"me.swipez.melonloader.morecompany",
				compatibility.medium
			},
			{
				"BrutalCompanyPlus",
				compatibility.medium
			},
			{
				"MoonOfTheDay",
				compatibility.good
			},
			{
				"Television_Controller",
				compatibility.bad
			},
			{
				"beeisyou.LandmineFix",
				compatibility.perfect
			},
			{
				"LethalAdjustments",
				compatibility.good
			},
			{
				"CoomfyDungeon",
				compatibility.bad
			},
			{
				"BiggerLobby",
				compatibility.critical
			},
			{
				"KoderTech.BoomboxController",
				compatibility.good
			},
			{
				"299792458.MoreMoneyStart",
				compatibility.good
			},
			{
				"ExtraDaysToDeadline",
				compatibility.good
			},
			{
				"AdvancedCompany",
				compatibility.unknown
			}
		};

		public static List<PluginInfo> loadedPlugins = new List<PluginInfo>();

		public static bool sessionWaiting = true;

		public static bool hostDataWaiting = true;

		public static bool ishost = false;

		public static bool alreadypatched = false;

		public static bool weathersReadyToShare = false;

		public static bool isInGame = false;

		public static bool dungeonGeneratorReady = false;

		public static int delayedLevelChange = -1;

		public static string lastKickReason = string.Empty;

		private static readonly Harmony Harmony = new Harmony("LethalExpansion");

		public static ManualLogSource Log = new ManualLogSource("LethalExpansion");

		public static ConfigFile config;

		public GameObject SpaceLight;

		public GameObject terrainfixer;

		public static Transform currentWaterSurface;

		private int width = 256;

		private int height = 256;

		private int depth = 20;

		private float scale = 20f;

		private void Awake()
		{
			//IL_0cc1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cc7: Expected O, but got Unknown
			//IL_0d10: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d1d: Expected O, but got Unknown
			//IL_0d22: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d2f: Expected O, but got Unknown
			//IL_0d96: Unknown result type (might be due to invalid IL or missing references)
			//IL_0da3: Expected O, but got Unknown
			//IL_0daa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0db7: Expected O, but got Unknown
			//IL_0dd5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0dda: Unknown result type (might be due to invalid IL or missing references)
			//IL_0de6: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"PluginName: LethalExpansion, VersionString: 1.3.37 is loading...");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Getting other plugins list");
			loadedPlugins = GetLoadedPlugins();
			foreach (PluginInfo loadedPlugin in loadedPlugins)
			{
				if (!(loadedPlugin.Metadata.GUID != "LethalExpansion"))
				{
					continue;
				}
				if (CompatibleMods.ContainsKey(loadedPlugin.Metadata.GUID))
				{
					switch (CompatibleMods[loadedPlugin.Metadata.GUID])
					{
					case compatibility.unknown:
						Console.BackgroundColor = ConsoleColor.Gray;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					case compatibility.perfect:
						Console.BackgroundColor = ConsoleColor.Blue;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					case compatibility.good:
						Console.BackgroundColor = ConsoleColor.Green;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					case compatibility.medium:
						Console.BackgroundColor = ConsoleColor.Yellow;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogWarning((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					case compatibility.bad:
						Console.BackgroundColor = ConsoleColor.Red;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogError((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					case compatibility.critical:
						Console.BackgroundColor = ConsoleColor.Magenta;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogFatal((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					default:
						Console.BackgroundColor = ConsoleColor.Gray;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					}
					((BaseUnityPlugin)this).Logger.LogInfo((object)"------------------------------");
				}
				else
				{
					Console.BackgroundColor = ConsoleColor.Gray;
					((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
					Console.ResetColor();
					((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {compatibility.unknown}");
					((BaseUnityPlugin)this).Logger.LogInfo((object)"------------------------------");
				}
			}
			config = ((BaseUnityPlugin)this).Config;
			ConfigManager.Instance.AddItem(new ConfigItem("GlobalTimeSpeedMultiplier", 1.4f, "Time", "Change the global time speed", 0.1f, 3f));
			ConfigManager.Instance.AddItem(new ConfigItem("NumberOfHours", 18, "Time", "Max lenght of an Expedition in hours. (Begin at 6 AM | 18 = Midnight)", 6, 20));
			ConfigManager.Instance.AddItem(new ConfigItem("DeadlineDaysAmount", 3, "Expeditions", "Change amount of days for the Quota.", 1, 9));
			ConfigManager.Instance.AddItem(new ConfigItem("StartingCredits", 60, "Expeditions", "Change amount of starting Credit.", 0, 1000));
			ConfigManager.Instance.AddItem(new ConfigItem("MoonsRoutePricesMultiplier", 1f, "Moons", "Change the Cost of the Moon Routes.", 0f, 5f));
			ConfigManager.Instance.AddItem(new ConfigItem("StartingQuota", 130, "Expeditions", "Change the starting Quota.", 0, 1000, sync: true, optional: true));
			ConfigManager.Instance.AddItem(new ConfigItem("ScrapAmountMultiplier", 1f, "Dungeons", "Change the amount of Scraps in dungeons.", 0f, 10f));
			ConfigManager.Instance.AddItem(new ConfigItem("ScrapValueMultiplier", 0.4f, "Dungeons", "Change the value of Scraps.", 0f, 10f));
			ConfigManager.Instance.AddItem(new ConfigItem("MapSizeMultiplier", 1.5f, "Dungeons", "Change the size of the Dungeons. (Can crash when under 1.0)", 0.8f, 10f));
			ConfigManager.Instance.AddItem(new ConfigItem("PreventMineToExplodeWithItems", false, "Dungeons", "Prevent Landmines to explode by dropping items on them"));
			ConfigManager.Instance.AddItem(new ConfigItem("MineActivationWeight", 0.15f, "Dungeons", "Set the minimal weight to prevent Landmine's explosion (0.15 = 16 lb, Player = 2.0)", 0.01f, 5f));
			ConfigManager.Instance.AddItem(new ConfigItem("WeightUnit", 0, "HUD", "Change the carried Weight unit : 0 = Pounds (lb), 1 = Kilograms (kg) and 2 = Both", 0, 2, sync: false));
			ConfigManager.Instance.AddItem(new ConfigItem("ConvertPoundsToKilograms", true, "HUD", "Convert Pounds into Kilograms (16 lb = 7 kg) (Only effective if WeightUnit = 1)", null, null, sync: false));
			ConfigManager.Instance.AddItem(new ConfigItem("PreventScrapWipeWhenAllPlayersDie", false, "Expeditions", "Prevent the Scraps Wipe when all players die."));
			ConfigManager.Instance.AddItem(new ConfigItem("24HoursClock", false, "HUD", "Display a 24h clock instead of 12h.", null, null, sync: false));
			ConfigManager.Instance.AddItem(new ConfigItem("ClockAlwaysVisible", false, "HUD", "Display clock while inside of the Ship."));
			ConfigManager.Instance.AddItem(new ConfigItem("AutomaticDeadline", false, "Expeditions", "Automatically increase the Deadline depending of the required quota."));
			ConfigManager.Instance.AddItem(new ConfigItem("AutomaticDeadlineStage", 300, "Expeditions", "Increase the quota deadline of one day each time the quota exceeds this value.", 100, 3000));
			ConfigManager.Instance.AddItem(new ConfigItem("LoadModules", true, "Modules", "Load SDK Modules that add new content to the game. Disable it to play with Vanilla players. (RESTART REQUIRED)", null, null, sync: false, optional: false, hidden: false, requireRestart: true));
			ConfigManager.Instance.AddItem(new ConfigItem("MaxItemsInShip", 45, "Expeditions", "Change the Items cap can be kept in the ship.", 10, 500));
			ConfigManager.Instance.AddItem(new ConfigItem("ShowMoonWeatherInCatalogue", true, "HUD", "Display the current weather of Moons in the Terminal's Moon Catalogue."));
			ConfigManager.Instance.AddItem(new ConfigItem("ShowMoonRankInCatalogue", false, "HUD", "Display the rank of Moons in the Terminal's Moon Catalogue."));
			ConfigManager.Instance.AddItem(new ConfigItem("ShowMoonPriceInCatalogue", false, "HUD", "Display the route price of Moons in the Terminal's Moon Catalogue."));
			ConfigManager.Instance.AddItem(new ConfigItem("QuotaIncreaseSteepness", 16, "Expeditions", "Change the Quota Increase Steepness. (Highter = less steep exponential increase)", 0, 32));
			ConfigManager.Instance.AddItem(new ConfigItem("QuotaBaseIncrease", 100, "Expeditions", "Change the Quota Base Increase.", 0, 300));
			ConfigManager.Instance.AddItem(new ConfigItem("KickPlayerWithoutMod", false, "Lobby", "Kick the players without Lethal Expansion installer. (Will be kicked anyway if LoadModules is True)"));
			ConfigManager.Instance.AddItem(new ConfigItem("BrutalCompanyPlusCompatibility", false, "Compatibility", "Leave Brutal Company Plus control the Quota settings."));
			ConfigManager.Instance.AddItem(new ConfigItem("LethalAdjustmentsCompatibility", false, "Compatibility", "Leave Lethal Adjustments control the Dungeon settings."));
			ConfigManager.Instance.AddItem(new ConfigItem("CoomfyDungeonCompatibility", false, "Compatibility", "Let Coomfy Dungeons control the Dungeon size & scrap settings."));
			ConfigManager.Instance.AddItem(new ConfigItem("MoreMoneyStartCompatibility", false, "Compatibility", "Let MoreMoneyStart control the Starting credits amount."));
			ConfigManager.Instance.AddItem(new ConfigItem("SettingsDebug", false, "Debug", "Show an output of every settings in the Console. (The Console must listen Info messages)", null, null, sync: false));
			ConfigManager.Instance.AddItem(new ConfigItem("LegacyMoonLoading", false, "Modules", "Roll back to Synchronous moon loading. (Freeze the game longer and highter chance of crash)"));
			ConfigManager.Instance.AddItem(new ConfigItem("ExtraDaysToDeadline", false, "Compatibility", "Leave ExtraDaysToDeadline control the deadline days amount. (not effect automatic deadlines)"));
			ConfigManager.Instance.AddItem(new ConfigItem("HideModSettingsMenu", false, "HUD", "Hide the ModSettings menu from the Main Menu, you still can open the menu by pressing O in Main Menu. (Restart Required)", null, null, sync: false));
			ConfigManager.Instance.AddItem(new ConfigItem("AdvancedCompanyCompatibility", false, "Compatibility", "Let AdvancedCompany control some settings."));
			ConfigManager.Instance.ReadConfig();
			((BaseUnityPlugin)this).Config.SettingChanged += ConfigSettingChanged;
			AssetBundlesManager.Instance.LoadAllAssetBundles();
			SceneManager.sceneLoaded += OnSceneLoaded;
			SceneManager.sceneUnloaded += OnSceneUnloaded;
			Harmony.PatchAll(typeof(GameNetworkManager_Patch));
			Harmony.PatchAll(typeof(Terminal_Patch));
			Harmony.PatchAll(typeof(MenuManager_Patch));
			Harmony.PatchAll(typeof(GrabbableObject_Patch));
			Harmony.PatchAll(typeof(RoundManager_Patch));
			Harmony.PatchAll(typeof(TimeOfDay_Patch));
			Harmony.PatchAll(typeof(HUDManager_Patch));
			Harmony.PatchAll(typeof(StartOfRound_Patch));
			Harmony.PatchAll(typeof(EntranceTeleport_Patch));
			Harmony.PatchAll(typeof(Landmine_Patch));
			Harmony.PatchAll(typeof(AudioReverbTrigger_Patch));
			Harmony.PatchAll(typeof(InteractTrigger_Patch));
			Harmony.PatchAll(typeof(RuntimeDungeon));
			Harmony val = new Harmony("LethalExpansion");
			MethodInfo methodInfo = AccessTools.Method(typeof(BaboonBirdAI), "GrabScrap", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(HoarderBugAI), "GrabItem", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(MonsterGrabItem_Patch), "MonsterGrabItem", (Type[])null, (Type[])null);
			val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo3), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(methodInfo3), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(HoarderBugAI), "DropItem", (Type[])null, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(typeof(MonsterGrabItem_Patch), "MonsterDropItem_Patch", (Type[])null, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.Method(typeof(HoarderBugAI), "KillEnemy", (Type[])null, (Type[])null);
			MethodInfo methodInfo7 = AccessTools.Method(typeof(MonsterGrabItem_Patch), "KillEnemy_Patch", (Type[])null, (Type[])null);
			val.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, new HarmonyMethod(methodInfo5), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo6, (HarmonyMethod)null, new HarmonyMethod(methodInfo7), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
			HDRenderPipelineAsset val2 = (HDRenderPipelineAsset)(object)((currentRenderPipeline is HDRenderPipelineAsset) ? currentRenderPipeline : null);
			if ((Object)(object)val2 != (Object)null)
			{
				RenderPipelineSettings currentPlatformRenderPipelineSettings = val2.currentPlatformRenderPipelineSettings;
				currentPlatformRenderPipelineSettings.supportWater = true;
				val2.currentPlatformRenderPipelineSettings = currentPlatformRenderPipelineSettings;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Water support applied to the HDRenderPipelineAsset.");
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"HDRenderPipelineAsset not found.");
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"PluginName: LethalExpansion, VersionString: 1.3.37 is loaded.");
		}

		private List<PluginInfo> GetLoadedPlugins()
		{
			return Chainloader.PluginInfos.Values.ToList();
		}

		private float[,] GenerateHeights()
		{
			float[,] array = new float[width, height];
			for (int i = 0; i < width; i++)
			{
				for (int j = 0; j < height; j++)
				{
					array[i, j] = CalculateHeight(i, j);
				}
			}
			return array;
		}

		private float CalculateHeight(int x, int y)
		{
			float num = (float)x / (float)width * scale;
			float num2 = (float)y / (float)height * scale;
			return Mathf.PerlinNoise(num, num2);
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03da: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e4: Expected O, but got Unknown
			//IL_040f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0427: Unknown result type (might be due to invalid IL or missing references)
			//IL_042e: Expected O, but got Unknown
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Expected O, but got Unknown
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0781: Unknown result type (might be due to invalid IL or missing references)
			//IL_0770: Unknown result type (might be due to invalid IL or missing references)
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Loading scene: " + ((Scene)(ref scene)).name));
			if (((Scene)(ref scene)).name == "MainMenu")
			{
				sessionWaiting = true;
				hostDataWaiting = true;
				ishost = false;
				alreadypatched = false;
				dungeonGeneratorReady = false;
				delayedLevelChange = -1;
				isInGame = false;
				AssetGather.Instance.AddAudioMixer(GameObject.Find("Canvas/MenuManager").GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer);
				SettingsMenu.Instance.InitSettingsMenu();
				if (lastKickReason != null && lastKickReason.Length > 0)
				{
					PopupManager.Instance.InstantiatePopup(scene, "Kicked from Lobby", "You have been kicked\r\nReason: " + lastKickReason, "Ok", "Ignore");
				}
				if (!ConfigManager.Instance.FindEntryValue<bool>("CoomfyDungeonCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "CoomfyDungeon"))
				{
					PopupManager instance = PopupManager.Instance;
					Scene sceneFocus = scene;
					object obj = <>c.<>9__31_0;
					if (obj == null)
					{
						UnityAction val = delegate
						{
							ConfigManager.Instance.SetItemValue("CoomfyDungeonCompatibility", value: true);
							ConfigManager.Instance.SetEntryValue("CoomfyDungeonCompatibility", value: true);
						};
						<>c.<>9__31_0 = val;
						obj = (object)val;
					}
					instance.InstantiatePopup(sceneFocus, "CoomfyDungeon mod found", "Warning: CoomfyDungeon is incompatible with LethalExpansion, Would you like to enable the compatibility mode? Otherwise dungeon generation Desync may occurs!", "Yes", "No", (UnityAction)obj, null, 20, 18);
				}
				if (loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "BiggerLobby"))
				{
					PopupManager.Instance.InstantiatePopup(scene, "BiggerLobby mod found", "Warning: BiggerLobby is incompatible with LethalExpansion, host/client synchronization will break and dungeon generation Desync may occurs!", "Ok", "Ignore", null, null, 20, 18);
				}
			}
			if (((Scene)(ref scene)).name == "CompanyBuilding")
			{
				if ((Object)(object)SpaceLight != (Object)null)
				{
					SpaceLight.SetActive(false);
				}
				if ((Object)(object)terrainfixer != (Object)null)
				{
					terrainfixer.SetActive(false);
				}
				dungeonGeneratorReady = true;
			}
			if (((Scene)(ref scene)).name == "SampleSceneRelay")
			{
				SpaceLight = Object.Instantiate<GameObject>(AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Prefabs/SpaceLight.prefab"));
				SceneManager.MoveGameObjectToScene(SpaceLight, scene);
				Mesh mesh = AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Meshes/MonitorWall.fbx").GetComponent<MeshFilter>().mesh;
				GameObject val2 = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube");
				val2.GetComponent<MeshFilter>().mesh = mesh;
				MeshRenderer component = val2.GetComponent<MeshRenderer>();
				GameObject val3 = Object.Instantiate<GameObject>(GameObject.Find("Systems/GameSystems/TimeAndWeather/Flooding"));
				Object.Destroy((Object)(object)val3.GetComponent<FloodWeather>());
				((Object)val3).name = "WaterSurface";
				val3.transform.position = Vector3.zero;
				((Component)val3.transform.Find("Water")).GetComponent<MeshFilter>().sharedMesh = null;
				SpawnPrefab.Instance.waterSurface = val3;
				((Renderer)component).materials = (Material[])(object)new Material[9]
				{
					((Renderer)component).materials[0],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[2]
				};
				((Component)StartOfRound.Instance.screenLevelDescription).gameObject.AddComponent<AutoScrollText>();
				AssetGather.Instance.AddAudioMixer(GameObject.Find("Systems/Audios/DiageticBackground").GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer);
				terrainfixer = new GameObject();
				((Object)terrainfixer).name = "terrainfixer";
				terrainfixer.transform.position = new Vector3(0f, -500f, 0f);
				Terrain val4 = terrainfixer.AddComponent<Terrain>();
				TerrainData val5 = new TerrainData();
				val5.heightmapResolution = width + 1;
				val5.size = new Vector3((float)width, (float)depth, (float)height);
				val5.SetHeights(0, 0, GenerateHeights());
				val4.terrainData = val5;
				Terminal_Patch.ResetFireExitAmounts();
				Object[] array = Resources.FindObjectsOfTypeAll(typeof(Volume));
				for (int i = 0; i < array.Length; i++)
				{
					Object obj2 = array[i];
					if ((Object)(object)((Volume)((obj2 is Volume) ? obj2 : null)).sharedProfile == (Object)null)
					{
						Object obj3 = array[i];
						((Volume)((obj3 is Volume) ? obj3 : null)).sharedProfile = AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<VolumeProfile>("Assets/Mods/LethalExpansion/Sky and Fog Global Volume Profile.asset");
					}
				}
				waitForSession().GetAwaiter();
				isInGame = true;
			}
			if (((Scene)(ref scene)).name.StartsWith("Level"))
			{
				if ((Object)(object)SpaceLight != (Object)null)
				{
					SpaceLight.SetActive(false);
				}
				if ((Object)(object)terrainfixer != (Object)null)
				{
					terrainfixer.SetActive(false);
				}
				dungeonGeneratorReady = true;
				if (ConfigManager.Instance.FindItemValue<bool>("SettingsDebug"))
				{
					foreach (ConfigItem item in ConfigManager.Instance.GetAll())
					{
						Log.LogInfo((object)"==========");
						Log.LogInfo((object)item.Key);
						Log.LogInfo(item.Value);
						Log.LogInfo(item.DefaultValue);
						Log.LogInfo((object)item.Sync);
					}
				}
			}
			if (!(((Scene)(ref scene)).name == "InitSceneLaunchOptions") || !isInGame)
			{
				return;
			}
			if ((Object)(object)SpaceLight != (Object)null)
			{
				SpaceLight.SetActive(false);
			}
			if ((Object)(object)terrainfixer != (Object)null)
			{
				terrainfixer.SetActive(false);
			}
			GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects();
			foreach (GameObject val6 in rootGameObjects)
			{
				val6.SetActive(false);
			}
			if (ConfigManager.Instance.FindItemValue<bool>("SettingsDebug"))
			{
				foreach (ConfigItem item2 in ConfigManager.Instance.GetAll())
				{
					Log.LogInfo((object)"==========");
					Log.LogInfo((object)item2.Key);
					Log.LogInfo(item2.Value);
					Log.LogInfo(item2.DefaultValue);
					Log.LogInfo((object)item2.Sync);
				}
			}
			if (ConfigManager.Instance.FindItemValue<bool>("LegacyMoonLoading"))
			{
				LoadCustomMoon(scene).RunSynchronously();
			}
			else
			{
				LoadCustomMoon(scene).GetAwaiter();
			}
		}

		private async Task LoadCustomMoon(Scene scene)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			await Task.Delay(400);
			try
			{
				if ((Object)(object)Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab != (Object)null && (Object)(object)Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab.transform != (Object)null)
				{
					CheckRiskyComponents(Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab.transform, Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MoonName);
					GameObject mainPrefab = Object.Instantiate<GameObject>(Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab);
					currentWaterSurface = mainPrefab.transform.Find("Environment/Water");
					if ((Object)(object)mainPrefab != (Object)null)
					{
						SceneManager.MoveGameObjectToScene(mainPrefab, scene);
						Transform DiageticBackground = mainPrefab.transform.Find("Systems/Audio/DiageticBackground");
						if ((Object)(object)DiageticBackground != (Object)null)
						{
							((Component)DiageticBackground).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null);
						}
						Terrain[] Terrains = mainPrefab.GetComponentsInChildren<Terrain>();
						if (Terrains != null && Terrains.Length != 0)
						{
							Terrain[] array = Terrains;
							foreach (Terrain terrain in array)
							{
								terrain.drawInstanced = true;
							}
						}
					}
				}
				string[] _tmp = new string[5] { "MapPropsContainer", "OutsideAINode", "SpawnDenialPoint", "ItemShipLandingNode", "OutsideLevelNavMesh" };
				string[] array2 = _tmp;
				foreach (string s in array2)
				{
					if ((Object)(object)GameObject.FindGameObjectWithTag(s) == (Object)null || GameObject.FindGameObjectsWithTag(s).Any(delegate(GameObject o)
					{
						//IL_0001: Unknown result type (might be due to invalid IL or missing references)
						//IL_0006: Unknown result type (might be due to invalid IL or missing references)
						Scene scene2 = o.scene;
						return ((Scene)(ref scene2)).name != "InitSceneLaunchOptions";
					}))
					{
						GameObject obj = new GameObject();
						((Object)obj).name = s;
						obj.tag = s;
						obj.transform.position = new Vector3(0f, -200f, 0f);
						SceneManager.MoveGameObjectToScene(obj, scene);
					}
				}
				await Task.Delay(200);
				GameObject DropShip = GameObject.Find("ItemShipAnimContainer");
				if ((Object)(object)DropShip != (Object)null)
				{
					Transform ItemShip = DropShip.transform.Find("ItemShip");
					if ((Object)(object)ItemShip != (Object)null)
					{
						((Component)ItemShip).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null);
					}
					Transform ItemShipMusicClose = DropShip.transform.Find("ItemShip/Music");
					if ((Object)(object)ItemShipMusicClose != (Object)null)
					{
						((Component)ItemShipMusicClose).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null);
					}
					Transform ItemShipMusicFar = DropShip.transform.Find("ItemShip/Music/Music (1)");
					if ((Object)(object)ItemShipMusicFar != (Object)null)
					{
						((Component)ItemShipMusicFar).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null);
					}
				}
				await Task.Delay(200);
				RuntimeDungeon runtimeDungeon2 = Object.FindObjectOfType<RuntimeDungeon>(false);
				if ((Object)(object)runtimeDungeon2 == (Object)null)
				{
					GameObject dungeonGenerator = new GameObject();
					((Object)dungeonGenerator).name = "DungeonGenerator";
					dungeonGenerator.tag = "DungeonGenerator";
					dungeonGenerator.transform.position = new Vector3(0f, -200f, 0f);
					runtimeDungeon2 = dungeonGenerator.AddComponent<RuntimeDungeon>();
					runtimeDungeon2.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0];
					runtimeDungeon2.Generator.LengthMultiplier = 0.8f;
					runtimeDungeon2.Generator.PauseBetweenRooms = 0.2f;
					runtimeDungeon2.GenerateOnStart = false;
					runtimeDungeon2.Root = dungeonGenerator;
					runtimeDungeon2.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0];
					UnityNavMeshAdapter dungeonNavMesh = dungeonGenerator.AddComponent<UnityNavMeshAdapter>();
					dungeonNavMesh.BakeMode = (RuntimeNavMeshBakeMode)3;
					dungeonNavMesh.LayerMask = LayerMask.op_Implicit(35072);
					SceneManager.MoveGameObjectToScene(dungeonGenerator, scene);
				}
				else if ((Object)(object)runtimeDungeon2.Generator.DungeonFlow == (Object)null)
				{
					runtimeDungeon2.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0];
				}
				dungeonGeneratorReady = true;
				GameObject OutOfBounds = GameObject.CreatePrimitive((PrimitiveType)3);
				((Object)OutOfBounds).name = "OutOfBounds";
				OutOfBounds.layer = 13;
				OutOfBounds.transform.position = new Vector3(0f, -300f, 0f);
				OutOfBounds.transform.localScale = new Vector3(1000f, 5f, 1000f);
				BoxCollider boxCollider = OutOfBounds.GetComponent<BoxCollider>();
				((Collider)boxCollider).isTrigger = true;
				OutOfBounds.AddComponent<OutOfBoundsTrigger>();
				Rigidbody rigidbody = OutOfBounds.AddComponent<Rigidbody>();
				rigidbody.useGravity = false;
				rigidbody.isKinematic = true;
				rigidbody.collisionDetectionMode = (CollisionDetectionMode)1;
				SceneManager.MoveGameObjectToScene(OutOfBounds, scene);
				await Task.Delay(200);
			}
			catch (Exception ex2)
			{
				Exception ex = ex2;
				Log.LogError((object)ex);
			}
		}

		private void CheckRiskyComponents(Transform root, string objname)
		{
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			try
			{
				Component[] components = ((Component)root).GetComponents<Component>();
				Component[] array = components;
				foreach (Component component in array)
				{
					if (!ComponentWhitelists.mainWhitelist.Any((Type whitelistType) => ((object)component).GetType() == whitelistType))
					{
						Log.LogWarning((object)(((object)component).GetType().Name + " component is not native of Unity or LethalSDK. It can contains malwares. From " + objname + "."));
					}
				}
				foreach (Transform item in root)
				{
					Transform root2 = item;
					CheckRiskyComponents(root2, objname);
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)ex.Message);
			}
		}

		private void OnSceneUnloaded(Scene scene)
		{
			if (((Scene)(ref scene)).name.Length > 0)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Unloading scene: " + ((Scene)(ref scene)).name));
			}
			if (((Scene)(ref scene)).name.StartsWith("Level") || ((Scene)(ref scene)).name == "CompanyBuilding" || (((Scene)(ref scene)).name == "InitSceneLaunchOptions" && isInGame))
			{
				if ((Object)(object)SpaceLight != (Object)null)
				{
					SpaceLight.SetActive(true);
				}
				if ((Object)(object)currentWaterSurface != (Object)null)
				{
					currentWaterSurface = null;
				}
				dungeonGeneratorReady = false;
				Terminal_Patch.ResetFireExitAmounts();
			}
		}

		private async Task waitForSession()
		{
			while (sessionWaiting)
			{
				await Task.Delay(1000);
			}
			for (int i = 0; i < ConfigManager.Instance.GetAll().Count; i++)
			{
				if (ConfigManager.Instance.MustBeSync(i))
				{
					ConfigManager.Instance.SetItemValue(i, ConfigManager.Instance.FindEntryValue(i));
				}
			}
			bool patchGlobalTimeSpeedMultiplier = true;
			bool patchNumberOfHours = true;
			bool patchDeadlineDaysAmount = true;
			bool patchStartingQuota = true;
			bool patchStartingCredits = true;
			bool patchBaseIncrease = true;
			bool patchIncreaseSteepness = true;
			bool patchScrapValueMultiplier = true;
			bool patchScrapAmountMultiplier = true;
			bool patchMapSizeMultiplier = true;
			bool patchMaxShipItemCapacity = true;
			if (ConfigManager.Instance.FindItemValue<bool>("BrutalCompanyPlusCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "BrutalCompanyPlus"))
			{
				patchDeadlineDaysAmount = false;
				patchStartingQuota = false;
				patchStartingCredits = false;
				patchBaseIncrease = false;
				patchIncreaseSteepness = false;
			}
			if (ConfigManager.Instance.FindItemValue<bool>("LethalAdjustmentsCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "LethalAdjustments"))
			{
				patchScrapValueMultiplier = false;
				patchScrapAmountMultiplier = false;
				patchMapSizeMultiplier = false;
			}
			if (ConfigManager.Instance.FindItemValue<bool>("CoomfyDungeonCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "CoomfyDungeon"))
			{
				patchScrapAmountMultiplier = false;
				patchMapSizeMultiplier = false;
			}
			if (ConfigManager.Instance.FindItemValue<bool>("MoreMoneyStartCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "299792458.MoreMoneyStart"))
			{
				patchStartingCredits = false;
			}
			if (ConfigManager.Instance.FindItemValue<bool>("ExtraDaysToDeadline") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "ExtraDaysToDeadline"))
			{
				patchDeadlineDaysAmount = false;
			}
			if (ConfigManager.Instance.FindItemValue<bool>("AdvancedCompanyCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "AdvancedCompany"))
			{
				patchGlobalTimeSpeedMultiplier = false;
				patchStartingCredits = false;
				patchScrapValueMultiplier = false;
				patchScrapAmountMultiplier = false;
				patchMapSizeMultiplier = false;
			}
			if (patchGlobalTimeSpeedMultiplier)
			{
				TimeOfDay.Instance.globalTimeSpeedMultiplier = ConfigManager.Instance.FindItemValue<float>("GlobalTimeSpeedMultiplier");
			}
			if (patchNumberOfHours)
			{
				TimeOfDay.Instance.numberOfHours = ConfigManager.Instance.FindItemValue<int>("NumberOfHours");
			}
			if (patchDeadlineDaysAmount)
			{
				TimeOfDay.Instance.quotaVariables.deadlineDaysAmount = ConfigManager.Instance.FindItemValue<int>("DeadlineDaysAmount");
			}
			if (patchStartingQuota)
			{
				TimeOfDay.Instance.quotaVariables.startingQuota = ConfigManager.Instance.FindItemValue<int>("StartingQuota");
			}
			if (patchStartingCredits)
			{
				TimeOfDay.Instance.quotaVariables.startingCredits = ConfigManager.Instance.FindItemValue<int>("StartingCredits");
			}
			if (patchBaseIncrease)
			{
				TimeOfDay.Instance.quotaVariables.baseIncrease = ConfigManager.Instance.FindItemValue<int>("QuotaBaseIncrease");
			}
			if (patchIncreaseSteepness)
			{
				TimeOfDay.Instance.quotaVariables.increaseSteepness = ConfigManager.Instance.FindItemValue<int>("QuotaIncreaseSteepness");
			}
			if (patchScrapValueMultiplier)
			{
				RoundManager.Instance.scrapValueMultiplier = ConfigManager.Instance.FindItemValue<float>("ScrapValueMultiplier");
			}
			if (patchScrapAmountMultiplier)
			{
				RoundManager.Instance.scrapAmountMultiplier = ConfigManager.Instance.FindItemValue<float>("ScrapAmountMultiplier");
			}
			if (patchMapSizeMultiplier)
			{
				RoundManager.Instance.mapSizeMultiplier = ConfigManager.Instance.FindItemValue<float>("MapSizeMultiplier");
			}
			if (patchMaxShipItemCapacity)
			{
				StartOfRound.Instance.maxShipItemCapacity = ConfigManager.Instance.FindItemValue<int>("MaxItemsInShip");
			}
			if (!alreadypatched)
			{
				Terminal_Patch.MainPatch(GameObject.Find("TerminalScript").GetComponent<Terminal>());
				alreadypatched = true;
			}
			if (!ishost)
			{
				while (!sessionWaiting && hostDataWaiting)
				{
					NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.request, "hostconfig", string.Empty, 0L);
					await Task.Delay(3000);
				}
				Terminal_Patch.MainPatchPostConfig(GameObject.Find("TerminalScript").GetComponent<Terminal>());
			}
		}

		private void ConfigSettingChanged(object sender, EventArgs e)
		{
			SettingChangedEventArgs val = (SettingChangedEventArgs)(object)((e is SettingChangedEventArgs) ? e : null);
			if (val != null)
			{
				Log.LogInfo((object)$"{val.ChangedSetting.Definition.Key} Changed to {val.ChangedSetting.BoxedValue}");
			}
		}
	}
}
namespace LethalExpansion.Utils
{
	public class AssetBundlesManager
	{
		private static AssetBundlesManager _instance;

		public AssetBundle mainAssetBundle = AssetBundle.LoadFromFile(Assembly.GetExecutingAssembly().Location.Replace("LethalExpansion.dll", "lethalexpansion.lem"));

		public Dictionary<string, (AssetBundle, ModManifest)> assetBundles = new Dictionary<string, (AssetBundle, ModManifest)>();

		public readonly string[] forcedNative = new string[1] { "lethalexpansion" };

		public DirectoryInfo modPath = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);

		public DirectoryInfo modDirectory;

		public DirectoryInfo pluginsDirectory;

		public static AssetBundlesManager Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new AssetBundlesManager();
				}
				return _instance;
			}
		}

		public (AssetBundle, ModManifest) Load(string name)
		{
			return assetBundles[name.ToLower()];
		}

		public void LoadAllAssetBundles()
		{
			modDirectory = modPath.Parent;
			pluginsDirectory = modDirectory;
			while (pluginsDirectory != null && pluginsDirectory.Name != "plugins")
			{
				pluginsDirectory = pluginsDirectory.Parent;
			}
			if (pluginsDirectory != null)
			{
				LethalExpansion.Log.LogInfo((object)("Plugins folder found: " + pluginsDirectory.FullName));
				LethalExpansion.Log.LogInfo((object)("Mod path is: " + modDirectory.FullName));
				if (modDirectory.FullName == pluginsDirectory.FullName)
				{
					LethalExpansion.Log.LogWarning((object)("LethalExpansion is Rooting the Plugins folder, this is not recommended. " + modDirectory.FullName));
				}
				string[] files = Directory.GetFiles(pluginsDirectory.FullName, "*.lem", SearchOption.AllDirectories);
				foreach (string file in files)
				{
					LoadBundle(file);
				}
			}
			else
			{
				LethalExpansion.Log.LogWarning((object)"Mod is not in a plugins folder.");
			}
		}

		public void LoadBundle(string file)
		{
			if (forcedNative.Contains<string>(Path.GetFileNameWithoutExtension(file)) && !file.Contains(modDirectory.FullName))
			{
				LethalExpansion.Log.LogWarning((object)("Illegal usage of reserved Asset Bundle name: " + Path.GetFileNameWithoutExtension(file) + " at: " + file + "."));
			}
			else
			{
				if (!(Path.GetFileName(file) != "lethalexpansion.lem"))
				{
					return;
				}
				if (!assetBundles.ContainsKey(Path.GetFileNameWithoutExtension(file)))
				{
					Stopwatch stopwatch = new Stopwatch();
					AssetBundle val = null;
					try
					{
						stopwatch.Start();
						val = AssetBundle.LoadFromFile(file);
						stopwatch.Stop();
					}
					catch (Exception ex)
					{
						LethalExpansion.Log.LogError((object)ex);
					}
					if ((Object)(object)val != (Object)null)
					{
						string text = "Assets/Mods/" + Path.GetFileNameWithoutExtension(file) + "/ModManifest.asset";
						ModManifest modManifest = val.LoadAsset<ModManifest>(text);
						if ((Object)(object)modManifest != (Object)null)
						{
							if (forcedNative.Contains(modManifest.modName.ToLower()) && !file.Contains(modDirectory.FullName))
							{
								LethalExpansion.Log.LogWarning((object)("Illegal usage of reserved Mod name: " + modManifest.modName));
								val.Unload(true);
								LethalExpansion.Log.LogInfo((object)("AssetBundle unloaded: " + Path.GetFileName(file)));
							}
							else if (!assetBundles.Any((KeyValuePair<string, (AssetBundle, ModManifest)> b) => b.Value.Item2.modName == modManifest.modName))
							{
								LethalExpansion.Log.LogInfo((object)string.Format("Module found: {0} v{1} Loaded in {2}ms", modManifest.modName, (modManifest.GetVersion() != null) ? ((object)modManifest.GetVersion()).ToString() : "0.0.0.0", stopwatch.ElapsedMilliseconds));
								if (modManifest.GetVersion() == null || ((object)modManifest.GetVersion()).ToString() == "0.0.0.0")
								{
									LethalExpansion.Log.LogWarning((object)("Module " + modManifest.modName + " have no version number, this is unsafe!"));
								}
								assetBundles.Add(Path.GetFileNameWithoutExtension(file).ToLower(), (val, modManifest));
							}
							else
							{
								LethalExpansion.Log.LogWarning((object)("Another mod with same name is already loaded: " + modManifest.modName));
								val.Unload(true);
								LethalExpansion.Log.LogInfo((object)("AssetBundle unloaded: " + Path.GetFileName(file)));
							}
						}
						else
						{
							LethalExpansion.Log.LogWarning((object)("AssetBundle have no ModManifest: " + Path.GetFileName(file)));
							val.Unload(true);
							LethalExpansion.Log.LogInfo((object)("AssetBundle unloaded: " + Path.GetFileName(file)));
						}
					}
					else
					{
						LethalExpansion.Log.LogWarning((object)("File is not an AssetBundle: " + Path.GetFileName(file)));
					}
				}
				else
				{
					LethalExpansion.Log.LogWarning((object)("AssetBundle with same name already loaded: " + Path.GetFileName(file)));
				}
			}
		}

		public bool BundleLoaded(string bundleName)
		{
			return assetBundles.ContainsKey(bundleName.ToLower());
		}

		public bool BundlesLoaded(string[] bundleNames)
		{
			foreach (string text in bundleNames)
			{
				if (!assetBundles.ContainsKey(text.ToLower()))
				{
					return false;
				}
			}
			return true;
		}

		public bool IncompatibleBundlesLoaded(string[] bundleNames)
		{
			foreach (string text in bundleNames)
			{
				if (assetBundles.ContainsKey(text.ToLower()))
				{
					return true;
				}
			}
			return false;
		}
	}
	public class AssetGather
	{
		private static AssetGather _instance;

		public Dictionary<string, AudioClip> audioClips = new Dictionary<string, AudioClip>();

		public Dictionary<string, (AudioMixer, AudioMixerGroup[])> audioMixers = new Dictionary<string, (AudioMixer, AudioMixerGroup[])>();

		public Dictionary<string, GameObject> planetPrefabs = new Dictionary<string, GameObject>();

		public Dictionary<string, GameObject> mapObjects = new Dictionary<string, GameObject>();

		public Dictionary<string, SpawnableOutsideObject> outsideObjects = new Dictionary<string, SpawnableOutsideObject>();

		public Dictionary<string, Item> scraps = new Dictionary<string, Item>();

		public Dictionary<string, LevelAmbienceLibrary> levelAmbiances = new Dictionary<string, LevelAmbienceLibrary>();

		public Dictionary<string, EnemyType> enemies = new Dictionary<string, EnemyType>();

		public Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();

		public static AssetGather Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new AssetGather();
				}
				return _instance;
			}
		}

		public void GetList()
		{
			LethalExpansion.Log.LogInfo((object)"===Audio Clips===");
			foreach (KeyValuePair<string, AudioClip> audioClip in audioClips)
			{
				LethalExpansion.Log.LogInfo((object)audioClip.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Audio Mixers===");
			foreach (KeyValuePair<string, (AudioMixer, AudioMixerGroup[])> audioMixer in audioMixers)
			{
				LethalExpansion.Log.LogInfo((object)audioMixer.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Planet Prefabs===");
			foreach (KeyValuePair<string, GameObject> planetPrefab in planetPrefabs)
			{
				LethalExpansion.Log.LogInfo((object)planetPrefab.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Map Objects===");
			foreach (KeyValuePair<string, GameObject> mapObject in mapObjects)
			{
				LethalExpansion.Log.LogInfo((object)mapObject.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Outside Objects===");
			foreach (KeyValuePair<string, SpawnableOutsideObject> outsideObject in outsideObjects)
			{
				LethalExpansion.Log.LogInfo((object)outsideObject.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Scraps===");
			foreach (KeyValuePair<string, Item> scrap in scraps)
			{
				LethalExpansion.Log.LogInfo((object)scrap.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Level Ambiances===");
			foreach (KeyValuePair<string, LevelAmbienceLibrary> levelAmbiance in levelAmbiances)
			{
				LethalExpansion.Log.LogInfo((object)levelAmbiance.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Enemies===");
			foreach (KeyValuePair<string, EnemyType> enemy in enemies)
			{
				LethalExpansion.Log.LogInfo((object)enemy.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Sprites===");
			foreach (KeyValuePair<string, Sprite> sprite in sprites)
			{
				LethalExpansion.Log.LogInfo((object)sprite.Key);
			}
		}

		public void AddAudioClip(AudioClip clip)
		{
			if ((Object)(object)clip != (Object)null && !audioClips.ContainsKey(((Object)clip).name) && !audioClips.ContainsValue(clip))
			{
				audioClips.Add(((Object)clip).name, clip);
			}
		}

		public void AddAudioClip(string name, AudioClip clip)
		{
			if ((Object)(object)clip != (Object)null && !audioClips.ContainsKey(name) && !audioClips.ContainsValue(clip))
			{
				audioClips.Add(name, clip);
			}
		}

		public void AddAudioClip(AudioClip[] clips)
		{
			foreach (AudioClip val in clips)
			{
				if ((Object)(object)val != (Object)null && !audioClips.ContainsKey(((Object)val).name) && !audioClips.ContainsValue(val))
				{
					audioClips.Add(((Object)val).name, val);
				}
			}
		}

		public void AddAudioClip(string[] names, AudioClip[] clips)
		{
			for (int i = 0; i < clips.Length && i < names.Length; i++)
			{
				if ((Object)(object)clips[i] != (Object)null && !audioClips.ContainsKey(names[i]) && !audioClips.ContainsValue(clips[i]))
				{
					audioClips.Add(names[i], clips[i]);
				}
			}
		}

		public void AddAudioMixer(AudioMixer mixer)
		{
			if (!((Object)(object)mixer != (Object)null) || audioMixers.ContainsKey(((Object)mixer).name))
			{
				return;
			}
			List<AudioMixerGroup> list = new List<AudioMixerGroup>();
			AudioMixerGroup[] array = mixer.FindMatchingGroups(string.Empty);
			foreach (AudioMixerGroup val in array)
			{
				if ((Object)(object)val != (Object)null && !list.Contains(val))
				{
					list.Add(val);
				}
			}
			audioMixers.Add(((Object)mixer).name, (mixer, list.ToArray()));
		}

		public void AddPlanetPrefabs(GameObject prefab)
		{
			if ((Object)(object)prefab != (Object)null && !planetPrefabs.ContainsKey(((Object)prefab).name) && !planetPrefabs.ContainsValue(prefab))
			{
				planetPrefabs.Add(((Object)prefab).name, prefab);
			}
		}

		public void AddPlanetPrefabs(string name, GameObject prefab)
		{
			if ((Object)(object)prefab != (Object)null && !planetPrefabs.ContainsKey(name) && !planetPrefabs.ContainsValue(prefab))
			{
				planetPrefabs.Add(name, prefab);
			}
		}

		public void AddMapObjects(GameObject mapObject)
		{
			if ((Object)(object)mapObject != (Object)null && !mapObjects.ContainsKey(((Object)mapObject).name) && !mapObjects.ContainsValue(mapObject))
			{
				mapObjects.Add(((Object)mapObject).name, mapObject);
			}
		}

		public void AddOutsideObject(SpawnableOutsideObject outsideObject)
		{
			if ((Object)(object)outsideObject != (Object)null && !outsideObjects.ContainsKey(((Object)outsideObject).name) && !outsideObjects.ContainsValue(outsideObject))
			{
				outsideObjects.Add(((Object)outsideObject).name, outsideObject);
			}
		}

		public void AddScrap(Item scrap)
		{
			if ((Object)(object)scrap != (Object)null && !scraps.ContainsKey(((Object)scrap).name) && !scraps.ContainsValue(scrap))
			{
				scraps.Add(((Object)scrap).name, scrap);
			}
		}

		public void AddLevelAmbiances(LevelAmbienceLibrary levelAmbiance)
		{
			if ((Object)(object)levelAmbiance != (Object)null && !levelAmbiances.ContainsKey(((Object)levelAmbiance).name) && !levelAmbiances.ContainsValue(levelAmbiance))
			{
				levelAmbiances.Add(((Object)levelAmbiance).name, levelAmbiance);
			}
		}

		public void AddEnemies(EnemyType enemie)
		{
			if ((Object)(object)enemie != (Object)null && !enemies.ContainsKey(((Object)enemie).name) && !enemies.ContainsValue(enemie))
			{
				enemies.Add(((Object)enemie).name, enemie);
			}
		}

		public void AddSprites(Sprite sprite)
		{
			if ((Object)(object)sprite != (Object)null && !sprites.ContainsKey(((Object)sprite).name) && !sprites.ContainsValue(sprite))
			{
				sprites.Add(((Object)sprite).name, sprite);
			}
		}

		public void AddSprites(string name, Sprite sprite)
		{
			if ((Object)(object)sprite != (Object)null && !sprites.ContainsKey(name) && !sprites.ContainsValue(sprite))
			{
				sprites.Add(name, sprite);
			}
		}
	}
	public class ChatMessageProcessor
	{
		public static bool ProcessMessage(string message)
		{
			if (Regex.IsMatch(message, "^\\[sync\\].*\\[sync\\]$"))
			{
				try
				{
					string value = Regex.Match(message, "^\\[sync\\](.*)\\[sync\\]$").Groups[1].Value;
					string[] array = value.Split('|');
					if (array.Length == 3)
					{
						NetworkPacketManager.packetType packetType = (NetworkPacketManager.packetType)int.Parse(array[0]);
						string[] array2 = array[1].Split('>');
						ulong num = ulong.Parse(array2[0]);
						long num2 = long.Parse(array2[1]);
						string[] array3 = array[2].Split('=');
						string header = array3[0];
						string packet = array3[1];
						if (num2 == -1 || num2 == (long)((NetworkBehaviour)RoundManager.Instance).NetworkManager.LocalClientId)
						{
							if (num != 0)
							{
								NetworkPacketManager.Instance.CancelTimeout((long)num);
							}
							LethalExpansion.Log.LogInfo((object)message);
							switch (packetType)
							{
							case NetworkPacketManager.packetType.request:
								ProcessRequest(num, header, packet);
								break;
							case NetworkPacketManager.packetType.data:
								ProcessData(num, header, packet);
								break;
							case NetworkPacketManager.packetType.other:
								LethalExpansion.Log.LogInfo((object)"Unsupported type.");
								break;
							default:
								LethalExpansion.Log.LogInfo((object)"Unrecognized type.");
								break;
							}
						}
					}
					return true;
				}
				catch (Exception ex)
				{
					LethalExpansion.Log.LogError((object)ex);
					return false;
				}
			}
			return false;
		}

		private static void ProcessRequest(ulong sender, string header, string packet)
		{
			try
			{
				switch (header)
				{
				case "clientinfo":
				{
					if (LethalExpansion.ishost || sender != 0)
					{
						break;
					}
					string text2 = LethalExpansion.ModVersion.ToString() + "$";
					foreach (KeyValuePair<string, (AssetBundle, ModManifest)> assetBundle in AssetBundlesManager.Instance.assetBundles)
					{
						text2 = text2 + assetBundle.Key + "v" + ((object)assetBundle.Value.Item2.GetVersion()).ToString() + "&";
					}
					if (text2.EndsWith('&'))
					{
						text2 = text2.Remove(text2.Length - 1);
					}
					NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "clientinfo", text2, 0L);
					break;
				}
				case "hostconfig":
					if (LethalExpansion.ishost && sender != 0)
					{
						NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.request, "clientinfo", string.Empty, (long)sender);
					}
					break;
				case "hostweathers":
					if (LethalExpansion.ishost && sender != 0L && LethalExpansion.weathersReadyToShare)
					{
						string text3 = string.Empty;
						int[] currentWeathers = StartOfRound_Patch.currentWeathers;
						foreach (int num2 in currentWeathers)
						{
							text3 = text3 + num2 + "&";
						}
						if (text3.EndsWith('&'))
						{
							text3 = text3.Remove(text3.Length - 1);
						}
						NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "hostweathers", text3, (long)sender, waitForAnswer: false);
					}
					break;
				case "networkobjectdata":
				{
					if (!LethalExpansion.ishost || sender == 0)
					{
						break;
					}
					string text = string.Empty;
					if (packet.Length > 0 && packet.Contains(','))
					{
						try
						{
							ulong[] array = Array.ConvertAll(packet.Split(','), ulong.Parse);
							ulong[] array2 = array;
							foreach (ulong num in array2)
							{
								text += $"{num}${NetworkDataManager.NetworkData[num].serializedData}&";
							}
							if (text.EndsWith('&'))
							{
								text = text.Remove(text.Length - 1);
							}
						}
						catch (Exception ex)
						{
							LethalExpansion.Log.LogError((object)ex);
							text = "error";
						}
						NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "networkobjectdata", text, (long)sender, waitForAnswer: false);
					}
					else
					{
						LethalExpansion.Log.LogError((object)"networkobjectdata packet error");
						text = "packet error";
					}
					break;
				}
				default:
					LethalExpansion.Log.LogInfo((object)"Unrecognized command.");
					break;
				}
			}
			catch (Exception ex2)
			{
				LethalExpansion.Log.LogError((object)ex2);
			}
		}

		private static void ProcessData(ulong sender, string header, string packet)
		{
			//IL_050b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				switch (header)
				{
				case "clientinfo":
				{
					if (!LethalExpansion.ishost || sender == 0)
					{
						break;
					}
					string[] array2 = ((!packet.Contains('$')) ? new string[1] { packet } : packet.Split('$'));
					string text = string.Empty;
					foreach (KeyValuePair<string, (AssetBundle, ModManifest)> assetBundle in AssetBundlesManager.Instance.assetBundles)
					{
						text = text + assetBundle.Key + "v" + ((object)assetBundle.Value.Item2.GetVersion()).ToString() + "&";
					}
					if (text.Length > 0 && text.EndsWith('&'))
					{
						text = text.Remove(text.Length - 1);
					}
					if (array2[0] != LethalExpansion.ModVersion.ToString())
					{
						if (StartOfRound.Instance.ClientPlayerList.ContainsKey(sender))
						{
							LethalExpansion.Log.LogError((object)$"Kicking {sender} for wrong version.");
							NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "kickreason", "Wrong version.", (long)sender);
							StartOfRound.Instance.KickPlayer(StartOfRound.Instance.ClientPlayerList[sender]);
						}
						break;
					}
					if (array2.Length > 1 && array2[1] != text)
					{
						if (StartOfRound.Instance.ClientPlayerList.ContainsKey(sender))
						{
							LethalExpansion.Log.LogError((object)$"Kicking {sender} for wrong bundles.");
							NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "kickreason", "Wrong bundles.", (long)sender);
							StartOfRound.Instance.KickPlayer(StartOfRound.Instance.ClientPlayerList[sender]);
						}
						break;
					}
					string text2 = string.Empty;
					foreach (ConfigItem item in ConfigManager.Instance.GetAll())
					{
						switch (item.type.Name)
						{
						case "Int32":
							text2 = text2 + "i" + ((int)item.Value).ToString(CultureInfo.InvariantCulture);
							break;
						case "Single":
							text2 = text2 + "f" + ((float)item.Value).ToString(CultureInfo.InvariantCulture);
							break;
						case "Boolean":
							text2 = text2 + "b" + (bool)item.Value;
							break;
						case "String":
							text2 = text2 + "s" + item;
							break;
						}
						text2 += "&";
					}
					if (text2.EndsWith('&'))
					{
						text2 = text2.Remove(text2.Length - 1);
					}
					NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "hostconfig", text2, (long)sender);
					break;
				}
				case "hostconfig":
				{
					if (LethalExpansion.ishost || sender != 0)
					{
						break;
					}
					string[] array6 = packet.Split('&');
					LethalExpansion.Log.LogInfo((object)("Received host config: " + packet));
					for (int k = 0; k < array6.Length; k++)
					{
						if (k < ConfigManager.Instance.GetCount() && ConfigManager.Instance.MustBeSync(k))
						{
							ConfigManager.Instance.SetItemValue(k, array6[k].Substring(1), array6[k][0]);
						}
					}
					LethalExpansion.hostDataWaiting = false;
					LethalExpansion.Log.LogInfo((object)"Updated config");
					break;
				}
				case "hostweathers":
				{
					if (LethalExpansion.ishost || sender != 0)
					{
						break;
					}
					string[] array = packet.Split('&');
					LethalExpansion.Log.LogInfo((object)("Received host weathers: " + packet));
					StartOfRound_Patch.currentWeathers = new int[array.Length];
					for (int i = 0; i < array.Length; i++)
					{
						int result = 0;
						if (int.TryParse(array[i], out result))
						{
							StartOfRound_Patch.currentWeathers[i] = result;
							StartOfRound.Instance.levels[i].currentWeather = (LevelWeatherType)result;
						}
					}
					break;
				}
				case "networkobjectdata":
				{
					if (LethalExpansion.ishost || sender != 0)
					{
						break;
					}
					string[] array3 = ((!packet.Contains('&')) ? new string[1] { packet } : packet.Split('&'));
					try
					{
						string[] array4 = array3;
						foreach (string text3 in array4)
						{
							if (text3.Contains('$'))
							{
								string[] array5 = text3.Split('$');
								ulong result2 = 0uL;
								if (array5.Length >= 2 && ulong.TryParse(array5[0], out result2) && array5[1].Contains(','))
								{
									NetworkDataManager.NetworkData[result2].serializedData = array5[1];
									LethalExpansion.Log.LogDebug((object)("networkobjectdata: " + array5[0] + " data received " + array5[1]));
								}
								else
								{
									LethalExpansion.Log.LogError((object)("networkobjectdata error " + packet));
								}
							}
							else
							{
								LethalExpansion.Log.LogError((object)("networkobjectdata error " + packet));
							}
						}
						break;
					}
					catch (Exception ex)
					{
						LethalExpansion.Log.LogError((object)ex);
						break;
					}
				}
				case "kickreason":
					if (!LethalExpansion.ishost && sender == 0)
					{
						LethalExpansion.lastKickReason = packet;
					}
					break;
				default:
					LethalExpansion.Log.LogInfo((object)"Unrecognized property.");
					break;
				}
			}
			catch (Exception ex2)
			{
				LethalExpansion.Log.LogError((object)ex2);
			}
		}
	}
	public class ComponentWhitelists
	{
		public static List<Type> mainWhitelist = new List<Type>
		{
			typeof(Transform),
			typeof(MeshFilter),
			typeof(MeshRenderer),
			typeof(SkinnedMeshRenderer),
			typeof(MeshCollider),
			typeof(BoxCollider),
			typeof(SphereCollider),
			typeof(CapsuleCollider),
			typeof(TerrainCollider),
			typeof(WheelCollider),
			typeof(ArticulationBody),
			typeof(ConstantForce),
			typeof(ConfigurableJoint),
			typeof(FixedJoint),
			typeof(HingeJoint),
			typeof(Cloth),
			typeof(Rigidbody),
			typeof(NetworkObject),
			typeof(NetworkRigidbody),
			typeof(NetworkTransform),
			typeof(NetworkAnimator),
			typeof(Animator),
			typeof(Animation),
			typeof(Terrain),
			typeof(Tree),
			typeof(WindZone),
			typeof(DecalProjector),
			typeof(LODGroup),
			typeof(Light),
			typeof(HDAdditionalLightData),
			typeof(LightProbeGroup),
			typeof(LightProbeProxyVolume),
			typeof(LocalVolumetricFog),
			typeof(OcclusionArea),
			typeof(OcclusionPortal),
			typeof(ReflectionProbe),
			typeof(PlanarReflectionProbe),
			typeof(HDAdditionalReflectionData),
			typeof(Skybox),
			typeof(SortingGroup),
			typeof(SpriteRenderer),
			typeof(Volume),
			typeof(AudioSource),
			typeof(AudioReverbZone),
			typeof(AudioReverbFilter),
			typeof(AudioChorusFilter),
			typeof(AudioDistortionFilter),
			typeof(AudioEchoFilter),
			typeof(AudioHighPassFilter),
			typeof(AudioLowPassFilter),
			typeof(AudioListener),
			typeof(LensFlare),
			typeof(TrailRenderer),
			typeof(LineRenderer),
			typeof(ParticleSystem),
			typeof(ParticleSystemRenderer),
			typeof(ParticleSystemForceField),
			typeof(Projector),
			typeof(VideoPlayer),
			typeof(NavMeshSurface),
			typeof(NavMeshModifier),
			typeof(NavMeshModifierVolume),
			typeof(NavMeshLink),
			typeof(NavMeshObstacle),
			typeof(OffMeshLink),
			typeof(SI_AudioReverbPresets),
			typeof(SI_AudioReverbTrigger),
			typeof(SI_DungeonGenerator),
			typeof(SI_MatchLocalPlayerPosition),
			typeof(SI_AnimatedSun),
			typeof(SI_EntranceTeleport),
			typeof(SI_ScanNode),
			typeof(SI_DoorLock),
			typeof(SI_WaterSurface),
			typeof(SI_Ladder),
			typeof(SI_ItemDropship),
			typeof(SI_NetworkPrefabInstancier),
			typeof(SI_InteractTrigger),
			typeof(SI_DamagePlayer),
			typeof(SI_SoundYDistance),
			typeof(SI_AudioOutputInterface),
			typeof(SI_NetworkDataInterfacing),
			typeof(SI_NetworkData),
			typeof(TerrainChecker),
			typeof(PlayerShip)
		};
	}
	public class ConfigManager
	{
		private static ConfigManager _instance;

		private List<ConfigItem> items = new List<ConfigItem>();

		private List<ConfigEntryBase> entries = new List<ConfigEntryBase>();

		public static ConfigManager Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new ConfigManager();
				}
				return _instance;
			}
		}

		public void AddItem(ConfigItem item)
		{
			try
			{
				items.Add(item);
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
			}
		}

		public void ReadConfig()
		{
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Expected O, but got Unknown
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Expected O, but got Unknown
			//IL_0308: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Expected O, but got Unknown
			items = (from item in items
				orderby item.Tab, item.Key
				select item).ToList();
			try
			{
				for (int i = 0; i < items.Count; i++)
				{
					if (!items[i].Hidden)
					{
						string description = items[i].Description;
						description = description + "\nNetwork synchronization: " + (items[i].Sync ? "Yes" : "No");
						description = description + "\nMod required by clients: " + (items[i].Optional ? "No" : "Yes");
						switch (items[i].type.Name)
						{
						case "Int32":
							entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<int>(items[i].Tab, items[i].Key, (int)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<int>((int)items[i].MinValue, (int)items[i].MaxValue), Array.Empty<object>())));
							break;
						case "Single":
							entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<float>(items[i].Tab, items[i].Key, (float)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<float>((float)items[i].MinValue, (float)items[i].MaxValue), Array.Empty<object>())));
							break;
						case "Boolean":
							entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<bool>(items[i].Tab, items[i].Key, (bool)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())));
							break;
						case "String":
							entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<string>(items[i].Tab, items[i].Key, (string)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())));
							break;
						}
						if (!items[i].Sync)
						{
							items[i].Value = entries.Last().BoxedValue;
						}
					}
					else
					{
						entries.Add(null);
					}
				}
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
			}
		}

		public object FindItemValue(string key)
		{
			try
			{
				return items.First((ConfigItem item) => item.Key == key).Value;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public object FindItemValue(int index)
		{
			try
			{
				return items[index].Value;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public object FindEntryValue(string key)
		{
			try
			{
				return entries.First((ConfigEntryBase item) => item.Definition.Key == key).BoxedValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public object FindEntryValue(int index)
		{
			try
			{
				return entries[index].BoxedValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public bool RequireRestart(string key)
		{
			try
			{
				return items.First((ConfigItem item) => item.Key == key).RequireRestart;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public bool RequireRestart(int index)
		{
			try
			{
				return items[index].RequireRestart;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public string FindDescription(string key)
		{
			try
			{
				return items.First((ConfigItem item) => item.Key == key).Description;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public string FindDescription(int index)
		{
			try
			{
				return items[index].Description;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public (bool, bool) FindNetInfo(string key)
		{
			try
			{
				ConfigItem configItem = items.First((ConfigItem item) => item.Key == key);
				return (configItem.Sync, configItem.Optional);
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return (false, false);
			}
		}

		public (bool, bool) FindNetInfo(int index)
		{
			try
			{
				return (items[index].Sync, items[index].Optional);
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return (false, false);
			}
		}

		public object FindDefaultValue(string key)
		{
			try
			{
				return items.First((ConfigItem item) => item.Key == key).DefaultValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public object FindDefaultValue(int index)
		{
			try
			{
				return items[index].DefaultValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public bool MustBeSync(string key)
		{
			try
			{
				return items.First((ConfigItem item) => item.Key == key).Sync;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return true;
			}
		}

		public bool MustBeSync(int index)
		{
			try
			{
				return items[index].Sync;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return true;
			}
		}

		public bool SetItemValue(string key, object value)
		{
			ConfigItem configItem = items.First((ConfigItem item) => item.Key == key);
			if (!items.First((ConfigItem item) => item.Key == key).RequireRestart)
			{
				try
				{
					configItem.Value = value;
					return true;
				}
				catch (Exception ex)
				{
					LethalExpansion.Log.LogError((object)ex.Message);
					return false;
				}
			}
			return false;
		}

		public bool SetEntryValue(string key, object value)
		{
			try
			{
				entries.First((ConfigEntryBase item) => item.Definition.Key == key).BoxedValue = value;
				return true;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public bool SetItemValue(int index, string value, char type)
		{
			if (!items[index].RequireRestart)
			{
				try
				{
					switch (type)
					{
					case 'i':
						items[index].Value = int.Parse(value, CultureInfo.InvariantCulture);
						break;
					case 'f':
						items[index].Value = float.Parse(value, CultureInfo.InvariantCulture);
						break;
					case 'b':
						items[index].Value = bool.Parse(value);
						break;
					case 's':
						items[index].Value = value;
						break;
					}
					return true;
				}
				catch (Exception ex)
				{
					LethalExpansion.Log.LogError((object)ex.Message);
					return false;
				}
			}
			return false;
		}

		public bool SetEntryValue(int index, string value, char type)
		{
			try
			{
				switch (type)
				{
				case 'i':
					entries[index].BoxedValue = int.Parse(value);
					break;
				case 'f':
					entries[index].BoxedValue = float.Parse(value);
					break;
				case 'b':
					entries[index].BoxedValue = bool.Parse(value);
					break;
				case 's':
					entries[index].BoxedValue = value;
					break;
				}
				return true;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public (object, int) FindValueAndIndex(string key)
		{
			try
			{
				return (items.First((ConfigItem item) => item.Key == key).Value, items.FindIndex((ConfigItem item) => item.Key == key));
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return (null, -1);
			}
		}

		public int FindIndex(string key)
		{
			try
			{
				return items.FindIndex((ConfigItem item) => item.Key == key);
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return -1;
			}
		}

		public T FindItemValue<T>(string key)
		{
			try
			{
				ConfigItem configItem = items.First((ConfigItem item) => item.Key == key);
				if (configItem != null && configItem.Value is T)
				{
					return (T)configItem.Value;
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return default(T);
			}
		}

		public T FindItemValue<T>(int index)
		{
			try
			{
				ConfigItem configItem = items[index];
				if (configItem != null && configItem.Value is T)
				{
					return (T)configItem.Value;
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return default(T);
			}
		}

		public T FindEntryValue<T>(string key)
		{
			try
			{
				ConfigEntryBase val = entries.First((ConfigEntryBase item) => item.Definition.Key == key);
				if (val != null && val.BoxedValue is T)
				{
					return (T)val.BoxedValue;
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return default(T);
			}
		}

		public T FindEntryValue<T>(int index)
		{
			try
			{
				ConfigEntryBase val = entries[index];
				if (val != null && val.BoxedValue is T)
				{
					return (T)val.BoxedValue;
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return default(T);
			}
		}

		public bool SetItemValue<T>(string key, T value)
		{
			ConfigItem configItem = items.First((ConfigItem item) => item.Key == key);
			if (!configItem.RequireRestart)
			{
				try
				{
					if (configItem == null || !(configItem.Value is T))
					{
						LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
						throw new InvalidOperationException("Key not found or value is of incorrect type");
					}
					configItem.Value = value;
					return true;
				}
				catch (Exception ex)
				{
					LethalExpansion.Log.LogError((object)ex.Message);
					return false;
				}
			}
			return false;
		}

		public bool SetEntryValue<T>(string key, T value)
		{
			try
			{
				ConfigEntryBase val = entries.First((ConfigEntryBase item) => item.Definition.Key == key);
				if (val != null && val.BoxedValue is T)
				{
					val.BoxedValue = value;
					return true;
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public bool SetItemValue<T>(int index, T value)
		{
			if (!items[index].RequireRestart)
			{
				try
				{
					items[index].Value = value;
					return true;
				}
				catch (Exception ex)
				{
					LethalExpansion.Log.LogError((object)ex.Message);
					return false;
				}
			}
			return false;
		}

		public bool SetEntryValue<T>(int index, T value)
		{
			try
			{
				entries[index].BoxedValue = value;
				return true;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public (T, int) FindValueAndIndex<T>(string key)
		{
			try
			{
				ConfigItem configItem = items.First((ConfigItem item) => item.Key == key);
				if (configItem != null && configItem.Value is T)
				{
					return ((T)configItem.Value, items.FindIndex((ConfigItem item) => item.Key == key));
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return (default(T), -1);
			}
		}

		public List<ConfigItem> GetAll()
		{
			try
			{
				return items;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public int GetCount()
		{
			try
			{
				return items.Count;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return -1;
			}
		}

		public int GetEntriesCount()
		{
			try
			{
				return entries.Count;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return -1;
			}
		}

		public object ReadConfigValue(string key)
		{
			try
			{
				return entries[FindIndex(key)].BoxedValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public T ReadConfigValue<T>(string key)
		{
			try
			{
				return (T)entries[FindIndex(key)].BoxedValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return default(T);
			}
		}

		public bool WriteConfigValue(string key, object value)
		{
			try
			{
				int index = FindIndex(key);
				SetItemValue(index, value);
				entries[index].BoxedValue = value;
				return true;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public bool WriteConfigValue<T>(string key, T value)
		{
			try
			{
				int index = FindIndex(key);
				SetItemValue(index, value);
				entries[index].BoxedValue = value;
				return true;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}
	}
	public static class ModUtils
	{
		public static T[] RemoveElementFromArray<T>(T[] originalArray, int indexToRemove)
		{
			if (indexToRemove < 0 || indexToRemove >= originalArray.Length)
			{
				throw new ArgumentOutOfRangeException("indexToRemove");
			}
			T[] array = new T[originalArray.Length - 1];
			int i = 0;
			int num = 0;
			for (; i < originalArray.Length; i++)
			{
				if (i != indexToRemove)
				{
					array[num] = originalArray[i];
					num++;
				}
			}
			return array;
		}
	}
	public class NetworkPacketManager
	{
		public enum packetType
		{
			request = 0,
			data = 1,
			other = -1
		}

		private static NetworkPacketManager _instance;

		private ConcurrentDictionary<long, CancellationTokenSource> timeoutDictionary = new ConcurrentDictionary<long, CancellationTokenSource>();

		public static NetworkPacketManager Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new NetworkPacketManager();
				}
				return _instance;
			}
		}

		private NetworkPacketManager()
		{
		}

		public void sendPacket(packetType type, string header, string packet, long destination = -1L, bool waitForAnswer = true)
		{
			HUDManager.Instance.AddTextToChatOnServer($"[sync]{(int)type}|{((NetworkBehaviour)RoundManager.Instance).NetworkManager.LocalClientId}>{destination}|{header}={packet}[sync]", -1);
			if ((waitForAnswer && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && ConfigManager.Instance.FindItemValue<bool>("LoadModules")) || ConfigManager.Instance.FindItemValue<bool>("KickPlayerWithoutMod"))
			{
				StartTimeout(destination);
			}
		}

		public void sendPacket(packetType type, string header, string packet, long[] destinations, bool waitForAnswer = true)
		{
			for (int i = 0; i < destinations.Length; i++)
			{
				int num = (int)destinations[i];
				if (num != -1)
				{
					HUDManager.Instance.AddTextToChatOnServer($"[sync]{(int)type}|{((NetworkBehaviour)RoundManager.Instance).NetworkManager.LocalClientId}>{num}|{header}={packet}[sync]", -1);
					if ((waitForAnswer && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && ConfigManager.Instance.FindItemValue<bool>("LoadModules")) || ConfigManager.Instance.FindItemValue<bool>("KickPlayerWithoutMod"))
					{
						StartTimeout(num);
					}
				}
			}
		}

		public void StartTimeout(long id)
		{
			CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
			if (!timeoutDictionary.TryAdd(id, cancellationTokenSource))
			{
				return;
			}
			Task.Run(async delegate
			{
				try
				{
					await PacketTimeout(id, cancellationTokenSource.Token);
				}
				catch (OperationCanceledException)
				{
				}
				finally
				{
					timeoutDictionary.TryRemove(id, out var _);
				}
			});
		}

		public void CancelTimeout(long id)
		{
			if (timeoutDictionary.TryRemove(id, out var value))
			{
				value.Cancel();
			}
		}

		private async Task PacketTimeout(long id, CancellationToken token)
		{
			await Task.Delay(5000, token);
			if (token.IsCancellationRequested)
			{
			}
		}
	}
	public class PopupManager
	{
		private static PopupManager _instance;

		private List<PopupObject> popups = new List<PopupObject>();

		public static PopupManager Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new PopupManager();
				}
				return _instance;
			}
		}

		private PopupManager()
		{
		}

		public void InstantiatePopup(Scene sceneFocus, string title = "Popup", string content = "", string button1 = "Ok", string button2 = "Cancel", UnityAction button1Action = null, UnityAction button2Action = null, int titlesize = 24, int contentsize = 24, int button1size = 24, int button2size = 24)
		{
			//IL_0067: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Expected O, but got Unknown
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Expected O, but got Unknown
			if (!((Scene)(ref sceneFocus)).isLoaded)
			{
				return;
			}
			GameObject[] rootGameObjects = ((Scene)(ref sceneFocus)).GetRootGameObjects();
			Canvas val = null;
			GameObject[] array = rootGameObjects;
			foreach (GameObject val2 in array)
			{
				val = val2.GetComponentInChildren<Canvas>();
				if ((Object)(object)val != (Object)null)
				{
					break;
				}
			}
			if ((Object)(object)val == (Object)null || ((Component)val).gameObject.scene != sceneFocus)
			{
				GameObject val3 = new GameObject();
				((Object)val3).name = "Canvas";
				val = val3.AddComponent<Canvas>();
				SceneManager.MoveGameObjectToScene(((Component)val).gameObject, sceneFocus);
			}
			GameObject _tmp = Object.Instantiate<GameObject>(AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Prefabs/HUD/Popup.prefab"), ((Component)val).transform);
			if ((Object)(object)_tmp != (Object)null)
			{
				((Component)_tmp.transform.Find("DragAndDropSurface")).gameObject.AddComponent<SettingMenu_DragAndDrop>().rectTransform = _tmp.GetComponent<RectTransform>();
				((UnityEvent)((Component)_tmp.transform.Find("CloseButton")).gameObject.GetComponent<Button>().onClick).AddListener((UnityAction)delegate
				{
					Object.Destroy((Object)(object)_tmp);
				});
				if (button1Action != null)
				{
					((UnityEvent)((Component)_tmp.transform.Find("Button1")).gameObject.GetComponent<Button>().onClick).AddListener(button1Action);
				}
				if (button2Action != null)
				{
					((UnityEvent)((Component)_tmp.transform.Find("Button2")).gameObject.GetCompone

plugins/LethalLevelLoader.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 System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLevelLoader.NetcodePatcher;
using LethalLevelLoader.Tools;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using On;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("LethalLevelLoader")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("A Custom API to support the manual and dynamic integration of custom levels and dungeons in Lethal Company.")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+e4357129de2bfee0b9a624c989c1b553463f153f")]
[assembly: AssemblyProduct("LethalLevelLoader")]
[assembly: AssemblyTitle("LethalLevelLoader")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public enum ContentType
{
	Vanilla,
	Custom,
	Any
}
internal static class HookHelper
{
	public class DisposableHookCollection
	{
		private List<ILHook> ilHooks = new List<ILHook>();

		private List<Hook> hooks = new List<Hook>();

		public void Clear()
		{
			foreach (Hook hook in hooks)
			{
				hook.Dispose();
			}
			hooks.Clear();
			foreach (ILHook ilHook in ilHooks)
			{
				ilHook.Dispose();
			}
			ilHooks.Clear();
		}

		public void ILHook<T>(string methodName, Manipulator to, Type[] parameters = null)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			ilHooks.Add(new ILHook((MethodBase)EzGetMethod<T>(methodName, parameters), to));
		}

		public void Hook<T>(string methodName, Delegate to, Type[] parameters = null)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			hooks.Add(new Hook((MethodBase)EzGetMethod<T>(methodName, parameters), to));
		}
	}

	public static MethodInfo methodof(Delegate method)
	{
		return method.Method;
	}

	public static MethodInfo EzGetMethod(Type type, string name, Type[] parameters = null)
	{
		BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
		if (parameters == null)
		{
			return type.GetMethod(name, bindingAttr);
		}
		return type.GetMethod(name, bindingAttr, null, parameters, null);
	}

	public static MethodInfo EzGetMethod<T>(string name, Type[] parameters = null)
	{
		return EzGetMethod(typeof(T), name, parameters);
	}
}
public static class NetworkScenePatcher
{
	[CompilerGenerated]
	private static class <>O
	{
		public static Action<Action<NetworkSceneManager>, NetworkSceneManager> <0>__GenerateScenesInBuild_Hook;

		public static Func<Func<NetworkSceneManager, uint, string>, NetworkSceneManager, uint, string> <1>__SceneNameFromHash_Hook;

		public static Func<Func<NetworkSceneManager, int, string, LoadSceneMode, bool>, NetworkSceneManager, int, string, LoadSceneMode, bool> <2>__ValidateSceneBeforeLoading_Hook;

		public static Manipulator <3>__ReplaceBuildIndexByScenePath;

		public static Manipulator <4>__ReplaceScenePathByBuildIndex;

		public static Func<int, string> <5>__GetScenePathByBuildIndex;

		public static Func<string, int> <6>__GetBuildIndexByScenePath;
	}

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

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

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

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

	private static HookHelper.DisposableHookCollection hooks = new HookHelper.DisposableHookCollection();

	internal static bool patched { get; private set; }

	public static void AddScenePath(string scenePath)
	{
		if (scenePaths.Contains(scenePath))
		{
			Debug.LogError((object)("Can not add scene path " + scenePath + " to the network scene patcher! (already exists in scene paths list)"));
		}
		else
		{
			scenePaths.Add(scenePath);
		}
	}

	internal static void Patch()
	{
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Expected O, but got Unknown
		//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)
		//IL_0117: Expected O, but got Unknown
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Expected O, but got Unknown
		if (!patched)
		{
			patched = true;
			hooks.Hook<NetworkSceneManager>("GenerateScenesInBuild", new Action<Action<NetworkSceneManager>, NetworkSceneManager>(GenerateScenesInBuild_Hook));
			hooks.Hook<NetworkSceneManager>("SceneNameFromHash", new Func<Func<NetworkSceneManager, uint, string>, NetworkSceneManager, uint, string>(SceneNameFromHash_Hook));
			hooks.Hook<NetworkSceneManager>("ValidateSceneBeforeLoading", new Func<Func<NetworkSceneManager, int, string, LoadSceneMode, bool>, NetworkSceneManager, int, string, LoadSceneMode, bool>(ValidateSceneBeforeLoading_Hook), new Type[3]
			{
				typeof(int),
				typeof(string),
				typeof(LoadSceneMode)
			});
			HookHelper.DisposableHookCollection disposableHookCollection = hooks;
			object obj = <>O.<3>__ReplaceBuildIndexByScenePath;
			if (obj == null)
			{
				Manipulator val = ReplaceBuildIndexByScenePath;
				<>O.<3>__ReplaceBuildIndexByScenePath = val;
				obj = (object)val;
			}
			disposableHookCollection.ILHook<NetworkSceneManager>("SceneHashFromNameOrPath", (Manipulator)obj);
			HookHelper.DisposableHookCollection disposableHookCollection2 = hooks;
			object obj2 = <>O.<3>__ReplaceBuildIndexByScenePath;
			if (obj2 == null)
			{
				Manipulator val2 = ReplaceBuildIndexByScenePath;
				<>O.<3>__ReplaceBuildIndexByScenePath = val2;
				obj2 = (object)val2;
			}
			disposableHookCollection2.ILHook<NetworkSceneManager>("ValidateSceneEvent", (Manipulator)obj2);
			HookHelper.DisposableHookCollection disposableHookCollection3 = hooks;
			object obj3 = <>O.<4>__ReplaceScenePathByBuildIndex;
			if (obj3 == null)
			{
				Manipulator val3 = ReplaceScenePathByBuildIndex;
				<>O.<4>__ReplaceScenePathByBuildIndex = val3;
				obj3 = (object)val3;
			}
			disposableHookCollection3.ILHook<NetworkSceneManager>("ScenePathFromHash", (Manipulator)obj3);
		}
	}

	internal static void Unpatch()
	{
		if (patched)
		{
			patched = false;
			hooks.Clear();
		}
	}

	private static void ReplaceScenePathByBuildIndex(ILContext il)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		ILCursor val = new ILCursor(il);
		MethodInfo methodInfo = HookHelper.methodof(new Func<int, string>(GetScenePathByBuildIndex));
		while (val.TryGotoNext(new Func<Instruction, bool>[1]
		{
			(Instruction instr) => ILPatternMatchingExt.MatchCall(instr, typeof(SceneUtility), "GetScenePathByBuildIndex")
		}))
		{
			val.Remove();
			val.Emit(OpCodes.Call, (MethodBase)methodInfo);
		}
	}

	private static void ReplaceBuildIndexByScenePath(ILContext il)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		ILCursor val = new ILCursor(il);
		MethodInfo methodInfo = HookHelper.methodof(new Func<string, int>(GetBuildIndexByScenePath));
		while (val.TryGotoNext(new Func<Instruction, bool>[1]
		{
			(Instruction instr) => ILPatternMatchingExt.MatchCall(instr, typeof(SceneUtility), "GetBuildIndexByScenePath")
		}))
		{
			val.Remove();
			val.Emit(OpCodes.Call, (MethodBase)methodInfo);
		}
	}

	private static string GetScenePathByBuildIndex(int buildIndex)
	{
		if (buildIndexToScenePath.ContainsKey(buildIndex))
		{
			return buildIndexToScenePath[buildIndex];
		}
		return SceneUtility.GetScenePathByBuildIndex(buildIndex);
	}

	private static int GetBuildIndexByScenePath(string scenePath)
	{
		int num = SceneUtility.GetBuildIndexByScenePath(scenePath);
		if (num == -1 && scenePathToBuildIndex.ContainsKey(scenePath))
		{
			num = scenePathToBuildIndex[scenePath];
		}
		return num;
	}

	private static void GenerateScenesInBuild_Hook(Action<NetworkSceneManager> orig, NetworkSceneManager self)
	{
		scenePathToBuildIndex.Clear();
		buildIndexToScenePath.Clear();
		sceneHashToScenePath.Clear();
		orig(self);
		int sceneCountInBuildSettings = SceneManager.sceneCountInBuildSettings;
		for (int i = 0; i < scenePaths.Count; i++)
		{
			int num = sceneCountInBuildSettings + i;
			string text = scenePaths[i];
			uint num2 = XXHash.Hash32(text);
			self.HashToBuildIndex.Add(num2, num);
			self.BuildIndexToHash.Add(num, num2);
			scenePathToBuildIndex.Add(text, num);
			buildIndexToScenePath.Add(num, text);
			sceneHashToScenePath.Add(num2, text);
			Debug.Log((object)("Added modded scene path: " + text));
		}
	}

	private static string SceneNameFromHash_Hook(Func<NetworkSceneManager, uint, string> orig, NetworkSceneManager self, uint sceneHash)
	{
		if (sceneHash == 0)
		{
			return "No Scene";
		}
		if (sceneHashToScenePath.ContainsKey(sceneHash))
		{
			return sceneHashToScenePath[sceneHash];
		}
		return orig(self, sceneHash);
	}

	private static bool ValidateSceneBeforeLoading_Hook(Func<NetworkSceneManager, int, string, LoadSceneMode, bool> orig, NetworkSceneManager self, int sceneIndex, string sceneName, LoadSceneMode loadSceneMode)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		Debug.LogWarning((object)(orig(self, sceneIndex, sceneName, loadSceneMode) ? ("Validation check success for scene: " + sceneName) : ("Bypassed validation check for scene " + sceneName)));
		return true;
	}
}
namespace LethalLevelLoader
{
	[CreateAssetMenu(menuName = "LethalLevelLoader/ExtendedDungeonFlow")]
	public class ExtendedDungeonFlow : ScriptableObject
	{
		[Header("Extended DungeonFlow Settings")]
		public string contentSourceName = string.Empty;

		[Space(5f)]
		public string dungeonDisplayName = string.Empty;

		[Space(5f)]
		public DungeonFlow dungeonFlow;

		[Space(5f)]
		public AudioClip dungeonFirstTimeAudio;

		[Space(10f)]
		[Header("Dynamic DungeonFlow Injections Settings")]
		public List<StringWithRarity> dynamicLevelTagsList = new List<StringWithRarity>();

		[Space(5f)]
		public List<Vector2WithRarity> dynamicRoutePricesList = new List<Vector2WithRarity>();

		[Space(5f)]
		public List<StringWithRarity> dynamicCurrentWeatherList = new List<StringWithRarity>();

		[Space(5f)]
		public List<StringWithRarity> manualPlanetNameReferenceList = new List<StringWithRarity>();

		[Space(5f)]
		public List<StringWithRarity> manualContentSourceNameReferenceList = new List<StringWithRarity>();

		[Space(10f)]
		[Header("Dynamic Dungeon Size Multiplier Lerp Settings")]
		public bool enableDynamicDungeonSizeRestriction = false;

		public float dungeonSizeMin = 1f;

		public float dungeonSizeMax = 1f;

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

		[Space(10f)]
		[Header("Dynamic DungeonFlow Modification Settings")]
		public List<GlobalPropCountOverride> globalPropCountOverridesList = new List<GlobalPropCountOverride>();

		[Space(10f)]
		[Header("Misc. Settings")]
		public bool generateAutomaticConfigurationOptions = true;

		[Space(10f)]
		[Header("Experimental Settings (Currently Unused As Of LethalLevelLoader 1.1.0")]
		public GameObject mainEntrancePropPrefab;

		[Space(5f)]
		public GameObject fireExitPropPrefab;

		[Space(5f)]
		public Animator mainEntrancePropAnimator;

		[Space(5f)]
		public Animator fireExitPropAnimator;

		[HideInInspector]
		public ContentType dungeonType;

		[HideInInspector]
		public int dungeonID;

		[HideInInspector]
		public int dungeonDefaultRarity;

		[HideInInspector]
		public DungeonEvents dungeonEvents = new DungeonEvents();

		internal static ExtendedDungeonFlow Create(DungeonFlow newDungeonFlow, AudioClip newFirstTimeDungeonAudio, string contentSourceName)
		{
			ExtendedDungeonFlow extendedDungeonFlow = ScriptableObject.CreateInstance<ExtendedDungeonFlow>();
			extendedDungeonFlow.dungeonFlow = newDungeonFlow;
			extendedDungeonFlow.dungeonFirstTimeAudio = newFirstTimeDungeonAudio;
			extendedDungeonFlow.contentSourceName = contentSourceName;
			return extendedDungeonFlow;
		}

		internal void Initialize(ContentType newDungeonType)
		{
			dungeonType = newDungeonType;
			GetDungeonFlowID();
			if (dungeonDisplayName == null || dungeonDisplayName == string.Empty)
			{
				dungeonDisplayName = ((Object)dungeonFlow).name;
			}
			((Object)this).name = ((Object)dungeonFlow).name.Replace("Flow", "") + "ExtendedDungeonFlow";
			if ((Object)(object)dungeonFirstTimeAudio == (Object)null)
			{
				DebugHelper.Log("Warning, Custom Dungeon: " + dungeonDisplayName + " Is Missing A DungeonFirstTimeAudio Reference! Assigning Facility Audio To Prevent Errors.");
				dungeonFirstTimeAudio = RoundManager.Instance.firstTimeDungeonAudios[0];
			}
		}

		private void GetDungeonFlowID()
		{
			if (dungeonType == ContentType.Custom)
			{
				dungeonID = PatchedContent.ExtendedDungeonFlows.Count;
			}
			if (dungeonType == ContentType.Vanilla)
			{
				dungeonID = RoundManager.Instance.dungeonFlowTypes.ToList().IndexOf(dungeonFlow);
			}
		}
	}
	[Serializable]
	public class StringWithRarity
	{
		[SerializeField]
		private string _name;

		[SerializeField]
		[Range(0f, 300f)]
		private int _rarity;

		[HideInInspector]
		public string Name
		{
			get
			{
				return _name;
			}
			set
			{
				_name = value;
			}
		}

		[HideInInspector]
		public int Rarity
		{
			get
			{
				return _rarity;
			}
			set
			{
				_rarity = value;
			}
		}

		[HideInInspector]
		public StringWithRarity(string newName, int newRarity)
		{
			_name = newName;
			_rarity = newRarity;
		}
	}
	[Serializable]
	public class Vector2WithRarity
	{
		[SerializeField]
		private Vector2 _minMax;

		[SerializeField]
		private int _rarity;

		[HideInInspector]
		public float Min
		{
			get
			{
				return _minMax.x;
			}
			set
			{
				_minMax.x = value;
			}
		}

		[HideInInspector]
		public float Max
		{
			get
			{
				return _minMax.y;
			}
			set
			{
				_minMax.y = value;
			}
		}

		[HideInInspector]
		public int Rarity
		{
			get
			{
				return _rarity;
			}
			set
			{
				_rarity = value;
			}
		}

		public Vector2WithRarity(Vector2 vector2, int newRarity)
		{
			//IL_000e: 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)
			_minMax.x = vector2.x;
			_minMax.y = vector2.y;
			_rarity = newRarity;
		}

		public Vector2WithRarity(float newMin, float newMax, int newRarity)
		{
			_minMax.x = newMin;
			_minMax.y = newMax;
			_rarity = newRarity;
		}
	}
	[Serializable]
	public class GlobalPropCountOverride
	{
		public int globalPropID;

		[Range(0f, 1f)]
		public float globalPropCountScaleRate = 0f;
	}
	[Serializable]
	public class DungeonEvents
	{
		public ExtendedEvent<RoundManager> onBeforeDungeonGenerate = new ExtendedEvent<RoundManager>();

		public ExtendedEvent<List<GameObject>> onSpawnedSyncedObjects = new ExtendedEvent<List<GameObject>>();

		public ExtendedEvent<List<GameObject>> onSpawnedMapObjects = new ExtendedEvent<List<GameObject>>();

		public ExtendedEvent<List<GrabbableObject>> onSpawnedScrapObjects = new ExtendedEvent<List<GrabbableObject>>();

		public ExtendedEvent<(EnemyVent, EnemyAI)> onEnemySpawnedFromVent = new ExtendedEvent<(EnemyVent, EnemyAI)>();

		public ExtendedEvent<(EntranceTeleport, PlayerControllerB)> onPlayerEnterDungeon = new ExtendedEvent<(EntranceTeleport, PlayerControllerB)>();

		public ExtendedEvent<(EntranceTeleport, PlayerControllerB)> onPlayerExitDungeon = new ExtendedEvent<(EntranceTeleport, PlayerControllerB)>();

		public ExtendedEvent<bool> onPowerSwitchToggle = new ExtendedEvent<bool>();

		public ExtendedEvent<LungProp> onApparatusTaken = new ExtendedEvent<LungProp>();
	}
	[CreateAssetMenu(menuName = "LethalLevelLoader/ExtendedLevel")]
	public class ExtendedLevel : ScriptableObject
	{
		[Header("Extended Level Settings")]
		[Space(5f)]
		public string contentSourceName = string.Empty;

		[Space(5f)]
		public SelectableLevel selectableLevel;

		[Space(5f)]
		[SerializeField]
		private int routePrice = 0;

		[Space(5f)]
		public bool isHidden = false;

		[Space(5f)]
		public bool isLocked = false;

		[Space(5f)]
		public string lockedNodeText = string.Empty;

		[Space(10f)]
		public List<StoryLogData> storyLogs = new List<StoryLogData>();

		[Space(10f)]
		[Header("Dynamic DungeonFlow Injections Settings")]
		[Space(5f)]
		public ContentType allowedDungeonContentTypes = ContentType.Any;

		[Space(5f)]
		public List<string> levelTags = new List<string>();

		[HideInInspector]
		public ContentType levelType;

		[SerializeField]
		[TextArea]
		public string infoNodeDescripton = string.Empty;

		[HideInInspector]
		public TerminalNode routeNode;

		[HideInInspector]
		public TerminalNode routeConfirmNode;

		[HideInInspector]
		public TerminalNode infoNode;

		[Space(10f)]
		[Header("Misc. Settings")]
		[Space(5f)]
		public bool generateAutomaticConfigurationOptions = true;

		[HideInInspector]
		public LevelEvents levelEvents = new LevelEvents();

		internal bool isLethalExpansion = false;

		public int RoutePrice
		{
			get
			{
				if ((Object)(object)routeNode != (Object)null)
				{
					routePrice = routeNode.itemCost;
					routeConfirmNode.itemCost = routePrice;
					return routeNode.itemCost;
				}
				DebugHelper.Log("routeNode Is Missing! Using internal value!");
				return routePrice;
			}
			set
			{
				routeNode.itemCost = value;
				routeConfirmNode.itemCost = value;
				routePrice = value;
			}
		}

		[HideInInspector]
		public string NumberlessPlanetName => GetNumberlessPlanetName(selectableLevel);

		public bool IsLoaded
		{
			get
			{
				//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)
				Scene sceneByName = SceneManager.GetSceneByName(selectableLevel.sceneName);
				return ((Scene)(ref sceneByName)).isLoaded;
			}
		}

		internal static ExtendedLevel Create(SelectableLevel newSelectableLevel, ContentType newContentType)
		{
			ExtendedLevel extendedLevel = ScriptableObject.CreateInstance<ExtendedLevel>();
			extendedLevel.levelType = newContentType;
			extendedLevel.selectableLevel = newSelectableLevel;
			return extendedLevel;
		}

		internal void Initialize(string newContentSourceName, bool generateTerminalAssets)
		{
			if (levelType == ContentType.Vanilla && selectableLevel.levelID > 8)
			{
				DebugHelper.LogWarning("LethalExpansion SelectableLevel " + NumberlessPlanetName + " Found, Setting To LevelType: Custom.");
				levelType = ContentType.Custom;
				generateTerminalAssets = true;
				contentSourceName = "Lethal Expansion";
				levelTags.Clear();
				isLethalExpansion = true;
			}
			if (contentSourceName == string.Empty)
			{
				contentSourceName = newContentSourceName;
			}
			if (levelType == ContentType.Custom)
			{
				levelTags.Add("Custom");
			}
			SetLevelID();
			if (generateTerminalAssets)
			{
				DebugHelper.Log("Generating Terminal Assets For: " + NumberlessPlanetName);
				TerminalManager.CreateLevelTerminalData(this, routePrice);
			}
			((Object)this).name = NumberlessPlanetName + "Level";
		}

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

		internal void SetLevelID()
		{
			if (levelType == ContentType.Custom)
			{
				selectableLevel.levelID = PatchedContent.ExtendedLevels.IndexOf(this);
				if ((Object)(object)routeNode != (Object)null)
				{
					routeNode.displayPlanetInfo = selectableLevel.levelID;
				}
				if ((Object)(object)routeConfirmNode != (Object)null)
				{
					routeConfirmNode.buyRerouteToMoon = selectableLevel.levelID;
				}
			}
		}
	}
	[Serializable]
	public class LevelEvents
	{
		public ExtendedEvent onLevelLoaded = new ExtendedEvent();

		public ExtendedEvent onNighttime = new ExtendedEvent();

		public ExtendedEvent<EnemyAI> onDaytimeEnemySpawn = new ExtendedEvent<EnemyAI>();

		public ExtendedEvent<EnemyAI> onNighttimeEnemySpawn = new ExtendedEvent<EnemyAI>();

		public ExtendedEvent<StoryLog> onStoryLogCollected = new ExtendedEvent<StoryLog>();

		public ExtendedEvent<LungProp> onApparatusTaken = new ExtendedEvent<LungProp>();

		public ExtendedEvent<(EntranceTeleport, PlayerControllerB)> onPlayerEnterDungeon = new ExtendedEvent<(EntranceTeleport, PlayerControllerB)>();

		public ExtendedEvent<(EntranceTeleport, PlayerControllerB)> onPlayerExitDungeon = new ExtendedEvent<(EntranceTeleport, PlayerControllerB)>();

		public ExtendedEvent<bool> onPowerSwitchToggle = new ExtendedEvent<bool>();
	}
	[Serializable]
	public class StoryLogData
	{
		public int storyLogID;

		public string terminalWord = string.Empty;

		public string storyLogTitle = string.Empty;

		[TextArea]
		public string storyLogDescription = string.Empty;

		[HideInInspector]
		internal int newStoryLogID;
	}
	public class MoonsCataloguePage
	{
		private List<ExtendedLevelGroup> extendedLevelGroups;

		public List<ExtendedLevelGroup> ExtendedLevelGroups => extendedLevelGroups;

		public List<ExtendedLevel> ExtendedLevels
		{
			get
			{
				List<ExtendedLevel> list = new List<ExtendedLevel>();
				foreach (ExtendedLevelGroup extendedLevelGroup in extendedLevelGroups)
				{
					foreach (ExtendedLevel extendedLevels in extendedLevelGroup.extendedLevelsList)
					{
						list.Add(extendedLevels);
					}
				}
				return list;
			}
		}

		public MoonsCataloguePage(List<ExtendedLevelGroup> newExtendedLevelGroupList)
		{
			extendedLevelGroups = new List<ExtendedLevelGroup>();
			extendedLevelGroups.Clear();
			foreach (ExtendedLevelGroup newExtendedLevelGroup in newExtendedLevelGroupList)
			{
				extendedLevelGroups.Add(new ExtendedLevelGroup(newExtendedLevelGroup.extendedLevelsList));
			}
		}

		public void RebuildLevelGroups(List<ExtendedLevelGroup> newExtendedLevelGroups, int splitCount)
		{
			List<ExtendedLevel> list = new List<ExtendedLevel>();
			foreach (ExtendedLevelGroup extendedLevelGroup in extendedLevelGroups)
			{
				foreach (ExtendedLevel extendedLevels in extendedLevelGroup.extendedLevelsList)
				{
					list.Add(extendedLevels);
				}
			}
			RebuildLevelGroups(list.ToArray(), splitCount);
		}

		public void RebuildLevelGroups(List<ExtendedLevel> newExtendedLevels, int splitCount)
		{
			RebuildLevelGroups(newExtendedLevels.ToArray(), splitCount);
		}

		public void RebuildLevelGroups(IOrderedEnumerable<ExtendedLevel> orderedExtendedLevels, int splitCount)
		{
			RebuildLevelGroups(orderedExtendedLevels.ToArray(), splitCount);
		}

		public void RebuildLevelGroups(ExtendedLevel[] newExtendedLevels, int splitCount)
		{
			List<ExtendedLevelGroup> list = new List<ExtendedLevelGroup>();
			int num = 0;
			int num2 = 0;
			List<ExtendedLevel> list2 = new List<ExtendedLevel>();
			foreach (ExtendedLevel item in new List<ExtendedLevel>(newExtendedLevels))
			{
				list2.Add(item);
				num2++;
				num++;
				if (num == splitCount || num2 == newExtendedLevels.Length)
				{
					list.Add(new ExtendedLevelGroup(list2));
					list2.Clear();
					num = 0;
				}
			}
			extendedLevelGroups = list;
		}

		public void RefreshLevelGroups(List<ExtendedLevelGroup> newLevelGroups)
		{
			extendedLevelGroups.Clear();
			foreach (ExtendedLevelGroup newLevelGroup in newLevelGroups)
			{
				if (newLevelGroup.extendedLevelsList.Count != 0)
				{
					extendedLevelGroups.Add(new ExtendedLevelGroup(newLevelGroup.extendedLevelsList));
				}
			}
		}
	}
	[Serializable]
	public class ExtendedLevelGroup
	{
		public List<ExtendedLevel> extendedLevelsList;

		public ExtendedLevelGroup(List<ExtendedLevel> newExtendedLevelsList)
		{
			extendedLevelsList = new List<ExtendedLevel>(newExtendedLevelsList);
		}

		public ExtendedLevelGroup(List<SelectableLevel> newSelectableLevelsList)
		{
			extendedLevelsList = new List<ExtendedLevel>();
			foreach (SelectableLevel newSelectableLevels in newSelectableLevelsList)
			{
				extendedLevelsList.Add(LevelManager.GetExtendedLevel(newSelectableLevels));
			}
		}
	}
	public static class PatchedContent
	{
		public static List<ExtendedLevel> ExtendedLevels { get; internal set; } = new List<ExtendedLevel>();


		public static List<ExtendedLevel> VanillaExtendedLevels
		{
			get
			{
				List<ExtendedLevel> list = new List<ExtendedLevel>();
				foreach (ExtendedLevel extendedLevel in ExtendedLevels)
				{
					if (extendedLevel.levelType == ContentType.Vanilla)
					{
						list.Add(extendedLevel);
					}
				}
				return list;
			}
		}

		public static List<ExtendedLevel> CustomExtendedLevels
		{
			get
			{
				List<ExtendedLevel> list = new List<ExtendedLevel>();
				foreach (ExtendedLevel extendedLevel in ExtendedLevels)
				{
					if (extendedLevel.levelType == ContentType.Custom)
					{
						list.Add(extendedLevel);
					}
				}
				return list;
			}
		}

		public static List<SelectableLevel> SeletectableLevels
		{
			get
			{
				List<SelectableLevel> list = new List<SelectableLevel>();
				foreach (ExtendedLevel extendedLevel in ExtendedLevels)
				{
					list.Add(extendedLevel.selectableLevel);
				}
				return list;
			}
		}

		public static List<SelectableLevel> MoonsCatalogue
		{
			get
			{
				List<SelectableLevel> list = new List<SelectableLevel>();
				foreach (SelectableLevel item in OriginalContent.MoonsCatalogue)
				{
					list.Add(item);
				}
				foreach (ExtendedLevel extendedLevel in ExtendedLevels)
				{
					if (extendedLevel.levelType == ContentType.Custom)
					{
						list.Add(extendedLevel.selectableLevel);
					}
				}
				return list;
			}
		}

		public static List<ExtendedDungeonFlow> ExtendedDungeonFlows { get; internal set; } = new List<ExtendedDungeonFlow>();


		public static List<ExtendedDungeonFlow> VanillaExtendedDungeonFlows
		{
			get
			{
				List<ExtendedDungeonFlow> list = new List<ExtendedDungeonFlow>();
				foreach (ExtendedDungeonFlow extendedDungeonFlow in ExtendedDungeonFlows)
				{
					if (extendedDungeonFlow.dungeonType == ContentType.Vanilla)
					{
						list.Add(extendedDungeonFlow);
					}
				}
				return list;
			}
		}

		public static List<ExtendedDungeonFlow> CustomExtendedDungeonFlows
		{
			get
			{
				List<ExtendedDungeonFlow> list = new List<ExtendedDungeonFlow>();
				foreach (ExtendedDungeonFlow extendedDungeonFlow in ExtendedDungeonFlows)
				{
					if (extendedDungeonFlow.dungeonType == ContentType.Custom)
					{
						list.Add(extendedDungeonFlow);
					}
				}
				return list;
			}
		}

		public static List<string> AllExtendedLevelTags
		{
			get
			{
				List<string> list = new List<string>();
				foreach (ExtendedLevel extendedLevel in ExtendedLevels)
				{
					foreach (string levelTag in extendedLevel.levelTags)
					{
						if (!list.Contains(levelTag))
						{
							list.Add(levelTag);
						}
					}
				}
				return list;
			}
		}

		public static List<AudioMixer> AudioMixers { get; internal set; } = new List<AudioMixer>();


		public static List<AudioMixerGroup> AudioMixerGroups { get; internal set; } = new List<AudioMixerGroup>();


		public static List<AudioMixerSnapshot> AudioMixerSnapshots { get; internal set; } = new List<AudioMixerSnapshot>();


		public static void RegisterExtendedDungeonFlow(ExtendedDungeonFlow extendedDungeonFlow)
		{
			AssetBundleLoader.obtainedExtendedDungeonFlowsList.Add(extendedDungeonFlow);
		}

		public static void RegisterExtendedLevel(ExtendedLevel extendedLevel)
		{
			AssetBundleLoader.obtainedExtendedLevelsList.Add(extendedLevel);
		}
	}
	public static class OriginalContent
	{
		public static List<SelectableLevel> SelectableLevels { get; internal set; } = new List<SelectableLevel>();


		public static List<SelectableLevel> MoonsCatalogue { get; internal set; } = new List<SelectableLevel>();


		public static List<DungeonFlow> DungeonFlows { get; internal set; } = new List<DungeonFlow>();


		public static List<Item> Items { get; internal set; } = new List<Item>();


		public static List<ItemGroup> ItemGroups { get; internal set; } = new List<ItemGroup>();


		public static List<EnemyType> Enemies { get; internal set; } = new List<EnemyType>();


		public static List<SpawnableOutsideObject> SpawnableOutsideObjects { get; internal set; } = new List<SpawnableOutsideObject>();


		public static List<GameObject> SpawnableMapObjects { get; internal set; } = new List<GameObject>();


		public static List<AudioMixer> AudioMixers { get; internal set; } = new List<AudioMixer>();


		public static List<AudioMixerGroup> AudioMixerGroups { get; internal set; } = new List<AudioMixerGroup>();


		public static List<AudioMixerSnapshot> AudioMixerSnapshots { get; internal set; } = new List<AudioMixerSnapshot>();


		public static List<LevelAmbienceLibrary> LevelAmbienceLibraries { get; internal set; } = new List<LevelAmbienceLibrary>();


		public static List<ReverbPreset> ReverbPresets { get; internal set; } = new List<ReverbPreset>();


		public static List<TerminalKeyword> TerminalKeywords { get; internal set; } = new List<TerminalKeyword>();


		public static List<TerminalNode> TerminalNodes { get; internal set; } = new List<TerminalNode>();

	}
	internal class EventPatches
	{
		private static EnemyVent cachedSelectedVent;

		internal static void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
		{
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null && LevelManager.CurrentExtendedLevel.IsLoaded)
			{
				LevelManager.CurrentExtendedLevel.levelEvents.onLevelLoaded.Invoke();
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(StoryLog), "CollectLog")]
		[HarmonyPrefix]
		internal static void StoryLogCollectLog_Prefix(StoryLog __instance)
		{
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null && ((NetworkBehaviour)__instance).IsServer)
			{
				LevelManager.CurrentExtendedLevel.levelEvents.onStoryLogCollected.Invoke(__instance);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnRandomDaytimeEnemy")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnRandomDaytimeEnemy_Postfix(RoundManager __instance, GameObject __result)
		{
			EnemyAI param = default(EnemyAI);
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null && ((NetworkBehaviour)__instance).IsServer && (Object)(object)__result != (Object)null && __result.TryGetComponent<EnemyAI>(ref param))
			{
				LevelManager.CurrentExtendedLevel.levelEvents.onDaytimeEnemySpawn.Invoke(param);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnRandomOutsideEnemy")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnRandomOutsideEnemy_Postfix(RoundManager __instance, GameObject __result)
		{
			EnemyAI param = default(EnemyAI);
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null && ((NetworkBehaviour)__instance).IsServer && (Object)(object)__result != (Object)null && __result.TryGetComponent<EnemyAI>(ref param))
			{
				LevelManager.CurrentExtendedLevel.levelEvents.onNighttimeEnemySpawn.Invoke(param);
			}
		}

		[HarmonyPriority(201)]
		[HarmonyPatch(typeof(DungeonGenerator), "Generate")]
		[HarmonyPrefix]
		internal static void DungeonGeneratorGenerate_Prefix()
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null)
			{
				DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onBeforeDungeonGenerate.Invoke(RoundManager.Instance);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SwitchPower")]
		[HarmonyPrefix]
		internal static void RoundManagerSwitchPower_Prefix(bool on)
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null)
			{
				DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onPowerSwitchToggle.Invoke(on);
			}
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
			{
				LevelManager.CurrentExtendedLevel.levelEvents.onPowerSwitchToggle.Invoke(on);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnScrapInLevel_Postfix()
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null && DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onSpawnedScrapObjects.HasListeners)
			{
				DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onSpawnedScrapObjects.Invoke(Object.FindObjectsOfType<GrabbableObject>().ToList());
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnSyncedProps")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnSyncedProps_Postfix()
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null && DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onSpawnedSyncedObjects.HasListeners)
			{
				DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onSpawnedSyncedObjects.Invoke(RoundManager.Instance.spawnedSyncedObjects);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnEnemyFromVent")]
		[HarmonyPrefix]
		internal static void RoundManagerSpawnEventFromVent_Prefix(EnemyVent vent)
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null)
			{
				cachedSelectedVent = vent;
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnEnemyGameObject")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnEventFromVent_Postfix()
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null && (Object)(object)cachedSelectedVent != (Object)null)
			{
				DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onEnemySpawnedFromVent.Invoke((cachedSelectedVent, RoundManager.Instance.SpawnedEnemies.Last()));
				cachedSelectedVent = null;
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "SpawnMapObjects")]
		[HarmonyPostfix]
		internal static void RoundManagerSpawnMapObjects_Postfix()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null))
			{
				return;
			}
			List<GameObject> list = new List<GameObject>();
			Scene sceneByName = SceneManager.GetSceneByName(LevelManager.CurrentExtendedLevel.selectableLevel.sceneName);
			GameObject[] rootGameObjects = ((Scene)(ref sceneByName)).GetRootGameObjects();
			foreach (GameObject val in rootGameObjects)
			{
				SpawnableMapObject[] spawnableMapObjects = LevelManager.CurrentExtendedLevel.selectableLevel.spawnableMapObjects;
				foreach (SpawnableMapObject val2 in spawnableMapObjects)
				{
					if (((Object)val).name.Sanitized().Contains(((Object)val2.prefabToSpawn).name.Sanitized()))
					{
						list.Add(val);
					}
				}
			}
			DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onSpawnedMapObjects.Invoke(list);
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(EntranceTeleport), "TeleportPlayerServerRpc")]
		[HarmonyPrefix]
		internal static void EntranceTeleportTeleportPlayerServerRpc_Prefix(EntranceTeleport __instance)
		{
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null)
			{
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if (__instance.isEntranceToBuilding)
				{
					DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onPlayerEnterDungeon.Invoke((__instance, localPlayerController));
				}
				else
				{
					DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onPlayerExitDungeon.Invoke((__instance, localPlayerController));
				}
			}
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
			{
				PlayerControllerB localPlayerController2 = GameNetworkManager.Instance.localPlayerController;
				if (__instance.isEntranceToBuilding)
				{
					LevelManager.CurrentExtendedLevel.levelEvents.onPlayerEnterDungeon.Invoke((__instance, localPlayerController2));
				}
				else
				{
					LevelManager.CurrentExtendedLevel.levelEvents.onPlayerExitDungeon.Invoke((__instance, localPlayerController2));
				}
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(LungProp), "EquipItem")]
		[HarmonyPrefix]
		internal static void LungPropEquipItem_Postfix(LungProp __instance)
		{
			if (((NetworkBehaviour)__instance).IsServer)
			{
				if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null)
				{
					DungeonManager.CurrentExtendedDungeonFlow.dungeonEvents.onApparatusTaken.Invoke(__instance);
				}
				if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
				{
					LevelManager.CurrentExtendedLevel.levelEvents.onApparatusTaken.Invoke(__instance);
				}
			}
		}
	}
	public class ExtendedEvent<T>
	{
		public delegate void ParameterEvent(T param);

		public bool HasListeners => Listeners != 0;

		public int Listeners { get; internal set; }

		private event ParameterEvent onParameterEvent;

		public void Invoke(T param)
		{
			this.onParameterEvent?.Invoke(param);
		}

		public void AddListener(ParameterEvent listener)
		{
			onParameterEvent += listener;
			Listeners++;
		}

		public void RemoveListener(ParameterEvent listener)
		{
			onParameterEvent -= listener;
			Listeners--;
		}
	}
	public class ExtendedEvent
	{
		public delegate void Event();

		public bool HasListeners => Listeners != 0;

		public int Listeners { get; internal set; }

		private event Event onEvent;

		public void Invoke()
		{
			this.onEvent?.Invoke();
		}

		public void AddListener(Event listener)
		{
			onEvent += listener;
			Listeners++;
		}

		public void RemoveListener(Event listener)
		{
			onEvent -= listener;
			Listeners--;
		}
	}
	public static class Extensions
	{
		public static List<Tile> GetTiles(this DungeonFlow dungeonFlow)
		{
			List<Tile> list = new List<Tile>();
			foreach (GraphNode node in dungeonFlow.Nodes)
			{
				foreach (TileSet tileSet in node.TileSets)
				{
					list.AddRange(GetTilesInTileSet(tileSet));
				}
			}
			foreach (GraphLine line in dungeonFlow.Lines)
			{
				foreach (DungeonArchetype dungeonArchetype in line.DungeonArchetypes)
				{
					foreach (TileSet branchCapTileSet in dungeonArchetype.BranchCapTileSets)
					{
						list.AddRange(GetTilesInTileSet(branchCapTileSet));
					}
					foreach (TileSet tileSet2 in dungeonArchetype.TileSets)
					{
						list.AddRange(GetTilesInTileSet(tileSet2));
					}
				}
			}
			foreach (Tile item in new List<Tile>(list))
			{
				if ((Object)(object)item == (Object)null)
				{
					list.Remove(item);
				}
			}
			return list;
		}

		public static List<Tile> GetTilesInTileSet(TileSet tileSet)
		{
			List<Tile> list = new List<Tile>();
			if (tileSet.TileWeights != null && tileSet.TileWeights.Weights != null)
			{
				foreach (GameObjectChance weight in tileSet.TileWeights.Weights)
				{
					Tile[] componentsInChildren = weight.Value.GetComponentsInChildren<Tile>();
					foreach (Tile item in componentsInChildren)
					{
						list.Add(item);
					}
				}
			}
			return list;
		}

		public static List<RandomMapObject> GetRandomMapObjects(this DungeonFlow dungeonFlow)
		{
			List<RandomMapObject> list = new List<RandomMapObject>();
			foreach (Tile tile in dungeonFlow.GetTiles())
			{
				RandomMapObject[] componentsInChildren = ((Component)tile).gameObject.GetComponentsInChildren<RandomMapObject>();
				foreach (RandomMapObject item in componentsInChildren)
				{
					list.Add(item);
				}
			}
			return list;
		}

		public static List<SpawnSyncedObject> GetSpawnSyncedObjects(this DungeonFlow dungeonFlow)
		{
			List<SpawnSyncedObject> list = new List<SpawnSyncedObject>();
			foreach (Tile tile in dungeonFlow.GetTiles())
			{
				Doorway[] componentsInChildren = ((Component)tile).gameObject.GetComponentsInChildren<Doorway>();
				foreach (Doorway val in componentsInChildren)
				{
					foreach (GameObjectWeight connectorPrefabWeight in val.ConnectorPrefabWeights)
					{
						SpawnSyncedObject[] componentsInChildren2 = connectorPrefabWeight.GameObject.GetComponentsInChildren<SpawnSyncedObject>();
						foreach (SpawnSyncedObject item in componentsInChildren2)
						{
							list.Add(item);
						}
					}
					foreach (GameObjectWeight blockerPrefabWeight in val.BlockerPrefabWeights)
					{
						SpawnSyncedObject[] componentsInChildren3 = blockerPrefabWeight.GameObject.GetComponentsInChildren<SpawnSyncedObject>();
						foreach (SpawnSyncedObject item2 in componentsInChildren3)
						{
							list.Add(item2);
						}
					}
				}
				SpawnSyncedObject[] componentsInChildren4 = ((Component)tile).gameObject.GetComponentsInChildren<SpawnSyncedObject>();
				foreach (SpawnSyncedObject item3 in componentsInChildren4)
				{
					list.Add(item3);
				}
			}
			return list;
		}

		public static void AddReferences(this CompatibleNoun compatibleNoun, TerminalKeyword firstNoun, TerminalNode firstResult)
		{
			compatibleNoun.noun = firstNoun;
			compatibleNoun.result = firstResult;
		}

		public static void AddCompatibleNoun(this TerminalKeyword terminalKeyword, TerminalKeyword newNoun, TerminalNode newResult)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			if (terminalKeyword.compatibleNouns == null)
			{
				terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[0];
			}
			CompatibleNoun val = new CompatibleNoun();
			val.noun = newNoun;
			val.result = newResult;
			terminalKeyword.compatibleNouns = CollectionExtensions.AddItem<CompatibleNoun>((IEnumerable<CompatibleNoun>)terminalKeyword.compatibleNouns, val).ToArray();
		}

		public static void AddCompatibleNoun(this TerminalNode terminalNode, TerminalKeyword newNoun, TerminalNode newResult)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			if (terminalNode.terminalOptions == null)
			{
				terminalNode.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[0];
			}
			CompatibleNoun val = new CompatibleNoun();
			val.noun = newNoun;
			val.result = newResult;
			terminalNode.terminalOptions = CollectionExtensions.AddItem<CompatibleNoun>((IEnumerable<CompatibleNoun>)terminalNode.terminalOptions, val).ToArray();
		}

		public static void Add(this IntWithRarity intWithRarity, int id, int rarity)
		{
			intWithRarity.id = id;
			intWithRarity.rarity = rarity;
		}

		public static string Sanitized(this string currentString)
		{
			return new string(currentString.SkipToLetters().RemoveWhitespace().ToLowerInvariant());
		}

		public static string RemoveWhitespace(this string input)
		{
			return new string((from c in input.ToCharArray()
				where !char.IsWhiteSpace(c)
				select c).ToArray());
		}

		public static string SkipToLetters(this string input)
		{
			return new string(input.SkipWhile((char c) => !char.IsLetter(c)).ToArray());
		}
	}
	internal static class Patches
	{
		internal const int harmonyPriority = 200;

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(PreInitSceneScript), "Awake")]
		[HarmonyPrefix]
		internal static void PreInitSceneScriptAwake_Prefix(PreInitSceneScript __instance)
		{
			if (!Plugin.hasVanillaBeenPatched)
			{
				AssetBundleLoader.CreateLoadingBundlesHeaderText(__instance);
				AudioSource val = default(AudioSource);
				if (((Component)__instance).TryGetComponent<AudioSource>(ref val))
				{
					OriginalContent.AudioMixers.Add(val.outputAudioMixerGroup.audioMixer);
				}
				AssetBundleLoader.LoadBundles(__instance);
				AssetBundleLoader.onBundlesFinishedLoading += AssetBundleLoader.LoadContentInBundles;
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(PreInitSceneScript), "ChooseLaunchOption")]
		[HarmonyPrefix]
		internal static bool PreInitSceneScriptChooseLaunchOption_Prefix()
		{
			return AssetBundleLoader.loadedFilesTotal - AssetBundleLoader.loadingAssetBundles.Count == AssetBundleLoader.loadedFilesTotal;
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		[HarmonyPrefix]
		internal static void GameNetworkManagerStart_Prefix(GameNetworkManager __instance)
		{
			if (Plugin.hasVanillaBeenPatched)
			{
				return;
			}
			foreach (NetworkPrefab prefab in ((Component)__instance).GetComponent<NetworkManager>().NetworkConfig.Prefabs.m_Prefabs)
			{
				if (((Object)prefab.Prefab).name.Contains("EntranceTeleport") && (Object)(object)prefab.Prefab.GetComponent<AudioSource>() != (Object)null)
				{
					OriginalContent.AudioMixers.Add(prefab.Prefab.GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer);
				}
			}
			GameObject val = NetworkPrefabs.CreateNetworkPrefab("LethalLevelLoaderNetworkManagerTest");
			val.AddComponent<LethalLevelLoaderNetworkManager>();
			val.GetComponent<NetworkObject>().DontDestroyWithOwner = true;
			val.GetComponent<NetworkObject>().SceneMigrationSynchronization = true;
			val.GetComponent<NetworkObject>().DestroyWithScene = false;
			Object.DontDestroyOnLoad((Object)(object)val);
			LethalLevelLoaderNetworkManager.networkingManagerPrefab = val;
			AssetBundleLoader.RegisterCustomContent(((Component)__instance).GetComponent<NetworkManager>());
			LethalLevelLoaderNetworkManager.RegisterPrefabs(((Component)__instance).GetComponent<NetworkManager>());
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		internal static void StartOfRoundAwake_Prefix(StartOfRound __instance)
		{
			if (!Plugin.hasVanillaBeenPatched)
			{
				ContentExtractor.TryScrapeVanillaItems(__instance);
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "Awake")]
		[HarmonyPostfix]
		internal static void RoundManagerAwake_Postfix(RoundManager __instance)
		{
			if (((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().IsServer)
			{
				LethalLevelLoaderNetworkManager component = Object.Instantiate<GameObject>(LethalLevelLoaderNetworkManager.networkingManagerPrefab).GetComponent<LethalLevelLoaderNetworkManager>();
				((Component)component).GetComponent<NetworkObject>().Spawn(false);
			}
			RoundManager.Instance.firstTimeDungeonAudios = CollectionExtensions.AddItem<AudioClip>((IEnumerable<AudioClip>)RoundManager.Instance.firstTimeDungeonAudios.ToList(), RoundManager.Instance.firstTimeDungeonAudios[0]).ToArray();
			if (Plugin.hasVanillaBeenPatched)
			{
				return;
			}
			ContentExtractor.TryScrapeVanillaContent(__instance);
			TerminalManager.CacheTerminalReferences();
			AssetBundleLoader.CreateVanillaExtendedDungeonFlows();
			AssetBundleLoader.CreateVanillaExtendedLevels(StartOfRound.Instance);
			AssetBundleLoader.InitializeBundles();
			string text = "LethalLevelLoader Loaded The Following ExtendedLevels:\n";
			foreach (ExtendedLevel extendedLevel in PatchedContent.ExtendedLevels)
			{
				text = text + (PatchedContent.ExtendedLevels.IndexOf(extendedLevel) + 1) + ". " + extendedLevel.selectableLevel.PlanetName + " (" + extendedLevel.levelType.ToString() + ")\n";
			}
			DebugHelper.Log(text);
			text = "LethalLevelLoader Loaded The Following ExtendedDungeonFlows:\n";
			foreach (ExtendedDungeonFlow extendedDungeonFlow in PatchedContent.ExtendedDungeonFlows)
			{
				text = text + (PatchedContent.ExtendedDungeonFlows.IndexOf(extendedDungeonFlow) + 1) + ". " + extendedDungeonFlow.dungeonDisplayName + " (" + ((Object)extendedDungeonFlow.dungeonFlow).name + ") (" + extendedDungeonFlow.dungeonType.ToString() + ")\n";
			}
			DebugHelper.Log(text);
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "Start")]
		[HarmonyPrefix]
		internal static void RoundManagerStart_Prefix()
		{
			if (!Plugin.hasVanillaBeenPatched)
			{
				foreach (ExtendedLevel customExtendedLevel in PatchedContent.CustomExtendedLevels)
				{
					ContentRestorer.RestoreVanillaLevelAssetReferences(customExtendedLevel);
				}
				foreach (ExtendedDungeonFlow customExtendedDungeonFlow in PatchedContent.CustomExtendedDungeonFlows)
				{
					ContentRestorer.RestoreVanillaDungeonAssetReferences(customExtendedDungeonFlow);
				}
				TerminalManager.CreateMoonsFilterTerminalAssets();
				ConfigLoader.BindConfigs();
				SceneManager.sceneLoaded += OnSceneLoaded;
				SceneManager.sceneLoaded += EventPatches.OnSceneLoaded;
				Plugin.hasVanillaBeenPatched = true;
			}
			AudioSource[] array = Resources.FindObjectsOfTypeAll<AudioSource>();
			foreach (AudioSource val in array)
			{
				val.spatialize = false;
			}
			LevelManager.ValidateLevelLists();
			LevelManager.PatchVanillaLevelLists();
			DungeonManager.PatchVanillaDungeonLists();
			LevelManager.RefreshCustomExtendedLevelIDs();
			TerminalManager.CreateExtendedLevelGroups();
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Terminal), "Start")]
		[HarmonyPostfix]
		internal static void TerminalStart_Postfix()
		{
			LevelManager.RefreshLethalExpansionMoons();
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Terminal), "ParseWord")]
		[HarmonyPostfix]
		internal static void TerminalParseWord_Postfix(Terminal __instance, ref TerminalKeyword __result, string playerWord)
		{
			if ((Object)(object)__result != (Object)null)
			{
				TerminalKeyword val = TerminalManager.TryFindAlternativeNoun(__instance, __result, playerWord);
				if ((Object)(object)val != (Object)null)
				{
					__result = val;
				}
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Terminal), "RunTerminalEvents")]
		[HarmonyPrefix]
		internal static bool TerminalRunTerminalEvents_Prefix(TerminalNode node)
		{
			return TerminalManager.RunLethalLevelLoaderTerminalEvents(node);
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Terminal), "LoadNewNode")]
		[HarmonyPrefix]
		internal static void TerminalLoadNewNode_Prefix(Terminal __instance, ref TerminalNode node)
		{
			if ((Object)(object)node == (Object)(object)TerminalManager.moonsKeyword.specialKeywordResult)
			{
				TerminalManager.RefreshExtendedLevelGroups();
				node.displayText = TerminalManager.GetMoonsTerminalText();
			}
			else
			{
				if (!((Object)(object)__instance.currentNode == (Object)(object)TerminalManager.moonsKeyword.specialKeywordResult))
				{
					return;
				}
				foreach (ExtendedLevel extendedLevel in PatchedContent.ExtendedLevels)
				{
					if ((Object)(object)extendedLevel.routeNode == (Object)(object)node && extendedLevel.isLocked)
					{
						TerminalManager.SwapRouteNodeToLockedNode(extendedLevel, ref node);
					}
				}
			}
		}

		internal static void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null && LevelManager.CurrentExtendedLevel.IsLoaded && LevelManager.CurrentExtendedLevel.levelType == ContentType.Custom && !LevelManager.CurrentExtendedLevel.isLethalExpansion)
			{
				Scene sceneByName = SceneManager.GetSceneByName(LevelManager.CurrentExtendedLevel.selectableLevel.sceneName);
				GameObject[] rootGameObjects = ((Scene)(ref sceneByName)).GetRootGameObjects();
				foreach (GameObject val in rootGameObjects)
				{
					LevelLoader.UpdateStoryLogs(LevelManager.CurrentExtendedLevel, val);
					ContentRestorer.RestoreAudioAssetReferencesInParent(val);
				}
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(DungeonGenerator), "Generate")]
		[HarmonyPrefix]
		internal static void DungeonGeneratorGenerate_Prefix(DungeonGenerator __instance)
		{
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
			{
				DungeonLoader.PrepareDungeon();
			}
			LevelManager.LogDayHistory();
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(RoundManager), "Generator_OnGenerationStatusChanged")]
		[HarmonyPrefix]
		internal static bool OnGenerationStatusChanged_Prefix(RoundManager __instance, GenerationStatus status)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Invalid comparison between Unknown and I4
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			DebugHelper.Log(((object)(GenerationStatus)(ref status)).ToString());
			if ((int)status == 6 && !__instance.dungeonCompletedGenerating)
			{
				__instance.FinishGeneratingLevel();
				__instance.dungeonGenerator.Generator.OnGenerationStatusChanged -= new GenerationStatusDelegate(__instance.Generator_OnGenerationStatusChanged);
				Debug.Log((object)"Dungeon has finished generating on this client after multiple frames");
			}
			return false;
		}

		[HarmonyPatch(typeof(RoundManager), "GenerateNewLevelClientRpc")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> GenerateNewLevelClientRpcTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null).SearchForward((Func<CodeInstruction, bool>)((CodeInstruction instructions) => CodeInstructionExtensions.Calls(instructions, AccessTools.Method(typeof(RoundManager), "GenerateNewFloor", (Type[])null, (Type[])null)))).SetInstruction(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Patches), "InjectHostDungeonFlowSelection", (Type[])null, (Type[])null))).Advance(-1)
				.SetInstruction(new CodeInstruction(OpCodes.Nop, (object)null));
			return val.InstructionEnumeration();
		}

		[HarmonyPatch(typeof(RoundManager), "GenerateNewFloor")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> GenerateNewFloorTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null).SearchForward((Func<CodeInstruction, bool>)((CodeInstruction instructions) => CodeInstructionExtensions.Calls(instructions, AccessTools.Method(typeof(RuntimeDungeon), "Generate", (Type[])null, (Type[])null)))).SetInstruction(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Patches), "InjectHostDungeonSizeSelection", (Type[])null, (Type[])null))).Advance(-1)
				.SetInstruction(new CodeInstruction(OpCodes.Nop, (object)null));
			return val.InstructionEnumeration();
		}

		public static void InjectHostDungeonSizeSelection(RoundManager roundManager)
		{
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
			{
				LethalLevelLoaderNetworkManager.Instance.GetDungeonFlowSizeServerRpc();
			}
			else
			{
				roundManager.dungeonGenerator.Generate();
			}
		}

		internal static void InjectHostDungeonFlowSelection()
		{
			if ((Object)(object)LevelManager.CurrentExtendedLevel != (Object)null)
			{
				DungeonManager.TryAddCurrentVanillaLevelDungeonFlow(RoundManager.Instance.dungeonGenerator.Generator, LevelManager.CurrentExtendedLevel);
				DungeonLoader.SelectDungeon();
			}
			else
			{
				RoundManager.Instance.GenerateNewFloor();
			}
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Dungeon), "RoundManager_Start")]
		[HarmonyPrefix]
		internal static bool Dungeon_Start_Prefix(orig_Start orig, RoundManager self)
		{
			DebugHelper.LogWarning("Disabling LethalLib Dungeon.RoundManager_Start() Function To Prevent Conflicts");
			orig.Invoke(self);
			return false;
		}

		[HarmonyPriority(200)]
		[HarmonyPatch(typeof(Dungeon), "RoundManager_GenerateNewFloor")]
		[HarmonyPrefix]
		internal static bool Dungeon_GenerateNewFloor_Prefix(orig_GenerateNewFloor orig, RoundManager self)
		{
			DebugHelper.LogWarning("Disabling LethalLib Dungeon.RoundManager_GenerateNewFloor() Function To Prevent Conflicts");
			orig.Invoke(self);
			return false;
		}
	}
	public enum PreviewInfoType
	{
		Price,
		Difficulty,
		Weather,
		History,
		All,
		None,
		Vanilla,
		Override
	}
	public enum SortInfoType
	{
		Price,
		Difficulty,
		Tag,
		LastTraveled,
		None
	}
	public enum FilterInfoType
	{
		Price,
		Weather,
		Tag,
		TraveledThisQuota,
		TraveledThisRun,
		None
	}
	public enum SimulateInfoType
	{
		Percentage,
		Rarity
	}
	public static class Settings
	{
		public static PreviewInfoType levelPreviewInfoType = PreviewInfoType.Weather;

		public static SortInfoType levelPreviewSortType = SortInfoType.None;

		public static FilterInfoType levelPreviewFilterType = FilterInfoType.None;

		public static SimulateInfoType levelSimulateInfoType = SimulateInfoType.Percentage;

		public static bool allDungeonFlowsRequireMatching = false;

		public static string GetOverridePreviewInfo(ExtendedLevel extendedLevel)
		{
			return string.Empty;
		}
	}
	[Serializable]
	public class ExtendedDungeonFlowWithRarity
	{
		public ExtendedDungeonFlow extendedDungeonFlow;

		public int rarity;

		public ExtendedDungeonFlowWithRarity(ExtendedDungeonFlow newExtendedDungeonFlow, int newRarity)
		{
			extendedDungeonFlow = newExtendedDungeonFlow;
			rarity = newRarity;
		}

		public bool UpdateRarity(int newRarity)
		{
			if (newRarity > rarity)
			{
				rarity = newRarity;
				return true;
			}
			return false;
		}
	}
	public static class DungeonLoader
	{
		internal static void SelectDungeon()
		{
			RoundManager.Instance.dungeonGenerator.Generator.DungeonFlow = null;
			if (((NetworkBehaviour)LethalLevelLoaderNetworkManager.Instance).IsServer)
			{
				LethalLevelLoaderNetworkManager.Instance.GetRandomExtendedDungeonFlowServerRpc();
			}
		}

		internal static void PrepareDungeon()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			DungeonGenerator generator = RoundManager.Instance.dungeonGenerator.Generator;
			ExtendedLevel currentExtendedLevel = LevelManager.CurrentExtendedLevel;
			ExtendedDungeonFlow currentExtendedDungeonFlow = DungeonManager.CurrentExtendedDungeonFlow;
			PatchFireEscapes(generator, currentExtendedLevel, SceneManager.GetSceneByName(currentExtendedLevel.selectableLevel.sceneName));
			PatchDynamicGlobalProps(generator, currentExtendedDungeonFlow);
		}

		public static float GetClampedDungeonSize()
		{
			float num = LevelManager.CurrentExtendedLevel.selectableLevel.factorySizeMultiplier * RoundManager.Instance.mapSizeMultiplier;
			if ((Object)(object)DungeonManager.CurrentExtendedDungeonFlow != (Object)null && DungeonManager.CurrentExtendedDungeonFlow.enableDynamicDungeonSizeRestriction)
			{
				ExtendedDungeonFlow currentExtendedDungeonFlow = DungeonManager.CurrentExtendedDungeonFlow;
				ExtendedLevel currentExtendedLevel = LevelManager.CurrentExtendedLevel;
				if (currentExtendedLevel.selectableLevel.factorySizeMultiplier > currentExtendedDungeonFlow.dungeonSizeMax)
				{
					num = Mathf.Lerp(currentExtendedLevel.selectableLevel.factorySizeMultiplier, currentExtendedDungeonFlow.dungeonSizeMax, currentExtendedDungeonFlow.dungeonSizeLerpPercentage) * RoundManager.Instance.mapSizeMultiplier;
				}
				else if (currentExtendedLevel.selectableLevel.factorySizeMultiplier < currentExtendedDungeonFlow.dungeonSizeMin)
				{
					num = Mathf.Lerp(currentExtendedLevel.selectableLevel.factorySizeMultiplier, currentExtendedDungeonFlow.dungeonSizeMin, currentExtendedDungeonFlow.dungeonSizeLerpPercentage) * RoundManager.Instance.mapSizeMultiplier;
				}
				DebugHelper.Log("CurrentLevel: " + LevelManager.CurrentExtendedLevel.NumberlessPlanetName + " DungeonSize Is: " + LevelManager.CurrentExtendedLevel.selectableLevel.factorySizeMultiplier + " | Overrriding DungeonSize To: " + num / RoundManager.Instance.mapSizeMultiplier + " (" + num + ")");
			}
			else
			{
				DebugHelper.Log("CurrentLevel: " + LevelManager.CurrentExtendedLevel.NumberlessPlanetName + " DungeonSize Is: " + LevelManager.CurrentExtendedLevel.selectableLevel.factorySizeMultiplier + " | Leaving DungeonSize As: " + num / RoundManager.Instance.mapSizeMultiplier + " (" + num + ")");
			}
			return num;
		}

		internal static void PatchDungeonSize(DungeonGenerator dungeonGenerator, ExtendedLevel extendedLevel, ExtendedDungeonFlow extendedDungeonFlow)
		{
		}

		internal static List<EntranceTeleport> GetEntranceTeleports(Scene scene)
		{
			List<EntranceTeleport> list = new List<EntranceTeleport>();
			GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects();
			foreach (GameObject val in rootGameObjects)
			{
				EntranceTeleport[] componentsInChildren = val.GetComponentsInChildren<EntranceTeleport>();
				foreach (EntranceTeleport item in componentsInChildren)
				{
					list.Add(item);
				}
			}
			return list;
		}

		internal static void PatchFireEscapes(DungeonGenerator dungeonGenerator, ExtendedLevel extendedLevel, Scene scene)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Expected O, but got Unknown
			string text = "Fire Exit Patch Report, Details Below;\n\n";
			if (!DungeonManager.TryGetExtendedDungeonFlow(dungeonGenerator.DungeonFlow, out var returnExtendedDungeonFlow))
			{
				return;
			}
			List<EntranceTeleport> list = (from o in GetEntranceTeleports(scene)
				orderby o.entranceId
				select o).ToList();
			foreach (EntranceTeleport item in list)
			{
				item.entranceId = list.IndexOf(item);
				item.dungeonFlowId = returnExtendedDungeonFlow.dungeonID;
			}
			text = text + "EntranceTeleport's Found, " + extendedLevel.NumberlessPlanetName + " Contains " + list.Count + " Entrances! ( " + (list.Count - 1) + " Fire Escapes) \n";
			text = text + "Main Entrance: " + ((Object)((Component)list[0]).gameObject).name + " (Entrance ID: " + list[0].entranceId + ") (Dungeon ID: " + list[0].dungeonFlowId + ")\n";
			foreach (EntranceTeleport item2 in list)
			{
				if (item2.entranceId != 0)
				{
					text = text + "Alternate Entrance: " + ((Object)((Component)item2).gameObject).name + " (Entrance ID: " + item2.entranceId + ") (Dungeon ID: " + item2.dungeonFlowId + ")\n";
				}
			}
			foreach (GlobalPropSettings globalProp in dungeonGenerator.DungeonFlow.GlobalProps)
			{
				if (globalProp.ID == 1231)
				{
					text = text + "Found Fire Escape GlobalProp: (ID: 1231), Modifying Spawnrate Count From (" + globalProp.Count.Min + "," + globalProp.Count.Max + ") To (" + (list.Count - 1) + "," + (list.Count - 1) + ")\n";
					globalProp.Count = new IntRange(list.Count - 1, list.Count - 1);
					break;
				}
			}
			DebugHelper.Log(text + "\n");
		}

		public static void PatchDynamicGlobalProps(DungeonGenerator dungeonGenerator, ExtendedDungeonFlow extendedDungeonFlow)
		{
			foreach (GlobalPropCountOverride globalPropCountOverrides in extendedDungeonFlow.globalPropCountOverridesList)
			{
				foreach (GlobalPropSettings globalProp in dungeonGenerator.DungeonFlow.GlobalProps)
				{
					if (globalPropCountOverrides.globalPropID == globalProp.ID)
					{
						globalProp.Count.Min = globalProp.Count.Min * Mathf.RoundToInt(Mathf.Lerp(1f, dungeonGenerator.LengthMultiplier / RoundManager.Instance.mapSizeMultiplier, globalPropCountOverrides.globalPropCountScaleRate));
						globalProp.Count.Max = globalProp.Count.Max * Mathf.RoundToInt(Mathf.Lerp(1f, dungeonGenerator.LengthMultiplier / RoundManager.Instance.mapSizeMultiplier, globalPropCountOverrides.globalPropCountScaleRate));
					}
				}
			}
		}
	}
	public class LevelLoader
	{
		internal static List<MeshCollider> customLevelMeshCollidersList = new List<MeshCollider>();

		internal static async void EnableMeshColliders()
		{
			List<MeshCollider> instansiatedCustomLevelMeshColliders = new List<MeshCollider>();
			int counter = 0;
			MeshCollider[] array = Object.FindObjectsOfType<MeshCollider>();
			foreach (MeshCollider meshCollider in array)
			{
				if (((Object)((Component)meshCollider).gameObject).name.Contains(" (LLL Tracked)"))
				{
					instansiatedCustomLevelMeshColliders.Add(meshCollider);
				}
			}
			Task[] meshColliderEnableTasks = new Task[instansiatedCustomLevelMeshColliders.Count];
			foreach (MeshCollider meshCollider2 in instansiatedCustomLevelMeshColliders)
			{
				meshColliderEnableTasks[counter] = EnableMeshCollider(meshCollider2);
				counter++;
			}
			await Task.WhenAll(meshColliderEnableTasks);
		}

		internal static async Task EnableMeshCollider(MeshCollider meshCollider)
		{
			((Collider)meshCollider).enabled = true;
			((Object)((Component)meshCollider).gameObject).name.Replace(" (LLL Tracked)", "");
			await Task.Yield();
		}

		internal static void UpdateStoryLogs(ExtendedLevel extendedLevel, GameObject sceneRootObject)
		{
			StoryLog[] componentsInChildren = sceneRootObject.GetComponentsInChildren<StoryLog>();
			foreach (StoryLog val in componentsInChildren)
			{
				foreach (StoryLogData storyLog in extendedLevel.storyLogs)
				{
					if (val.storyLogID == storyLog.storyLogID)
					{
						val.storyLogID = storyLog.newStoryLogID;
					}
				}
			}
		}
	}
	public class DungeonManager
	{
		public static ExtendedDungeonFlow CurrentExtendedDungeonFlow
		{
			get
			{
				ExtendedDungeonFlow result = null;
				if ((Object)(object)RoundManager.Instance != (Object)null && (Object)(object)RoundManager.Instance.dungeonGenerator != (Object)null && TryGetExtendedDungeonFlow(RoundManager.Instance.dungeonGenerator.Generator.DungeonFlow, out var returnExtendedDungeonFlow))
				{
					result = returnExtendedDungeonFlow;
				}
				return result;
			}
		}

		internal static void PatchVanillaDungeonLists()
		{
			foreach (ExtendedDungeonFlow customExtendedDungeonFlow in PatchedContent.CustomExtendedDungeonFlows)
			{
				customExtendedDungeonFlow.dungeonID = RoundManager.Instance.dungeonFlowTypes.Length;
				RoundManager.Instance.dungeonFlowTypes = CollectionExtensions.AddItem<DungeonFlow>((IEnumerable<DungeonFlow>)RoundManager.Instance.dungeonFlowTypes, customExtendedDungeonFlow.dungeonFlow).ToArray();
				if ((Object)(object)customExtendedDungeonFlow.dungeonFirstTimeAudio != (Object)null)
				{
					RoundManager.Instance.firstTimeDungeonAudios = CollectionExtensions.AddItem<AudioClip>((IEnumerable<AudioClip>)RoundManager.Instance.firstTimeDungeonAudios, customExtendedDungeonFlow.dungeonFirstTimeAudio).ToArray();
				}
			}
		}

		internal static void AddExtendedDungeonFlow(ExtendedDungeonFlow extendedDungeonFlow)
		{
			PatchedContent.ExtendedDungeonFlows.Add(extendedDungeonFlow);
		}

		internal static void TryAddCurrentVanillaLevelDungeonFlow(DungeonGenerator dungeonGenerator, ExtendedLevel currentExtendedLevel)
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			if ((Object)(object)dungeonGenerator.DungeonFlow != (Object)null && !RoundManager.Instance.dungeonFlowTypes.ToList().Contains(dungeonGenerator.DungeonFlow))
			{
				DebugHelper.Log("Level: " + currentExtendedLevel.selectableLevel.PlanetName + " Contains DungeonFlow: " + ((Object)dungeonGenerator.DungeonFlow).name + " In DungeonGenerator That Was Not Found In RoundManager, Adding!");
				AssetBundleLoader.CreateVanillaExtendedDungeonFlow(dungeonGenerator.DungeonFlow);
				if (TryGetExtendedDungeonFlow(dungeonGenerator.DungeonFlow, out var returnExtendedDungeonFlow))
				{
					IntWithRarity val = new IntWithRarity();
					val.id = returnExtendedDungeonFlow.dungeonID;
					val.rarity = 300;
					currentExtendedLevel.selectableLevel.dungeonFlowTypes = CollectionExtensions.AddItem<IntWithRarity>((IEnumerable<IntWithRarity>)currentExtendedLevel.selectableLevel.dungeonFlowTypes, val).ToArray();
				}
			}
		}

		internal static List<ExtendedDungeonFlowWithRarity> GetValidExtendedDungeonFlows(ExtendedLevel extendedLevel, bool debugResults)
		{
			string text = "Trying To Find All Matching DungeonFlows For Level: " + extendedLevel.NumberlessPlanetName + "\n";
			List<ExtendedDungeonFlowWithRarity> list = new List<ExtendedDungeonFlowWithRarity>();
			List<ExtendedDungeonFlowWithRarity> list2 = new List<ExtendedDungeonFlowWithRarity>();
			if (extendedLevel.allowedDungeonContentTypes == ContentType.Vanilla || extendedLevel.allowedDungeonContentTypes == ContentType.Any)
			{
				IntWithRarity[] dungeonFlowTypes = extendedLevel.selectableLevel.dungeonFlowTypes;
				foreach (IntWithRarity val in dungeonFlowTypes)
				{
					if (TryGetExtendedDungeonFlow(RoundManager.Instance.dungeonFlowTypes[val.id], out var returnExtendedDungeonFlow))
					{
						if (!Settings.allDungeonFlowsRequireMatching)
						{
							list.Add(new ExtendedDungeonFlowWithRarity(returnExtendedDungeonFlow, val.rarity));
						}
						else
						{
							list2.Add(new ExtendedDungeonFlowWithRarity(returnExtendedDungeonFlow, val.rarity));
						}
					}
				}
			}
			if (extendedLevel.allowedDungeonContentTypes == ContentType.Custom || extendedLevel.allowedDungeonContentTypes == ContentType.Any)
			{
				foreach (ExtendedDungeonFlow customExtendedDungeonFlow in PatchedContent.CustomExtendedDungeonFlows)
				{
					list2.Add(new ExtendedDungeonFlowWithRarity(customExtendedDungeonFlow, 0));
				}
			}
			text += "Potential DungeonFlows Collected, List Below: \n";
			foreach (ExtendedDungeonFlowWithRarity item in list.Concat(list2))
			{
				text = text + item.extendedDungeonFlow.dungeonDisplayName + " - " + item.rarity + ", ";
			}
			text = text + "\n\nSelectableLevel - " + extendedLevel.selectableLevel.PlanetName + " Level Tags: ";
			foreach (string levelTag in extendedLevel.levelTags)
			{
				text = text + levelTag + ", ";
			}
			text += "\n";
			foreach (ExtendedDungeonFlowWithRarity item2 in list)
			{
				text = text + "\nDungeonFlow " + (list.IndexOf(item2) + 1) + ". : " + ((Object)item2.extendedDungeonFlow.dungeonFlow).name + " - Matched " + extendedLevel.NumberlessPlanetName + " With A Rarity Of: " + item2.rarity + " Based On The Levels DungeonFlowTypes!\n";
			}
			foreach (ExtendedDungeonFlowWithRarity item3 in new List<ExtendedDungeonFlowWithRarity>(list2))
			{
				string text2 = string.Empty;
				ExtendedDungeonFlow extendedDungeonFlow = item3.extendedDungeonFlow;
				if (item3.UpdateRarity(GetHighestRarityViaMatchingNormalizedString(extendedLevel.contentSourceName, extendedDungeonFlow.manualContentSourceNameReferenceList)))
				{
					text2 = " Based On Content Source Name!";
				}
				if (item3.UpdateRarity(GetHighestRarityViaMatchingNormalizedString(extendedLevel.NumberlessPlanetName, extendedDungeonFlow.manualPlanetNameReferenceList)))
				{
					text2 = " Based On Planet Name!";
				}
				if (item3.UpdateRarity(GetHighestRarityViaMatchingWithinRanges(extendedLevel.RoutePrice, extendedDungeonFlow.dynamicRoutePricesList)))
				{
					text2 = " Based On Route Price!";
				}
				if (item3.UpdateRarity(GetHighestRarityViaMatchingNormalizedStrings(extendedLevel.levelTags, extendedDungeonFlow.dynamicLevelTagsList)))
				{
					text2 = " Based On Level Tags!";
				}
				if (item3.UpdateRarity(GetHighestRarityViaMatchingNormalizedString(((object)(LevelWeatherType)(ref extendedLevel.selectableLevel.currentWeather)).ToString(), extendedDungeonFlow.dynamicCurrentWeatherList)))
				{
					text2 = " Based On Current Weather!";
				}
				if (text2 != string.Empty)
				{
					text = text + "\nDungeonFlow " + (list2.IndexOf(item3) + 1) + ". : " + ((Object)extendedDungeonFlow.dungeonFlow).name + " - Matched " + extendedLevel.NumberlessPlanetName + " With A Rarity Of: " + item3.rarity + text2 + "\n";
				}
				if (item3.rarity != 0)
				{
					list.Add(item3);
				}
			}
			if (debugResults)
			{
				DebugHelper.Log(text + "\nMatching DungeonFlows Collected, Count Is: " + list.Count + "\n\n");
			}
			return list;
		}

		internal static void RefreshDungeonFlowIDs()
		{
			DebugHelper.Log("Re-Adjusting DungeonFlowTypes Array For Late Arriving Vanilla DungeonFlow");
			List<DungeonFlow> list = new List<DungeonFlow>();
			foreach (ExtendedDungeonFlow vanillaExtendedDungeonFlow in PatchedContent.VanillaExtendedDungeonFlows)
			{
				vanillaExtendedDungeonFlow.dungeonID = list.Count;
				list.Add(vanillaExtendedDungeonFlow.dungeonFlow);
			}
			foreach (ExtendedDungeonFlow customExtendedDungeonFlow in PatchedContent.CustomExtendedDungeonFlows)
			{
				customExtendedDungeonFlow.dungeonID = list.Count;
				list.Add(customExtendedDungeonFlow.dungeonFlow);
			}
			RoundManager.Instance.dungeonFlowTypes = list.ToArray();
		}

		internal static int GetHighestRarityViaMatchingWithinRanges(int comparingValue, List<Vector2WithRarity> matchingVectors)
		{
			int num = 0;
			foreach (Vector2WithRarity matchingVector in matchingVectors)
			{
				if (matchingVector.Rarity >= num && (float)comparingValue >= matchingVector.Min && (float)comparingValue <= matchingVector.Max)
				{
					num = matchingVector.Rarity;
				}
			}
			return num;
		}

		internal static int GetHighestRarityViaMatchingNormalizedString(string comparingString, List<StringWithRarity> matchingStrings)
		{
			return GetHighestRarityViaMatchingNormalizedStrings(new List<string> { comparingString }, matchingStrings);
		}

		internal static int GetHighestRarityViaMatchingNormalizedStrings(List<string> comparingStrings, List<StringWithRarity> matchingStrings)
		{
			int num = 0;
			foreach (StringWithRarity matchingString in matchingStrings)
			{
				foreach (string item in new List<string>(comparingStrings))
				{
					if (matchingString.Rarity >= num && (matchingString.Name.Sanitized().Contains(item.Sanitized()) || item.Sanitized().Contains(matchingString.Name.Sanitized())))
					{
						num = matchingString.Rarity;
					}
				}
			}
			return num;
		}

		internal static bool TryGetExtendedDungeonFlow(DungeonFlow dungeonFlow, out ExtendedDungeonFlow returnExtendedDungeonFlow, ContentType contentType = ContentType.Any)
		{
			returnExtendedDungeonFlow = null;
			List<ExtendedDungeonFlow> list = null;
			if ((Object)(object)dungeonFlow == (Object)null)
			{
				return false;
			}
			switch (contentType)
			{
			case ContentType.Any:
				list = PatchedContent.ExtendedDungeonFlows;
				break;
			case ContentType.Custom:
				list = PatchedContent.CustomExtendedDungeonFlows;
				break;
			case ContentType.Vanilla:
				list = PatchedContent.VanillaExtendedDungeonFlows;
				break;
			}
			foreach (ExtendedDungeonFlow item in list)
			{
				if ((Object)(object)item.dungeonFlow == (Object)(object)dungeonFlow)
				{
					returnExtendedDungeonFlow = item;
				}
			}
			return (Object)(object)returnExtendedDungeonFlow != (Object)null;
		}
	}
	public class LethalLevelLoaderNetworkManager : NetworkBehaviour
	{
		public static GameObject networkingManagerPrefab;

		private static LethalLevelLoaderNetworkManager _instance;

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

		public static bool networkHasStarted;

		public static LethalLevelLoaderNetworkManager Instance
		{
			get
			{
				if ((Object)(object)_instance == (Object)null)
				{
					_instance = Object.FindObjectOfType<LethalLevelLoaderNetworkManager>();
				}
				if ((Object)(object)_instance == (Object)null)
				{
					DebugHelper.LogWarning("LethalLevelLoaderNetworkManager Could Not Be Found! Returning Null!");
				}
				return _instance;
			}
			set
			{
				_instance = value;
			}
		}

		public override void OnNetworkSpawn()
		{
			((NetworkBehaviour)this).OnNetworkSpawn();
			((Object)((Component)this).gameObject).name = "LethalLevelLoaderNetworkManager";
			Instance = this;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
		}

		[ServerRpc]
		public void GetRandomExtendedDungeonFlowServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Invalid comparison between Unknown and I4
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(12573863u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 12573863u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			DebugHelper.Log("Getting Random DungeonFlow!");
			List<ExtendedDungeonFlowWithRarity> validExtendedDungeonFlows = DungeonManager.GetValidExtendedDungeonFlows(LevelManager.CurrentExtendedLevel, debugResults: true);
			List<int> list = new List<int>();
			List<int> list2 = new List<int>();
			if (validExtendedDungeonFlows.Count == 0)
			{
				DebugHelper.LogError("No ExtendedDungeonFlow's could be found! This should only happen if the Host's requireMatchesOnAllDungeonFlows is set to true!");
				DebugHelper.LogError("Loading Facility DungeonFlow to prevent infinite loading!");
				list.Add(0);
				list2.Add(300);
			}
			else
			{
				foreach (ExtendedDungeonFlowWithRarity item in validExtendedDungeonFlows)
				{
					list.Add(RoundManager.Instance.dungeonFlowTypes.ToList().IndexOf(item.extendedDungeonFlow.dungeonFlow));
					list2.Add(item.rarity);
				}
			}
			SetRandomExtendedDungeonFlowClientRpc(list.ToArray(), list2.ToArray());
		}

		[ClientRpc]
		public void SetRandomExtendedDungeonFlowClientRpc(int[] dungeonFlowIDs, int[] rarities)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Expected O, but got Unknown
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1934987400u, val, (RpcDelivery)0);
				bool flag = dungeonFlowIDs != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<int>(dungeonFlowIDs, default(ForPrimitives));
				}
				bool flag2 = rarities != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<int>(rarities, default(ForPrimitives));
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1934987400u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				DebugHelper.Log("Setting Random DungeonFlow!");
				List<IntWithRarity> list = new List<IntWithRarity>();
				List<IntWithRarity> list2 = new List<IntWithRarity>();
				for (int i = 0; i < dungeonFlowIDs.Length; i++)
				{
					IntWithRarity val3 = new IntWithRarity();
					val3.Add(dungeonFlowIDs[i], rarities[i]);
					list.Add(val3);
				}
				list2 = new List<IntWithRarity>(LevelManager.CurrentExtendedLevel.selectableLevel.dungeonFlowTypes.ToList());
				LevelManager.CurrentExtendedLevel.selectableLevel.dungeonFlowTypes = list.ToArray();
				RoundManager.Instance.GenerateNewFloor();
				LevelManager.CurrentExtendedLevel.selectableLevel.dungeonFlowTypes = list2.ToArray();
			}
		}

		[ServerRpc]
		public void GetDungeonFlowSizeServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Invalid comparison between Unknown and I4
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1367970965u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1367970965u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				SetDungeonFlowSizeClientRpc(DungeonLoader.GetClampedDungeonSize());
			}
		}

		[ClientRpc]
		public void SetDungeonFlowSizeClientRpc(float hostSize)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1778200789u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref hostSize, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1778200789u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					RoundManager.Instance.dungeonGenerator.Generator.LengthMultiplier = hostSize;
					RoundManager.Instance.dungeonGenerator.Generate();
				}
			}
		}

		public static void RegisterNetworkPrefab(GameObject prefab)
		{
			if (!networkHasStarted)
			{
				queuedNetworkPrefabs.Add(prefab);
			}
			else
			{
				DebugHelper.Log("Attempted To Register NetworkPrefab: " + ((object)prefab)?.ToString() + " After GameNetworkManager Has Started!");
			}
		}

		internal static void RegisterPrefabs(NetworkManager networkManager)
		{
			List<GameObject> list = new List<GameObject>();
			foreach (NetworkPrefab prefab in networkManager.NetworkConfig.Prefabs.m_Prefabs)
			{
				list.Add(prefab.Prefab);
			}
			int num = 0;
			foreach (GameObject queuedNetworkPrefab in queuedNetworkPrefabs)
			{
				if (!list.Contains(queuedNetworkPrefab))
				{
					networkManager.AddNetworkPrefab(queuedNetworkPrefab);
					list.Add(queuedNetworkPrefab);
				}
				else
				{
					num++;
				}
			}
			DebugHelper.Log("Skipped Registering " + num + " NetworkObjects As They Were Already Registered.");
			networkHasStarted = true;
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_LethalLevelLoaderNetworkManager()
		{
			//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(12573863u, new RpcReceiveHandler(__rpc_handler_12573863));
			NetworkManager.__rpc_func_table.Add(1934987400u, new RpcReceiveHandler(__rpc_handler_1934987400));
			NetworkManager.__rpc_func_table.Add(1367970965u, new RpcReceiveHandler(__rpc_handler_1367970965));
			NetworkManager.__rpc_func_table.Add(1778200789u, new RpcReceiveHandler(__rpc_handler_1778200789));
		}

		private static void __rpc_handler_12573863(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Invalid comparison between Unknown and I4
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
			}
			else
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((LethalLevelLoaderNetworkManager)(object)target).GetRandomExtendedDungeonFlowServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1934987400(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: 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_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				int[] dungeonFlowIDs = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref dungeonFlowIDs, default(ForPrimitives));
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				int[] rarities = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref rarities, default(ForPrimitives));
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((LethalLevelLoaderNetworkManager)(object)target).SetRandomExtendedDungeonFlowClientRpc(dungeonFlowIDs, rarities);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1367970965(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Invalid comparison between Unknown and I4
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
			}
			else
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((LethalLevelLoaderNetworkManager)(object)target).GetDungeonFlowSizeServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

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

		protected internal override string __getTypeName()
		{
			return "LethalLevelLoaderNetworkManager";
		}
	}
	public class LevelManager
	{
		public static List<DayHistory> dayHistoryList = new List<DayHistory>();

		public static int daysTotal;

		public static int quotasTotal;

		public static ExtendedLevel CurrentExtendedLevel
		{
			get
			{
				ExtendedLevel result = null;
				if ((Object)(object)StartOfRound.Instance != (Object)null && TryGetExtendedLevel(StartOfRound.Instance.currentLevel, out var returnExtendedLevel))
				{
					result = returnExtendedLevel;
				}
				return result;
			}
		}

		internal static void ValidateLevelLists()
		{
			List<SelectableLevel> list = new List<SelectableLevel>(OriginalContent.SelectableLevels);
			List<SelectableLevel> list2 = new List<SelectableLevel>(OriginalContent.MoonsCatalogue);
			List<SelectableLevel> list3 = new List<SelectableLevel>(StartOfRound.Instance.levels);
			foreach (SelectableLevel item in new List<SelectableLevel>(list))
			{
				if (item.levelID > 8)
				{
					list.Remove(item);
				}
			}
			foreach (SelectableLevel item2 in new List<SelectableLevel>(list2))
			{
				if (item2.levelID > 8)
				{
					list2.Remove(item2);
				}
			}
			foreach (SelectableLevel item3 in new List<SelectableLevel>(list3))
			{
				if (item3.levelID > 8)
				{
					list3.Remove(item3);
				}
			}
			OriginalContent.SelectableLevels = list;
			OriginalContent.MoonsCatalogue = list2;
			PatchVanillaLevelLists();
		}

		internal static void PatchVanillaLevelLists()
		{
			StartOfRound.Instance.levels = PatchedContent.SeletectableLevels.ToArray();
			TerminalManager.Terminal.moonsCatalogueList = PatchedContent.MoonsCatalogue.ToArray();
		}

		internal static void RefreshCustomExtendedLevelIDs()
		{
			foreach (ExtendedLevel item in new List<ExtendedLevel>(PatchedContent.CustomExtendedLevels))
			{
				item.SetLevelID();
			}
		}

		internal static void RefreshLethalExpansionMoons()
		{
			foreach (ExtendedLevel customExtendedLevel in PatchedContent.CustomExtendedLevels)
			{
				if (!customExtendedLevel.isLethalExpansion)
				{
					continue;
				}
				CompatibleNoun[] compatibleNouns = TerminalManager.routeKeyword.compatibleNouns;
				foreach (CompatibleNoun val in compatibleNouns)
				{
					if (((Object)val.noun).name.ToLower().Contains(customExtendedLevel.NumberlessPlanetName.ToLower()))
					{
						customExtendedLevel.routeNode = val.result;
						customExtendedLevel.routeConfirmNode = val.result.terminalOptions[1].result;
						customExtendedLevel.RoutePrice = customExtendedLevel.routeNode.itemCost;
						break;
					}
				}
			}
			RefreshCustomExtendedLevelIDs();
		}

		public static bool TryGetExtendedLevel(SelectableLevel selectableLevel, out ExtendedLevel returnExtendedLevel, ContentType levelType = ContentType.Any)
		{
			returnExtendedLevel = null;
			List<ExtendedLevel> list = null;
			if ((Object)(object)selectableLevel == (Object)null)
			{
				return false;
			}
			switch (levelType)
			{
			case ContentType.Any:
				list = PatchedContent.ExtendedLevels;
				break;
			case ContentType.Custom:
				list = PatchedContent.CustomExtendedLevels;
				break;
			case ContentType.Vanilla:
				list = PatchedContent.VanillaExtendedLevels;
				break;
			}
			foreach (ExtendedLevel item in list)
			{
				if ((Object)(object)item.selectableLevel == (Object)(object)selectableLevel)
				{
					returnExtendedLevel = item;
				}
			}
			return (Object)(object)returnExtendedLevel != (Object)null;
		}

		public static ExtendedLevel GetExtendedLevel(SelectableLevel selectableLevel)
		{
			ExtendedLevel result = null;
			foreach (ExtendedLevel extendedLevel in PatchedContent.ExtendedLevels)
			{
				if ((Object)(object)extendedLevel.selectableLevel == (Object)(object)selectableLevel)
				{
					result = extendedLevel;
				}
			}
			return result;
		}

		public static void LogDayHistory()
		{
			//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)
			DayHistory dayHistory = new DayHistory();
			daysTotal++;
			dayHistory.extendedLevel = GetExtendedLevel(StartOfRound.Instance.currentLevel);
			DungeonManager.TryGetExtendedDungeonFlow(RoundManager.Instance.dungeonGenerator.Generator.DungeonFlow, out var returnExtendedDungeonFlow);
			dayHistory.extendedDungeonFlow = returnExtendedDungeonFlow;
			dayHistory.day = daysTotal;
			dayHistory.quota = TimeOfDay.Instance.timesFulfilledQuota;
			dayHistory.weatherEffect = StartOfRound.Instance.currentLevel.currentWeather;
			DebugHelper.Log("Created New Day History Log! PlanetName: " + dayHistory.extendedLevel.NumberlessPlanetName + " , DungeonName: " + dayHistory.extendedDungeonFlow.dungeonDisplayName + " , Quota: " + dayHistory.quota + " , Day: " + dayHistory.day + " , Weather: " + ((object)(LevelWeatherType)(ref dayHistory.weatherEffect)).ToString());
			if (dayHistoryList == null)
			{
				dayHistoryList = new List<DayHistory>();
			}
			dayHistoryList.Add(dayHistory);
		}
	}
	public class DayHistory
	{
		public int quota;

		public int day;

		public ExtendedLevel extendedLevel;

		public ExtendedDungeonFlow extendedDungeonFlow;

		public LevelWeatherType weatherEffect;
	}
	public class TerminalManager
	{
		public delegate string PreviewInfoText(ExtendedLevel extendedLevel, PreviewInfoType infoType);

		private static Terminal _terminal;

		internal static TerminalNode lockedNode;

		internal static MoonsCataloguePage defaultMoonsCataloguePage;

		internal static MoonsCataloguePage currentMoonsCataloguePage;

		internal static TerminalKeyword routeKeyword;

		internal static TerminalKeyword infoKeyword;

		internal static TerminalKeyword confirmKeyword;

		internal static TerminalKeyword denyKeyword;

		internal static TerminalKeyword moonsKeyword;

		internal static TerminalKeyword viewKeyword;

		internal static TerminalNode cancelRouteNode;

		internal static string currentTagFilter;

		internal static TerminalKeyword lastParsedVerbKeyword;

		internal static Terminal Terminal
		{
			get
			{
				if ((Object)(object)_terminal == (Object)null)
				{
					_terminal = Object.FindObjectOfType<Terminal>();
				}
				return _terminal;
			}
		}

		public static event PreviewInfoText onBeforePreviewInfoTextAdded;

		internal static void CacheTerminalReferences()
		{
			routeKeyword = Terminal.terminalNodes.allKeywords[26];
			infoKeyword = Terminal.terminalNodes.allKeywords[6];
			confirmKeyword = Terminal.terminalNodes.allKeywords[3];
			denyKeyword = Terminal.terminalNodes.allKeywords[4];
			moonsKeyword = Terminal.terminalNodes.allKeywords[21];
			viewKeyword = Terminal.terminalNodes.allKeywords[19];
			cancelRouteNode = routeKeyword.compatibleNouns[0].result.terminalOptions[0].result;
			lockedNode = CreateNewTerminalNode();
			((Object)lockedNode).name = "lockedLevelNode";
			lockedNode.clearPreviousText = true;
		}

		internal static void SwapRouteNodeToLockedNode(Extended

plugins/LethalLib.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.Cryptography;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using LethalLib.Extras;
using LethalLib.Modules;
using LethalLib.NetcodePatcher;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using On;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;

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

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

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

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

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

		public const string ModName = "LethalLib";

		public const string ModVersion = "0.14.2";

		public static AssetBundle MainAssets;

		public static ManualLogSource logger;

		public static ConfigFile config;

		public static Plugin Instance;

		public static ConfigEntry<bool> extendedLogging;

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

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

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

		public const string PLUGIN_NAME = "LethalLib";

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

			public string ID => id;

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

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

			public string contentPath = "";

			internal Item item;

			public Item Item => item;

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

		public class ShopItem : CustomItem
		{
			public int initPrice;

			public string buyNode1Path;

			public string buyNode2Path;

			public string itemInfoPath;

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

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

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

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

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

			public int Rarity => 0;

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

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

			public ScrapItem(string id, string contentPath, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, Action<Item> registryCallback = null)
				: base(id, contentPath, registryCallback)
			{
				if (levelRarities != null)
				{
					this.levelRarities = levelRarities;
				}
				if (customLevelRarities != null)
				{
					this.customLevelRarities = customLevelRarities;
				}
			}
		}

		public class Unlockable : CustomContent
		{
			public Action<UnlockableItem> registryCallback = delegate
			{
			};

			internal UnlockableItem unlockable;

			public string contentPath = "";

			public int initPrice;

			public string buyNode1Path;

			public string buyNode2Path;

			public string itemInfoPath;

			public StoreType storeType;

			public UnlockableItem UnlockableItem => unlockable;

			public void RemoveFromShop()
			{
				Unlockables.DisableUnlockable(UnlockableItem);
			}

			public void SetPrice(int price)
			{
				Unlockables.UpdateUnlockablePrice(UnlockableItem, price);
			}

			public Unlockable(string id, string contentPath, int price = 0, string buyNode1Path = null, string buyNode2Path = null, string itemInfoPath = null, StoreType storeType = StoreType.None, Action<UnlockableItem> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				initPrice = price;
				this.buyNode1Path = buyNode1Path;
				this.buyNode2Path = buyNode2Path;
				this.itemInfoPath = itemInfoPath;
				this.storeType = storeType;
			}
		}

		public class CustomEnemy : CustomContent
		{
			public Action<EnemyType> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal EnemyType enemy;

			public string infoNodePath;

			public string infoKeywordPath;

			public int rarity;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides;

			public Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1);

			public EnemyType Enemy => enemy;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags)
			{
				Enemies.RemoveEnemyFromLevels(Enemy, levelFlags);
			}

			public CustomEnemy(string id, string contentPath, int rarity = 0, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1), string[] levelOverrides = null, string infoNodePath = null, string infoKeywordPath = null, Action<EnemyType> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				this.infoNodePath = infoNodePath;
				this.infoKeywordPath = infoKeywordPath;
				this.rarity = rarity;
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnType = spawnType;
			}
		}

		public class MapHazard : CustomContent
		{
			public Action<SpawnableMapObjectDef> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal SpawnableMapObjectDef hazard;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides;

			public SpawnableMapObjectDef Hazard => hazard;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
			{
				MapObjects.RemoveMapObject(Hazard, levelFlags, levelOverrides);
			}

			public MapHazard(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableMapObjectDef> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnRateFunction = spawnRateFunction;
			}
		}

		public class OutsideObject : CustomContent
		{
			public Action<SpawnableOutsideObjectDef> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal SpawnableOutsideObjectDef mapObject;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides;

			public SpawnableOutsideObjectDef MapObject => mapObject;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
			{
				MapObjects.RemoveOutsideObject(MapObject, levelFlags, levelOverrides);
			}

			public OutsideObject(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableOutsideObjectDef> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnRateFunction = spawnRateFunction;
			}
		}

		public PluginInfo modInfo;

		private AssetBundle modBundle;

		public Action<CustomContent, GameObject> prefabCallback = delegate
		{
		};

		public Dictionary<string, CustomContent> LoadedContent { get; } = new Dictionary<string, CustomContent>();


		public string modName => modInfo.Metadata.Name;

		public string modVersion => modInfo.Metadata.Version.ToString();

		public string modGUID => modInfo.Metadata.GUID;

		public ContentLoader(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null)
		{
			this.modInfo = modInfo;
			this.modBundle = modBundle;
			if (prefabCallback != null)
			{
				this.prefabCallback = prefabCallback;
			}
		}

		public ContentLoader Create(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null)
		{
			return new ContentLoader(modInfo, modBundle, prefabCallback);
		}

		public void Register(CustomContent content)
		{
			if (LoadedContent.ContainsKey(content.ID))
			{
				Debug.LogError((object)("[LethalLib] " + modName + " tried to register content with ID " + content.ID + " but it already exists!"));
				return;
			}
			if (content is CustomItem customItem)
			{
				Item val = (customItem.item = modBundle.LoadAsset<Item>(customItem.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
				Utilities.FixMixerGroups(val.spawnPrefab);
				prefabCallback(customItem, val.spawnPrefab);
				customItem.registryCallback(val);
				if (content is ShopItem shopItem)
				{
					TerminalNode buyNode = null;
					TerminalNode buyNode2 = null;
					TerminalNode itemInfo = null;
					if (shopItem.buyNode1Path != null)
					{
						buyNode = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode1Path);
					}
					if (shopItem.buyNode2Path != null)
					{
						buyNode2 = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode2Path);
					}
					if (shopItem.itemInfoPath != null)
					{
						itemInfo = modBundle.LoadAsset<TerminalNode>(shopItem.itemInfoPath);
					}
					Items.RegisterShopItem(val, buyNode, buyNode2, itemInfo, shopItem.initPrice);
				}
				else if (content is ScrapItem scrapItem)
				{
					Items.RegisterScrap(val, scrapItem.levelRarities, scrapItem.customLevelRarities);
				}
				else
				{
					Items.RegisterItem(val);
				}
			}
			else if (content is Unlockable unlockable)
			{
				UnlockableItemDef unlockableItemDef = modBundle.LoadAsset<UnlockableItemDef>(unlockable.contentPath);
				if ((Object)(object)unlockableItemDef.unlockable.prefabObject != (Object)null)
				{
					NetworkPrefabs.RegisterNetworkPrefab(unlockableItemDef.unlockable.prefabObject);
					prefabCallback(content, unlockableItemDef.unlockable.prefabObject);
					Utilities.FixMixerGroups(unlockableItemDef.unlockable.prefabObject);
				}
				unlockable.unlockable = unlockableItemDef.unlockable;
				unlockable.registryCallback(unlockableItemDef.unlockable);
				TerminalNode buyNode3 = null;
				TerminalNode buyNode4 = null;
				TerminalNode itemInfo2 = null;
				if (unlockable.buyNode1Path != null)
				{
					buyNode3 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode1Path);
				}
				if (unlockable.buyNode2Path != null)
				{
					buyNode4 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode2Path);
				}
				if (unlockable.itemInfoPath != null)
				{
					itemInfo2 = modBundle.LoadAsset<TerminalNode>(unlockable.itemInfoPath);
				}
				Unlockables.RegisterUnlockable(unlockableItemDef, unlockable.storeType, buyNode3, buyNode4, itemInfo2, unlockable.initPrice);
			}
			else if (content is CustomEnemy customEnemy)
			{
				EnemyType val2 = modBundle.LoadAsset<EnemyType>(customEnemy.contentPath);
				NetworkPrefabs.RegisterNetworkPrefab(val2.enemyPrefab);
				Utilities.FixMixerGroups(val2.enemyPrefab);
				customEnemy.enemy = val2;
				prefabCallback(content, val2.enemyPrefab);
				customEnemy.registryCallback(val2);
				TerminalNode infoNode = null;
				TerminalKeyword infoKeyword = null;
				if (customEnemy.infoNodePath != null)
				{
					infoNode = modBundle.LoadAsset<TerminalNode>(customEnemy.infoNodePath);
				}
				if (customEnemy.infoKeywordPath != null)
				{
					infoKeyword = modBundle.LoadAsset<TerminalKeyword>(customEnemy.infoKeywordPath);
				}
				if (customEnemy.spawnType == (Enemies.SpawnType)(-1))
				{
					Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.levelOverrides, infoNode, infoKeyword);
				}
				else
				{
					Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.spawnType, customEnemy.levelOverrides, infoNode, infoKeyword);
				}
			}
			else if (content is MapHazard mapHazard)
			{
				SpawnableMapObjectDef spawnableMapObjectDef = (mapHazard.hazard = modBundle.LoadAsset<SpawnableMapObjectDef>(mapHazard.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				Utilities.FixMixerGroups(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				prefabCallback(content, spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				mapHazard.registryCallback(spawnableMapObjectDef);
				MapObjects.RegisterMapObject(spawnableMapObjectDef, mapHazard.LevelTypes, mapHazard.levelOverrides, mapHazard.spawnRateFunction);
			}
			else if (content is OutsideObject outsideObject)
			{
				SpawnableOutsideObjectDef spawnableOutsideObjectDef = (outsideObject.mapObject = modBundle.LoadAsset<SpawnableOutsideObjectDef>(outsideObject.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				Utilities.FixMixerGroups(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				prefabCallback(content, spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				outsideObject.registryCallback(spawnableOutsideObjectDef);
				MapObjects.RegisterOutsideObject(spawnableOutsideObjectDef, outsideObject.LevelTypes, outsideObject.levelOverrides, outsideObject.spawnRateFunction);
			}
			LoadedContent.Add(content.ID, content);
		}

		public void RegisterAll(CustomContent[] content)
		{
			Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Length} content items!");
			foreach (CustomContent content2 in content)
			{
				Register(content2);
			}
		}

		public void RegisterAll(List<CustomContent> content)
		{
			Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Count} content items!");
			foreach (CustomContent item in content)
			{
				Register(item);
			}
		}
	}
	public class Dungeon
	{
		public class CustomDungeonArchetype
		{
			public DungeonArchetype archeType;

			public Levels.LevelTypes LevelTypes;

			public int lineIndex = -1;
		}

		public class CustomGraphLine
		{
			public GraphLine graphLine;

			public Levels.LevelTypes LevelTypes;
		}

		public class CustomDungeon
		{
			public int rarity;

			public DungeonFlow dungeonFlow;

			public Levels.LevelTypes LevelTypes;

			public string[] levelOverrides;

			public int dungeonIndex = -1;

			public AudioClip firstTimeDungeonAudio;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_GenerateNewFloor <0>__RoundManager_GenerateNewFloor;

			public static hook_Start <1>__RoundManager_Start;
		}

		public static List<CustomDungeonArchetype> customDungeonArchetypes = new List<CustomDungeonArchetype>();

		public static List<CustomGraphLine> customGraphLines = new List<CustomGraphLine>();

		public static Dictionary<string, TileSet> extraTileSets = new Dictionary<string, TileSet>();

		public static Dictionary<string, GameObjectChance> extraRooms = new Dictionary<string, GameObjectChance>();

		public static List<CustomDungeon> customDungeons = new List<CustomDungeon>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			object obj = <>O.<0>__RoundManager_GenerateNewFloor;
			if (obj == null)
			{
				hook_GenerateNewFloor val = RoundManager_GenerateNewFloor;
				<>O.<0>__RoundManager_GenerateNewFloor = val;
				obj = (object)val;
			}
			RoundManager.GenerateNewFloor += (hook_GenerateNewFloor)obj;
			object obj2 = <>O.<1>__RoundManager_Start;
			if (obj2 == null)
			{
				hook_Start val2 = RoundManager_Start;
				<>O.<1>__RoundManager_Start = val2;
				obj2 = (object)val2;
			}
			RoundManager.Start += (hook_Start)obj2;
		}

		private static void RoundManager_Start(orig_Start orig, RoundManager self)
		{
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Expected O, but got Unknown
			foreach (CustomDungeon customDungeon in customDungeons)
			{
				if (self.dungeonFlowTypes.Contains(customDungeon.dungeonFlow))
				{
					continue;
				}
				List<DungeonFlow> list = self.dungeonFlowTypes.ToList();
				list.Add(customDungeon.dungeonFlow);
				self.dungeonFlowTypes = list.ToArray();
				int dungeonIndex = self.dungeonFlowTypes.Length - 1;
				customDungeon.dungeonIndex = dungeonIndex;
				List<AudioClip> list2 = self.firstTimeDungeonAudios.ToList();
				if (list2.Count != self.dungeonFlowTypes.Length - 1)
				{
					while (list2.Count < self.dungeonFlowTypes.Length - 1)
					{
						list2.Add(null);
					}
				}
				list2.Add(customDungeon.firstTimeDungeonAudio);
				self.firstTimeDungeonAudios = list2.ToArray();
			}
			StartOfRound instance = StartOfRound.Instance;
			foreach (CustomDungeon dungeon in customDungeons)
			{
				SelectableLevel[] levels = instance.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = dungeon.LevelTypes.HasFlag(Levels.LevelTypes.All) || (dungeon.levelOverrides != null && dungeon.levelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (dungeon.LevelTypes.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
					{
						flag = true;
					}
					if (Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)
					{
						Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
						if ((flag || dungeon.LevelTypes.HasFlag(levelTypes)) && !val.dungeonFlowTypes.Any((IntWithRarity rarityInt) => rarityInt.id == dungeon.dungeonIndex))
						{
							List<IntWithRarity> list3 = val.dungeonFlowTypes.ToList();
							list3.Add(new IntWithRarity
							{
								id = dungeon.dungeonIndex,
								rarity = dungeon.rarity
							});
							val.dungeonFlowTypes = list3.ToArray();
						}
					}
				}
			}
			orig.Invoke(self);
		}

		private static void RoundManager_GenerateNewFloor(orig_GenerateNewFloor orig, RoundManager self)
		{
			string name = ((Object)self.currentLevel).name;
			if (Enum.IsDefined(typeof(Levels.LevelTypes), name))
			{
				Levels.LevelTypes levelEnum = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name);
				int index = 0;
				self.dungeonGenerator.Generator.DungeonFlow.Lines.ForEach(delegate(GraphLine line)
				{
					foreach (CustomDungeonArchetype customDungeonArchetype in customDungeonArchetypes)
					{
						if (customDungeonArchetype.LevelTypes.HasFlag(levelEnum) && !line.DungeonArchetypes.Contains(customDungeonArchetype.archeType) && (customDungeonArchetype.lineIndex == -1 || customDungeonArchetype.lineIndex == index))
						{
							line.DungeonArchetypes.Add(customDungeonArchetype.archeType);
							if (Plugin.extendedLogging.Value)
							{
								Plugin.logger.LogInfo((object)("Added " + ((Object)customDungeonArchetype.archeType).name + " to " + name));
							}
						}
					}
					foreach (DungeonArchetype dungeonArchetype in line.DungeonArchetypes)
					{
						string name2 = ((Object)dungeonArchetype).name;
						if (extraTileSets.ContainsKey(name2))
						{
							TileSet val4 = extraTileSets[name2];
							if (!dungeonArchetype.TileSets.Contains(val4))
							{
								dungeonArchetype.TileSets.Add(val4);
								if (Plugin.extendedLogging.Value)
								{
									Plugin.logger.LogInfo((object)("Added " + ((Object)val4).name + " to " + name));
								}
							}
						}
						foreach (TileSet tileSet in dungeonArchetype.TileSets)
						{
							string name3 = ((Object)tileSet).name;
							if (extraRooms.ContainsKey(name3))
							{
								GameObjectChance item = extraRooms[name3];
								if (!tileSet.TileWeights.Weights.Contains(item))
								{
									tileSet.TileWeights.Weights.Add(item);
								}
							}
						}
					}
					index++;
				});
				foreach (CustomGraphLine customGraphLine in customGraphLines)
				{
					if (customGraphLine.LevelTypes.HasFlag(levelEnum) && !self.dungeonGenerator.Generator.DungeonFlow.Lines.Contains(customGraphLine.graphLine))
					{
						self.dungeonGenerator.Generator.DungeonFlow.Lines.Add(customGraphLine.graphLine);
					}
				}
			}
			orig.Invoke(self);
			NetworkManager val = Object.FindObjectOfType<NetworkManager>();
			RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>();
			foreach (RandomMapObject val2 in array)
			{
				for (int j = 0; j < val2.spawnablePrefabs.Count; j++)
				{
					string prefabName = ((Object)val2.spawnablePrefabs[j]).name;
					NetworkPrefab val3 = ((IEnumerable<NetworkPrefab>)val.NetworkConfig.Prefabs.m_Prefabs).FirstOrDefault((Func<NetworkPrefab, bool>)((NetworkPrefab x) => ((Object)x.Prefab).name == prefabName));
					if (val3 != null && (Object)(object)val3.Prefab != (Object)(object)val2.spawnablePrefabs[j])
					{
						val2.spawnablePrefabs[j] = val3.Prefab;
					}
					else if (val3 == null)
					{
						Plugin.logger.LogError((object)("DungeonGeneration - Could not find network prefab (" + prefabName + ")! Make sure your assigned prefab is registered with the network manager, or named identically to the vanilla prefab you are referencing."));
					}
				}
			}
		}

		public static void AddArchetype(DungeonArchetype archetype, Levels.LevelTypes levelFlags, int lineIndex = -1)
		{
			CustomDungeonArchetype customDungeonArchetype = new CustomDungeonArchetype();
			customDungeonArchetype.archeType = archetype;
			customDungeonArchetype.LevelTypes = levelFlags;
			customDungeonArchetype.lineIndex = lineIndex;
			customDungeonArchetypes.Add(customDungeonArchetype);
		}

		public static void AddLine(GraphLine line, Levels.LevelTypes levelFlags)
		{
			CustomGraphLine customGraphLine = new CustomGraphLine();
			customGraphLine.graphLine = line;
			customGraphLine.LevelTypes = levelFlags;
			customGraphLines.Add(customGraphLine);
		}

		public static void AddLine(DungeonGraphLineDef line, Levels.LevelTypes levelFlags)
		{
			AddLine(line.graphLine, levelFlags);
		}

		public static void AddTileSet(TileSet set, string archetypeName)
		{
			extraTileSets.Add(archetypeName, set);
		}

		public static void AddRoom(GameObjectChance room, string tileSetName)
		{
			extraRooms.Add(tileSetName, room);
		}

		public static void AddRoom(GameObjectChanceDef room, string tileSetName)
		{
			AddRoom(room.gameObjectChance, tileSetName);
		}

		public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags)
		{
			AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, dungeon.firstTimeDungeonAudio);
		}

		public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags, string[] levelOverrides)
		{
			AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, levelOverrides, dungeon.firstTimeDungeonAudio);
		}

		public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, AudioClip firstTimeDungeonAudio = null)
		{
			customDungeons.Add(new CustomDungeon
			{
				dungeonFlow = dungeon,
				rarity = rarity,
				LevelTypes = levelFlags,
				firstTimeDungeonAudio = firstTimeDungeonAudio
			});
		}

		public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, string[] levelOverrides = null, AudioClip firstTimeDungeonAudio = null)
		{
			customDungeons.Add(new CustomDungeon
			{
				dungeonFlow = dungeon,
				rarity = rarity,
				LevelTypes = levelFlags,
				firstTimeDungeonAudio = firstTimeDungeonAudio,
				levelOverrides = levelOverrides
			});
		}
	}
	public class Enemies
	{
		public struct EnemyAssetInfo
		{
			public EnemyType EnemyAsset;

			public TerminalKeyword keyword;
		}

		public enum SpawnType
		{
			Default,
			Daytime,
			Outside
		}

		public class SpawnableEnemy
		{
			public EnemyType enemy;

			public SpawnType spawnType;

			public TerminalNode terminalNode;

			public TerminalKeyword infoKeyword;

			public string modName;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public string[] spawnLevelOverrides;

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

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

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

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

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

			public static hook_Start <1>__Terminal_Start;

			public static hook_Start <2>__QuickMenuManager_Start;
		}

		private static bool addedToDebug = false;

		public static Terminal terminal;

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

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

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

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

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

		private static void RegisterLevelEnemies(orig_Awake orig, StartOfRound self)
		{
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Expected O, but got Unknown
			orig.Invoke(self);
			foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
			{
				SelectableLevel[] levels = self.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = spawnableEnemy.levelRarities.ContainsKey(Levels.LevelTypes.All) || (spawnableEnemy.customLevelRarities != null && spawnableEnemy.customLevelRarities.ContainsKey(name));
					if (spawnableEnemy.levelRarities.ContainsKey(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
					{
						flag = true;
					}
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelEnum = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (!flag && !spawnableEnemy.spawnLevels.HasFlag(levelEnum))
					{
						continue;
					}
					int rarity = 0;
					if (spawnableEnemy.levelRarities.Keys.Any((Levels.LevelTypes key) => key.HasFlag(levelEnum)))
					{
						rarity = spawnableEnemy.levelRarities.First((KeyValuePair<Levels.LevelTypes, int> x) => x.Key.HasFlag(levelEnum)).Value;
					}
					else if (spawnableEnemy.customLevelRarities != null && spawnableEnemy.customLevelRarities.ContainsKey(name))
					{
						rarity = spawnableEnemy.customLevelRarities[name];
					}
					SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity
					{
						enemyType = spawnableEnemy.enemy,
						rarity = rarity
					};
					switch (spawnableEnemy.spawnType)
					{
					case SpawnType.Default:
						if (!val.Enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
						{
							val.Enemies.Add(item);
							if (Plugin.extendedLogging.Value)
							{
								Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Default]"));
							}
						}
						break;
					case SpawnType.Daytime:
						if (!val.DaytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
						{
							val.DaytimeEnemies.Add(item);
							if (Plugin.extendedLogging.Value)
							{
								Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Daytime]"));
							}
						}
						break;
					case SpawnType.Outside:
						if (!val.OutsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
						{
							val.OutsideEnemies.Add(item);
							if (Plugin.extendedLogging.Value)
							{
								Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Outside]"));
							}
						}
						break;
					}
				}
			}
		}

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

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

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

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

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

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

		public static void RemoveEnemyFromLevels(EnemyType enemyType, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			EnemyType enemyType2 = enemyType;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					List<SpawnableEnemyWithRarity> enemies = val.Enemies;
					List<SpawnableEnemyWithRarity> daytimeEnemies = val.DaytimeEnemies;
					List<SpawnableEnemyWithRarity> outsideEnemies = val.OutsideEnemies;
					enemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
					daytimeEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
					outsideEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
				}
			}
		}
	}
	public class Items
	{
		public struct ItemSaveOrderData
		{
			public int itemId;

			public string itemName;

			public string assetName;
		}

		public struct BuyableItemAssetInfo
		{
			public Item itemAsset;

			public TerminalKeyword keyword;
		}

		public class ScrapItem
		{
			public Item item;

			public Item origItem;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public string[] spawnLevelOverrides;

			public string modName = "Unknown";

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

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

			public ScrapItem(Item item, int rarity, Levels.LevelTypes spawnLevels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null)
			{
				//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
				origItem = item;
				if (!item.isScrap)
				{
					item = item.Clone<Item>();
					item.isScrap = true;
					if (item.maxValue == 0 && item.minValue == 0)
					{
						item.minValue = 40;
						item.maxValue = 100;
					}
					else if (item.maxValue == 0)
					{
						item.maxValue = item.minValue * 2;
					}
					else if (item.minValue == 0)
					{
						item.minValue = item.maxValue / 2;
					}
					GameObject val = NetworkPrefabs.CloneNetworkPrefab(item.spawnPrefab);
					if ((Object)(object)val.GetComponent<GrabbableObject>() != (Object)null)
					{
						val.GetComponent<GrabbableObject>().itemProperties = item;
					}
					if ((Object)(object)val.GetComponentInChildren<ScanNodeProperties>() == (Object)null)
					{
						GameObject obj = Object.Instantiate<GameObject>(scanNodePrefab, val.transform);
						((Object)obj).name = "ScanNode";
						obj.transform.localPosition = new Vector3(0f, 0f, 0f);
						obj.GetComponent<ScanNodeProperties>().headerText = item.itemName;
					}
					item.spawnPrefab = val;
				}
				this.item = item;
				if (spawnLevelOverrides != null)
				{
					foreach (string key in spawnLevelOverrides)
					{
						customLevelRarities.Add(key, rarity);
					}
				}
				if (spawnLevels == Levels.LevelTypes.None)
				{
					return;
				}
				foreach (Levels.LevelTypes value in Enum.GetValues(typeof(Levels.LevelTypes)))
				{
					if (spawnLevels.HasFlag(value))
					{
						levelRarities.Add(value, rarity);
					}
				}
			}

			public ScrapItem(Item item, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null)
			{
				//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
				origItem = item;
				if (!item.isScrap)
				{
					item = item.Clone<Item>();
					item.isScrap = true;
					if (item.maxValue == 0 && item.minValue == 0)
					{
						item.minValue = 40;
						item.maxValue = 100;
					}
					else if (item.maxValue == 0)
					{
						item.maxValue = item.minValue * 2;
					}
					else if (item.minValue == 0)
					{
						item.minValue = item.maxValue / 2;
					}
					GameObject val = NetworkPrefabs.CloneNetworkPrefab(item.spawnPrefab);
					if ((Object)(object)val.GetComponent<GrabbableObject>() != (Object)null)
					{
						val.GetComponent<GrabbableObject>().itemProperties = item;
					}
					if ((Object)(object)val.GetComponentInChildren<ScanNodeProperties>() == (Object)null)
					{
						GameObject obj = Object.Instantiate<GameObject>(scanNodePrefab, val.transform);
						((Object)obj).name = "ScanNode";
						obj.transform.localPosition = new Vector3(0f, 0f, 0f);
						obj.GetComponent<ScanNodeProperties>().headerText = item.itemName;
					}
					item.spawnPrefab = val;
				}
				this.item = item;
				if (customLevelRarities != null)
				{
					this.customLevelRarities = customLevelRarities;
				}
				if (levelRarities != null)
				{
					this.levelRarities = levelRarities;
				}
			}
		}

		public class PlainItem
		{
			public Item item;

			public string modName;

			public PlainItem(Item item)
			{
				this.item = item;
			}
		}

		public class ShopItem
		{
			public Item item;

			public Item origItem;

			public TerminalNode buyNode1;

			public TerminalNode buyNode2;

			public TerminalNode itemInfo;

			public bool wasRemoved;

			public int price;

			public string modName;

			public ShopItem(Item item, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = 0)
			{
				origItem = item;
				this.item = item;
				this.price = price;
				if ((Object)(object)buyNode1 != (Object)null)
				{
					this.buyNode1 = buyNode1;
				}
				if ((Object)(object)buyNode2 != (Object)null)
				{
					this.buyNode2 = buyNode2;
				}
				if ((Object)(object)itemInfo != (Object)null)
				{
					this.itemInfo = itemInfo;
				}
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Start <0>__StartOfRound_Start;

			public static hook_Awake <1>__Terminal_Awake;

			public static hook_TextPostProcess <2>__Terminal_TextPostProcess;
		}

		public static ConfigEntry<bool> useSavedataFix;

		public static GameObject scanNodePrefab;

		public static List<Item> LethalLibItemList = new List<Item>();

		public static List<BuyableItemAssetInfo> buyableItemAssetInfos = new List<BuyableItemAssetInfo>();

		public static Terminal terminal;

		public static List<ScrapItem> scrapItems = new List<ScrapItem>();

		public static List<ShopItem> shopItems = new List<ShopItem>();

		public static List<PlainItem> plainItems = new List<PlainItem>();

		public static void Init()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			useSavedataFix = Plugin.config.Bind<bool>("Items", "EnableItemSaveFix", false, "Allow for LethalLib to store/reorder the item list, which should fix issues where items get reshuffled when loading an old save. This is experimental and may cause save corruptions occasionally.");
			scanNodePrefab = Plugin.MainAssets.LoadAsset<GameObject>("Assets/Custom/ItemScanNode.prefab");
			object obj = <>O.<0>__StartOfRound_Start;
			if (obj == null)
			{
				hook_Start val = StartOfRound_Start;
				<>O.<0>__StartOfRound_Start = val;
				obj = (object)val;
			}
			StartOfRound.Start += (hook_Start)obj;
			object obj2 = <>O.<1>__Terminal_Awake;
			if (obj2 == null)
			{
				hook_Awake val2 = Terminal_Awake;
				<>O.<1>__Terminal_Awake = val2;
				obj2 = (object)val2;
			}
			Terminal.Awake += (hook_Awake)obj2;
			object obj3 = <>O.<2>__Terminal_TextPostProcess;
			if (obj3 == null)
			{
				hook_TextPostProcess val3 = Terminal_TextPostProcess;
				<>O.<2>__Terminal_TextPostProcess = val3;
				obj3 = (object)val3;
			}
			Terminal.TextPostProcess += (hook_TextPostProcess)obj3;
		}

		private static string Terminal_TextPostProcess(orig_TextPostProcess orig, Terminal self, string modifiedDisplayText, TerminalNode node)
		{
			List<Item> list = self.buyableItemsList.ToList();
			List<Item> list2 = self.buyableItemsList.ToList();
			list2.RemoveAll((Item x) => shopItems.FirstOrDefault((ShopItem item) => (Object)(object)item.origItem == (Object)(object)x || (Object)(object)item.item == (Object)(object)x)?.wasRemoved ?? false);
			self.buyableItemsList = list2.ToArray();
			string result = orig.Invoke(self, modifiedDisplayText, node);
			self.buyableItemsList = list.ToArray();
			return result;
		}

		private static void StartOfRound_Start(orig_Start orig, StartOfRound self)
		{
			if (useSavedataFix.Value && ((NetworkBehaviour)self).IsHost)
			{
				Plugin.logger.LogInfo((object)"Fixing Item savedata!!");
				List<ItemSaveOrderData> itemList = new List<ItemSaveOrderData>();
				StartOfRound.Instance.allItemsList.itemsList.ForEach(delegate(Item item)
				{
					itemList.Add(new ItemSaveOrderData
					{
						itemId = item.itemId,
						itemName = item.itemName,
						assetName = ((Object)item).name
					});
				});
				if (ES3.KeyExists("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName))
				{
					itemList = ES3.Load<List<ItemSaveOrderData>>("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName);
				}
				List<Item> itemsList = StartOfRound.Instance.allItemsList.itemsList;
				List<Item> list = new List<Item>();
				foreach (ItemSaveOrderData item2 in itemList)
				{
					Item val = ((IEnumerable<Item>)itemsList).FirstOrDefault((Func<Item, bool>)((Item x) => x.itemId == item2.itemId && x.itemName == item2.itemName && item2.assetName == ((Object)x).name));
					if ((Object)(object)val != (Object)null)
					{
						list.Add(val);
					}
					else
					{
						list.Add(ScriptableObject.CreateInstance<Item>());
					}
				}
				foreach (Item item3 in itemsList)
				{
					if (!list.Contains(item3))
					{
						list.Add(item3);
					}
				}
				StartOfRound.Instance.allItemsList.itemsList = list;
				ES3.Save<List<ItemSaveOrderData>>("LethalLibAllItemsList", itemList, GameNetworkManager.Instance.currentSaveFileName);
			}
			orig.Invoke(self);
		}

		private static void Terminal_Awake(orig_Awake orig, Terminal self)
		{
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Expected O, but got Unknown
			//IL_0855: Unknown result type (might be due to invalid IL or missing references)
			//IL_085a: Unknown result type (might be due to invalid IL or missing references)
			//IL_088f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0898: Expected O, but got Unknown
			//IL_089a: Unknown result type (might be due to invalid IL or missing references)
			//IL_089f: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_08dc: Expected O, but got Unknown
			//IL_093f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0944: Unknown result type (might be due to invalid IL or missing references)
			//IL_094c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0959: Expected O, but got Unknown
			//IL_09e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_09eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_09f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a00: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			foreach (ScrapItem scrapItem in scrapItems)
			{
				SelectableLevel[] levels = instance.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = scrapItem.levelRarities.ContainsKey(Levels.LevelTypes.All) || (scrapItem.customLevelRarities != null && scrapItem.customLevelRarities.ContainsKey(name));
					if (scrapItem.levelRarities.ContainsKey(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
					{
						flag = true;
					}
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelEnum = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (!flag && !scrapItem.levelRarities.Keys.Any((Levels.LevelTypes key) => key.HasFlag(levelEnum)))
					{
						continue;
					}
					int rarity = 0;
					if (scrapItem.levelRarities.Keys.Any((Levels.LevelTypes key) => key.HasFlag(levelEnum)))
					{
						rarity = scrapItem.levelRarities.First((KeyValuePair<Levels.LevelTypes, int> x) => x.Key.HasFlag(levelEnum)).Value;
					}
					else if (scrapItem.customLevelRarities != null && scrapItem.customLevelRarities.ContainsKey(name))
					{
						rarity = scrapItem.customLevelRarities[name];
					}
					SpawnableItemWithRarity item2 = new SpawnableItemWithRarity
					{
						spawnableItem = scrapItem.item,
						rarity = rarity
					};
					if (!val.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem.item))
					{
						val.spawnableScrap.Add(item2);
						if (Plugin.extendedLogging.Value)
						{
							Plugin.logger.LogInfo((object)("Added " + ((Object)scrapItem.item).name + " to " + name));
						}
					}
				}
			}
			foreach (ScrapItem scrapItem2 in scrapItems)
			{
				if (instance.allItemsList.itemsList.Contains(scrapItem2.item))
				{
					continue;
				}
				if (Plugin.extendedLogging.Value)
				{
					if (scrapItem2.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(scrapItem2.modName + " registered scrap item: " + scrapItem2.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered scrap item: " + scrapItem2.item.itemName));
					}
				}
				LethalLibItemList.Add(scrapItem2.item);
				instance.allItemsList.itemsList.Add(scrapItem2.item);
			}
			foreach (ShopItem shopItem in shopItems)
			{
				if (instance.allItemsList.itemsList.Contains(shopItem.item))
				{
					continue;
				}
				if (Plugin.extendedLogging.Value)
				{
					if (shopItem.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(shopItem.modName + " registered shop item: " + shopItem.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered shop item: " + shopItem.item.itemName));
					}
				}
				LethalLibItemList.Add(shopItem.item);
				instance.allItemsList.itemsList.Add(shopItem.item);
			}
			foreach (PlainItem plainItem in plainItems)
			{
				if (instance.allItemsList.itemsList.Contains(plainItem.item))
				{
					continue;
				}
				if (Plugin.extendedLogging.Value)
				{
					if (plainItem.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(plainItem.modName + " registered item: " + plainItem.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered item: " + plainItem.item.itemName));
					}
				}
				LethalLibItemList.Add(plainItem.item);
				instance.allItemsList.itemsList.Add(plainItem.item);
			}
			terminal = self;
			List<Item> list = self.buyableItemsList.ToList();
			TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			TerminalNode result = val2.compatibleNouns[0].result.terminalOptions[1].result;
			TerminalKeyword val3 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			Plugin.logger.LogInfo((object)$"Adding {shopItems.Count} items to terminal");
			foreach (ShopItem item in shopItems)
			{
				if (list.Any((Item x) => x.itemName == item.item.itemName) && !item.wasRemoved)
				{
					Plugin.logger.LogInfo((object)("Item " + item.item.itemName + " already exists in terminal, skipping"));
					continue;
				}
				item.wasRemoved = false;
				if (item.price == -1)
				{
					item.price = item.item.creditsWorth;
				}
				else
				{
					item.item.creditsWorth = item.price;
				}
				int num = -1;
				if (!list.Any((Item x) => (Object)(object)x == (Object)(object)item.item))
				{
					list.Add(item.item);
				}
				else
				{
					num = list.IndexOf(item.item);
				}
				int buyItemIndex = ((num == -1) ? (list.Count - 1) : num);
				string itemName = item.item.itemName;
				_ = itemName[itemName.Length - 1];
				string text = itemName;
				TerminalNode val4 = item.buyNode2;
				if ((Object)(object)val4 == (Object)null)
				{
					val4 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val4).name = itemName.Replace(" ", "-") + "BuyNode2";
					val4.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n";
					val4.clearPreviousText = true;
					val4.maxCharactersToType = 15;
				}
				val4.buyItemIndex = buyItemIndex;
				val4.isConfirmationNode = false;
				val4.itemCost = item.price;
				val4.playSyncedClip = 0;
				TerminalNode val5 = item.buyNode1;
				if ((Object)(object)val5 == (Object)null)
				{
					val5 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val5).name = itemName.Replace(" ", "-") + "BuyNode1";
					val5.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n";
					val5.clearPreviousText = true;
					val5.maxCharactersToType = 35;
				}
				val5.buyItemIndex = buyItemIndex;
				val5.isConfirmationNode = true;
				val5.overrideOptions = true;
				val5.itemCost = item.price;
				val5.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2]
				{
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"),
						result = val4
					},
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"),
						result = result
					}
				};
				TerminalKeyword val6 = TerminalUtils.CreateTerminalKeyword(itemName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val2);
				List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList();
				list2.Add(val6);
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list3 = val2.compatibleNouns.ToList();
				list3.Add(new CompatibleNoun
				{
					noun = val6,
					result = val5
				});
				val2.compatibleNouns = list3.ToArray();
				TerminalNode val7 = item.itemInfo;
				if ((Object)(object)val7 == (Object)null)
				{
					val7 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val7).name = itemName.Replace(" ", "-") + "InfoNode";
					val7.displayText = "[No information about this object was found.]\n\n";
					val7.clearPreviousText = true;
					val7.maxCharactersToType = 25;
				}
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list4 = val3.compatibleNouns.ToList();
				list4.Add(new CompatibleNoun
				{
					noun = val6,
					result = val7
				});
				val3.compatibleNouns = list4.ToArray();
				BuyableItemAssetInfo buyableItemAssetInfo = default(BuyableItemAssetInfo);
				buyableItemAssetInfo.itemAsset = item.item;
				buyableItemAssetInfo.keyword = val6;
				BuyableItemAssetInfo item3 = buyableItemAssetInfo;
				buyableItemAssetInfos.Add(item3);
				if (Plugin.extendedLogging.Value)
				{
					Plugin.logger.LogInfo((object)$"Added {itemName} to terminal (Item price: {val5.itemCost}, Item Index: {val5.buyItemIndex}, Terminal keyword: {val6.word})");
				}
			}
			self.buyableItemsList = list.ToArray();
			orig.Invoke(self);
		}

		public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					scrapItem.levelRarities.Add(levelFlags, rarity);
				}
			}
			else
			{
				scrapItem = new ScrapItem(spawnableItem2, rarity, levelFlags);
				string name = Assembly.GetCallingAssembly().GetName().Name;
				scrapItem.modName = name;
				scrapItems.Add(scrapItem);
			}
		}

		public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					scrapItem.levelRarities.Add(levelFlags, rarity);
				}
				if (levelOverrides != null)
				{
					foreach (string key in levelOverrides)
					{
						scrapItem.customLevelRarities.Add(key, rarity);
					}
				}
			}
			else
			{
				scrapItem = new ScrapItem(spawnableItem2, rarity, levelFlags, levelOverrides);
				string name = Assembly.GetCallingAssembly().GetName().Name;
				scrapItem.modName = name;
				scrapItems.Add(scrapItem);
			}
		}

		public static void RegisterScrap(Item spawnableItem, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelRarities != null)
				{
					foreach (KeyValuePair<Levels.LevelTypes, int> levelRarity in levelRarities)
					{
						scrapItem.levelRarities.Add(levelRarity.Key, levelRarity.Value);
					}
				}
				if (customLevelRarities == null)
				{
					return;
				}
				{
					foreach (KeyValuePair<string, int> customLevelRarity in customLevelRarities)
					{
						scrapItem.customLevelRarities.Add(customLevelRarity.Key, customLevelRarity.Value);
					}
					return;
				}
			}
			scrapItem = new ScrapItem(spawnableItem2, levelRarities, customLevelRarities);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			scrapItem.modName = name;
			scrapItems.Add(scrapItem);
		}

		public static void RegisterShopItem(Item shopItem, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1)
		{
			ShopItem shopItem2 = new ShopItem(shopItem, buyNode1, buyNode2, itemInfo, price);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			shopItem2.modName = name;
			shopItems.Add(shopItem2);
		}

		public static void RegisterShopItem(Item shopItem, int price = -1)
		{
			ShopItem shopItem2 = new ShopItem(shopItem, null, null, null, price);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			shopItem2.modName = name;
			shopItems.Add(shopItem2);
		}

		public static void RegisterItem(Item plainItem)
		{
			PlainItem plainItem2 = new PlainItem(plainItem);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			plainItem2.modName = name;
			plainItems.Add(plainItem2);
		}

		public static void RemoveScrapFromLevels(Item scrapItem, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			Item scrapItem2 = scrapItem;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					ScrapItem actualItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)scrapItem2 || (Object)(object)x.item == (Object)(object)scrapItem2);
					SpawnableItemWithRarity val2 = ((IEnumerable<SpawnableItemWithRarity>)val.spawnableScrap).FirstOrDefault((Func<SpawnableItemWithRarity, bool>)((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)actualItem.item));
					if (val2 != null)
					{
						val.spawnableScrap.Remove(val2);
					}
				}
			}
		}

		public static void RemoveShopItem(Item shopItem)
		{
			Item shopItem2 = shopItem;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem2 || (Object)(object)x.item == (Object)(object)shopItem2);
			actualItem.wasRemoved = true;
			List<TerminalKeyword> list = terminal.terminalNodes.allKeywords.ToList();
			TerminalKeyword obj = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			TerminalKeyword val = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			List<CompatibleNoun> list2 = val.compatibleNouns.ToList();
			List<CompatibleNoun> list3 = obj.compatibleNouns.ToList();
			if (buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item))
			{
				BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item);
				list.Remove(asset.keyword);
				list2.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
				list3.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
			}
			terminal.terminalNodes.allKeywords = list.ToArray();
			val.compatibleNouns = list2.ToArray();
			obj.compatibleNouns = list3.ToArray();
		}

		public static void UpdateShopItemPrice(Item shopItem, int price)
		{
			Item shopItem2 = shopItem;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem2 || (Object)(object)x.item == (Object)(object)shopItem2);
			actualItem.item.creditsWorth = price;
			TerminalKeyword obj = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			_ = obj.compatibleNouns[0].result.terminalOptions[1].result;
			List<CompatibleNoun> source = obj.compatibleNouns.ToList();
			if (!buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item))
			{
				return;
			}
			BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item);
			if (!source.Any((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword))
			{
				return;
			}
			TerminalNode result = source.First((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword).result;
			result.itemCost = price;
			if (result.terminalOptions.Length == 0)
			{
				return;
			}
			CompatibleNoun[] terminalOptions = result.terminalOptions;
			foreach (CompatibleNoun val in terminalOptions)
			{
				if ((Object)(object)val.result != (Object)null && val.result.buyItemIndex != -1)
				{
					val.result.itemCost = price;
				}
			}
		}
	}
	public class Levels
	{
		[Flags]
		public enum LevelTypes
		{
			None = 1,
			ExperimentationLevel = 4,
			AssuranceLevel = 8,
			VowLevel = 0x10,
			OffenseLevel = 0x20,
			MarchLevel = 0x40,
			RendLevel = 0x80,
			DineLevel = 0x100,
			TitanLevel = 0x200,
			Vanilla = 0x3FC,
			Modded = 0x400,
			All = -1
		}
	}
	public class MapObjects
	{
		public class RegisteredMapObject
		{
			public SpawnableMapObject mapObject;

			public SpawnableOutsideObjectWithRarity outsideObject;

			public Levels.LevelTypes levels;

			public string[] spawnLevelOverrides;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;
		}

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

			public static hook_SpawnMapObjects <1>__RoundManager_SpawnMapObjects;
		}

		public static List<RegisteredMapObject> mapObjects = new List<RegisteredMapObject>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__RoundManager_SpawnMapObjects;
			if (obj2 == null)
			{
				hook_SpawnMapObjects val2 = RoundManager_SpawnMapObjects;
				<>O.<1>__RoundManager_SpawnMapObjects = val2;
				obj2 = (object)val2;
			}
			RoundManager.SpawnMapObjects += (hook_SpawnMapObjects)obj2;
		}

		private static void RoundManager_SpawnMapObjects(orig_SpawnMapObjects orig, RoundManager self)
		{
			RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>();
			foreach (RandomMapObject val in array)
			{
				foreach (RegisteredMapObject mapObject in mapObjects)
				{
					if (mapObject.mapObject != null && !val.spawnablePrefabs.Any((GameObject prefab) => (Object)(object)prefab == (Object)(object)mapObject.mapObject.prefabToSpawn))
					{
						val.spawnablePrefabs.Add(mapObject.mapObject.prefabToSpawn);
					}
				}
			}
			orig.Invoke(self);
		}

		private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self)
		{
			orig.Invoke(self);
			foreach (RegisteredMapObject mapObject in mapObjects)
			{
				SelectableLevel[] levels = self.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = mapObject.levels.HasFlag(Levels.LevelTypes.All) || (mapObject.spawnLevelOverrides != null && mapObject.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (mapObject.levels.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
					{
						flag = true;
					}
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (!flag && !mapObject.levels.HasFlag(levelTypes))
					{
						continue;
					}
					if (mapObject.mapObject != null)
					{
						if (val.spawnableMapObjects.Any((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn))
						{
							List<SpawnableMapObject> list = val.spawnableMapObjects.ToList();
							list.RemoveAll((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn);
							val.spawnableMapObjects = list.ToArray();
						}
						SpawnableMapObject mapObject2 = mapObject.mapObject;
						if (mapObject.spawnRateFunction != null)
						{
							mapObject2.numberToSpawn = mapObject.spawnRateFunction(val);
						}
						List<SpawnableMapObject> list2 = val.spawnableMapObjects.ToList();
						list2.Add(mapObject2);
						val.spawnableMapObjects = list2.ToArray();
						if (Plugin.extendedLogging.Value)
						{
							Plugin.logger.LogInfo((object)("Added " + ((Object)mapObject2.prefabToSpawn).name + " to " + name));
						}
					}
					else
					{
						if (mapObject.outsideObject == null)
						{
							continue;
						}
						if (val.spawnableOutsideObjects.Any((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn))
						{
							List<SpawnableOutsideObjectWithRarity> list3 = val.spawnableOutsideObjects.ToList();
							list3.RemoveAll((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn);
							val.spawnableOutsideObjects = list3.ToArray();
						}
						SpawnableOutsideObjectWithRarity outsideObject = mapObject.outsideObject;
						if (mapObject.spawnRateFunction != null)
						{
							outsideObject.randomAmount = mapObject.spawnRateFunction(val);
						}
						List<SpawnableOutsideObjectWithRarity> list4 = val.spawnableOutsideObjects.ToList();
						list4.Add(outsideObject);
						val.spawnableOutsideObjects = list4.ToArray();
						if (Plugin.extendedLogging.Value)
						{
							Plugin.logger.LogInfo((object)("Added " + ((Object)outsideObject.spawnableObject.prefabToSpawn).name + " to " + name));
						}
					}
				}
			}
		}

		public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterMapObject(mapObject.spawnableMapObject, levels, spawnRateFunction);
		}

		public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterMapObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction);
		}

		public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				mapObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction
			});
		}

		public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				mapObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction,
				spawnLevelOverrides = levelOverrides
			});
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterOutsideObject(mapObject.spawnableMapObject, levels, spawnRateFunction);
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterOutsideObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction);
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				outsideObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction
			});
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				outsideObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction,
				spawnLevelOverrides = levelOverrides
			});
		}

		public static void RemoveMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			RemoveMapObject(mapObject.spawnableMapObject, levelFlags, levelOverrides);
		}

		public static void RemoveMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			SpawnableMapObject mapObject2 = mapObject;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					val.spawnableMapObjects = val.spawnableMapObjects.Where((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn != (Object)(object)mapObject2.prefabToSpawn).ToArray();
				}
			}
		}

		public static void RemoveOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			RemoveOutsideObject(mapObject.spawnableMapObject, levelFlags, levelOverrides);
		}

		public static void RemoveOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			SpawnableOutsideObjectWithRarity mapObject2 = mapObject;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name))
				{
					flag = true;
				}
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					val.spawnableOutsideObjects = val.spawnableOutsideObjects.Where((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn != (Object)(object)mapObject2.spawnableObject.prefabToSpawn).ToArray();
				}
			}
		}
	}
	public class NetworkPrefabs
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Start <0>__GameNetworkManager_Start;
		}

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

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

		public static void RegisterNetworkPrefab(GameObject prefab)
		{
			if (!_networkPrefabs.Contains(prefab))
			{
				_networkPrefabs.Add(prefab);
			}
		}

		public static GameObject CreateNetworkPrefab(string name)
		{
			GameObject obj = PrefabUtils.CreatePrefab(name);
			obj.AddComponent<NetworkObject>();
			byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetCallingAssembly().GetName().Name + name));
			obj.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0);
			RegisterNetworkPrefab(obj);
			return obj;
		}

		public static GameObject CloneNetworkPrefab(GameObject prefabToClone, string newName = null)
		{
			GameObject val = PrefabUtils.ClonePrefab(prefabToClone, newName);
			byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetCallingAssembly().GetName().Name + ((Object)val).name));
			val.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0);
			RegisterNetworkPrefab(val);
			return val;
		}

		private static void GameNetworkManager_Start(orig_Start orig, GameNetworkManager self)
		{
			orig.Invoke(self);
			foreach (GameObject networkPrefab in _networkPrefabs)
			{
				if (!NetworkManager.Singleton.NetworkConfig.Prefabs.Contains(networkPrefab))
				{
					NetworkManager.Singleton.AddNetworkPrefab(networkPrefab);
				}
			}
		}
	}
	public class Player
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__StartOfRound_Awake;
		}

		public static Dictionary<string, GameObject> ragdollRefs = new Dictionary<string, GameObject>();

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

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
		}

		private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self)
		{
			orig.Invoke(self);
			foreach (KeyValuePair<string, GameObject> ragdollRef in ragdollRefs)
			{
				if (!self.playerRagdolls.Contains(ragdollRef.Value))
				{
					self.playerRagdolls.Add(ragdollRef.Value);
					int value = self.playerRagdolls.Count - 1;
					if (ragdollIndexes.ContainsKey(ragdollRef.Key))
					{
						ragdollIndexes[ragdollRef.Key] = value;
					}
					else
					{
						ragdollIndexes.Add(ragdollRef.Key, value);
					}
				}
			}
		}

		public static int GetRagdollIndex(string id)
		{
			return ragdollIndexes[id];
		}

		public static GameObject GetRagdoll(string id)
		{
			return ragdollRefs[id];
		}

		public static void RegisterPlayerRagdoll(string id, GameObject ragdoll)
		{
			Plugin.logger.LogInfo((object)("Registering player ragdoll " + id));
			ragdollRefs.Add(id, ragdoll);
		}
	}
	public class PrefabUtils
	{
		internal static Lazy<GameObject> _prefabParent;

		internal static GameObject prefabParent => _prefabParent.Value;

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

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

		public static GameObject CreatePrefab(string name)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			GameObject val = new GameObject(name)
			{
				hideFlags = (HideFlags)61
			};
			val.transform.SetParent(prefabParent.transform);
			return val;
		}
	}
	public class Shaders
	{
		public static void FixShaders(GameObject gameObject)
		{
			Renderer[] componentsInChildren = gameObject.GetComponentsInChildren<Renderer>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Material[] materials = componentsInChildren[i].materials;
				foreach (Material val in materials)
				{
					if (((Object)val.shader).name.Contains("Standard"))
					{
						val.shader = Shader.Find("HDRP/Lit");
					}
				}
			}
		}
	}
	public class TerminalUtils
	{
		public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, CompatibleNoun[] compatibleNouns = null, TerminalNode specialKeywordResult = null, TerminalKeyword defaultVerb = null, bool accessTerminalObjects = false)
		{
			TerminalKeyword obj = ScriptableObject.CreateInstance<TerminalKeyword>();
			((Object)obj).name = word;
			obj.word = word;
			obj.isVerb = isVerb;
			obj.compatibleNouns = compatibleNouns;
			obj.specialKeywordResult = specialKeywordResult;
			obj.defaultVerb = defaultVerb;
			obj.accessTerminalObjects = accessTerminalObjects;
			return obj;
		}
	}
	public enum StoreType
	{
		None,
		ShipUpgrade,
		Decor
	}
	public class Unlockables
	{
		public class RegisteredUnlockable
		{
			public UnlockableItem unlockable;

			public StoreType StoreType;

			public TerminalNode buyNode1;

			public TerminalNode buyNode2;

			public TerminalNode itemInfo;

			public int price;

			public string modName;

			public bool disabled;

			public bool wasAlwaysInStock;

			public RegisteredUnlockable(UnlockableItem unlockable, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1)
			{
				this.unlockable = unlockable;
				this.buyNode1 = buyNode1;
				this.buyNode2 = buyNode2;
				this.itemInfo = itemInfo;
				this.price = price;
			}
		}

		public struct BuyableUnlockableAssetInfo
		{
			public UnlockableItem itemAsset;

			public TerminalKeyword keyword;
		}

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

			public static hook_TextPostProcess <1>__Terminal_TextPostProcess;

			public static hook_RotateShipDecorSelection <2>__Terminal_RotateShipDecorSelection;
		}

		public static List<RegisteredUnlockable> registeredUnlockables = new List<RegisteredUnlockable>();

		public static List<BuyableUnlockableAssetInfo> buyableUnlockableAssetInfos = new List<BuyableUnlockableAssetInfo>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			object obj = <>O.<0>__Terminal_Awake;
			if (obj == null)
			{
				hook_Awake val = Terminal_Awake;
				<>O.<0>__Terminal_Awake = val;
				obj = (object)val;
			}
			Terminal.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__Terminal_TextPostProcess;
			if (obj2 == null)
			{
				hook_TextPostProcess val2 = Terminal_TextPostProcess;
				<>O.<1>__Terminal_TextPostProcess = val2;
				obj2 = (object)val2;
			}
			Terminal.TextPostProcess += (hook_TextPostProcess)obj2;
			object obj3 = <>O.<2>__Terminal_RotateShipDecorSelection;
			if (obj3 == null)
			{
				hook_RotateShipDecorSelection val3 = Terminal_RotateShipDecorSelection;
				<>O.<2>__Terminal_RotateShipDecorSelection = val3;
				obj3 = (object)val3;
			}
			Terminal.RotateShipDecorSelection += (hook_RotateShipDecorSelection)obj3;
		}

		private static void Terminal_RotateShipDecorSelection(orig_RotateShipDecorSelection orig, Terminal self)
		{
			foreach (RegisteredUnlockable registeredUnlockable in registeredUnlockables)
			{
				if (registeredUnlockable.StoreType == StoreType.Decor && registeredUnlockable.disabled)
				{
					registeredUnlockable.wasAlwaysInStock = registeredUnlockable.unlockable.alwaysInStock;
					registeredUnlockable.unlockable.alwaysInStock = true;
				}
			}
			orig.Invoke(self);
			foreach (RegisteredUnlockable registeredUnlockable2 in registeredUnlockables)
			{
				if (registeredUnlockable2.StoreType == StoreType.Decor && registeredUnlockable2.disabled)
				{
					registeredUnlockable2.unlockable.alwaysInStock = registeredUnlockable2.wasAlwaysInStock;
				}
			}
		}

		private static string Terminal_TextPostProcess(orig_TextPostProcess orig, Terminal self, string modifiedDisplayText, TerminalNode node)
		{
			if (modifiedDisplayText.Contains("[buyableItemsList]") && modifiedDisplayText.Contains("[unlockablesSelectionList]"))
			{
				int num = modifiedDisplayText.IndexOf(":");
				foreach (RegisteredUnlockable registeredUnlockable in registeredUnlockables)
				{
					if (registeredUnlockable.StoreType == StoreType.ShipUpgrade && !registeredUnlockable.disabled)
					{
						string unlockableName = registeredUnlockable.unlockable.unlockableName;
						int price = registeredUnlockable.price;
						string value = $"\n* {unlockableName}    //    Price: ${price}";
						modifiedDisplayText = modifiedDisplayText.Insert(num + 1, value);
					}
				}
			}
			return orig.Invoke(self, modifiedDisplayText, node);
		}

		private static void Terminal_Awake(orig_Awake orig, Terminal self)
		{
			//IL_0473: Unknown result type (might be due to invalid IL or missing references)
			//IL_0478: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b6: Expected O, but got Unknown
			//IL_04b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fa: Expected O, but got Unknown
			//IL_0576: Unknown result type (might be due to invalid IL or missing references)
			//IL_057b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0588: Unknown result type (might be due to invalid IL or missing references)
			//IL_0595: Expected O, but got Unknown
			//IL_0621: Unknown result type (might be due to invalid IL or missing references)
			//IL_0626: Unknown result type (might be due to invalid IL or missing references)
			//IL_0633: Unknown result type (might be due to invalid IL or missing references)
			//IL_0640: Expected O, but got Unknown
			StartOfR

plugins/LethalPresents.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 Microsoft.CodeAnalysis;
using On;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LethalPresents")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("LethalPresents mod")]
[assembly: AssemblyFileVersion("1.0.4.0")]
[assembly: AssemblyInformationalVersion("1.0.4")]
[assembly: AssemblyProduct("LethalPresents")]
[assembly: AssemblyTitle("LethalPresents")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.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 LethalPresents
{
	[BepInPlugin("LethalPresents", "LethalPresents", "1.0.4")]
	public class LethalPresentsPlugin : BaseUnityPlugin
	{
		public static ManualLogSource mls;

		private static int spawnChance = 5;

		private static string[] disabledEnemies = new string[0];

		private static bool IsAllowlist = false;

		private static bool ShouldSpawnMines = false;

		private static bool ShouldSpawnTurrets = false;

		private static bool ShouldSpawnBees = false;

		private static bool isHost => ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost;

		private static SelectableLevel currentLevel => RoundManager.Instance.currentLevel;

		internal static T GetPrivateField<T>(object instance, string fieldName)
		{
			FieldInfo field = instance.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
			return (T)field.GetValue(instance);
		}

		private void Awake()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			mls = Logger.CreateLogSource("LethalPresents");
			mls.LogInfo((object)"Plugin LethalPresents is loaded!");
			loadConfig();
			RoundManager.AdvanceHourAndSpawnNewBatchOfEnemies += new hook_AdvanceHourAndSpawnNewBatchOfEnemies(updateCurrentLevelInfo);
			GiftBoxItem.OpenGiftBoxServerRpc += new hook_OpenGiftBoxServerRpc(spawnRandomEntity);
		}

		private void updateCurrentLevelInfo(orig_AdvanceHourAndSpawnNewBatchOfEnemies orig, RoundManager self)
		{
			orig.Invoke(self);
			mls.LogInfo((object)"List of spawnable enemies (inside):");
			currentLevel.Enemies.ForEach(delegate(SpawnableEnemyWithRarity e)
			{
				mls.LogInfo((object)((Object)e.enemyType).name);
			});
			mls.LogInfo((object)"List of spawnable enemies (outside):");
			currentLevel.OutsideEnemies.ForEach(delegate(SpawnableEnemyWithRarity e)
			{
				mls.LogInfo((object)((Object)e.enemyType).name);
			});
		}

		private void loadConfig()
		{
			spawnChance = ((BaseUnityPlugin)this).Config.Bind<int>("General", "SpawnChance", 5, "Chance of spawning an enemy when opening a present [0-100]").Value;
			disabledEnemies = ((BaseUnityPlugin)this).Config.Bind<string>("General", "EnemyBlocklist", "", "Enemy blocklist separated by , and without whitespaces").Value.Split(",");
			IsAllowlist = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "IsAllowlist", false, "Turns blocklist into allowlist, blocklist must contain at least one inside and one outside enemy, use at your own risk").Value;
			ShouldSpawnMines = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShouldSpawnMines", true, "Add mines to the spawn pool").Value;
			ShouldSpawnTurrets = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShouldSpawnTurrets", true, "Add turrets to the spawn pool").Value;
			if (IsAllowlist)
			{
				mls.LogInfo((object)"Only following enemies can spawn from the gift:");
			}
			else
			{
				mls.LogInfo((object)"Following enemies wont be spawned from the gift:");
			}
			string[] array = disabledEnemies;
			foreach (string text in array)
			{
				mls.LogInfo((object)text);
			}
		}

		private void spawnRandomEntity(orig_OpenGiftBoxServerRpc orig, GiftBoxItem self)
		{
			//IL_00fe: 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)
			NetworkManager networkManager = ((NetworkBehaviour)self).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				orig.Invoke(self);
				return;
			}
			int privateField = GetPrivateField<int>(self, "__rpc_exec_stage");
			mls.LogInfo((object)("IsServer:" + networkManager.IsServer + " IsHost:" + networkManager.IsHost + " __rpc_exec_stage:" + privateField));
			if (privateField != 1 || !isHost)
			{
				orig.Invoke(self);
				return;
			}
			int num = Random.Range(1, 100);
			mls.LogInfo((object)("Player's fortune:" + num));
			if (num >= spawnChance)
			{
				orig.Invoke(self);
				return;
			}
			chooseAndSpawnEnemy(((GrabbableObject)self).isInFactory, ((Component)self).transform.position, ((Component)self.previousPlayerHeldBy).transform.position);
			orig.Invoke(self);
		}

		private static void chooseAndSpawnEnemy(bool inside, Vector3 pos, Vector3 player_pos)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: 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_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: 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_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Unknown result type (might be due to invalid IL or missing references)
			//IL_033d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			//IL_034c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0351: 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_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_038a: Unknown result type (might be due to invalid IL or missing references)
			ManualLogSource obj = mls;
			Vector3 val = player_pos;
			obj.LogInfo((object)("Player pos " + ((object)(Vector3)(ref val)).ToString()));
			List<SpawnableEnemyWithRarity> list = currentLevel.Enemies.Where((SpawnableEnemyWithRarity e) => disabledEnemies.Contains(((Object)e.enemyType).name) ? IsAllowlist : (!IsAllowlist)).ToList();
			List<SpawnableEnemyWithRarity> list2 = currentLevel.OutsideEnemies.Where((SpawnableEnemyWithRarity e) => disabledEnemies.Contains(((Object)e.enemyType).name) ? IsAllowlist : (!IsAllowlist)).ToList();
			int num = Random.Range(1, 2 + (list2.Count + list.Count) / 2);
			if (num == 2 && !ShouldSpawnMines)
			{
				num = 1;
			}
			if (num == 1 && !ShouldSpawnTurrets)
			{
				num = 2;
			}
			if (num == 2 && !ShouldSpawnMines)
			{
				num = 3;
			}
			switch (num)
			{
			case 1:
			{
				SpawnableMapObject[] spawnableMapObjects2 = currentLevel.spawnableMapObjects;
				foreach (SpawnableMapObject val4 in spawnableMapObjects2)
				{
					if (!((Object)(object)val4.prefabToSpawn.GetComponentInChildren<Turret>() == (Object)null))
					{
						pos -= Vector3.up * 1.8f;
						GameObject val5 = Object.Instantiate<GameObject>(val4.prefabToSpawn, pos, Quaternion.identity);
						val5.transform.position = pos;
						Transform transform = val5.transform;
						val = player_pos - pos;
						transform.forward = ((Vector3)(ref val)).normalized;
						val5.GetComponent<NetworkObject>().Spawn(true);
						ManualLogSource obj3 = mls;
						val = pos;
						obj3.LogInfo((object)("Tried spawning a turret at " + ((object)(Vector3)(ref val)).ToString()));
						break;
					}
				}
				return;
			}
			case 2:
			{
				SpawnableMapObject[] spawnableMapObjects = currentLevel.spawnableMapObjects;
				foreach (SpawnableMapObject val2 in spawnableMapObjects)
				{
					if (!((Object)(object)val2.prefabToSpawn.GetComponentInChildren<Landmine>() == (Object)null))
					{
						pos -= Vector3.up * 1.8f;
						GameObject val3 = Object.Instantiate<GameObject>(val2.prefabToSpawn, pos, Quaternion.identity);
						val3.transform.position = pos;
						val3.transform.forward = new Vector3(1f, 0f, 0f);
						val3.GetComponent<NetworkObject>().Spawn(true);
						ManualLogSource obj2 = mls;
						val = pos;
						obj2.LogInfo((object)("Tried spawning a mine at " + ((object)(Vector3)(ref val)).ToString()));
						break;
					}
				}
				return;
			}
			}
			SpawnableEnemyWithRarity val6;
			if (inside)
			{
				if (list.Count < 1)
				{
					mls.LogInfo((object)"Cant spawn enemy - no other enemies present to copy from");
					return;
				}
				val6 = list[Random.Range(0, list.Count - 1)];
			}
			else
			{
				if (list2.Count < 1)
				{
					mls.LogInfo((object)"Cant spawn enemy - no other enemies present to copy from");
					return;
				}
				val6 = list2[Random.Range(0, list2.Count - 1)];
			}
			pos += Vector3.up * 0.25f;
			ManualLogSource obj4 = mls;
			string enemyName = val6.enemyType.enemyName;
			val = pos;
			obj4.LogInfo((object)("Spawning " + enemyName + " at " + ((object)(Vector3)(ref val)).ToString()));
			SpawnEnemy(val6, pos, 0f);
		}

		private static void SpawnEnemy(SpawnableEnemyWithRarity enemy, Vector3 pos, float rot)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			RoundManager.Instance.SpawnEnemyGameObject(pos, rot, -1, enemy.enemyType);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LethalPresents";

		public const string PLUGIN_NAME = "LethalPresents";

		public const string PLUGIN_VERSION = "1.0.4";
	}
}

plugins/LethalSDK.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.RegularExpressions;
using DunGen;
using DunGen.Adapters;
using GameNetcodeStuff;
using LethalSDK.Component;
using LethalSDK.ScriptableObjects;
using LethalSDK.Utils;
using Unity.Netcode;
using UnityEditor;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.Video;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("LethalSDK")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LethalSDK")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4d234a4d-c807-438a-b717-4c6d77706054")]
[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")]
public class AssetModificationProcessor : AssetPostprocessor
{
	private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
	{
		foreach (string assetPath in importedAssets)
		{
			ProcessAsset(assetPath);
		}
		foreach (string assetPath2 in movedAssets)
		{
			ProcessAsset(assetPath2);
		}
	}

	private static void ProcessAsset(string assetPath)
	{
		if (assetPath.Contains("NavMesh-Environment"))
		{
			AssetDatabase.RenameAsset(assetPath, (SelectionLogger.name != string.Empty) ? (SelectionLogger.name + "NavMesh") : "New NavMesh");
		}
		if (assetPath.Contains("New Terrain"))
		{
			AssetDatabase.RenameAsset(assetPath, (SelectionLogger.name != string.Empty) ? SelectionLogger.name : "New Terrain");
		}
		if (assetPath.ToLower().StartsWith("assets/mods/") && assetPath.Split(new char[1] { '/' }).Length > 3 && !assetPath.ToLower().EndsWith(".unity") && !assetPath.ToLower().Contains("/scenes"))
		{
			AssetImporter atPath = AssetImporter.GetAtPath(assetPath);
			if ((Object)(object)atPath != (Object)null)
			{
				string text2 = (atPath.assetBundleName = ExtractBundleNameFromPath(assetPath));
				atPath.assetBundleVariant = "lem";
				Debug.Log((object)(assetPath + " asset moved to " + text2 + " asset bundle."));
			}
			if (assetPath != "Assets/Mods/" + assetPath.Replace("Assets/Mods/", string.Empty).RemoveNonAlphanumeric(4))
			{
				AssetDatabase.MoveAsset(assetPath, "Assets/Mods/" + assetPath.Replace("Assets/Mods/", string.Empty).RemoveNonAlphanumeric(4));
			}
		}
		else
		{
			AssetImporter atPath2 = AssetImporter.GetAtPath(assetPath);
			if ((Object)(object)atPath2 != (Object)null)
			{
				atPath2.assetBundleName = null;
				Debug.Log((object)(assetPath + " asset removed from asset bundle."));
			}
		}
	}

	public static string ExtractBundleNameFromPath(string path)
	{
		string[] array = path.Split(new char[1] { '/' });
		if (array.Length > 3)
		{
			return array[2].ToLower();
		}
		return "";
	}
}
[InitializeOnLoad]
public class SelectionLogger
{
	public static string name;

	static SelectionLogger()
	{
		Selection.selectionChanged = (Action)Delegate.Combine(Selection.selectionChanged, new Action(OnSelectionChanged));
	}

	private static void OnSelectionChanged()
	{
		if ((Object)(object)Selection.activeGameObject != (Object)null)
		{
			name = ((Object)GetRootParent(Selection.activeGameObject)).name;
		}
		else
		{
			name = string.Empty;
		}
	}

	public static GameObject GetRootParent(GameObject obj)
	{
		if ((Object)(object)obj != (Object)null && (Object)(object)obj.transform.parent != (Object)null)
		{
			return GetRootParent(((Component)obj.transform.parent).gameObject);
		}
		return obj;
	}
}
[InitializeOnLoad]
public class AssetBundleVariantAssigner
{
	static AssetBundleVariantAssigner()
	{
		AssignVariantToAssetBundles();
	}

	[InitializeOnLoadMethod]
	private static void AssignVariantToAssetBundles()
	{
		string[] allAssetBundleNames = AssetDatabase.GetAllAssetBundleNames();
		string[] array = allAssetBundleNames;
		foreach (string text in array)
		{
			if (!text.Contains("."))
			{
				string[] assetPathsFromAssetBundle = AssetDatabase.GetAssetPathsFromAssetBundle(text);
				string[] array2 = assetPathsFromAssetBundle;
				foreach (string text2 in array2)
				{
					AssetImporter.GetAtPath(text2).SetAssetBundleNameAndVariant(text, "lem");
				}
				Debug.Log((object)("File extention added to AssetBundle: " + text));
			}
		}
		AssetDatabase.SaveAssets();
		string text3 = "Assets/AssetBundles";
		if (!Directory.Exists(text3))
		{
			Debug.LogError((object)("The folder doesn't exist : " + text3));
			return;
		}
		string[] files = Directory.GetFiles(text3);
		string[] array3 = files;
		foreach (string text4 in array3)
		{
			if (Path.GetExtension(text4) == "" && Path.GetFileName(text4) != "AssetBundles")
			{
				string path = text4 + ".meta";
				string text5 = text4 + ".manifest";
				string path2 = text5 + ".meta";
				File.Delete(text4);
				if (File.Exists(path))
				{
					File.Delete(path);
				}
				if (File.Exists(text5))
				{
					File.Delete(text5);
				}
				if (File.Exists(path2))
				{
					File.Delete(path2);
				}
				Debug.Log((object)("File deleted : " + text4));
			}
		}
		AssetDatabase.Refresh();
	}
}
public class CubemapTextureBuilder : EditorWindow
{
	private Texture2D[] textures = (Texture2D[])(object)new Texture2D[6];

	private string[] labels = new string[6] { "Right", "Left", "Top", "Bottom", "Front", "Back" };

	private TextureFormat[] HDRFormats;

	private Vector2Int[] placementRects;

	[MenuItem("LethalSDK/Cubemap Builder", false, 100)]
	public static void OpenWindow()
	{
		EditorWindow.GetWindow<CubemapTextureBuilder>();
	}

	private Texture2D UpscaleTexture(Texture2D original, int targetWidth, int targetHeight)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Expected O, but got Unknown
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		RenderTexture val = (RenderTexture.active = RenderTexture.GetTemporary(targetWidth, targetHeight));
		Graphics.Blit((Texture)(object)original, val);
		Texture2D val2 = new Texture2D(targetWidth, targetHeight);
		val2.ReadPixels(new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), 0, 0);
		val2.Apply();
		RenderTexture.ReleaseTemporary(val);
		return val2;
	}

	private void OnGUI()
	{
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0256: Expected O, but got Unknown
		for (int i = 0; i < 6; i++)
		{
			ref Texture2D reference = ref textures[i];
			Object obj = EditorGUILayout.ObjectField(labels[i], (Object)(object)textures[i], typeof(Texture2D), false, Array.Empty<GUILayoutOption>());
			reference = (Texture2D)(object)((obj is Texture2D) ? obj : null);
		}
		if (!GUILayout.Button("Build Cubemap", Array.Empty<GUILayoutOption>()))
		{
			return;
		}
		if (textures.Any((Texture2D t) => (Object)(object)t == (Object)null))
		{
			EditorUtility.DisplayDialog("Cubemap Builder Error", "One or more texture is missing.", "Ok");
			return;
		}
		int size = ((Texture)textures[0]).width;
		if (textures.Any((Texture2D t) => ((Texture)t).width != size || ((Texture)t).height != size))
		{
			EditorUtility.DisplayDialog("Cubemap Builder Error", "All the textures need to be the same size and square.", "Ok");
			return;
		}
		bool flag = HDRFormats.Any((TextureFormat f) => f == textures[0].format);
		string[] array = textures.Select((Texture2D t) => AssetDatabase.GetAssetPath((Object)(object)t)).ToArray();
		string text = EditorUtility.SaveFilePanel("Save Cubemap", Path.GetDirectoryName(array[0]), "Cubemap", flag ? "exr" : "png");
		if (!string.IsNullOrEmpty(text))
		{
			bool[] array2 = textures.Select((Texture2D t) => ((Texture)t).isReadable).ToArray();
			TextureImporter[] array3 = array.Select(delegate(string p)
			{
				AssetImporter atPath2 = AssetImporter.GetAtPath(p);
				return (TextureImporter)(object)((atPath2 is TextureImporter) ? atPath2 : null);
			}).ToArray();
			TextureImporter[] array4 = array3;
			foreach (TextureImporter val in array4)
			{
				val.isReadable = true;
			}
			AssetDatabase.Refresh();
			string[] array5 = array;
			foreach (string text2 in array5)
			{
				AssetDatabase.ImportAsset(text2);
			}
			Texture2D val2 = new Texture2D(size * 4, size * 3, (TextureFormat)(flag ? 20 : 4), false);
			for (int l = 0; l < 6; l++)
			{
				val2.SetPixels(((Vector2Int)(ref placementRects[l])).x * size, ((Vector2Int)(ref placementRects[l])).y * size, size, size, textures[l].GetPixels(0));
			}
			val2.Apply(false);
			byte[] bytes = (flag ? ImageConversion.EncodeToEXR(val2) : ImageConversion.EncodeToPNG(val2));
			File.WriteAllBytes(text, bytes);
			Object.Destroy((Object)(object)val2);
			for (int m = 0; m < 6; m++)
			{
				array3[m].isReadable = array2[m];
			}
			text = text.Remove(0, Application.dataPath.Length - 6);
			AssetDatabase.ImportAsset(text);
			AssetImporter atPath = AssetImporter.GetAtPath(text);
			TextureImporter val3 = (TextureImporter)(object)((atPath is TextureImporter) ? atPath : null);
			val3.textureShape = (TextureImporterShape)2;
			val3.sRGBTexture = false;
			val3.generateCubemap = (TextureImporterGenerateCubemap)5;
			string[] array6 = array;
			foreach (string text3 in array6)
			{
				AssetDatabase.ImportAsset(text3);
			}
			AssetDatabase.ImportAsset(text);
			AssetDatabase.Refresh();
		}
	}

	public CubemapTextureBuilder()
	{
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
		TextureFormat[] array = new TextureFormat[9];
		RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
		HDRFormats = (TextureFormat[])(object)array;
		placementRects = (Vector2Int[])(object)new Vector2Int[6]
		{
			new Vector2Int(2, 1),
			new Vector2Int(0, 1),
			new Vector2Int(1, 2),
			new Vector2Int(1, 0),
			new Vector2Int(1, 1),
			new Vector2Int(3, 1)
		};
		((EditorWindow)this)..ctor();
	}
}
public class PlayerShip : MonoBehaviour
{
	public readonly Vector3 shipPosition = new Vector3(-17.5f, 5.75f, -16.55f);

	private void Start()
	{
		Object.Destroy((Object)(object)this);
	}
}
[CustomEditor(typeof(PlayerShip))]
public class PlayerShipEditor : Editor
{
	public override void OnInspectorGUI()
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		((Editor)this).OnInspectorGUI();
		PlayerShip playerShip = (PlayerShip)(object)((Editor)this).target;
		if (((Component)playerShip).transform.position != playerShip.shipPosition)
		{
			((Component)playerShip).transform.position = playerShip.shipPosition;
		}
	}
}
namespace LethalSDK.ScriptableObjects
{
	[CreateAssetMenu(fileName = "AssetBank", menuName = "LethalSDK/Asset Bank")]
	public class AssetBank : ScriptableObject
	{
		[Header("Audio Clips")]
		[SerializeField]
		private AudioClipInfoPair[] _audioClips = new AudioClipInfoPair[0];

		[SerializeField]
		private PlanetPrefabInfoPair[] _planetPrefabs = new PlanetPrefabInfoPair[0];

		[SerializeField]
		private PrefabInfoPair[] _networkPrefabs = new PrefabInfoPair[0];

		[HideInInspector]
		public string serializedAudioClips;

		[HideInInspector]
		public string serializedPlanetPrefabs;

		[HideInInspector]
		public string serializedNetworkPrefabs;

		private void OnValidate()
		{
			for (int i = 0; i < _audioClips.Length; i++)
			{
				_audioClips[i].AudioClipName = _audioClips[i].AudioClipName.RemoveNonAlphanumeric(1);
				_audioClips[i].AudioClipPath = _audioClips[i].AudioClipPath.RemoveNonAlphanumeric(4);
			}
			for (int j = 0; j < _planetPrefabs.Length; j++)
			{
				_planetPrefabs[j].PlanetPrefabName = _planetPrefabs[j].PlanetPrefabName.RemoveNonAlphanumeric(1);
				_planetPrefabs[j].PlanetPrefabPath = _planetPrefabs[j].PlanetPrefabPath.RemoveNonAlphanumeric(4);
			}
			for (int k = 0; k < _networkPrefabs.Length; k++)
			{
				_networkPrefabs[k].PrefabName = _networkPrefabs[k].PrefabName.RemoveNonAlphanumeric(1);
				_networkPrefabs[k].PrefabPath = _networkPrefabs[k].PrefabPath.RemoveNonAlphanumeric(4);
			}
			serializedAudioClips = string.Join(";", _audioClips.Select((AudioClipInfoPair p) => ((p.AudioClipName.Length != 0) ? p.AudioClipName : (((Object)(object)p.AudioClip != (Object)null) ? ((Object)p.AudioClip).name : "")) + "," + AssetDatabase.GetAssetPath((Object)(object)p.AudioClip)));
			serializedPlanetPrefabs = string.Join(";", _planetPrefabs.Select((PlanetPrefabInfoPair p) => ((p.PlanetPrefabName.Length != 0) ? p.PlanetPrefabName : (((Object)(object)p.PlanetPrefab != (Object)null) ? ((Object)p.PlanetPrefab).name : "")) + "," + AssetDatabase.GetAssetPath((Object)(object)p.PlanetPrefab)));
			serializedNetworkPrefabs = string.Join(";", _networkPrefabs.Select((PrefabInfoPair p) => ((p.PrefabName.Length != 0) ? p.PrefabName : (((Object)(object)p.Prefab != (Object)null) ? ((Object)p.Prefab).name : "")) + "," + AssetDatabase.GetAssetPath((Object)(object)p.Prefab)));
		}

		public AudioClipInfoPair[] AudioClips()
		{
			if (serializedAudioClips != null)
			{
				return (from s in serializedAudioClips.Split(new char[1] { ';' })
					select s.Split(new char[1] { ',' }) into split
					where split.Length == 2
					select new AudioClipInfoPair(split[0], split[1])).ToArray();
			}
			return new AudioClipInfoPair[0];
		}

		public bool HaveAudioClip(string audioClipName)
		{
			if (serializedAudioClips != null)
			{
				return AudioClips().Any((AudioClipInfoPair a) => a.AudioClipName == audioClipName);
			}
			return false;
		}

		public string AudioClipPath(string audioClipName)
		{
			if (serializedAudioClips != null)
			{
				return AudioClips().First((AudioClipInfoPair c) => c.AudioClipName == audioClipName).AudioClipPath;
			}
			return string.Empty;
		}

		public Dictionary<string, string> AudioClipsDictionary()
		{
			if (serializedAudioClips != null)
			{
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				AudioClipInfoPair[] audioClips = _audioClips;
				for (int i = 0; i < audioClips.Length; i++)
				{
					AudioClipInfoPair audioClipInfoPair = audioClips[i];
					dictionary.Add(audioClipInfoPair.AudioClipName, audioClipInfoPair.AudioClipPath);
				}
				return dictionary;
			}
			return new Dictionary<string, string>();
		}

		public PlanetPrefabInfoPair[] PlanetPrefabs()
		{
			if (serializedPlanetPrefabs != null)
			{
				return (from s in serializedPlanetPrefabs.Split(new char[1] { ';' })
					select s.Split(new char[1] { ',' }) into split
					where split.Length == 2
					select new PlanetPrefabInfoPair(split[0], split[1])).ToArray();
			}
			return new PlanetPrefabInfoPair[0];
		}

		public bool HavePlanetPrefabs(string planetPrefabName)
		{
			if (serializedPlanetPrefabs != null)
			{
				return PlanetPrefabs().Any((PlanetPrefabInfoPair a) => a.PlanetPrefabName == planetPrefabName);
			}
			return false;
		}

		public string PlanetPrefabsPath(string planetPrefabName)
		{
			if (serializedPlanetPrefabs != null)
			{
				return PlanetPrefabs().First((PlanetPrefabInfoPair c) => c.PlanetPrefabName == planetPrefabName).PlanetPrefabPath;
			}
			return string.Empty;
		}

		public Dictionary<string, string> PlanetPrefabsDictionary()
		{
			if (serializedPlanetPrefabs != null)
			{
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				PlanetPrefabInfoPair[] planetPrefabs = _planetPrefabs;
				for (int i = 0; i < planetPrefabs.Length; i++)
				{
					PlanetPrefabInfoPair planetPrefabInfoPair = planetPrefabs[i];
					dictionary.Add(planetPrefabInfoPair.PlanetPrefabName, planetPrefabInfoPair.PlanetPrefabPath);
				}
				return dictionary;
			}
			return new Dictionary<string, string>();
		}

		public PrefabInfoPair[] NetworkPrefabs()
		{
			if (serializedNetworkPrefabs != null)
			{
				return (from s in serializedNetworkPrefabs.Split(new char[1] { ';' })
					select s.Split(new char[1] { ',' }) into split
					where split.Length == 2
					select new PrefabInfoPair(split[0], split[1])).ToArray();
			}
			return new PrefabInfoPair[0];
		}

		public bool HaveNetworkPrefabs(string networkPrefabName)
		{
			if (serializedNetworkPrefabs != null)
			{
				return NetworkPrefabs().Any((PrefabInfoPair a) => a.PrefabName == networkPrefabName);
			}
			return false;
		}

		public string NetworkPrefabsPath(string networkPrefabName)
		{
			if (serializedNetworkPrefabs != null)
			{
				return NetworkPrefabs().First((PrefabInfoPair c) => c.PrefabName == networkPrefabName).PrefabPath;
			}
			return string.Empty;
		}

		public Dictionary<string, string> NetworkPrefabsDictionary()
		{
			if (serializedNetworkPrefabs != null)
			{
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				PrefabInfoPair[] networkPrefabs = _networkPrefabs;
				for (int i = 0; i < networkPrefabs.Length; i++)
				{
					PrefabInfoPair prefabInfoPair = networkPrefabs[i];
					dictionary.Add(prefabInfoPair.PrefabName, prefabInfoPair.PrefabPath);
				}
				return dictionary;
			}
			return new Dictionary<string, string>();
		}
	}
	[CreateAssetMenu(fileName = "ModManifest", menuName = "LethalSDK/Mod Manifest")]
	public class ModManifest : ScriptableObject
	{
		public string modName = "New Mod";

		[Space]
		[SerializeField]
		private SerializableVersion version = new SerializableVersion(0, 0, 0, 0);

		[HideInInspector]
		public string serializedVersion;

		[Space]
		public string author = "Author";

		[Space]
		[TextArea(5, 15)]
		public string description = "Mod Description";

		[Space]
		[Header("Content")]
		public Scrap[] scraps = new Scrap[0];

		public Moon[] moons = new Moon[0];

		[Space]
		public AssetBank assetBank;

		private void OnValidate()
		{
			serializedVersion = version.ToString();
		}

		public SerializableVersion GetVersion()
		{
			int[] array = ((serializedVersion != null) ? serializedVersion.Split(new char[1] { '.' }).Select(int.Parse).ToArray() : new int[4]);
			return new SerializableVersion(array[0], array[1], array[2], array[3]);
		}
	}
	[CreateAssetMenu(fileName = "New Moon", menuName = "LethalSDK/Moon")]
	public class Moon : ScriptableObject
	{
		public string MoonName = "NewMoon";

		public string[] RequiredBundles;

		public string[] IncompatibleBundles;

		public bool IsEnabled = true;

		public bool IsHidden = false;

		public bool IsLocked = false;

		[Header("Info")]
		public string OrbitPrefabName = "Moon1";

		public bool SpawnEnemiesAndScrap = true;

		public string PlanetName = "New Moon";

		public GameObject MainPrefab;

		[TextArea(5, 15)]
		public string PlanetDescription;

		[TextArea(5, 15)]
		public string PlanetLore;

		public VideoClip PlanetVideo;

		public string RiskLevel = "X";

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

		[Header("Time")]
		[Range(0.1f, 5f)]
		public float DaySpeedMultiplier = 1f;

		public bool PlanetHasTime = true;

		[SerializeField]
		private RandomWeatherPair[] _RandomWeatherTypes = new RandomWeatherPair[6]
		{
			new RandomWeatherPair(LevelWeatherType.None, 0, 0),
			new RandomWeatherPair(LevelWeatherType.Rainy, 0, 0),
			new RandomWeatherPair(LevelWeatherType.Stormy, 1, 0),
			new RandomWeatherPair(LevelWeatherType.Foggy, 1, 0),
			new RandomWeatherPair(LevelWeatherType.Flooded, -4, 5),
			new RandomWeatherPair(LevelWeatherType.Eclipsed, 1, 0)
		};

		public bool OverwriteWeather = false;

		public LevelWeatherType OverwriteWeatherType = LevelWeatherType.None;

		[Header("Route")]
		public string RouteWord = "newmoon";

		public int RoutePrice;

		public string BoughtComment = "Please enjoy your flight.";

		[Header("Dungeon")]
		[Range(1f, 5f)]
		public float FactorySizeMultiplier = 1f;

		public int FireExitsAmountOverwrite = 1;

		[SerializeField]
		private DungeonFlowPair[] _DungeonFlowTypes = new DungeonFlowPair[2]
		{
			new DungeonFlowPair(0, 300),
			new DungeonFlowPair(1, 1)
		};

		[SerializeField]
		private SpawnableScrapPair[] _SpawnableScrap = new SpawnableScrapPair[19]
		{
			new SpawnableScrapPair("Cog1", 80),
			new SpawnableScrapPair("EnginePart1", 90),
			new SpawnableScrapPair("FishTestProp", 12),
			new SpawnableScrapPair("MetalSheet", 88),
			new SpawnableScrapPair("FlashLaserPointer", 4),
			new SpawnableScrapPair("BigBolt", 80),
			new SpawnableScrapPair("BottleBin", 19),
			new SpawnableScrapPair("Ring", 3),
			new SpawnableScrapPair("SteeringWheel", 32),
			new SpawnableScrapPair("MoldPan", 5),
			new SpawnableScrapPair("EggBeater", 10),
			new SpawnableScrapPair("PickleJar", 10),
			new SpawnableScrapPair("DustPan", 32),
			new SpawnableScrapPair("Airhorn", 3),
			new SpawnableScrapPair("ClownHorn", 3),
			new SpawnableScrapPair("CashRegister", 3),
			new SpawnableScrapPair("Candy", 2),
			new SpawnableScrapPair("GoldBar", 1),
			new SpawnableScrapPair("YieldSign", 6)
		};

		public string[] spawnableScrapBlacklist = new string[0];

		[Range(0f, 100f)]
		public int MinScrap = 8;

		[Range(0f, 100f)]
		public int MaxScrap = 12;

		public string LevelAmbienceClips = "Level1TypeAmbience";

		[Range(0f, 30f)]
		public int MaxEnemyPowerCount = 4;

		[SerializeField]
		private SpawnableEnemiesPair[] _Enemies = new SpawnableEnemiesPair[8]
		{
			new SpawnableEnemiesPair("Centipede", 51),
			new SpawnableEnemiesPair("SandSpider", 58),
			new SpawnableEnemiesPair("HoarderBug", 28),
			new SpawnableEnemiesPair("Flowerman", 13),
			new SpawnableEnemiesPair("Crawler", 16),
			new SpawnableEnemiesPair("Blob", 31),
			new SpawnableEnemiesPair("DressGirl", 1),
			new SpawnableEnemiesPair("Puffer", 28)
		};

		public AnimationCurve EnemySpawnChanceThroughoutDay = CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0015411376953125,\"value\":-3.0,\"inSlope\":19.556997299194337,\"outSlope\":19.556997299194337,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0,\"outWeight\":0.12297855317592621},{\"serializedVersion\":\"3\",\"time\":0.4575331211090088,\"value\":4.796203136444092,\"inSlope\":24.479534149169923,\"outSlope\":24.479534149169923,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.396077424287796,\"outWeight\":0.35472238063812258},{\"serializedVersion\":\"3\",\"time\":0.7593884468078613,\"value\":4.973001480102539,\"inSlope\":2.6163148880004885,\"outSlope\":2.6163148880004885,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.2901076376438141,\"outWeight\":0.5360636115074158},{\"serializedVersion\":\"3\",\"time\":1.0,\"value\":15.0,\"inSlope\":35.604026794433597,\"outSlope\":35.604026794433597,\"tangentMode\":0,\"weightedMode\":1,\"inWeight\":0.04912583902478218,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}");

		[Range(0f, 30f)]
		public float SpawnProbabilityRange = 4f;

		[Header("Outside")]
		[SerializeField]
		private SpawnableMapObjectPair[] _SpawnableMapObjects = new SpawnableMapObjectPair[2]
		{
			new SpawnableMapObjectPair("Landmine", spawnFacingAwayFromWall: false, CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":-0.003082275390625,\"value\":0.0,\"inSlope\":0.23179344832897187,\"outSlope\":0.23179344832897187,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27936428785324099},{\"serializedVersion\":\"3\",\"time\":0.8171924352645874,\"value\":1.7483322620391846,\"inSlope\":7.064207077026367,\"outSlope\":7.064207077026367,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.2631833553314209,\"outWeight\":0.6898177862167358},{\"serializedVersion\":\"3\",\"time\":1.0002186298370362,\"value\":11.760997772216797,\"inSlope\":968.80810546875,\"outSlope\":968.80810546875,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.029036391526460649,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableMapObjectPair("TurretContainer", spawnFacingAwayFromWall: true, CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.354617178440094,\"outSlope\":0.354617178440094,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.9190289974212647,\"value\":1.0005745887756348,\"inSlope\":Infinity,\"outSlope\":1.7338485717773438,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0,\"outWeight\":0.6534967422485352},{\"serializedVersion\":\"3\",\"time\":1.0038425922393799,\"value\":7.198680877685547,\"inSlope\":529.4945068359375,\"outSlope\":529.4945068359375,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.14589552581310273,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}"))
		};

		[SerializeField]
		private SpawnableOutsideObjectPair[] _SpawnableOutsideObjects = new SpawnableOutsideObjectPair[7]
		{
			new SpawnableOutsideObjectPair("LargeRock1", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.7571572661399841,\"value\":0.6448163986206055,\"inSlope\":2.974250078201294,\"outSlope\":2.974250078201294,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.3333333432674408,\"outWeight\":0.3333333432674408},{\"serializedVersion\":\"3\",\"time\":0.9995536804199219,\"value\":5.883961200714111,\"inSlope\":65.30631256103516,\"outSlope\":65.30631256103516,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.12097536772489548,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("LargeRock2", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.7562879920005798,\"value\":1.2308543920516968,\"inSlope\":5.111926555633545,\"outSlope\":5.111926555633545,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.3333333432674408,\"outWeight\":0.21955738961696626},{\"serializedVersion\":\"3\",\"time\":1.0010795593261719,\"value\":7.59307336807251,\"inSlope\":92.0470199584961,\"outSlope\":92.0470199584961,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.05033162236213684,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("LargeRock3", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.9964686632156372,\"value\":2.0009398460388185,\"inSlope\":6.82940673828125,\"outSlope\":6.82940673828125,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.06891261041164398,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("LargeRock4", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.9635604619979858,\"value\":2.153383493423462,\"inSlope\":6.251225471496582,\"outSlope\":6.251225471496582,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.07428120821714401,\"outWeight\":0.3333333432674408},{\"serializedVersion\":\"3\",\"time\":0.9995394349098206,\"value\":5.0,\"inSlope\":15.746581077575684,\"outSlope\":15.746581077575684,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.06317413598299027,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("TreeLeafless1", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":1.6912956237792969,\"outSlope\":1.6912956237792969,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27726083993911745},{\"serializedVersion\":\"3\",\"time\":0.776531994342804,\"value\":6.162014007568359,\"inSlope\":30.075166702270509,\"outSlope\":30.075166702270509,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.15920747816562653,\"outWeight\":0.5323987007141113},{\"serializedVersion\":\"3\",\"time\":1.0002281665802003,\"value\":38.093849182128909,\"inSlope\":1448.839111328125,\"outSlope\":1448.839111328125,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0620061457157135,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("SmallGreyRocks1", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":1.6912956237792969,\"outSlope\":1.6912956237792969,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27726083993911745},{\"serializedVersion\":\"3\",\"time\":0.802714467048645,\"value\":1.5478605031967164,\"inSlope\":9.096116065979004,\"outSlope\":9.096116065979004,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.15920747816562653,\"outWeight\":0.58766108751297},{\"serializedVersion\":\"3\",\"time\":1.0002281665802003,\"value\":14.584033966064454,\"inSlope\":1244.9173583984375,\"outSlope\":1244.9173583984375,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.054620321840047839,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("GiantPumpkin", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":1.6912956237792969,\"outSlope\":1.6912956237792969,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27726083993911745},{\"serializedVersion\":\"3\",\"time\":0.8832725882530212,\"value\":0.5284063816070557,\"inSlope\":3.2962090969085695,\"outSlope\":29.38977813720703,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.19772815704345704,\"outWeight\":0.8989489078521729},{\"serializedVersion\":\"3\",\"time\":0.972209095954895,\"value\":6.7684478759765629,\"inSlope\":140.27394104003907,\"outSlope\":140.27394104003907,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.39466607570648196,\"outWeight\":0.47049039602279665},{\"serializedVersion\":\"3\",\"time\":1.0002281665802003,\"value\":23.0,\"inSlope\":579.3037109375,\"outSlope\":14.8782377243042,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.648808479309082,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}"))
		};

		[Range(0f, 30f)]
		public int MaxOutsideEnemyPowerCount = 8;

		[Range(0f, 30f)]
		public int MaxDaytimeEnemyPowerCount = 5;

		[SerializeField]
		private SpawnableEnemiesPair[] _OutsideEnemies = new SpawnableEnemiesPair[3]
		{
			new SpawnableEnemiesPair("MouthDog", 75),
			new SpawnableEnemiesPair("ForestGiant", 0),
			new SpawnableEnemiesPair("SandWorm", 56)
		};

		[SerializeField]
		private SpawnableEnemiesPair[] _DaytimeEnemies = new SpawnableEnemiesPair[3]
		{
			new SpawnableEnemiesPair("RedLocustBees", 22),
			new SpawnableEnemiesPair("Doublewing", 74),
			new SpawnableEnemiesPair("DocileLocustBees", 52)
		};

		public AnimationCurve OutsideEnemySpawnChanceThroughDay = CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":-7.736962288618088e-7,\"value\":-2.996999979019165,\"inSlope\":Infinity,\"outSlope\":0.5040292143821716,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0,\"outWeight\":0.08937685936689377},{\"serializedVersion\":\"3\",\"time\":0.7105481624603272,\"value\":-0.6555822491645813,\"inSlope\":9.172262191772461,\"outSlope\":9.172262191772461,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.3333333432674408,\"outWeight\":0.7196550369262695},{\"serializedVersion\":\"3\",\"time\":1.0052626132965088,\"value\":5.359400749206543,\"inSlope\":216.42247009277345,\"outSlope\":11.374387741088868,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.044637180864810947,\"outWeight\":0.48315444588661196}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}");

		public AnimationCurve DaytimeEnemySpawnChanceThroughDay = CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":2.2706568241119386,\"inSlope\":-7.500085353851318,\"outSlope\":-7.500085353851318,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.3333333432674408,\"outWeight\":0.20650266110897065},{\"serializedVersion\":\"3\",\"time\":0.38507816195487978,\"value\":-0.0064108967781066898,\"inSlope\":-2.7670974731445314,\"outSlope\":-2.7670974731445314,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.28388944268226626,\"outWeight\":0.30659767985343935},{\"serializedVersion\":\"3\",\"time\":0.6767024993896484,\"value\":-7.021658420562744,\"inSlope\":-27.286888122558595,\"outSlope\":-27.286888122558595,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.10391546785831452,\"outWeight\":0.12503522634506226},{\"serializedVersion\":\"3\",\"time\":0.9998173117637634,\"value\":-14.818100929260254,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}");

		[Range(0f, 30f)]
		public float DaytimeEnemiesProbabilityRange = 5f;

		public bool LevelIncludesSnowFootprints = false;

		[HideInInspector]
		public string serializedRandomWeatherTypes;

		[HideInInspector]
		public string serializedDungeonFlowTypes;

		[HideInInspector]
		public string serializedSpawnableScrap;

		[HideInInspector]
		public string serializedEnemies;

		[HideInInspector]
		public string serializedOutsideEnemies;

		[HideInInspector]
		public string serializedDaytimeEnemies;

		[HideInInspector]
		public string serializedSpawnableMapObjects;

		[HideInInspector]
		public string serializedSpawnableOutsideObjects;

		private void OnValidate()
		{
			RequiredBundles = RequiredBundles.RemoveNonAlphanumeric(1);
			IncompatibleBundles = IncompatibleBundles.RemoveNonAlphanumeric(1);
			MoonName = MoonName.RemoveNonAlphanumeric(1);
			OrbitPrefabName = OrbitPrefabName.RemoveNonAlphanumeric(1);
			RiskLevel = RiskLevel.RemoveNonAlphanumeric();
			RouteWord = RouteWord.RemoveNonAlphanumeric(2);
			BoughtComment = BoughtComment.RemoveNonAlphanumeric();
			LevelAmbienceClips = LevelAmbienceClips.RemoveNonAlphanumeric(1);
			TimeToArrive = Mathf.Clamp(TimeToArrive, 0f, 16f);
			DaySpeedMultiplier = Mathf.Clamp(DaySpeedMultiplier, 0.1f, 5f);
			RoutePrice = Mathf.Clamp(RoutePrice, 0, int.MaxValue);
			FactorySizeMultiplier = Mathf.Clamp(FactorySizeMultiplier, 1f, 5f);
			FireExitsAmountOverwrite = Mathf.Clamp(FireExitsAmountOverwrite, 0, 20);
			MinScrap = Mathf.Clamp(MinScrap, 0, MaxScrap);
			MaxScrap = Mathf.Clamp(MaxScrap, MinScrap, 100);
			MaxEnemyPowerCount = Mathf.Clamp(MaxEnemyPowerCount, 0, 30);
			MaxOutsideEnemyPowerCount = Mathf.Clamp(MaxOutsideEnemyPowerCount, 0, 30);
			MaxDaytimeEnemyPowerCount = Mathf.Clamp(MaxDaytimeEnemyPowerCount, 0, 30);
			SpawnProbabilityRange = Mathf.Clamp(SpawnProbabilityRange, 0f, 30f);
			DaytimeEnemiesProbabilityRange = Mathf.Clamp(DaytimeEnemiesProbabilityRange, 0f, 30f);
			for (int i = 0; i < _SpawnableScrap.Length; i++)
			{
				_SpawnableScrap[i].ObjectName = _SpawnableScrap[i].ObjectName.RemoveNonAlphanumeric(1);
			}
			for (int j = 0; j < _Enemies.Length; j++)
			{
				_Enemies[j].EnemyName = _Enemies[j].EnemyName.RemoveNonAlphanumeric(1);
			}
			for (int k = 0; k < _SpawnableMapObjects.Length; k++)
			{
				_SpawnableMapObjects[k].ObjectName = _SpawnableMapObjects[k].ObjectName.RemoveNonAlphanumeric(1);
			}
			for (int l = 0; l < _SpawnableOutsideObjects.Length; l++)
			{
				_SpawnableOutsideObjects[l].ObjectName = _SpawnableOutsideObjects[l].ObjectName.RemoveNonAlphanumeric(1);
			}
			for (int m = 0; m < _OutsideEnemies.Length; m++)
			{
				_OutsideEnemies[m].EnemyName = _OutsideEnemies[m].EnemyName.RemoveNonAlphanumeric(1);
			}
			for (int n = 0; n < _DaytimeEnemies.Length; n++)
			{
				_DaytimeEnemies[n].EnemyName = _DaytimeEnemies[n].EnemyName.RemoveNonAlphanumeric(1);
			}
			serializedRandomWeatherTypes = string.Join(";", _RandomWeatherTypes.Select((RandomWeatherPair p) => $"{(int)p.Weather},{p.WeatherVariable1},{p.WeatherVariable2}"));
			serializedDungeonFlowTypes = string.Join(";", _DungeonFlowTypes.Select((DungeonFlowPair p) => $"{p.ID},{p.Rarity}"));
			serializedSpawnableScrap = string.Join(";", _SpawnableScrap.Select((SpawnableScrapPair p) => $"{p.ObjectName},{p.SpawnWeight}"));
			serializedEnemies = string.Join(";", _Enemies.Select((SpawnableEnemiesPair p) => $"{p.EnemyName},{p.SpawnWeight}"));
			serializedOutsideEnemies = string.Join(";", _OutsideEnemies.Select((SpawnableEnemiesPair p) => $"{p.EnemyName},{p.SpawnWeight}"));
			serializedDaytimeEnemies = string.Join(";", _DaytimeEnemies.Select((SpawnableEnemiesPair p) => $"{p.EnemyName},{p.SpawnWeight}"));
			serializedSpawnableMapObjects = string.Join(";", _SpawnableMapObjects.Select((SpawnableMapObjectPair p) => $"{p.ObjectName}|{p.SpawnFacingAwayFromWall}|{CurveContainer.SerializeCurve(p.SpawnRate)}"));
			serializedSpawnableOutsideObjects = string.Join(";", _SpawnableOutsideObjects.Select((SpawnableOutsideObjectPair p) => p.ObjectName + "|" + CurveContainer.SerializeCurve(p.SpawnRate)));
		}

		public RandomWeatherPair[] RandomWeatherTypes()
		{
			return (from s in serializedRandomWeatherTypes.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 3
				select new RandomWeatherPair((LevelWeatherType)int.Parse(split[0]), int.Parse(split[1]), int.Parse(split[2]))).ToArray();
		}

		public DungeonFlowPair[] DungeonFlowTypes()
		{
			return (from s in serializedDungeonFlowTypes.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new DungeonFlowPair(int.Parse(split[0]), int.Parse(split[1]))).ToArray();
		}

		public SpawnableScrapPair[] SpawnableScrap()
		{
			return (from s in serializedSpawnableScrap.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new SpawnableScrapPair(split[0], int.Parse(split[1]))).ToArray();
		}

		public SpawnableEnemiesPair[] Enemies()
		{
			return (from s in serializedEnemies.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new SpawnableEnemiesPair(split[0], int.Parse(split[1]))).ToArray();
		}

		public SpawnableEnemiesPair[] OutsideEnemies()
		{
			return (from s in serializedOutsideEnemies.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new SpawnableEnemiesPair(split[0], int.Parse(split[1]))).ToArray();
		}

		public SpawnableEnemiesPair[] DaytimeEnemies()
		{
			return (from s in serializedDaytimeEnemies.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new SpawnableEnemiesPair(split[0], int.Parse(split[1]))).ToArray();
		}

		public SpawnableMapObjectPair[] SpawnableMapObjects()
		{
			return (from s in serializedSpawnableMapObjects.Split(new char[1] { ';' })
				select s.Split(new char[1] { '|' }) into split
				where split.Length == 3
				select new SpawnableMapObjectPair(split[0], bool.Parse(split[1]), CurveContainer.DeserializeCurve(split[2]))).ToArray();
		}

		public SpawnableOutsideObjectPair[] SpawnableOutsideObjects()
		{
			return (from s in serializedSpawnableOutsideObjects.Split(new char[1] { ';' })
				select s.Split(new char[1] { '|' }) into split
				where split.Length == 2
				select new SpawnableOutsideObjectPair(split[0], CurveContainer.DeserializeCurve(split[1]))).ToArray();
		}
	}
	[CreateAssetMenu(fileName = "New Scrap", menuName = "LethalSDK/Scrap")]
	public class Scrap : ScriptableObject
	{
		public string[] RequiredBundles;

		public string[] IncompatibleBundles;

		[Header("Base")]
		public ScrapType scrapType = ScrapType.Normal;

		public string itemName = string.Empty;

		public int minValue = 0;

		public int maxValue = 0;

		public bool twoHanded = false;

		public GrabAnim HandedAnimation = GrabAnim.OneHanded;

		public bool requiresBattery = false;

		public bool isConductiveMetal = false;

		public int weight = 0;

		public GameObject prefab;

		[Header("Sounds")]
		public string grabSFX = string.Empty;

		public string dropSFX = string.Empty;

		[Header("Offsets")]
		public float verticalOffset = 0f;

		public Vector3 restingRotation = Vector3.zero;

		public Vector3 positionOffset = Vector3.zero;

		public Vector3 rotationOffset = Vector3.zero;

		[Header("Variants")]
		public Mesh[] meshVariants = (Mesh[])(object)new Mesh[0];

		public Material[] materialVariants = (Material[])(object)new Material[0];

		[Header("Spawn rate")]
		public bool useGlobalSpawnWeight = true;

		[Range(0f, 100f)]
		public int globalSpawnWeight = 10;

		[SerializeField]
		private ScrapSpawnChancePerScene[] _perPlanetSpawnWeight = new ScrapSpawnChancePerScene[9]
		{
			new ScrapSpawnChancePerScene("41 Experimentation", 10),
			new ScrapSpawnChancePerScene("220 Assurance", 10),
			new ScrapSpawnChancePerScene("56 Vow", 10),
			new ScrapSpawnChancePerScene("21 Offense", 10),
			new ScrapSpawnChancePerScene("61 March", 10),
			new ScrapSpawnChancePerScene("85 Rend", 10),
			new ScrapSpawnChancePerScene("7 Dine", 10),
			new ScrapSpawnChancePerScene("8 Titan", 10),
			new ScrapSpawnChancePerScene("Others", 10)
		};

		public string[] playetSpawnBlacklist = new string[0];

		[Header("Shovel")]
		public int shovelHitForce = 1;

		public AudioSource shovelAudio;

		public string reelUp = "ShovelReelUp";

		public string swing = "ShovelSwing";

		public string[] hitSFX = new string[2] { "ShovelHitDefault", "ShovelHitDefault2" };

		[Header("Flashlight")]
		public bool usingPlayerHelmetLight = false;

		public int flashlightInterferenceLevel = 0;

		public Light flashlightBulb;

		public Light flashlightBulbGlow;

		public AudioSource flashlightAudio;

		public string[] flashlightClips = new string[1] { "FlashlightClick" };

		public string outOfBatteriesClip = "FlashlightOutOfBatteries";

		public string flashlightFlicker = "FlashlightFlicker";

		public Material bulbLight;

		public Material bulbDark;

		public MeshRenderer flashlightMesh;

		public int flashlightTypeID = 0;

		public bool changeMaterial = true;

		[Header("Noisemaker")]
		public AudioSource noiseAudio;

		public AudioSource noiseAudioFar;

		public string[] noiseSFX = new string[1] { "ClownHorn1" };

		public string[] noiseSFXFar = new string[1] { "ClownHornFar" };

		public float noiseRange = 60f;

		public float maxLoudness = 1f;

		public float minLoudness = 0.6f;

		public float minPitch = 0.93f;

		public float maxPitch = 1f;

		public Animator triggerAnimator;

		[Header("WhoopieCushion")]
		public AudioSource whoopieCushionAudio;

		public string[] fartAudios = new string[4] { "Fart1", "Fart2", "Fart3", "Fart5" };

		[HideInInspector]
		public string serializedData;

		private void OnValidate()
		{
			RequiredBundles = RequiredBundles.RemoveNonAlphanumeric(1);
			IncompatibleBundles = IncompatibleBundles.RemoveNonAlphanumeric(1);
			itemName = itemName.RemoveNonAlphanumeric(1);
			grabSFX = grabSFX.RemoveNonAlphanumeric(1);
			dropSFX = dropSFX.RemoveNonAlphanumeric(1);
			for (int i = 0; i < _perPlanetSpawnWeight.Length; i++)
			{
				_perPlanetSpawnWeight[i].SceneName = _perPlanetSpawnWeight[i].SceneName.RemoveNonAlphanumeric(1);
			}
			serializedData = string.Join(";", _perPlanetSpawnWeight.Select((ScrapSpawnChancePerScene p) => $"{p.SceneName},{p.SpawnWeight}"));
		}

		public ScrapSpawnChancePerScene[] perPlanetSpawnWeight()
		{
			return (from s in serializedData.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new ScrapSpawnChancePerScene(split[0], int.Parse(split[1]))).ToArray();
		}
	}
	public enum ScrapType
	{
		Normal,
		Shovel,
		Flashlight,
		Noisemaker,
		WhoopieCushion
	}
	public enum GrabAnim
	{
		OneHanded,
		TwoHanded,
		Shotgun,
		Jetpack,
		Clipboard
	}
}
namespace LethalSDK.Utils
{
	public static class AssetGatherDialog
	{
		public static Dictionary<string, AudioClip> audioClips = new Dictionary<string, AudioClip>();

		public static Dictionary<string, (AudioMixer, AudioMixerGroup[])> audioMixers = new Dictionary<string, (AudioMixer, AudioMixerGroup[])>();

		public static Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();
	}
	[Serializable]
	public class SerializableVersion
	{
		public int Major = 1;

		public int Minor = 0;

		public int Build = 0;

		public int Revision = 0;

		public SerializableVersion(int major, int minor, int build, int revision)
		{
			Major = major;
			Minor = minor;
			Build = build;
			Revision = revision;
		}

		public Version ToVersion()
		{
			return new Version(Major, Minor, Build, Revision);
		}

		public override string ToString()
		{
			return $"{Major}.{Minor}.{Build}.{Revision}";
		}
	}
	[Serializable]
	public class CurveContainer
	{
		public AnimationCurve curve;

		public static string SerializeCurve(AnimationCurve curve)
		{
			CurveContainer curveContainer = new CurveContainer
			{
				curve = curve
			};
			return JsonUtility.ToJson((object)curveContainer);
		}

		public static AnimationCurve DeserializeCurve(string json)
		{
			CurveContainer curveContainer = JsonUtility.FromJson<CurveContainer>(json);
			return curveContainer.curve;
		}
	}
	public static class NetworkDataManager
	{
		public static Dictionary<ulong, SI_NetworkData> NetworkData = new Dictionary<ulong, SI_NetworkData>();
	}
	public class SI_NetworkData : NetworkBehaviour
	{
		public StringStringPair[] data = new StringStringPair[0];

		[HideInInspector]
		public string serializedData = string.Empty;

		public string datacache = string.Empty;

		public UnityEvent dataChangeEvent = new UnityEvent();

		public void Start()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			if (dataChangeEvent != null)
			{
				dataChangeEvent.AddListener(new UnityAction(OnDataChanged));
			}
		}

		public void Update()
		{
			if (datacache != serializedData && dataChangeEvent != null)
			{
				dataChangeEvent.Invoke();
			}
		}

		public override void OnNetworkSpawn()
		{
			NetworkDataManager.NetworkData.Add(((NetworkBehaviour)this).NetworkObjectId, this);
		}

		public override void OnNetworkDespawn()
		{
			NetworkDataManager.NetworkData.Remove(((NetworkBehaviour)this).NetworkObjectId);
		}

		public virtual void OnDataChanged()
		{
			datacache = serializedData;
		}

		public override void OnDestroy()
		{
			if (dataChangeEvent != null)
			{
				((UnityEventBase)dataChangeEvent).RemoveAllListeners();
			}
		}

		public virtual StringStringPair[] getData()
		{
			return (from s in serializedData.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new StringStringPair(split[0], split[1])).ToArray();
		}

		public virtual void setData(string datastring)
		{
			if (!Enumerable.Contains(datastring, ','))
			{
				Debug.LogWarning((object)"Invalid datastring format.");
			}
			else
			{
				serializedData = datastring;
			}
		}

		public virtual void setData(StringStringPair[] dataarray)
		{
			string source = string.Join(";", dataarray.Select((StringStringPair p) => p._string1 + "," + p._string2));
			if (!Enumerable.Contains(source, ','))
			{
				Debug.LogWarning((object)"Invalid datastring format.");
			}
			else
			{
				serializedData = source;
			}
		}

		public virtual void addData(string datastring)
		{
			if (!Enumerable.Contains(datastring, ','))
			{
				Debug.LogWarning((object)"Invalid datastring format.");
				return;
			}
			serializedData += datastring;
			serializedData = serializedData.Replace(";;", string.Empty);
			if (serializedData.StartsWith(";"))
			{
				serializedData = serializedData.Substring(1);
			}
			if (serializedData.EndsWith(";"))
			{
				serializedData = serializedData.Substring(0, serializedData.Length - 1);
			}
		}

		public virtual void addData(StringStringPair[] dataarray)
		{
			string text = string.Join(";", dataarray.Select((StringStringPair p) => p._string1 + "," + p._string2)).Insert(0, ";");
			if (!Enumerable.Contains(text, ','))
			{
				Debug.LogWarning((object)"Invalid datastring format.");
				return;
			}
			serializedData += text;
			serializedData = serializedData.Replace(";;", string.Empty);
			if (serializedData.StartsWith(";"))
			{
				serializedData = serializedData.Substring(1);
			}
			if (serializedData.EndsWith(";"))
			{
				serializedData = serializedData.Substring(0, serializedData.Length - 1);
			}
		}

		public virtual void delData(string datastring)
		{
			if (!Enumerable.Contains(datastring, ','))
			{
				Debug.LogWarning((object)"Invalid datastring format.");
				return;
			}
			if (!serializedData.Contains(datastring))
			{
				Debug.Log((object)"Datastring doesn't exist in serializedData.");
				return;
			}
			serializedData = serializedData.Replace(datastring, string.Empty);
			serializedData = serializedData.Replace(";;", string.Empty);
			if (serializedData.StartsWith(";"))
			{
				serializedData = serializedData.Substring(1);
			}
			if (serializedData.EndsWith(";"))
			{
				serializedData = serializedData.Substring(0, serializedData.Length - 1);
			}
		}

		public virtual void delData(StringStringPair[] dataarray)
		{
			string text = string.Join(";", dataarray.Select((StringStringPair p) => p._string1 + "," + p._string2)).Insert(0, ";");
			if (!Enumerable.Contains(text, ','))
			{
				Debug.LogWarning((object)"Invalid datastring format.");
				return;
			}
			if (!serializedData.Contains(text))
			{
				Debug.Log((object)"Datastring doesn't exist in serializedData.");
				return;
			}
			serializedData = serializedData.Replace(text, string.Empty);
			serializedData = serializedData.Replace(";;", string.Empty);
			if (serializedData.StartsWith(";"))
			{
				serializedData = serializedData.Substring(1);
			}
			if (serializedData.EndsWith(";"))
			{
				serializedData = serializedData.Substring(0, serializedData.Length - 1);
			}
		}
	}
	[Serializable]
	public struct StringIntPair
	{
		public string _string;

		public int _int;

		public StringIntPair(string _string, int _int)
		{
			this._string = _string.RemoveNonAlphanumeric(1);
			this._int = Mathf.Clamp(_int, 0, 100);
		}
	}
	[Serializable]
	public struct StringStringPair
	{
		public string _string1;

		public string _string2;

		public StringStringPair(string _string1, string _string2)
		{
			this._string1 = _string1.RemoveNonAlphanumeric(1);
			this._string2 = _string2.RemoveNonAlphanumeric(1);
		}
	}
	[Serializable]
	public struct IntIntPair
	{
		public int _int1;

		public int _int2;

		public IntIntPair(int _int1, int _int2)
		{
			this._int1 = _int1;
			this._int2 = _int2;
		}
	}
	[Serializable]
	public struct DungeonFlowPair
	{
		public int ID;

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

		public DungeonFlowPair(int id, int rarity)
		{
			ID = id;
			Rarity = Mathf.Clamp(rarity, 0, 300);
		}
	}
	[Serializable]
	public struct SpawnableScrapPair
	{
		public string ObjectName;

		[Range(0f, 100f)]
		public int SpawnWeight;

		public SpawnableScrapPair(string objectName, int spawnWeight)
		{
			ObjectName = objectName.RemoveNonAlphanumeric(1);
			SpawnWeight = Mathf.Clamp(spawnWeight, 0, 100);
		}
	}
	[Serializable]
	public struct SpawnableMapObjectPair
	{
		public string ObjectName;

		public bool SpawnFacingAwayFromWall;

		public AnimationCurve SpawnRate;

		public SpawnableMapObjectPair(string objectName, bool spawnFacingAwayFromWall, AnimationCurve spawnRate)
		{
			ObjectName = objectName.RemoveNonAlphanumeric(1);
			SpawnFacingAwayFromWall = spawnFacingAwayFromWall;
			SpawnRate = spawnRate;
		}
	}
	[Serializable]
	public struct SpawnableOutsideObjectPair
	{
		public string ObjectName;

		public AnimationCurve SpawnRate;

		public SpawnableOutsideObjectPair(string objectName, AnimationCurve spawnRate)
		{
			ObjectName = objectName.RemoveNonAlphanumeric(1);
			SpawnRate = spawnRate;
		}
	}
	[Serializable]
	public struct SpawnableEnemiesPair
	{
		public string EnemyName;

		[Range(0f, 100f)]
		public int SpawnWeight;

		public SpawnableEnemiesPair(string enemyName, int spawnWeight)
		{
			EnemyName = enemyName.RemoveNonAlphanumeric(1);
			SpawnWeight = Mathf.Clamp(spawnWeight, 0, 100);
		}
	}
	[Serializable]
	public struct ScrapSpawnChancePerScene
	{
		public string SceneName;

		[Range(0f, 100f)]
		public int SpawnWeight;

		public ScrapSpawnChancePerScene(string sceneName, int spawnWeight)
		{
			SceneName = sceneName.RemoveNonAlphanumeric(1);
			SpawnWeight = Mathf.Clamp(spawnWeight, 0, 100);
		}
	}
	[Serializable]
	public struct ScrapInfoPair
	{
		public string ScrapPath;

		public Scrap Scrap;

		public ScrapInfoPair(string scrapPath, Scrap scrap)
		{
			ScrapPath = scrapPath.RemoveNonAlphanumeric(4);
			Scrap = scrap;
		}
	}
	[Serializable]
	public struct AudioClipInfoPair
	{
		public string AudioClipName;

		[HideInInspector]
		public string AudioClipPath;

		[SerializeField]
		public AudioClip AudioClip;

		public AudioClipInfoPair(string audioClipName, string audioClipPath)
		{
			AudioClipName = audioClipName.RemoveNonAlphanumeric(1);
			AudioClipPath = audioClipPath.RemoveNonAlphanumeric(4);
			AudioClip = null;
		}
	}
	[Serializable]
	public struct PlanetPrefabInfoPair
	{
		public string PlanetPrefabName;

		[HideInInspector]
		public string PlanetPrefabPath;

		[SerializeField]
		public GameObject PlanetPrefab;

		public PlanetPrefabInfoPair(string planetPrefabName, string planetPrefabPath)
		{
			PlanetPrefabName = planetPrefabName.RemoveNonAlphanumeric(1);
			PlanetPrefabPath = planetPrefabPath.RemoveNonAlphanumeric(4);
			PlanetPrefab = null;
		}
	}
	[Serializable]
	public struct PrefabInfoPair
	{
		public string PrefabName;

		[HideInInspector]
		public string PrefabPath;

		[SerializeField]
		public GameObject Prefab;

		public PrefabInfoPair(string prefabName, string prefabPath)
		{
			PrefabName = prefabName.RemoveNonAlphanumeric(1);
			PrefabPath = prefabPath.RemoveNonAlphanumeric(4);
			Prefab = null;
		}
	}
	[Serializable]
	public struct RandomWeatherPair
	{
		public LevelWeatherType Weather;

		[Tooltip("Thunder Frequency, Flooding speed or minimum initial enemies in eclipses")]
		public int WeatherVariable1;

		[Tooltip("Flooding offset when Weather is Flooded")]
		public int WeatherVariable2;

		public RandomWeatherPair(LevelWeatherType weather, int weatherVariable1, int weatherVariable2)
		{
			Weather = weather;
			WeatherVariable1 = weatherVariable1;
			WeatherVariable2 = weatherVariable2;
		}
	}
	public enum LevelWeatherType
	{
		None = -1,
		DustClouds,
		Rainy,
		Stormy,
		Foggy,
		Flooded,
		Eclipsed
	}
	public class SpawnPrefab
	{
		private static SpawnPrefab _instance;

		public GameObject waterSurface;

		public static SpawnPrefab Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new SpawnPrefab();
				}
				return _instance;
			}
		}
	}
	public static class TypeExtensions
	{
		public enum removeType
		{
			Normal,
			Serializable,
			Keyword,
			Path,
			SerializablePath
		}

		public static readonly Dictionary<removeType, string> regexes = new Dictionary<removeType, string>
		{
			{
				removeType.Normal,
				"[^a-zA-Z0-9 ,.!?_-]"
			},
			{
				removeType.Serializable,
				"[^a-zA-Z0-9 .!_-]"
			},
			{
				removeType.Keyword,
				"[^a-zA-Z0-9._-]"
			},
			{
				removeType.Path,
				"[^a-zA-Z0-9 ,.!_/-]"
			},
			{
				removeType.SerializablePath,
				"[^a-zA-Z0-9 .!_/-]"
			}
		};

		public static string RemoveNonAlphanumeric(this string input)
		{
			if (input != null)
			{
				return Regex.Replace(input, regexes[removeType.Normal], string.Empty);
			}
			return string.Empty;
		}

		public static string[] RemoveNonAlphanumeric(this string[] input)
		{
			if (input != null)
			{
				for (int i = 0; i < input.Length; i++)
				{
					input[i] = Regex.Replace(input[i], regexes[removeType.Normal], string.Empty);
				}
				return input;
			}
			return new string[0];
		}

		public static string RemoveNonAlphanumeric(this string input, removeType removeType = removeType.Normal)
		{
			if (input != null)
			{
				return Regex.Replace(input, regexes[removeType], string.Empty);
			}
			return string.Empty;
		}

		public static string[] RemoveNonAlphanumeric(this string[] input, removeType removeType = removeType.Normal)
		{
			if (input != null)
			{
				for (int i = 0; i < input.Length; i++)
				{
					input[i] = Regex.Replace(input[i], regexes[removeType], string.Empty);
				}
				return input;
			}
			return new string[0];
		}

		public static string RemoveNonAlphanumeric(this string input, int removeType = 0)
		{
			if (input != null)
			{
				return Regex.Replace(input, regexes[(removeType)removeType], string.Empty);
			}
			return string.Empty;
		}

		public static string[] RemoveNonAlphanumeric(this string[] input, int removeType = 0)
		{
			if (input != null)
			{
				for (int i = 0; i < input.Length; i++)
				{
					input[i] = Regex.Replace(input[i], regexes[(removeType)removeType], string.Empty);
				}
				return input;
			}
			return new string[0];
		}
	}
}
namespace LethalSDK.Editor
{
	internal class CopyrightsWindow : EditorWindow
	{
		private Vector2 scrollPosition;

		private readonly Dictionary<string, string> assetAuthorList = new Dictionary<string, string>
		{
			{ "Drop Ship assets, Sun cycle animations, ScrapItem sprite, ScavengerSuit Textures/Arms Mesh and MonitorWall mesh", "Zeekerss" },
			{ "SDK Scripts, Sun Texture, CrossButton Sprite (Inspired of vanilla), OldSeaPort planet prefab texture", "HolographicWings" },
			{ "Old Sea Port asset package", "VIVID Arts" },
			{ "Survival Game Tools asset package", "cookiepopworks.com" }
		};

		[MenuItem("LethalSDK/Copyrights", false, 999)]
		public static void ShowWindow()
		{
			EditorWindow.GetWindow<CopyrightsWindow>("Copyrights");
		}

		private void OnGUI()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.Label("List of Copyrights", EditorStyles.boldLabel, Array.Empty<GUILayoutOption>());
			scrollPosition = GUILayout.BeginScrollView(scrollPosition, Array.Empty<GUILayoutOption>());
			EditorGUILayout.Space(5f);
			foreach (KeyValuePair<string, string> assetAuthor in assetAuthorList)
			{
				GUILayout.Label("Asset: " + assetAuthor.Key + " - By: " + assetAuthor.Value, EditorStyles.wordWrappedLabel, Array.Empty<GUILayoutOption>());
				EditorGUILayout.Space(2f);
			}
			EditorGUILayout.Space(5f);
			GUILayout.Label("This SDK do not embed any Vanilla script.", Array.Empty<GUILayoutOption>());
			GUILayout.EndScrollView();
		}
	}
	public class EditorChecker : Editor
	{
		public override void OnInspectorGUI()
		{
			((Editor)this).DrawDefaultInspector();
		}
	}
	[CustomEditor(typeof(ModManifest))]
	public class ModManifestEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			ModManifest modManifest = (ModManifest)(object)((Editor)this).target;
			if (modManifest.serializedVersion == "0.0.0.0")
			{
				EditorGUILayout.HelpBox("Please define a version to your mod and don't forget to increment it at each update.", (MessageType)2);
			}
			if (modManifest.modName == null || modManifest.modName.Length == 0)
			{
				EditorGUILayout.HelpBox("Your mod need a name.", (MessageType)3);
			}
			IEnumerable<string> enumerable = from e in modManifest.scraps.Where((Scrap e) => (Object)(object)e != (Object)null).ToList()
				group e by e.itemName into g
				where g.Count() > 1
				select g.Key;
			if (enumerable.Any())
			{
				string text = string.Empty;
				foreach (string item in enumerable)
				{
					text = text + item + ",";
				}
				text = text.Remove(text.Length - 1);
				EditorGUILayout.HelpBox("You are trying to register two times or more the same Scraps. Duplicated Scraps are: " + text, (MessageType)2);
			}
			IEnumerable<string> enumerable2 = from e in modManifest.moons.Where((Moon e) => (Object)(object)e != (Object)null).ToList()
				group e by e.MoonName into g
				where g.Count() > 1
				select g.Key;
			if (enumerable2.Any())
			{
				string text2 = string.Empty;
				foreach (string item2 in enumerable2)
				{
					text2 = text2 + item2 + ",";
				}
				text2 = text2.Remove(text2.Length - 1);
				EditorGUILayout.HelpBox("You are trying to register two times or more the same Moons. Duplicated Moons are: " + text2, (MessageType)2);
			}
			string text3 = string.Empty;
			Scrap[] scraps = modManifest.scraps;
			foreach (Scrap scrap in scraps)
			{
				if ((Object)(object)scrap != (Object)null && AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)scrap)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest)))
				{
					text3 = text3 + ((Object)scrap).name + ",";
				}
			}
			Moon[] moons = modManifest.moons;
			foreach (Moon moon in moons)
			{
				if ((Object)(object)moon != (Object)null && AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)moon)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest)))
				{
					text3 = text3 + ((Object)moon).name + ",";
				}
			}
			if (text3 != null && text3.Length > 0)
			{
				text3 = text3.Remove(text3.Length - 1);
				EditorGUILayout.HelpBox("You try to register a Scrap or a Moon from another mod folder. " + text3, (MessageType)2);
			}
			if ((Object)(object)modManifest.assetBank != (Object)null && AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest.assetBank)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest)))
			{
				EditorGUILayout.HelpBox("You try to register an AssetBank from another mod folder.", (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(AssetBank))]
	public class AssetBankEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			AssetBank assetBank = (AssetBank)(object)((Editor)this).target;
			IEnumerable<string> enumerable = from e in (from e in assetBank.AudioClips()
					where e.AudioClipName != null && e.AudioClipName.Length > 0
					select e).ToList()
				group e by e.AudioClipName into g
				where g.Count() > 1
				select g.Key;
			if (enumerable.Any())
			{
				string text = string.Empty;
				foreach (string item in enumerable)
				{
					text = text + item + ",";
				}
				text = text.Remove(text.Length - 1);
				EditorGUILayout.HelpBox("You are trying to register two times or more the same Audio Clip. Duplicated Clips are: " + text, (MessageType)2);
			}
			IEnumerable<string> enumerable2 = from e in (from e in assetBank.PlanetPrefabs()
					where e.PlanetPrefabName != null && e.PlanetPrefabName.Length > 0
					select e).ToList()
				group e by e.PlanetPrefabName into g
				where g.Count() > 1
				select g.Key;
			if (enumerable2.Any())
			{
				string text2 = string.Empty;
				foreach (string item2 in enumerable2)
				{
					text2 = text2 + item2 + ",";
				}
				text2 = text2.Remove(text2.Length - 1);
				EditorGUILayout.HelpBox("You are trying to register two times or more the same Planet Prefabs. Duplicated Planet Prefabs are: " + text2, (MessageType)2);
			}
			string text3 = string.Empty;
			AudioClipInfoPair[] array = assetBank.AudioClips();
			for (int i = 0; i < array.Length; i++)
			{
				AudioClipInfoPair audioClipInfoPair = array[i];
				if (audioClipInfoPair.AudioClipName != null && audioClipInfoPair.AudioClipName.Length > 0 && AssetModificationProcessor.ExtractBundleNameFromPath(audioClipInfoPair.AudioClipPath) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)assetBank)))
				{
					text3 = text3 + audioClipInfoPair.AudioClipName + ",";
				}
			}
			PlanetPrefabInfoPair[] array2 = assetBank.PlanetPrefabs();
			for (int j = 0; j < array2.Length; j++)
			{
				PlanetPrefabInfoPair planetPrefabInfoPair = array2[j];
				if (planetPrefabInfoPair.PlanetPrefabName != null && planetPrefabInfoPair.PlanetPrefabName.Length > 0 && AssetModificationProcessor.ExtractBundleNameFromPath(planetPrefabInfoPair.PlanetPrefabPath) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)assetBank)))
				{
					text3 = text3 + planetPrefabInfoPair.PlanetPrefabName + ",";
				}
			}
			if (text3 != null && text3.Length > 0)
			{
				text3 = text3.Remove(text3.Length - 1);
				EditorGUILayout.HelpBox("You try to register an Audio Clip or a Planet Prefab from another mod folder. " + text3, (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_DungeonGenerator))]
	public class SI_DungeonGeneratorEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_DungeonGenerator sI_DungeonGenerator = (SI_DungeonGenerator)(object)((Editor)this).target;
			string assetPath = AssetDatabase.GetAssetPath((Object)(object)sI_DungeonGenerator.DungeonRoot);
			if (assetPath != null && assetPath.Length > 0)
			{
				EditorGUILayout.HelpBox("Dungeon Root must be in the scene.", (MessageType)3);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_ScanNode))]
	public class SI_ScanNodeEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_ScanNode sI_ScanNode = (SI_ScanNode)(object)((Editor)this).target;
			if (sI_ScanNode.MinRange > sI_ScanNode.MaxRange)
			{
				EditorGUILayout.HelpBox("Min Range must be smaller than Max Ranger.", (MessageType)3);
			}
			if (sI_ScanNode.CreatureScanID < -1)
			{
				EditorGUILayout.HelpBox("Creature Scan ID can't be less than -1.", (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_AnimatedSun))]
	public class SI_AnimatedSunEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_AnimatedSun sI_AnimatedSun = (SI_AnimatedSun)(object)((Editor)this).target;
			if ((Object)(object)sI_AnimatedSun.directLight == (Object)null || (Object)(object)sI_AnimatedSun.indirectLight == (Object)null)
			{
				EditorGUILayout.HelpBox("A direct and an indirect light must be defined.", (MessageType)2);
			}
			if ((Object)(object)((Component)sI_AnimatedSun.directLight).transform.parent != (Object)(object)((Component)sI_AnimatedSun).transform || (Object)(object)((Component)sI_AnimatedSun.indirectLight).transform.parent != (Object)(object)((Component)sI_AnimatedSun).transform)
			{
				EditorGUILayout.HelpBox("Direct and an indirect light must be a child of the AnimatedSun in the hierarchy.", (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_EntranceTeleport))]
	public class SI_EntranceTeleportEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_EntranceTeleport sI_EntranceTeleport = (SI_EntranceTeleport)(object)((Editor)this).target;
			IEnumerable<int> enumerable = from e in Object.FindObjectsOfType<SI_EntranceTeleport>().ToList()
				group e by e.EntranceID into g
				where g.Count() > 1
				select g.Key;
			if (enumerable.Any())
			{
				string text = string.Empty;
				foreach (int item in enumerable)
				{
					text += $"{item},";
				}
				text = text.Remove(text.Length - 1);
				EditorGUILayout.HelpBox("Two entrances or more have same Entrance ID. Duplicated entrances are: " + text, (MessageType)2);
			}
			if ((Object)(object)sI_EntranceTeleport.EntrancePoint == (Object)null)
			{
				EditorGUILayout.HelpBox("An entrance point must be defined.", (MessageType)3);
			}
			if (sI_EntranceTeleport.AudioReverbPreset < 0)
			{
				EditorGUILayout.HelpBox("Audio Reverb Preset can't be negative.", (MessageType)3);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(Scrap))]
	public class ScrapEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			Scrap scrap = (Scrap)(object)((Editor)this).target;
			if ((Object)(object)scrap.prefab == (Object)null)
			{
				EditorGUILayout.HelpBox("You must add a Prefab to your Scrap.", (MessageType)1);
			}
			else
			{
				if ((Object)(object)scrap.prefab.GetComponent<NetworkObject>() == (Object)null)
				{
					EditorGUILayout.HelpBox("The Prefab must have a NetworkObject.", (MessageType)3);
				}
				else
				{
					NetworkObject component = scrap.prefab.GetComponent<NetworkObject>();
					string text = string.Empty;
					if (component.AlwaysReplicateAsRoot)
					{
						text += "\n- AlwaysReplicateAsRoot should be false.";
					}
					if (!component.SynchronizeTransform)
					{
						text += "\n- SynchronizeTransform should be true.";
					}
					if (component.ActiveSceneSynchronization)
					{
						text += "\n- ActiveSceneSynchronization should be false.";
					}
					if (!component.SceneMigrationSynchronization)
					{
						text += "\n- SceneMigrationSynchronization should be true.";
					}
					if (!component.SpawnWithObservers)
					{
						text += "\n- SpawnWithObservers should be true.";
					}
					if (!component.DontDestroyWithOwner)
					{
						text += "\n- DontDestroyWithOwner should be true.";
					}
					if (component.AutoObjectParentSync)
					{
						text += "\n- AutoObjectParentSync should be false.";
					}
					if (text.Length > 0)
					{
						EditorGUILayout.HelpBox("The NetworkObject of the Prefab have incorrect settings: " + text, (MessageType)2);
					}
				}
				if ((Object)(object)scrap.prefab.transform.Find("ScanNode") == (Object)null)
				{
					EditorGUILayout.HelpBox("The Prefab don't have a ScanNode.", (MessageType)2);
				}
				if (AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)scrap.prefab)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)scrap)))
				{
					EditorGUILayout.HelpBox("The Prefab must come from the same mod folder as your Scrap.", (MessageType)2);
				}
			}
			if (scrap.itemName == null || scrap.itemName.Length == 0)
			{
				EditorGUILayout.HelpBox("Your scrap must have a Name.", (MessageType)3);
			}
			if (!scrap.useGlobalSpawnWeight && !scrap.perPlanetSpawnWeight().Any((ScrapSpawnChancePerScene w) => w.SceneName != null && w.SceneName.Length > 0))
			{
				EditorGUILayout.HelpBox("Your scrap use Per Planet Spawn Weight but no planet are defined.", (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(Moon))]
	public class MoonEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			Moon moon = (Moon)(object)((Editor)this).target;
			if (moon.MoonName == null || moon.MoonName.Length == 0)
			{
				EditorGUILayout.HelpBox("Your moon must have a Name.", (MessageType)3);
			}
			if (moon.PlanetName == null || moon.PlanetName.Length == 0)
			{
				EditorGUILayout.HelpBox("Your moon must have a Planet Name.", (MessageType)3);
			}
			if (moon.RouteWord == null || moon.RouteWord.Length < 3)
			{
				EditorGUILayout.HelpBox("Your moon route word must be at least 3 characters long.", (MessageType)3);
			}
			if ((Object)(object)moon.MainPrefab == (Object)null)
			{
				EditorGUILayout.HelpBox("You must add a Main Prefab to your Scrap.", (MessageType)1);
			}
			else if (AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)moon.MainPrefab)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)moon)))
			{
				EditorGUILayout.HelpBox("The Main Prefab must come from the same mod folder as your Moon.", (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_DoorLock))]
	public class SI_DoorLockEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_DoorLock sI_DoorLock = (SI_DoorLock)(object)((Editor)this).target;
			EditorGUILayout.HelpBox("DoorLock is not implemented yet.", (MessageType)1);
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_Ladder))]
	public class SI_LadderEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_Ladder sI_Ladder = (SI_Ladder)(object)((Editor)this).target;
			EditorGUILayout.HelpBox("Ladder is experimental.", (MessageType)1);
			base.OnInspectorGUI();
		}
	}
	[InitializeOnLoad]
	[CustomEditor(typeof(TerrainChecker))]
	public class TerrainCheckerEditor : EditorChecker
	{
		static TerrainCheckerEditor()
		{
			Selection.selectionChanged = (Action)Delegate.Combine(Selection.selectionChanged, new Action(OnSelectionChanged));
		}

		private static void OnSelectionChanged()
		{
			if (Object.op_Implicit((Object)(object)Selection.activeGameObject) && Object.op_Implicit((Object)(object)Selection.activeGameObject.GetComponent<Terrain>()))
			{
				Terrain component = Selection.activeGameObject.GetComponent<Terrain>();
				if (!Object.op_Implicit((Object)(object)((Component)component).gameObject.GetComponent<TerrainChecker>()))
				{
					((Component)component).gameObject.AddComponent<TerrainChecker>();
				}
			}
		}

		public override void OnInspectorGUI()
		{
			TerrainChecker terrainChecker = (TerrainChecker)(object)((Editor)this).target;
			if ((Object)(object)terrainChecker.terrain != (Object)null)
			{
				int num = 1024;
				if ((terrainChecker.terrain.renderingLayerMask & num) == 0)
				{
					EditorGUILayout.HelpBox("Quicksand will not show on this terrain, to fix you must enable the '10: Decal Layer 2' in Terrain Settings > Rendering Layer Mask.", (MessageType)2);
				}
				if ((Object)(object)terrainChecker.terrain.materialTemplate != (Object)null && ((Object)terrainChecker.terrain.materialTemplate.shader).name != "HDRP/UpdatedTerrainLit")
				{
					EditorGUILayout.HelpBox("To use Terrain Holes, you must change the material of the terrain with another one that use the HDRP/UpdatedTerrainLit shader in Terrain Settings > Basic Terrain > Material.", (MessageType)1);
				}
				if (!terrainChecker.terrain.drawInstanced)
				{
					EditorGUILayout.HelpBox("For performances with a lot of trees, grass and other details, it's recommended to enable Terrain Settings > Basic Terrain > Draw Instanced.", (MessageType)1);
				}
			}
		}
	}
	internal class OldAssetsRemover
	{
		private static readonly List<string> assetPaths = new List<string>
		{
			"Assets/LethalCompanyAssets", "Assets/Mods/LethalExpansion/Audio", "Assets/Mods/LethalExpansion/AudioMixerController", "Assets/Mods/LethalExpansion/Materials/Default.mat", "Assets/Mods/LethalExpansion/Prefabs/Settings", "Assets/Mods/LethalExpansion/Prefabs/EntranceTeleportA.prefab", "Assets/Mods/LethalExpansion/Prefabs/Prefabs.zip", "Assets/Mods/LethalExpansion/Scenes/ItemPlaceTest", "Assets/Mods/LethalExpansion/Sprites/HandIcon.png", "Assets/Mods/LethalExpansion/Sprites/HandIconPoint.png",
			"Assets/Mods/LethalExpansion/Sprites/HandLadderIcon.png", "Assets/Mods/TemplateMod/Moons/NavMesh-Environment.asset", "Assets/Mods/TemplateMod/Moons/OldSeaPort.asset", "Assets/Mods/TemplateMod/Moons/Sky and Fog Global Volume Profile.asset", "Assets/Mods/TemplateMod/Moons/Sky and Fog Global Volume Profile 1.asset", "Assets/Mods/TemplateMod/AssetBank.asset", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunCompanyLevel.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeB.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeBEclipse.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeBStormy.anim",
			"Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeC.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeCEclipse.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeCStormy.anim", "Assets/Mods/LethalExpansion/Skybox", "Assets/Mods/LethalExpansion/Sprites/XButton.png", "Assets/Mods/LethalExpansion/Textures/sunTexture1.png", "Assets/Mods/OldSeaPort/Materials/Maple_bark_1.mat", "Assets/Mods/OldSeaPort/Materials/maple_leaves.mat", "Assets/Mods/TemplateMod/AssetBank.asset", "Assets/Mods/OldSeaPort/EffectExamples/Shared/Scripts",
			"Assets/Mods/OldSeaPort/scenes", "Assets/Mods/OldSeaPort/prefabs/Plane (12).prefab", "Assets/Mods/LethalExpansion/Meshes/labyrinth.fbx", "Assets/Mods/ChristmasVillage/christmas-assets-free/fbx/Materials"
		};

		[InitializeOnLoadMethod]
		public static void CheckOldAssets()
		{
			foreach (string assetPath in assetPaths)
			{
				if (AssetDatabase.IsValidFolder(assetPath))
				{
					DeleteFolder(assetPath);
				}
				else if ((Object)(object)AssetDatabase.LoadAssetAtPath<GameObject>(assetPath) != (Object)null)
				{
					DeleteAsset(assetPath);
				}
			}
		}

		private static void DeleteFolder(string path)
		{
			if (AssetDatabase.DeleteAsset(path))
			{
				Debug.Log((object)("Deleted folder at: " + path));
			}
			else
			{
				Debug.LogError((object)("Failed to delete folder at: " + path));
			}
		}

		private static void DeleteAsset(string path)
		{
			if (AssetDatabase.DeleteAsset(path))
			{
				Debug.Log((object)("Deleted asset at: " + path));
			}
			else
			{
				Debug.LogError((object)("Failed to delete asset at: " + path));
			}
		}
	}
	public class VersionChecker : Editor
	{
		[InitializeOnLoadMethod]
		public static void CheckVersion()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			UnityWebRequest www = UnityWebRequest.Get("https://raw.githubusercontent.com/HolographicWings/LethalSDK-Unity-Project/main/last.txt");
			UnityWebRequestAsyncOperation operation = www.SendWebRequest();
			CallbackFunction callback = null;
			callback = (CallbackFunction)delegate
			{
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Expected O, but got Unknown
				if (((AsyncOperation)operation).isDone)
				{
					EditorApplication.update = (CallbackFunction)Delegate.Remove((Delegate?)(object)EditorApplication.update, (Delegate?)(object)callback);
					OnRequestComplete(www);
				}
			};
			EditorApplication.update = (CallbackFunction)Delegate.Combine((Delegate?)(object)EditorApplication.update, (Delegate?)(object)callback);
		}

		private static void OnRequestComplete(UnityWebRequest www)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			if ((int)www.result == 2 || (int)www.result == 3)
			{
				Debug.LogError((object)("Error when getting last version number: " + www.error));
			}
			else
			{
				CompareVersions(www.downloadHandler.text);
			}
		}

		private static void CompareVersions(string onlineVersion)
		{
			if (Version.Parse(PlayerSettings.bundleVersion) < Version.Parse(onlineVersion) && EditorUtility.DisplayDialogComplex("Warning", "The SDK is not up to date: " + onlineVersion, "Update", "Ignore", "") == 0)
			{
				Application.OpenURL("https://thunderstore.io/c/lethal-company/p/HolographicWings/LethalSDK/");
			}
		}
	}
	internal class LethalSDKCategory : EditorWindow
	{
		[MenuItem("LethalSDK/Lethal SDK v1.3.0", false, 0)]
		public static void ShowWindow()
		{
		}
	}
	public class Lethal_AssetBundleBuilderWindow : EditorWindow
	{
		private enum compressionOption
		{
			NormalCompression,
			FastCompression,
			Uncompressed
		}

		private static string assetBundleDirectoryKey = "LethalSDK_AssetBundleBuilderWindow_assetBundleDirectory";

		private static string compressionModeKey = "LethalSDK_AssetBundleBuilderWindow_compressionMode";

		private static string _64BitsModeKey = "LethalSDK_AssetBundleBuilderWindow_64BitsMode";

		private string assetBundleDirectory = string.Empty;

		private compressionOption compressionMode = compressionOption.NormalCompression;

		private bool _64BitsMode;

		[MenuItem("LethalSDK/AssetBundle Builder", false, 100)]
		public static void ShowWindow()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			Lethal_AssetBundleBuilderWindow window = EditorWindow.GetWindow<Lethal_AssetBundleBuilderWindow>("AssetBundle Builder");
			((EditorWindow)window).minSize = new Vector2(295f, 133f);
			((EditorWindow)window).maxSize = new Vector2(295f, 133f);
			window.LoadPreferences();
		}

		private void OnGUI()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Expected O, but got Unknown
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			GUILayout.Label("Base Settings", EditorStyles.boldLabel, Array.Empty<GUILayoutOption>());
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			EditorGUILayout.LabelField(new GUIContent("Output Path", "The directory where the asset bundles will be saved."), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(84f) });
			assetBundleDirectory = EditorGUILayout.TextField(assetBundleDirectory, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) });
			GUILayout.EndHorizontal();
			EditorGUILayout.Space(5f);
			GUILayout.Label("Options", EditorStyles.boldLabel, Array.Empty<GUILayoutOption>());
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			EditorGUILayout.LabelField(new GUIContent("Compression Mode", "Select the compression option for the asset bundle. Faster the compression is, faster the assets will load and less CPU it will use, but the Bundle will be bigger."), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(145f) });
			compressionMode = (compressionOption)(object)EditorGUILayout.EnumPopup((Enum)compressionMode, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) });
			GUILayout.EndHorizontal();
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			EditorGUILayout.LabelField(new GUIContent("64 Bits Asset Bundle (Not recommended)", "Better performances but incompatible with 32 bits computers."), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(270f) });
			_64BitsMode = EditorGUILayout.Toggle(_64BitsMode, Array.Empty<GUILayoutOption>());
			GUILayout.EndHorizontal();
			EditorGUILayout.Space(5f);
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("Build AssetBundles", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) }))
			{
				BuildAssetBundles();
			}
			if (GUILayout.Button("Reset", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(45f) }))
			{
				ClearPreferences();
			}
			GUILayout.EndHorizontal();
		}

		private void ClearPreferences()
		{
			EditorPrefs.DeleteKey(assetBundleDirectoryKey);
			EditorPrefs.DeleteKey(compressionModeKey);
			EditorPrefs.DeleteKey(_64BitsModeKey);
			LoadPreferences();
		}

		private void BuildAssetBundles()
		{
			//IL_0022: 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_004b: 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_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if (!Directory.Exists(assetBundleDirectory))
			{
				Directory.CreateDirectory(assetBundleDirectory);
			}
			BuildAssetBundleOptions val = (BuildAssetBundleOptions)0;
			val = (BuildAssetBundleOptions)(compressionMode switch
			{
				compressionOption.NormalCompression => 0, 
				compressionOption.FastCompression => 256, 
				compressionOption.Uncompressed => 1, 
				_ => 0, 
			});
			BuildTarget val2 = (BuildTarget)(_64BitsMode ? 19 : 5);
			if (assetBundleDirectory != null || assetBundleDirectory.Length != 0 || assetBundleDirectory != string.Empty)
			{
				AssetBundleManifest val3 = null;
				try
				{
					val3 = BuildPipeline.BuildAssetBundles(assetBundleDirectory, val, val2);
				}
				catch (Exception ex)
				{
					Debug.LogError((object)ex.Message);
				}
				if ((Object)(object)val3 != (Object)null)
				{
					Debug.Log((object)"AssetBundles built successfully.");
				}
				else
				{
					Debug.LogError((object)"Cannot build AssetBundles.");
				}
			}
			else
			{
				Debug.LogError((object)"AssetBundles path cannot be blank.");
			}
		}

		private void OnLostFocus()
		{
			SavePreferences();
		}

		private void OnDisable()
		{
			SavePreferences();
		}

		private void LoadPreferences()
		{
			assetBundleDirectory = EditorPrefs.GetString(assetBundleDirectoryKey, "Assets/AssetBundles");
			compressionMode = (compressionOption)EditorPrefs.GetInt(compressionModeKey, 0);
			_64BitsMode = EditorPrefs.GetBool(_64BitsModeKey, false);
		}

		private void SavePreferences()
		{
			EditorPrefs.SetString(assetBundleDirectoryKey, assetBundleDirectory);
			EditorPrefs.SetInt(compressionModeKey, (int)compressionMode);
			EditorPrefs.SetBool(_64BitsModeKey, _64BitsMode);
		}
	}
	[RequireComponent(typeof(Terrain))]
	public class TerrainChecker : MonoBehaviour
	{
		[HideInInspector]
		public Terrain terrain;

		private void OnDrawGizmosSelected()
		{
			terrain = ((Component)this).GetComponent<Terrain>();
		}

		private void Awake()
		{
			Object.Destroy((Object)(object)this);
		}
	}
}
namespace LethalSDK.Component
{
	[AddComponentMenu("LethalSDK/DamagePlayer")]
	public class SI_DamagePlayer : MonoBehaviour
	{
		public bool kill = false;

		public bool dontSpawnBody = false;

		public SI_CauseOfDeath causeOfDeath = SI_CauseOfDeath.Gravity;

		public int damages = 25;

		public int numberIterations = 1;

		public int iterationCooldown = 1000;

		public int warmupCooldown = 0;

		public UnityEvent postEvent = new UnityEvent();

		public void Trigger(object player)
		{
			if (kill)
			{
				((MonoBehaviour)this).StartCoroutine(Kill(player));
			}
			else
			{
				((MonoBehaviour)this).StartCoroutine(Damage(player));
			}
		}

		public IEnumerator Kill(object player)
		{
			yield return (object)new WaitForSeconds((float)warmupCooldown / 1000f);
			((PlayerControllerB)((player is PlayerControllerB) ? player : null)).KillPlayer(Vector3.zero, !dontSpawnBody, (CauseOfDeath)causeOfDeath, 0);
			postEvent.Invoke();
		}

		public IEnumerator Damage(object player)
		{
			yield return (object)new WaitForSeconds((float)warmupCooldown / 1000f);
			int iteration = 0;
			while (iteration < numberIterations || numberIterations == -1)
			{
				((PlayerControllerB)((player is PlayerControllerB) ? player : null)).DamagePlayer(damages, true, true, (CauseOfDeath)causeOfDeath, 0, false, Vector3.zero);
				postEvent.Invoke();
				iteration++;
				yield return (object)new WaitForSeconds((float)iterationCooldown / 1000f);
			}
		}

		public void StopCounter(object player)
		{
			((MonoBehaviour)this).StopAllCoroutines();
		}
	}
	[AddComponentMenu("LethalSDK/SoundYDistance")]
	public class SI_SoundYDistance : MonoBehaviour
	{
		public AudioSource audioSource;

		public int maxDistance = 50;

		public void Awake()
		{
			if ((Object)(object)audioSource == (Object)null)
			{
				audioSource = ((Component)this).gameObject.GetComponent<AudioSource>();
				if ((Object)(object)audioSource == (Object)null)
				{
					audioSource = ((Component)this).gameObject.AddComponent<AudioSource>();
				}
			}
		}

		public void Update()
		{
			//IL_0032: 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)
			if ((Object)(object)RoundManager.Instance != (Object)null && (Object)(object)StartOfRound.Instance != (Object)null)
			{
				audioSource.volume = 1f - Mathf.Abs(((Component)this).transform.position.y - ((Component)RoundManager.Instance.playersManager.allPlayerScripts[StartOfRound.Instance.ClientPlayerList[((NetworkBehaviour)StartOfRound.Instance).NetworkManager.LocalClientId]].gameplayCamera).transform.position.y) / (float)maxDistance;
			}
		}
	}
	[AddComponentMenu("LethalSDK/AudioOutputInterface")]
	public class SI_AudioOutputInterface : MonoBehaviour
	{
		public AudioSource audioSource;

		public string mixerName = "Diagetic";

		public string mixerGroupName = "Master";

		public void Awake()
		{
			if ((Object)(object)audioSource == (Object)null)
			{
				audioSource = ((Component)this).gameObject.GetComponent<AudioSource>();
				if ((Object)(object)audioSource == (Object)null)
				{
					audioSource = ((Component)this).gameObject.AddComponent<AudioSource>();
				}
			}
			if (mixerName != null && mixerName.Length > 0 && mixerGroupName != null && mixerGroupName.Length > 0)
			{
				audioSource.outputAudioMixerGroup = AssetGatherDialog.audioMixers[mixerName].Item2.First((AudioMixerGroup g) => ((Object)g).name == mixerGroupName);
			}
			Object.Destroy((Object)(object)this);
		}
	}
	[AddComponentMenu("LethalSDK/NetworkPrefabInstancier")]
	public class SI_NetworkPrefabInstancier : MonoBehaviour
	{
		public GameObject prefab;

		[HideInInspector]
		public GameObject instance;

		public void Awake()
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)prefab != (Object)null)
			{
				NetworkObject component = prefab.GetComponent<NetworkObject>();
				if ((Object)(object)component != (Object)null && (Object)(object)component.NetworkManager != (Object)null)
				{
					SI_NetworkDataInterfacing component2 = ((Component)this).GetComponent<SI_NetworkDataInterfacing>();
					SI_NetworkData sI_NetworkData = null;
					if ((Object)(object)component2 != (Object)null)
					{
						sI_NetworkData = prefab.GetComponent<SI_NetworkData>();
						if ((Object)(object)sI_NetworkData == (Object)null)
						{
							prefab.AddComponent<SI_NetworkData>();
						}
					}
					if (component.NetworkManager.IsHost)
					{
						instance = Object.Instantiate<GameObject>(prefab, ((Component)this).transform.position, ((Component)this).transform.rotation, ((Component)this).transform.parent);
						SI_NetworkData component3 = instance.GetComponent<SI_NetworkData>();
						if ((Object)(object)component2 != (Object)null && (Object)(object)component3 != (Object)null)
						{
							component3.setData(component2.getData());
						}
						instance.GetComponent<NetworkObject>().Spawn(false);
					}
				}
			}
			((Component)this).gameObject.SetActive(false);
		}

		public void OnDestroy()
		{
			if ((Object)(object)instance != (Object)null)
			{
				NetworkObject component = prefab.GetComponent<NetworkObject>();
				if ((Object)(object)component != (Object)null && (Object)(object)component.NetworkManager != (Object)null && component.NetworkManager.IsHost)
				{
					instance.GetComponent<NetworkObject>().Despawn(true);
					Object.Destroy((Object)(object)instance);
				}
			}
		}
	}
	[AddComponentMenu("LethalSDK/NetworkDataInterfacing")]
	public class SI_NetworkDataInterfacing : MonoBehaviour
	{
		public StringStringPair[] data = new StringStringPair[0];

		[HideInInspector]
		public string serializedData = string.Empty;

		private void OnValidate()
		{
			serializedData = string.Join(";", data.Select((StringStringPair p) => p._string1.RemoveNonAlphanumeric(1) + "," + p._string2.RemoveNonAlphanumeric(1)));
		}

		public virtual StringStringPair[] getData()
		{
			return (from s in serializedData.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new StringStringPair(split[0], split[1])).ToArray();
		}
	}
	public class ScriptImporter : MonoBehaviour
	{
		public virtual void Awake()
		{
			Object.Destroy((Object)(object)this);
		}
	}
	[AddComponentMenu("LethalSDK/MatchLocalPlayerPosition")]
	public class SI_MatchLocalPlayerPosition : ScriptImporter
	{
		public override void Awake()
		{
			((Component)this).gameObject.AddComponent<MatchLocalPlayerPosition>();
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/AnimatedSun")]
	public class SI_AnimatedSun : ScriptImporter
	{
		public Light indirectLight;

		public Light directLight;

		public override void Awake()
		{
			animatedSun val = ((Component)this).gameObject.AddComponent<animatedSun>();
			val.indirectLight = indirectLight;
			val.directLight = directLight;
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/ScanNode")]
	public class SI_ScanNode : ScriptImporter
	{
		public int MaxRange;

		public int MinRange;

		public bool RequiresLineOfSight;

		public string HeaderText;

		public string SubText;

		public int ScrapValue;

		public int CreatureScanID;

		public NodeType NodeType;

		public override void Awake()
		{
			ScanNodeProperties val = ((Component)this).gameObject.AddComponent<ScanNodeProperties>();
			val.minRange = MinRange;
			val.maxRange = MaxRange;
			val.requiresLineOfSight = RequiresLineOfSight;
			val.headerText = HeaderText;
			val.subText = SubText;
			val.scrapValue = ScrapValue;
			val.creatureScanID = CreatureScanID;
			val.nodeType = (int)NodeType;
			base.Awake();
		}
	}
	public enum NodeType
	{
		Information = 0,
		Danger = 0,
		Ressource = 0
	}
	[AddComponentMenu("LethalSDK/AudioReverbPresets")]
	public class SI_AudioReverbPresets : ScriptImporter
	{
		public GameObject[] presets;

		public override void Awake()
		{
		}

		public void Update()
		{
			int num = 0;
			GameObject[] array = presets;
			foreach (GameObject val in array)
			{
				if ((Object)(object)val.GetComponent<SI_AudioReverbTrigger>() != (Object)null)
				{
					num++;
				}
			}
			if (num != 0)
			{
				return;
			}
			List<AudioReverbTrigger> list = new List<AudioReverbTrigger>();
			GameObject[] array2 = presets;
			foreach (GameObject val2 in array2)
			{
				if ((Object)(object)val2.GetComponent<AudioReverbTrigger>() != (Object)null)
				{
					list.Add(val2.GetComponent<AudioReverbTrigger>());
				}
			}
			AudioReverbPresets val3 = ((Component)this).gameObject.AddComponent<AudioReverbPresets>();
			val3.audioPresets = list.ToArray();
			Object.Destroy((Object)(object)this);
		}
	}
	[AddComponentMenu("LethalSDK/AudioReverbTrigger")]
	public class SI_AudioReverbTrigger : ScriptImporter
	{
		[Header("Reverb Preset")]
		public bool ChangeDryLevel = false;

		[Range(-10000f, 0f)]
		public float DryLevel = 0f;

		public bool ChangeHighFreq = false;

		[Range(-10000f, 0f)]
		public float HighFreq = -270f;

		public bool ChangeLowFreq = false;

		[Range(-10000f, 0f)]
		public float LowFreq = -244f;

		public bool ChangeDecayTime = false;

		[Range(0f, 35f)]
		public float DecayTime = 1.4f;

		public bool ChangeRoom = false;

		[Range(-10000f, 0f)]
		public float Room = -600f;

		[Header("MISC")]
		public bool ElevatorTriggerForProps = false;

		public bool SetInElevatorTrigger = false;

		public bool IsShipRoom = false;

		public bool ToggleLocalFog = false;

		public float FogEnabledAmount = 10f;

		[Header("Weather and effects")]
		public bool SetInsideAtmosphere = false;

		public bool InsideLighting = false;

		public int WeatherEffect = -1;

		public bool EffectEnabled = true;

		public bool DisableAllWeather = false;

		public bool EnableCurrentLevelWeather = true;

		public override void Awake()
		{
			AudioReverbTrigger val = ((Component)this).gameObject.AddComponent<AudioReverbTrigger>();
			ReverbPreset val2 = ScriptableObject.CreateInstance<ReverbPreset>();
			val2.changeDryLevel = ChangeDryLevel;
			val2.dryLevel = DryLevel;
			val2.changeHighFreq = ChangeHighFreq;
			val2.highFreq = HighFreq;
			val2.changeLowFreq = ChangeLowFreq;
			val2.lowFreq = LowFreq;
			val2.changeDecayTime = ChangeDecayTime;
			val2.decayTime = DecayTime;
			val2.changeRoom = ChangeRoom;
			val2.room = Room;
			val.reverbPreset = val2;
			val.usePreset = -1;
			val.audioChanges = (switchToAudio[])(object)new switchToAudio[0];
			val.elevatorTriggerForProps = ElevatorTriggerForProps;
			val.setInElevatorTrigger = SetInElevatorTrigger;
			val.isShipRoom = IsShipRoom;
			val.toggleLocalFog = ToggleLocalFog;
			val.fogEnabledAmount = FogEnabledAmount;
			val.setInsideAtmosphere = SetInsideAtmosphere;
			val.insideLighting = InsideLighting;
			val.weatherEffect = WeatherEffect;
			val.effectEnabled = EffectEnabled;
			val.disableAllWeather = DisableAllWeather;
			val.enableCurrentLevelWeather = EnableCurrentLevelWeather;
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/DungeonGenerator")]
	public class SI_DungeonGenerator : ScriptImporter
	{
		public GameObject DungeonRoot;

		public override void Awake()
		{
			//IL_0081: 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_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_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			if (((Component)this).tag != "DungeonGenerator")
			{
				((Component)this).tag = "DungeonGenerator";
			}
			RuntimeDungeon val = ((Component)this).gameObject.AddComponent<RuntimeDungeon>();
			val.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0];
			val.Generator.LengthMultiplier = 0.8f;
			val.Generator.PauseBetweenRooms = 0.2f;
			val.GenerateOnStart = false;
			if ((Object)(object)DungeonRoot != (Object)null)
			{
				_ = DungeonRoot.scene;
				if (false)
				{
					DungeonRoot = new GameObject();
					((Object)DungeonRoot).name = "DungeonRoot";
					DungeonRoot.transform.position = new Vector3(0f, -200f, 0f);
				}
			}
			val.Root = DungeonRoot;
			val.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0];
			UnityNavMeshAdapter val2 = ((Component)this).gameObject.AddComponent<UnityNavMeshAdapter>();
			val2.BakeMode = (RuntimeNavMeshBakeMode)3;
			val2.LayerMask = LayerMask.op_Implicit(35072);
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/EntranceTeleport")]
	public class SI_EntranceTeleport : ScriptImporter
	{
		public int EntranceID = 0;

		public Transform EntrancePoint;

		public int AudioReverbPreset = 2;

		public AudioClip[] DoorAudios = (AudioClip[])(object)new AudioClip[0];

		public override void Awake()
		{
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Expected O, but got Unknown
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Expected O, but got Unknown
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Expected O, but got Unknown
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Expected O, but got Unknown
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Expected O, but got Unknown
			AudioSource val = ((Component)this).gameObject.AddComponent<AudioSource>();
			val.outputAudioMixerGroup = AssetGatherDialog.audioMixers["Diagetic"].Item2.First((AudioMixerGroup g) => ((Object)g).name == "Master");
			val.playOnAwake = false;
			val.spatialBlend = 1f;
			EntranceTeleport entra

plugins/MaskedEnemyRework.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using MaskedEnemyRework.External_Classes;
using MaskedEnemyRework.Patches;
using Microsoft.CodeAnalysis;
using MoreCompany;
using MoreCompany.Cosmetics;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MaskedEnemyRework
{
	[BepInPlugin("MaskedEnemyRework", "MaskedEnemyRework", "3.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("MaskedEnemyRework");

		private static Plugin Instance;

		internal ManualLogSource logger;

		public static List<int> PlayerMimicList;

		public static int PlayerMimicIndex;

		private ConfigEntry<bool> RemoveMasksConfig;

		private ConfigEntry<bool> RevealMasksConfig;

		private ConfigEntry<bool> ShowMaskedNamesConfig;

		private ConfigEntry<bool> RemoveZombieArmsConfig;

		private ConfigEntry<bool> UseSpawnRarityConfig;

		private ConfigEntry<int> SpawnRarityConfig;

		private ConfigEntry<bool> CanSpawnOutsideConfig;

		private ConfigEntry<int> MaxSpawnCountConfig;

		private ConfigEntry<bool> ZombieApocalypeModeConfig;

		private ConfigEntry<bool> UseVanillaSpawnsConfig;

		private ConfigEntry<int> ZombieApocalypeRandomChanceConfig;

		private ConfigEntry<int> MaxZombiesZombieConfig;

		private ConfigEntry<float> InsideEnemySpawnCurveConfig;

		private ConfigEntry<float> MiddayInsideEnemySpawnCurveConfig;

		private ConfigEntry<float> StartOutsideEnemySpawnCurveConfig;

		private ConfigEntry<float> MidOutsideEnemySpawnCurveConfig;

		private ConfigEntry<float> EndOutsideEnemySpawnCurveConfig;

		public static bool RemoveMasks;

		public static bool RevealMasks;

		public static bool ShowMaskedNames;

		public static bool RemoveZombieArms;

		public static bool UseSpawnRarity;

		public static int SpawnRarity;

		public static bool CanSpawnOutside;

		public static int MaxSpawnCount;

		public static int MaxZombies;

		public static bool ZombieApocalypseMode;

		public static bool UseVanillaSpawns;

		public static int RandomChanceZombieApocalypse;

		public static float InsideEnemySpawnCurve;

		public static float MiddayInsideEnemySpawnCurve;

		public static float StartOutsideEnemySpawnCurve;

		public static float MidOutsideEnemySpawnCurve;

		public static float EndOutsideEnemySpawnCurve;

		public static int InitialPlayerCount;

		public static SpawnableEnemyWithRarity maskedPrefab;

		public static SpawnableEnemyWithRarity flowerPrefab;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			PlayerMimicList = new List<int>();
			PlayerMimicIndex = 0;
			InitialPlayerCount = 0;
			ShowMaskedNamesConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Show Masked Usernames", false, "Will show username of player being mimicked.");
			RemoveMasksConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Remove Mask From Masked Enemy", true, "Whether or not the Masked Enemy has a mask on.");
			RevealMasksConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Reveal Mask When Attacking", false, "The enemy would reveal their mask permanently after trying to attack someone. Mask would be off until the attempt to attack is made");
			RemoveZombieArmsConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Remove Zombie Arms", true, "Remove the animation where the Masked raise arms like a zombie.");
			UseVanillaSpawnsConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Use Vanilla Spawns", false, "Ignores anything else in this mod. Only uses the above settings from this config. Will not spawn on all moons. will ignore EVERYTHING in the config below this point.");
			UseSpawnRarityConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Spawns", "Use Spawn Rarity", false, "Use custom spawn rate from config. If this is false, the masked spawns at the same rate as the Bracken. If true, will spawn at whatever rarity is given in Spawn Rarity config option");
			SpawnRarityConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Spawns", "Spawn Rarity", 15, "The rarity for the Masked Enemy to spawn. The higher the number, the more likely to spawn. Can go to 1000000000, any higher will break. Use Spawn Rarity must be set to True");
			CanSpawnOutsideConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Spawns", "Allow Masked To Spawn Outside", false, "Whether the Masked Enemy can spawn outside the building");
			MaxSpawnCountConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Spawns", "Max Number of Masked", 2, "Max Number of possible masked to spawn in one level");
			ZombieApocalypeModeConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Zombie Apocalypse Mode", "Zombie Apocalypse Mode", false, "Only spawns Masked! Make sure to crank up the Max Spawn Count in this config! Would also recommend bringing a gun (mod), a shovel works fine too though.... This mode does not play nice with other mods that affect spawn rates. Disable those before playing for best results");
			MaxZombiesZombieConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Zombie Apocalypse Mode", "Max Number of Masked in Zombie Apocalypse", 2, "Max Number of possible masked to spawn in Zombie Apocalypse");
			ZombieApocalypeRandomChanceConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Zombie Apocalypse Mode", "Random Zombie Apocalypse Mode", -1, "[Must Be Whole Number] The percent chance from 1 to 100 that a day could contain a zombie apocalypse. Put at -1 to never have the chance arise and don't have Only Spawn Masked turned on");
			InsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "StartOfDay Inside Masked Spawn Curve", 0.1f, "Spawn curve for masked inside, start of the day. Crank this way up for immediate action. More info in the readme");
			MiddayInsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "Midday Inside Masked Spawn Curve", 500f, "Spawn curve for masked inside, midday.");
			StartOutsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "StartOfDay Masked Outside Spawn Curve", -30f, "Spawn curve for outside masked, start of the day.");
			MidOutsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "Midday Outside Masked Spawn Curve", -30f, "Spawn curve for outside masked, midday.");
			EndOutsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "EOD Outside Masked Spawn Curve", 10f, "Spawn curve for outside masked, end of day");
			RemoveMasks = RemoveMasksConfig.Value;
			ShowMaskedNames = ShowMaskedNamesConfig.Value;
			RevealMasks = RevealMasksConfig.Value;
			UseVanillaSpawns = UseVanillaSpawnsConfig.Value;
			RemoveZombieArms = RemoveZombieArmsConfig.Value;
			UseSpawnRarity = UseSpawnRarityConfig.Value;
			CanSpawnOutside = CanSpawnOutsideConfig.Value;
			MaxSpawnCount = MaxSpawnCountConfig.Value;
			SpawnRarity = SpawnRarityConfig.Value;
			ZombieApocalypseMode = ZombieApocalypeModeConfig.Value;
			MaxZombies = MaxZombiesZombieConfig.Value;
			InsideEnemySpawnCurve = InsideEnemySpawnCurveConfig.Value;
			MiddayInsideEnemySpawnCurve = MiddayInsideEnemySpawnCurveConfig.Value;
			StartOutsideEnemySpawnCurve = StartOutsideEnemySpawnCurveConfig.Value;
			MidOutsideEnemySpawnCurve = MidOutsideEnemySpawnCurveConfig.Value;
			EndOutsideEnemySpawnCurve = EndOutsideEnemySpawnCurveConfig.Value;
			RandomChanceZombieApocalypse = ZombieApocalypeRandomChanceConfig.Value;
			logger = Logger.CreateLogSource("MaskedEnemyRework");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MaskedEnemyRework is loaded! Woohoo!");
			harmony.PatchAll(typeof(Plugin));
			harmony.PatchAll(typeof(GetMaskedPrefabForLaterUse));
			harmony.PatchAll(typeof(MaskedVisualRework));
			harmony.PatchAll(typeof(MaskedSpawnSettings));
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "MaskedEnemyRework";

		public const string PLUGIN_NAME = "MaskedEnemyRework";

		public const string PLUGIN_VERSION = "3.1.1";
	}
}
namespace MaskedEnemyRework.Patches
{
	[HarmonyPatch]
	internal class GetMaskedPrefabForLaterUse
	{
		[HarmonyPatch(typeof(Terminal), "Start")]
		[HarmonyPostfix]
		private static void SavesPrefabForLaterUse(ref SelectableLevel[] ___moonsCatalogueList)
		{
			ManualLogSource val = Logger.CreateLogSource("MaskedEnemyRework");
			SelectableLevel[] array = ___moonsCatalogueList;
			foreach (SelectableLevel val2 in array)
			{
				foreach (SpawnableEnemyWithRarity enemy in val2.Enemies)
				{
					if (enemy.enemyType.enemyName == "Masked")
					{
						val.LogInfo((object)"Found Masked!");
						Plugin.maskedPrefab = enemy;
					}
					else if (enemy.enemyType.enemyName == "Flowerman")
					{
						Plugin.flowerPrefab = enemy;
						val.LogInfo((object)"Found Flowerman!");
					}
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SetHoverTipAndCurrentInteractTrigger")]
		[HarmonyPrefix]
		private static void LookingAtMasked(ref PlayerControllerB __instance)
		{
			//IL_0020: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.ShowMaskedNames)
			{
				return;
			}
			Ray val = default(Ray);
			((Ray)(ref val))..ctor(((Component)__instance.gameplayCamera).transform.position, ((Component)__instance.gameplayCamera).transform.forward);
			LayerMask val2 = LayerMask.op_Implicit(524288);
			RaycastHit val3 = default(RaycastHit);
			if (!__instance.isFreeCamera && Physics.Raycast(val, ref val3, 5f, LayerMask.op_Implicit(val2)))
			{
				EnemyAICollisionDetect component = ((Component)((RaycastHit)(ref val3)).collider).gameObject.GetComponent<EnemyAICollisionDetect>();
				MaskedPlayerEnemy val4 = null;
				if (Object.op_Implicit((Object)(object)component))
				{
					val4 = ((Component)component.mainScript).gameObject.GetComponent<MaskedPlayerEnemy>();
				}
				if ((Object)(object)val4 != (Object)null)
				{
					MaskedNamePatch.ToggleName(val4, TurnOn: true);
				}
			}
		}
	}
	internal class MaskedNamePatch
	{
		public static void UpdateNameBillboard(MaskedPlayerEnemy masked)
		{
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: 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)
			MaskedNameBillboard maskedNameBillboard = default(MaskedNameBillboard);
			if (((Component)masked).gameObject.TryGetComponent<MaskedNameBillboard>(ref maskedNameBillboard))
			{
				Canvas usernameCanvas = maskedNameBillboard.usernameCanvas;
				CanvasGroup canvasGroup = GetCanvasGroup(usernameCanvas);
				Transform transform = ((Component)usernameCanvas).transform;
				TextMeshProUGUI usernameText = maskedNameBillboard.usernameText;
				if (Object.op_Implicit((Object)(object)usernameCanvas) && Object.op_Implicit((Object)(object)transform) && Object.op_Implicit((Object)(object)canvasGroup))
				{
					if (!((Component)usernameText).gameObject.activeInHierarchy || !Object.op_Implicit((Object)(object)((Graphic)usernameText).canvas))
					{
						((TMP_Text)usernameText).transform.SetParent(transform, false);
					}
					if (canvasGroup.alpha >= 0f && (Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null)
					{
						canvasGroup.alpha -= Time.deltaTime;
						Vector3 val = default(Vector3);
						((Vector3)(ref val)).Set(((Component)masked).transform.position.x, ((Component)masked).transform.position.y + 2.64f, ((Component)masked).transform.position.z);
						transform.SetPositionAndRotation(val, transform.rotation);
						transform.LookAt(GameNetworkManager.Instance.localPlayerController.localVisorTargetPoint);
					}
					else if (((Component)usernameCanvas).gameObject.activeSelf)
					{
						((Component)usernameCanvas).gameObject.SetActive(false);
					}
				}
			}
			else if ((Object)(object)masked.mimickingPlayer != (Object)null)
			{
				SetNameBillboard(masked);
			}
		}

		public static void ToggleName(MaskedPlayerEnemy masked, bool TurnOn)
		{
			MaskedNameBillboard maskedNameBillboard = default(MaskedNameBillboard);
			if (!((Object)(object)masked == (Object)null) && ((Component)masked).gameObject.TryGetComponent<MaskedNameBillboard>(ref maskedNameBillboard))
			{
				((Component)maskedNameBillboard.usernameCanvas).gameObject.SetActive(TurnOn);
				if (TurnOn)
				{
					GetCanvasGroup(maskedNameBillboard.usernameCanvas).alpha = 1f;
				}
			}
		}

		public static CanvasGroup GetCanvasGroup(Canvas canvas)
		{
			CanvasGroup val = null;
			if ((Object)(object)canvas != (Object)null)
			{
				val = ((Component)canvas).gameObject.GetComponent<CanvasGroup>();
				if ((Object)(object)val == (Object)null)
				{
					val = ((Component)canvas).gameObject.AddComponent<CanvasGroup>();
				}
			}
			return val;
		}

		public static void SetNameBillboard(MaskedPlayerEnemy masked)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)masked.mimickingPlayer == (Object)null))
			{
				PlayerControllerB mimickingPlayer = masked.mimickingPlayer;
				MaskedNameBillboard maskedNameBillboard = default(MaskedNameBillboard);
				if (!((Component)masked).gameObject.TryGetComponent<MaskedNameBillboard>(ref maskedNameBillboard))
				{
					maskedNameBillboard = ((Component)masked).gameObject.AddComponent<MaskedNameBillboard>();
				}
				maskedNameBillboard.usernameCanvas = mimickingPlayer.usernameCanvas;
				GetCanvasGroup(maskedNameBillboard.usernameCanvas);
				GameObject val = new GameObject("usernameText");
				val.transform.SetParent(((Component)maskedNameBillboard.usernameCanvas).transform, false);
				maskedNameBillboard.usernameText = val.AddComponent<TextMeshProUGUI>();
				((TMP_Text)maskedNameBillboard.usernameText).transform.SetParent(((Component)maskedNameBillboard.usernameCanvas).transform, false);
				((TMP_Text)maskedNameBillboard.usernameText).text = ((TMP_Text)mimickingPlayer.usernameBillboardText).text;
				((TMP_Text)maskedNameBillboard.usernameText).font = ((TMP_Text)mimickingPlayer.usernameBillboardText).font;
				((Graphic)maskedNameBillboard.usernameText).color = ((Graphic)mimickingPlayer.usernameBillboardText).color;
				((TMP_Text)maskedNameBillboard.usernameText).fontSize = ((TMP_Text)mimickingPlayer.usernameBillboardText).fontSize;
				((TMP_Text)maskedNameBillboard.usernameText).enableAutoSizing = ((TMP_Text)mimickingPlayer.usernameBillboardText).enableAutoSizing;
				((TMP_Text)maskedNameBillboard.usernameText).extraPadding = ((TMP_Text)mimickingPlayer.usernameBillboardText).extraPadding;
				((TMP_Text)maskedNameBillboard.usernameText).alignment = ((TMP_Text)mimickingPlayer.usernameBillboardText).alignment;
				((TMP_Text)maskedNameBillboard.usernameText).textStyle = ((TMP_Text)mimickingPlayer.usernameBillboardText).textStyle;
				((TMP_Text)maskedNameBillboard.usernameText).textPreprocessor = ((TMP_Text)mimickingPlayer.usernameBillboardText).textPreprocessor;
				((TMP_Text)maskedNameBillboard.usernameText).characterSpacing = ((TMP_Text)mimickingPlayer.usernameBillboardText).characterSpacing;
				((TMP_Text)maskedNameBillboard.usernameText).wordSpacing = ((TMP_Text)mimickingPlayer.usernameBillboardText).wordSpacing;
				((TMP_Text)maskedNameBillboard.usernameText).lineSpacing = ((TMP_Text)mimickingPlayer.usernameBillboardText).lineSpacing;
				((TMP_Text)maskedNameBillboard.usernameText).margin = ((TMP_Text)mimickingPlayer.usernameBillboardText).margin;
				((TMP_Text)maskedNameBillboard.usernameText).overflowMode = ((TMP_Text)mimickingPlayer.usernameBillboardText).overflowMode;
				((TMP_Text)maskedNameBillboard.usernameText).fontSharedMaterial = ((TMP_Text)mimickingPlayer.usernameBillboardText).fontSharedMaterial;
				((TMP_Text)maskedNameBillboard.usernameText).fontSizeMin = ((TMP_Text)mimickingPlayer.usernameBillboardText).fontSizeMin;
				((TMP_Text)maskedNameBillboard.usernameText).fontSizeMax = ((TMP_Text)mimickingPlayer.usernameBillboardText).fontSizeMax;
				((TMP_Text)maskedNameBillboard.usernameText).enableKerning = ((TMP_Text)mimickingPlayer.usernameBillboardText).enableKerning;
				RectTransform component = ((Component)mimickingPlayer.usernameBillboardText).GetComponent<RectTransform>();
				RectTransform component2 = ((Component)maskedNameBillboard.usernameText).GetComponent<RectTransform>();
				((Transform)component2).localPosition = ((Transform)component).localPosition;
				component2.sizeDelta = component.sizeDelta;
				component2.anchorMin = component.anchorMin;
				component2.anchorMax = component.anchorMax;
				component2.pivot = component.pivot;
				component2.anchoredPosition = component.anchoredPosition;
				((Transform)component2).localScale = ((Transform)component).localScale;
				component2.offsetMin = component.offsetMin;
				component2.offsetMax = component.offsetMax;
				((Transform)component2).right = ((Transform)component).right;
				((Component)maskedNameBillboard.usernameText).gameObject.SetActive(true);
				((Behaviour)maskedNameBillboard.usernameText).enabled = true;
				((Behaviour)maskedNameBillboard.usernameCanvas).enabled = true;
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	internal class MaskedSpawnSettings
	{
		[HarmonyPatch("BeginEnemySpawning")]
		[HarmonyPrefix]
		private static void UpdateSpawnRates(ref SelectableLevel ___currentLevel)
		{
			//IL_01a5: 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_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_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Expected O, but got Unknown
			//IL_022b: 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_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Expected O, but got Unknown
			if (Plugin.UseVanillaSpawns)
			{
				return;
			}
			try
			{
				SpawnableEnemyWithRarity maskedPrefab = Plugin.maskedPrefab;
				SpawnableEnemyWithRarity val = Plugin.flowerPrefab;
				List<SpawnableEnemyWithRarity> enemies = ___currentLevel.Enemies;
				for (int i = 0; i < ___currentLevel.Enemies.Count; i++)
				{
					SpawnableEnemyWithRarity val2 = ___currentLevel.Enemies[i];
					if (val2.enemyType.enemyName == "Masked")
					{
						enemies.Remove(val2);
					}
					if (val2.enemyType.enemyName == "Flowerman")
					{
						val = val2;
					}
				}
				___currentLevel.Enemies = enemies;
				maskedPrefab.enemyType.PowerLevel = 1;
				maskedPrefab.enemyType.probabilityCurve = val.enemyType.probabilityCurve;
				if (Plugin.UseSpawnRarity)
				{
					maskedPrefab.rarity = Plugin.SpawnRarity;
				}
				else
				{
					maskedPrefab.rarity = val.rarity;
				}
				maskedPrefab.enemyType.MaxCount = Plugin.MaxSpawnCount;
				int num = 0;
				num = ((StartOfRound.Instance.randomMapSeed.ToString().Length >= 3) ? int.Parse(StartOfRound.Instance.randomMapSeed.ToString().Substring(1, 2)) : 0);
				num = Mathf.Clamp(num, 0, 100);
				if (Plugin.ZombieApocalypseMode || (num <= Plugin.RandomChanceZombieApocalypse && Plugin.RandomChanceZombieApocalypse >= 0))
				{
					maskedPrefab.enemyType.MaxCount = Plugin.MaxZombies;
					Plugin.RandomChanceZombieApocalypse = -1;
					___currentLevel.enemySpawnChanceThroughoutDay = new AnimationCurve((Keyframe[])(object)new Keyframe[2]
					{
						new Keyframe(0f, Plugin.InsideEnemySpawnCurve),
						new Keyframe(0.5f, Plugin.MiddayInsideEnemySpawnCurve)
					});
					___currentLevel.daytimeEnemySpawnChanceThroughDay = new AnimationCurve((Keyframe[])(object)new Keyframe[2]
					{
						new Keyframe(0f, 7f),
						new Keyframe(0.5f, 7f)
					});
					___currentLevel.outsideEnemySpawnChanceThroughDay = new AnimationCurve((Keyframe[])(object)new Keyframe[3]
					{
						new Keyframe(0f, Plugin.StartOutsideEnemySpawnCurve),
						new Keyframe(20f, Plugin.MidOutsideEnemySpawnCurve),
						new Keyframe(21f, Plugin.EndOutsideEnemySpawnCurve)
					});
					maskedPrefab.rarity = 1000000;
				}
				maskedPrefab.enemyType.isOutsideEnemy = Plugin.CanSpawnOutside;
				if (Plugin.CanSpawnOutside)
				{
					___currentLevel.OutsideEnemies.Add(maskedPrefab);
				}
				SelectableLevel obj = ___currentLevel;
				obj.maxEnemyPowerCount += maskedPrefab.enemyType.MaxCount;
				SelectableLevel obj2 = ___currentLevel;
				obj2.maxDaytimeEnemyPowerCount += maskedPrefab.enemyType.MaxCount;
				SelectableLevel obj3 = ___currentLevel;
				obj3.maxOutsideEnemyPowerCount += maskedPrefab.enemyType.MaxCount;
				___currentLevel.Enemies.Add(maskedPrefab);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(MaskedPlayerEnemy))]
	internal class MaskedVisualRework
	{
		private static int randomPlayerIndex;

		private static IEnumerator coroutine;

		[HarmonyPatch("Start")]
		[HarmonyBefore(new string[] { "AdvancedCompany" })]
		[HarmonyPostfix]
		private static void ReformVisuals(ref MaskedPlayerEnemy __instance)
		{
			//IL_0067: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
			ManualLogSource val = Logger.CreateLogSource("MaskedEnemyRework");
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			int num = StartOfRound.Instance.ClientPlayerList.Count;
			if (num == 0)
			{
				num = 1;
				val.LogError((object)"Player count was zero");
			}
			if (Plugin.PlayerMimicList.Count <= 1 || Plugin.InitialPlayerCount != num)
			{
				Plugin.InitialPlayerCount = num;
				State state = Random.state;
				Random.InitState(1234);
				for (int i = 0; i < 50; i++)
				{
					Plugin.PlayerMimicList.Add(Random.Range(0, num));
				}
				Random.state = state;
			}
			randomPlayerIndex = Plugin.PlayerMimicList[Plugin.PlayerMimicIndex % 50];
			randomPlayerIndex = Mathf.Clamp(randomPlayerIndex, 0, num);
			Plugin.PlayerMimicIndex++;
			if ((Object)(object)__instance.mimickingPlayer == (Object)null)
			{
				__instance.mimickingPlayer = allPlayerScripts[randomPlayerIndex];
			}
			__instance.SetSuit(__instance.mimickingPlayer.currentSuitID);
			if (Plugin.RemoveMasks || Plugin.RevealMasks)
			{
				((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskComedy")).gameObject.SetActive(false);
				((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskTragedy")).gameObject.SetActive(false);
			}
			if (Chainloader.PluginInfos.ContainsKey("me.swipez.melonloader.morecompany") && !Chainloader.PluginInfos.ContainsKey("com.potatoepet.AdvancedCompany"))
			{
				MoreCompanyPatch.ApplyCosmetics(__instance);
			}
			if (Plugin.ShowMaskedNames)
			{
				MaskedNamePatch.SetNameBillboard(__instance);
			}
		}

		[HarmonyPatch("SetHandsOutClientRpc")]
		[HarmonyPrefix]
		private static void MaskAndArmsReveal(ref bool setOut, ref MaskedPlayerEnemy __instance)
		{
			GameObject gameObject = ((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskComedy")).gameObject;
			if (Plugin.RevealMasks && !gameObject.activeSelf && ((EnemyAI)__instance).currentBehaviourStateIndex == 1)
			{
				ManualLogSource val = Logger.CreateLogSource("MaskedEnemyRework");
				IEnumerator enumerator = FadeInAndOut(gameObject, fadeIn: true, 1f);
				((MonoBehaviour)__instance).StartCoroutine(enumerator);
			}
			if (Plugin.RemoveZombieArms)
			{
				setOut = false;
			}
			if (Plugin.ShowMaskedNames)
			{
				MaskedNamePatch.SetNameBillboard(__instance);
			}
		}

		[HarmonyPatch("SetEnemyOutside")]
		[HarmonyPostfix]
		[HarmonyPriority(300)]
		private static void HideCosmeticsIfMarked(ref MaskedPlayerEnemy __instance)
		{
			if (Chainloader.PluginInfos.ContainsKey("me.swipez.melonloader.morecompany") && !Chainloader.PluginInfos.ContainsKey("com.potatoepet.AdvancedCompany"))
			{
				MoreCompanyPatch.ApplyCosmetics(__instance);
			}
		}

		[HarmonyPatch("DoAIInterval")]
		[HarmonyPostfix]
		private static void HideRevealedMask(ref MaskedPlayerEnemy __instance)
		{
			if (Plugin.RevealMasks && (Object)(object)((EnemyAI)__instance).targetPlayer == (Object)null)
			{
				GameObject gameObject = ((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskComedy")).gameObject;
				if (gameObject.activeSelf)
				{
					IEnumerator enumerator = FadeInAndOut(gameObject, fadeIn: false, 1f);
					((MonoBehaviour)__instance).StartCoroutine(enumerator);
				}
			}
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdateMaskName(ref MaskedPlayerEnemy __instance)
		{
			if (Plugin.ShowMaskedNames)
			{
				MaskedNamePatch.UpdateNameBillboard(__instance);
			}
		}

		private static IEnumerator FadeInAndOut(GameObject mask, bool fadeIn, float duration)
		{
			float counter = 0f;
			mask.SetActive(true);
			float startLoc;
			float endLoc;
			if (fadeIn)
			{
				startLoc = 0.095f;
				endLoc = 0.215f;
			}
			else
			{
				startLoc = 0.215f;
				endLoc = 0.095f;
			}
			while (counter < duration)
			{
				counter += Time.deltaTime;
				float loc = Mathf.Lerp(startLoc, endLoc, counter / duration);
				mask.transform.localPosition = new Vector3(-0.009f, 0.143f, loc);
				yield return null;
			}
			if (!fadeIn)
			{
				mask.SetActive(false);
			}
		}
	}
	internal class MoreCompanyPatch
	{
		public static void ApplyCosmetics(MaskedPlayerEnemy masked)
		{
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			if (!MainClass.showCosmetics || MainClass.playerIdsAndCosmetics.Count == 0)
			{
				return;
			}
			Transform val = ((Component)masked).transform.Find("ScavengerModel").Find("metarig");
			CosmeticApplication component = ((Component)val).GetComponent<CosmeticApplication>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.ClearCosmetics();
				Object.Destroy((Object)(object)component);
			}
			List<string> list = MainClass.playerIdsAndCosmetics[(int)masked.mimickingPlayer.playerClientId];
			component = ((Component)val).gameObject.AddComponent<CosmeticApplication>();
			foreach (string item in list)
			{
				component.ApplyCosmetic(item, true);
			}
			foreach (CosmeticInstance spawnedCosmetic in component.spawnedCosmetics)
			{
				Transform transform = ((Component)spawnedCosmetic).transform;
				transform.localScale *= 0.38f;
			}
		}
	}
	internal class RemoveZombieArms
	{
		[HarmonyPatch(typeof(MaskedPlayerEnemy), "SetHandsOutClientRpc")]
		[HarmonyPrefix]
		private static void RemoveArms(ref bool setOut)
		{
			if (Plugin.RemoveZombieArms)
			{
				setOut = false;
			}
		}
	}
}
namespace MaskedEnemyRework.External_Classes
{
	internal class MaskedMimicFields : MonoBehaviour
	{
		public PlayerControllerB MimickingPlayerController { get; set; }
	}
	internal class MaskedNameBillboard : MonoBehaviour
	{
		public Canvas usernameCanvas;

		public TextMeshProUGUI usernameText;
	}
}

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.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using 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.3.2.0")]
[assembly: AssemblyInformationalVersion("2.3.2")]
[assembly: AssemblyProduct("Mimics")]
[assembly: AssemblyTitle("Mimics")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.3.2.0")]
[module: UnverifiableCode]
internal class <Module>
{
	static <Module>()
	{
		NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>();
		NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>();
	}
}
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.3.2")]
	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(StartOfRound))]
		internal class StartOfRoundPatch
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			private static void StartPatch(ref StartOfRound __instance)
			{
				if (((NetworkBehaviour)__instance).IsServer && (Object)(object)MimicNetworker.Instance == (Object)null)
				{
					GameObject val = Object.Instantiate<GameObject>(MimicNetworkerPrefab);
					val.GetComponent<NetworkObject>().Spawn(true);
					MimicNetworker.SpawnWeight0.Value = SpawnRates[0];
					MimicNetworker.SpawnWeight1.Value = SpawnRates[1];
					MimicNetworker.SpawnWeight2.Value = SpawnRates[2];
					MimicNetworker.SpawnWeight3.Value = SpawnRates[3];
					MimicNetworker.SpawnWeight4.Value = SpawnRates[4];
					MimicNetworker.SpawnWeightMax.Value = SpawnRates[5];
					MimicNetworker.SpawnRateDynamic.Value = DynamicSpawnRate;
				}
			}
		}

		[HarmonyPatch(typeof(Terminal))]
		internal class TerminalPatch
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			private static void StartPatch(ref StartOfRound __instance)
			{
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_009e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a9: 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_00b8: Expected O, but got Unknown
				//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e1: Expected O, but got Unknown
				Terminal val = Object.FindObjectOfType<Terminal>();
				if (!Object.op_Implicit((Object)(object)val.enemyFiles.Find((TerminalNode node) => node.creatureName == "Mimics")))
				{
					MimicCreatureID = val.enemyFiles.Count;
					MimicFile.creatureFileID = MimicCreatureID;
					val.enemyFiles.Add(MimicFile);
					TerminalKeyword val2 = val.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
					TerminalKeyword val3 = new TerminalKeyword
					{
						word = "mimics",
						isVerb = false,
						defaultVerb = val2
					};
					List<CompatibleNoun> list = val2.compatibleNouns.ToList();
					list.Add(new CompatibleNoun
					{
						noun = val3,
						result = MimicFile
					});
					val2.compatibleNouns = list.ToArray();
					List<TerminalKeyword> list2 = val.terminalNodes.allKeywords.ToList();
					list2.Add(val3);
					val.terminalNodes.allKeywords = list2.ToArray();
				}
			}
		}

		[HarmonyPatch(typeof(RoundManager))]
		internal class RoundManagerPatch
		{
			[HarmonyPatch("SetExitIDs")]
			[HarmonyPostfix]
			private static void SetExitIDsPatch(ref RoundManager __instance, Vector3 mainEntrancePosition)
			{
				//IL_0536: Unknown result type (might be due to invalid IL or missing references)
				//IL_0547: Unknown result type (might be due to invalid IL or missing references)
				//IL_054c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0551: Unknown result type (might be due to invalid IL or missing references)
				//IL_0556: Unknown result type (might be due to invalid IL or missing references)
				//IL_0235: Unknown result type (might be due to invalid IL or missing references)
				//IL_0241: Unknown result type (might be due to invalid IL or missing references)
				//IL_0255: Unknown result type (might be due to invalid IL or missing references)
				//IL_025a: Unknown result type (might be due to invalid IL or missing references)
				//IL_025f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0272: Unknown result type (might be due to invalid IL or missing references)
				//IL_0286: Unknown result type (might be due to invalid IL or missing references)
				//IL_0296: 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)
				//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_0565: Unknown result type (might be due to invalid IL or missing references)
				//IL_056a: Unknown result type (might be due to invalid IL or missing references)
				//IL_056c: Unknown result type (might be due to invalid IL or missing references)
				//IL_056e: Unknown result type (might be due to invalid IL or missing references)
				//IL_05a3: 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_06c0: Unknown result type (might be due to invalid IL or missing references)
				//IL_06c5: Unknown result type (might be due to invalid IL or missing references)
				//IL_06c9: Unknown result type (might be due to invalid IL or missing references)
				//IL_06d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_06da: Unknown result type (might be due to invalid IL or missing references)
				//IL_06de: Unknown result type (might be due to invalid IL or missing references)
				//IL_06e3: Unknown result type (might be due to invalid IL or missing references)
				//IL_033d: Unknown result type (might be due to invalid IL or missing references)
				//IL_034e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0353: Unknown result type (might be due to invalid IL or missing references)
				//IL_0358: Unknown result type (might be due to invalid IL or missing references)
				//IL_035d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0367: Unknown result type (might be due to invalid IL or missing references)
				//IL_036c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0371: Unknown result type (might be due to invalid IL or missing references)
				//IL_0377: Unknown result type (might be due to invalid IL or missing references)
				//IL_037f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0388: Unknown result type (might be due to invalid IL or missing references)
				//IL_0392: Unknown result type (might be due to invalid IL or missing references)
				//IL_067b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0414: Unknown result type (might be due to invalid IL or missing references)
				//IL_041c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0425: Unknown result type (might be due to invalid IL or missing references)
				//IL_042f: Unknown result type (might be due to invalid IL or missing references)
				//IL_07d3: Unknown result type (might be due to invalid IL or missing references)
				//IL_07dd: Expected O, but got Unknown
				//IL_08ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_08d3: Unknown result type (might be due to invalid IL or missing references)
				//IL_084d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0874: Unknown result type (might be due to invalid IL or missing references)
				//IL_0987: Unknown result type (might be due to invalid IL or missing references)
				//IL_09ae: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)MimicNetworker.Instance == (Object)null)
				{
					return;
				}
				MimicDoor.allMimics = new List<MimicDoor>();
				int num = 0;
				Dungeon currentDungeon = __instance.dungeonGenerator.Generator.CurrentDungeon;
				if (!((Object)currentDungeon.DungeonFlow).name.StartsWith("Level1") && !((Object)currentDungeon.DungeonFlow).name.StartsWith("Level2"))
				{
					return;
				}
				int num2 = 0;
				int[] array = new int[6]
				{
					MimicNetworker.SpawnWeight0.Value,
					MimicNetworker.SpawnWeight1.Value,
					MimicNetworker.SpawnWeight2.Value,
					MimicNetworker.SpawnWeight3.Value,
					MimicNetworker.SpawnWeight4.Value,
					MimicNetworker.SpawnWeightMax.Value
				};
				int num3 = 0;
				int[] array2 = array;
				foreach (int num4 in array2)
				{
					num3 += num4;
				}
				Random random = new Random(StartOfRound.Instance.randomMapSeed + 753);
				int num5 = random.Next(0, num3);
				int num6 = 0;
				for (int j = 0; j < array.Length; j++)
				{
					if (num5 < array[j] + num6)
					{
						num2 = j;
						break;
					}
					num6 += array[j];
				}
				if (num2 == 5)
				{
					num2 = 999;
				}
				EntranceTeleport[] array3 = Object.FindObjectsOfType<EntranceTeleport>(false);
				int num7 = (array3.Length - 2) / 2;
				if (MimicNetworker.SpawnRateDynamic.Value && num2 < num7 && num7 > 1)
				{
					num2 += random.Next(0, 2);
				}
				if (MimicNetworker.SpawnRateDynamic.Value && currentDungeon.AllTiles.Count > 100)
				{
					num2 += random.Next(0, 2);
				}
				List<Doorway> list = new List<Doorway>();
				Bounds val2 = 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 val = Matrix4x4.TRS(((Component)unusedDoorway).transform.position, ((Component)unusedDoorway).transform.rotation, new Vector3(1f, 1f, 1f));
						((Bounds)(ref val2))..ctor(new Vector3(0f, 1.5f, 5.5f), new Vector3(2f, 6f, 8f));
						((Bounds)(ref val2)).center = ((Matrix4x4)(ref val)).MultiplyPoint3x4(((Bounds)(ref val2)).center);
						Collider[] array4 = Physics.OverlapBox(((Bounds)(ref val2)).center, ((Bounds)(ref val2)).extents, ((Component)unusedDoorway).transform.rotation, LayerMask.GetMask(new string[3] { "Room", "Railing", "MapHazards" }));
						Collider[] array5 = array4;
						int num8 = 0;
						if (num8 < array5.Length)
						{
							Collider val3 = array5[num8];
							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 val4 = UnityUtil.CalculateProxyBounds(((Component)allTile2).gameObject, true, Vector3.up);
								Ray val5 = default(Ray);
								((Ray)(ref val5)).origin = origin;
								((Ray)(ref val5)).direction = Vector3.up;
								if (((Bounds)(ref val4)).IntersectRay(val5) && (((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;
								}
								val5 = default(Ray);
								((Ray)(ref val5)).origin = origin;
								((Ray)(ref val5)).direction = Vector3.down;
								if (((Bounds)(ref val4)).IntersectRay(val5) && (((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)
				{
					if (num >= num2)
					{
						break;
					}
					bool flag2 = false;
					Vector3 val6 = ((Component)item).transform.position + 5f * ((Component)item).transform.forward;
					foreach (Vector3 item2 in list2)
					{
						if (Vector3.Distance(val6, item2) < 4f)
						{
							flag2 = true;
							break;
						}
					}
					if (flag2)
					{
						continue;
					}
					list2.Add(val6);
					GameObject gameObject2 = ((Component)((Component)((Component)item).GetComponentInChildren<SpawnSyncedObject>(true)).transform.parent).gameObject;
					GameObject val7 = Object.Instantiate<GameObject>(MimicPrefab, ((Component)item).transform);
					val7.transform.position = gameObject2.transform.position;
					MimicDoor component = val7.GetComponent<MimicDoor>();
					component.scanNode.creatureScanID = MimicCreatureID;
					AudioSource[] componentsInChildren = val7.GetComponentsInChildren<AudioSource>(true);
					foreach (AudioSource val8 in componentsInChildren)
					{
						val8.volume = MimicVolume / 100f;
						val8.outputAudioMixerGroup = StartOfRound.Instance.ship3DAudio.outputAudioMixerGroup;
					}
					if (SpawnRates[5] == 9753 && num == 0)
					{
						val7.transform.position = new Vector3(-7f, 0f, -10f);
					}
					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[] array6 = Physics.OverlapBox(center, ((Bounds)(ref bounds)).extents, Quaternion.identity);
					foreach (Collider val9 in array6)
					{
						if (((Object)((Component)val9).gameObject).name.Contains("Shelf"))
						{
							((Component)val9).gameObject.SetActive(false);
						}
					}
					Light componentInChildren = gameObject2.GetComponentInChildren<Light>(true);
					((Component)componentInChildren).transform.parent.SetParent(val7.transform);
					MeshRenderer[] componentsInChildren2 = val7.GetComponentsInChildren<MeshRenderer>();
					MeshRenderer[] array7 = componentsInChildren2;
					foreach (MeshRenderer val10 in array7)
					{
						Material[] materials = ((Renderer)val10).materials;
						foreach (Material val11 in materials)
						{
							val11.shader = ((Renderer)gameObject3.GetComponentInChildren<MeshRenderer>(true)).material.shader;
							val11.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)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.490566f, 0.1226415f, 0.1302275f);
							((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(0.4339623f, 0.1043965f, 0.1150277f);
							componentInChildren.colorTemperature = 1250f;
						}
						else
						{
							((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.5f, 0.1580188f, 0.1657038f);
							((Renderer)val7.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)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.489f, 0.2415526f, 0.1479868f);
							((Renderer)val7.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_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)MimicNetworker.Instance == (Object)null)
				{
					return;
				}
				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 > 8)
					{
						MimicNetworker.Instance.MimicAddAnger(1, component.mimicIndex);
					}
				}
			}
		}

		[HarmonyPatch(typeof(LockPicker))]
		internal class LockPickerPatch
		{
			private static FieldInfo RayHit = typeof(LockPicker).GetField("hit", BindingFlags.Instance | BindingFlags.NonPublic);

			[HarmonyPatch("ItemActivate")]
			[HarmonyPostfix]
			private static void ItemActivatePatch(LockPicker __instance, bool used, bool buttonDown = true)
			{
				//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_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)MimicNetworker.Instance == (Object)null)
				{
					return;
				}
				RaycastHit val = (RaycastHit)RayHit.GetValue(__instance);
				if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null) && !((object)(RaycastHit)(ref val)).Equals((object)default(RaycastHit)) && !((Object)(object)((RaycastHit)(ref val)).transform.parent == (Object)null))
				{
					Transform parent = ((RaycastHit)(ref val)).transform.parent;
					if (((Object)parent).name.StartsWith("MimicDoor"))
					{
						MimicNetworker.Instance.MimicLockPick(__instance, ((Component)parent).GetComponent<MimicDoor>().mimicIndex);
					}
				}
			}
		}

		private const string modGUID = "x753.Mimics";

		private const string modName = "Mimics";

		private const string modVersion = "2.3.2";

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

		private static Mimics Instance;

		public static GameObject MimicPrefab;

		public static GameObject MimicNetworkerPrefab;

		public static TerminalNode MimicFile;

		public static int MimicCreatureID;

		public static int[] SpawnRates;

		public static bool MimicPerfection;

		public static bool EasyMode;

		public static bool ColorBlindMode;

		public static float MimicVolume;

		public static bool DynamicSpawnRate;

		private void Awake()
		{
			AssetBundle val = AssetBundle.LoadFromMemory(Resources.mimicdoor);
			MimicPrefab = val.LoadAsset<GameObject>("Assets/MimicDoor.prefab");
			MimicNetworkerPrefab = val.LoadAsset<GameObject>("Assets/MimicNetworker.prefab");
			MimicFile = val.LoadAsset<TerminalNode>("Assets/MimicFile.asset");
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Mimics is loaded!");
			SpawnRates = new int[6]
			{
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Zero Mimics", 23, "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", 0, "Weight of four mimics spawning").Value,
				((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Maximum Mimics", 0, "Weight of maximum mimics spawning").Value
			};
			DynamicSpawnRate = ((BaseUnityPlugin)this).Config.Bind<bool>("Spawn Rate", "Dynamic Spawn Rate", true, "Increases mimic spawn rate based on dungeon size and the number of instances of the real thing.").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.Bind<int>("Spawn Rate", "Five Mimics", 0, "This is an old setting, ignore it.");
			((BaseUnityPlugin)this).Config.Remove(((BaseUnityPlugin)this).Config["Spawn Rate", "Five Mimics"].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;

		public static NetworkVariable<int> SpawnWeight0 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<int> SpawnWeight1 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<int> SpawnWeight2 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<int> SpawnWeight3 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<int> SpawnWeight4 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<int> SpawnWeightMax = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static NetworkVariable<bool> SpawnRateDynamic = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

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

		public void MimicLockPick(LockPicker lockPicker, int mimicIndex, bool ownerOnly = false)
		{
			int playerId = (int)((GrabbableObject)lockPicker).playerHeldBy.playerClientId;
			if (((NetworkBehaviour)this).IsOwner)
			{
				Instance.MimicLockPickClientRpc(playerId, mimicIndex);
			}
			else if (!ownerOnly)
			{
				Instance.MimicLockPickServerRpc(playerId, mimicIndex);
			}
		}

		[ClientRpc]
		public void MimicLockPickClientRpc(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(3716888238u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3716888238u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					((MonoBehaviour)this).StartCoroutine(MimicDoor.allMimics[mimicIndex].MimicLockPick(playerId));
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void MimicLockPickServerRpc(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(1897916243u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, playerId);
					BytePacker.WriteValueBitPacked(val2, mimicIndex);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1897916243u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					Instance.MimicLockPickClientRpc(playerId, mimicIndex);
				}
			}
		}

		protected override void __initializeVariables()
		{
			if (SpawnWeight0 == null)
			{
				throw new Exception("MimicNetworker.SpawnWeight0 cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeight0).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight0, "SpawnWeight0");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight0);
			if (SpawnWeight1 == null)
			{
				throw new Exception("MimicNetworker.SpawnWeight1 cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeight1).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight1, "SpawnWeight1");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight1);
			if (SpawnWeight2 == null)
			{
				throw new Exception("MimicNetworker.SpawnWeight2 cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeight2).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight2, "SpawnWeight2");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight2);
			if (SpawnWeight3 == null)
			{
				throw new Exception("MimicNetworker.SpawnWeight3 cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeight3).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight3, "SpawnWeight3");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight3);
			if (SpawnWeight4 == null)
			{
				throw new Exception("MimicNetworker.SpawnWeight4 cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeight4).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight4, "SpawnWeight4");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight4);
			if (SpawnWeightMax == null)
			{
				throw new Exception("MimicNetworker.SpawnWeightMax cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnWeightMax).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeightMax, "SpawnWeightMax");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeightMax);
			if (SpawnRateDynamic == null)
			{
				throw new Exception("MimicNetworker.SpawnRateDynamic cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)SpawnRateDynamic).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnRateDynamic, "SpawnRateDynamic");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnRateDynamic);
			((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
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			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));
			NetworkManager.__rpc_func_table.Add(3716888238u, new RpcReceiveHandler(__rpc_handler_3716888238));
			NetworkManager.__rpc_func_table.Add(1897916243u, new RpcReceiveHandler(__rpc_handler_1897916243));
		}

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

		private static void __rpc_handler_3716888238(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).MimicLockPickClientRpc(playerId, mimicIndex);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1897916243(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).MimicLockPickServerRpc(playerId, 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 ScanNodeProperties scanNode;

		public int anger;

		public bool angering;

		public int sprayCount;

		private bool attacking;

		public static List<MimicDoor> allMimics;

		public int mimicIndex;

		private static MethodInfo RetractClaws = typeof(LockPicker).GetMethod("RetractClaws", BindingFlags.Instance | BindingFlags.NonPublic);

		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 MimicLockPick(int playerId)
		{
			if (angering || attacking)
			{
				yield break;
			}
			LockPicker lockPicker = default(LockPicker);
			ref LockPicker reference = ref lockPicker;
			GrabbableObject currentlyHeldObjectServer = StartOfRound.Instance.allPlayerScripts[playerId].currentlyHeldObjectServer;
			reference = (LockPicker)(object)((currentlyHeldObjectServer is LockPicker) ? currentlyHeldObjectServer : null);
			if ((Object)(object)lockPicker == (Object)null)
			{
				yield break;
			}
			attacking = true;
			interactTrigger.interactable = false;
			AudioSource component = ((Component)lockPicker).GetComponent<AudioSource>();
			component.PlayOneShot(lockPicker.placeLockPickerClips[Random.Range(0, lockPicker.placeLockPickerClips.Length)]);
			lockPicker.armsAnimator.SetBool("mounted", true);
			lockPicker.armsAnimator.SetBool("picking", true);
			component.Play();
			component.pitch = Random.Range(0.94f, 1.06f);
			lockPicker.isOnDoor = true;
			lockPicker.isPickingLock = true;
			((GrabbableObject)lockPicker).grabbable = false;
			if (((NetworkBehaviour)lockPicker).IsOwner)
			{
				((GrabbableObject)lockPicker).playerHeldBy.DiscardHeldObject(true, ((NetworkBehaviour)MimicNetworker.Instance).NetworkObject, ((Component)this).transform.position + ((Component)this).transform.up * 1.5f - ((Component)this).transform.forward * 1.15f, true);
			}
			float startTime = Time.timeSinceLevelLoad;
			yield return (object)new WaitUntil((Func<bool>)(() => !((GrabbableObject)lockPicker).isHeld || Time.timeSinceLevelLoad - startTime > 10f));
			((Component)lockPicker).transform.localEulerAngles = new Vector3(((Component)this).transform.eulerAngles.x, ((Component)this).transform.eulerAngles.y + 90f, ((Component)this).transform.eulerAngles.z);
			yield return (object)new WaitForSeconds(5f);
			RetractClaws.Invoke(lockPicker, null);
			((Component)lockPicker).transform.SetParent((Transform)null);
			((GrabbableObject)lockPicker).startFallingPosition = ((Component)lockPicker).transform.position;
			((GrabbableObject)lockPicker).FallToGround(false);
			((GrabbableObject)lockPicker).grabbable = true;
			yield return (object)new WaitForSeconds(1f);
			anger = 3;
			attacking = false;
			interactTrigger.interactable = false;
			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);
			}
			else
			{
				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;

		bool IHittable.Hit(int force, Vector3 hitDirection, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
		{
			MimicNetworker.Instance.MimicAddAnger(force, mimic.mimicIndex);
			return true;
		}
	}
	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);
				}
			}
		}
	}
}

plugins/MoreBlood.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.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using MoreBlood.Config;
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("MoreBlood")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MoreBlood")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("d1f1321d-30a3-4600-9bf8-1e69fe1abf8c")]
[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 MoreBlood
{
	[BepInPlugin("FlipMods.MoreBlood", "MoreBlood", "1.0.2")]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		private Harmony _harmony;

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

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

		public const string PLUGIN_NAME = "MoreBlood";

		public const string PLUGIN_VERSION = "1.0.2";
	}
}
namespace MoreBlood.Patches
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class MoreBloodPatcher
	{
		private static int bloodCount;

		[HarmonyPatch("DropBlood")]
		[HarmonyPostfix]
		public static void MoreBlood(PlayerControllerB __instance, Vector3 direction = default(Vector3), bool leaveBlood = true, bool leaveFootprint = false)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			bloodCount++;
			if (bloodCount < ConfigSettings.numBloodPools.Value)
			{
				__instance.DropBlood(direction, leaveBlood, leaveFootprint);
			}
			else
			{
				bloodCount = 0;
			}
		}

		[HarmonyPatch("RandomizeBloodRotationAndScale")]
		[HarmonyPostfix]
		public static void RandomizeBloodScale(ref Transform blood, PlayerControllerB __instance)
		{
			//IL_0004: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			Transform obj = blood;
			obj.localScale *= ConfigSettings.bloodScale.Value;
			blood.position += new Vector3((float)Random.Range(-1, 1) * ConfigSettings.bloodScale.Value, 0.55f, (float)Random.Range(-1, 1) * ConfigSettings.bloodScale.Value);
		}
	}
}
namespace MoreBlood.Config
{
	public static class ConfigSettings
	{
		public static ConfigEntry<float> bloodScale;

		public static ConfigEntry<int> numBloodPools;

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			bloodScale = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("MoreBlood", "BloodScale", 4f, "The size of the blood pools");
			numBloodPools = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("MoreBlood", "NumberOfBloodPools", 4, "Max number of blood pools spread around the blood source.");
		}
	}
}

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.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MoreCompany.Cosmetics;
using MoreCompany.Utils;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
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: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MoreCompany")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright © NotNotSwipez 2023")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MoreCompany")]
[assembly: AssemblyTitle("MoreCompany")]
[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 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];
				if ((Object)(object)val != (Object)null)
				{
					AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource;
					if (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(' '));
				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(ref 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(ref chatMessage);
				}
				else if (chatMessage.StartsWith("[morecompanycosmetics]"))
				{
					return false;
				}
			}
			else if (chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				HandleDataMessage(ref chatMessage);
			}
			return true;
		}

		private static void HandleDataMessage(ref string chatMessage)
		{
			//IL_015a: 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)
			if (ignoreSample)
			{
				return;
			}
			chatMessage = chatMessage.Replace("[morecompanycosmetics]", "");
			string[] array = chatMessage.Split(';');
			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(ref ForestGiantAI __instance)
		{
			if (__instance.playerStealthMeters.Length != MainClass.newPlayerCount)
			{
				Array.Resize(ref __instance.playerStealthMeters, MainClass.newPlayerCount);
				for (int i = 0; i < MainClass.newPlayerCount; i++)
				{
					__instance.playerStealthMeters[i] = 0f;
				}
			}
		}
	}
	[HarmonyPatch(typeof(BlobAI), "Start")]
	public static class BlobAIStartPatch
	{
		public static void Postfix(ref BlobAI __instance)
		{
			Collider[] value = (Collider[])(object)new Collider[MainClass.newPlayerCount];
			ReflectionUtils.SetFieldValue(__instance, "ragdollColliders", value);
		}
	}
	[HarmonyPatch(typeof(CrawlerAI), "Start")]
	public static class CrawlerAIStartPatch
	{
		public static void Postfix(ref CrawlerAI __instance)
		{
			Collider[] value = (Collider[])(object)new Collider[MainClass.newPlayerCount];
			ReflectionUtils.SetFieldValue(__instance, "nearPlayerColliders", value);
		}
	}
	[HarmonyPatch(typeof(SpringManAI), "Update")]
	public static class SpringManAIUpdatePatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "call static float UnityEngine.Vector3::Distance(UnityEngine.Vector3 a, UnityEngine.Vector3 b)")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(SpringManAI), "DoAIInterval")]
	public static class SpringManAIIntervalPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "call void EnemyAI::SwitchToBehaviourState(int stateIndex)")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(EnemyAI), "GetClosestPlayer")]
	public static class GetClosestPlayerPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					flag = true;
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(EnemyAI), "GetAllPlayersInLineOfSight")]
	public static class GetAllPlayersInLineOfSightPatch
	{
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					flag = true;
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")]
	public static class DressGirlHauntPatch
	{
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			foreach (CodeInstruction instruction in instructions)
			{
				if (((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			return list.AsEnumerable();
		}
	}
	[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 List<TMP_InputField> inputFields = new List<TMP_InputField>();

		public static void Postfix(MenuManager __instance)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				MainClass.ReadSettingsFromFile();
				GameObject gameObject = ((Component)((Component)__instance).transform.parent).gameObject;
				Sprite 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));
				Transform val = gameObject.transform.Find("MenuContainer/MainButtons/HeaderImage");
				if ((Object)(object)val != (Object)null)
				{
					((Component)val).gameObject.GetComponent<Image>().sprite = sprite;
				}
				Transform val2 = gameObject.transform.Find("MenuContainer/LoadingScreen");
				if ((Object)(object)val2 != (Object)null)
				{
					val2.localScale = new Vector3(1.02f, 1.06f, 1.02f);
					Transform val3 = val2.Find("Image");
					if ((Object)(object)val3 != (Object)null)
					{
						((Component)val3).GetComponent<Image>().sprite = sprite;
					}
				}
				CosmeticRegistry.SpawnCosmeticGUI();
				LANMenu.InitializeMenu();
				inputFields.Clear();
				Transform val4 = gameObject.transform.Find("MenuContainer/LobbyHostSettings/HostSettingsContainer/LobbyHostOptions");
				if ((Object)(object)val4 != (Object)null)
				{
					CreateCrewCountInput(val4.Find(GameNetworkManager.Instance.disableSteam ? "LANOptions" : "OptionsNormal"));
				}
				Transform val5 = gameObject.transform.Find("MenuContainer/LobbyJoinSettings/JoinSettingsContainer/LobbyJoinOptions");
				if ((Object)(object)val5 != (Object)null)
				{
					CreateCrewCountInput(val5.Find("LANOptions"));
				}
			}
			catch (Exception ex)
			{
				MainClass.StaticLogger.LogError((object)ex);
			}
		}

		private static void CreateCrewCountInput(Transform parent)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(MainClass.crewCountUI, parent);
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).localPosition = new Vector3(96.9f, -70f, -6.7f);
			TMP_InputField inputField = ((Component)val.transform.Find("InputField (TMP)")).GetComponent<TMP_InputField>();
			inputField.characterLimit = 3;
			inputField.text = MainClass.newPlayerCount.ToString();
			inputFields.Add(inputField);
			((UnityEvent<string>)(object)inputField.onValueChanged).AddListener((UnityAction<string>)delegate(string s)
			{
				if (!(inputField.text == MainClass.newPlayerCount.ToString()))
				{
					if (int.TryParse(s, out var result))
					{
						MainClass.newPlayerCount = Mathf.Clamp(result, MainClass.minPlayerCount, MainClass.maxPlayerCount);
						foreach (TMP_InputField inputField2 in inputFields)
						{
							inputField2.text = MainClass.newPlayerCount.ToString();
						}
						MainClass.SaveSettingsToFile();
						MainClass.StaticLogger.LogInfo((object)$"Changed Crew Count: {MainClass.newPlayerCount}");
					}
					else if (s.Length != 0)
					{
						foreach (TMP_InputField inputField3 in inputFields)
						{
							inputField3.text = MainClass.newPlayerCount.ToString();
							inputField3.caretPosition = 1;
						}
					}
				}
			});
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "AddUserToPlayerList")]
	public static class AddUserPlayerListPatch
	{
		private 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()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "NonHostPlayerSlotsEnabled")]
	public static class QuickMenuDisplayPatch
	{
		public static bool Prefix(ref bool __result)
		{
			__result = false;
			for (int i = 1; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[i];
				if (val.isPlayerControlled || val.isPlayerDead)
				{
					__result = true;
					break;
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "Start")]
	public static class QuickmenuVisualInjectPatch
	{
		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_028c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Expected O, but got Unknown
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: 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 ((Object)(object)StartOfRound.Instance.localPlayerController != (Object)null && 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>();
				((UnityEvent)component4.onClick).AddListener((UnityAction)delegate
				{
					//IL_001d: Unknown result type (might be due to invalid IL or missing references)
					if (!GameNetworkManager.Instance.disableSteam)
					{
						SteamFriends.OpenUserOverlay(SteamId.op_Implicit(playerScript.playerSteamId), "steamid");
					}
				});
			}
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "ConfirmKickUserFromServer")]
	public static class KickPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "ldfld int QuickMenuManager::playerObjToKick")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.3 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[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), "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 class LANMenu : MonoBehaviour
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__0_0;

			internal void <InitializeMenu>b__0_0()
			{
				TextMeshProUGUI component = GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings/JoinSettingsContainer/PrivatePublicDescription").GetComponent<TextMeshProUGUI>();
				if ((Object)(object)component != (Object)null)
				{
					((TMP_Text)component).text = "The mod will attempt to auto-detect the crew size however you can manually specify it to reduce chance of failure.";
				}
				GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings").gameObject.SetActive(true);
			}
		}

		public static void InitializeMenu()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			CreateUI();
			GameObject val = GameObject.Find("Canvas/MenuContainer/MainButtons/StartLAN");
			if (!((Object)(object)val != (Object)null))
			{
				return;
			}
			MainClass.StaticLogger.LogInfo((object)"LANMenu startLAN Patched");
			val.GetComponent<Button>().onClick = new ButtonClickedEvent();
			ButtonClickedEvent onClick = val.GetComponent<Button>().onClick;
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				UnityAction val2 = delegate
				{
					TextMeshProUGUI component = GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings/JoinSettingsContainer/PrivatePublicDescription").GetComponent<TextMeshProUGUI>();
					if ((Object)(object)component != (Object)null)
					{
						((TMP_Text)component).text = "The mod will attempt to auto-detect the crew size however you can manually specify it to reduce chance of failure.";
					}
					GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings").gameObject.SetActive(true);
				};
				<>c.<>9__0_0 = val2;
				obj = (object)val2;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
		}

		private static GameObject CreateUI()
		{
			//IL_0066: 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_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Expected O, but got Unknown
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Expected O, but got Unknown
			if ((Object)(object)GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings") != (Object)null)
			{
				return null;
			}
			GameObject val = GameObject.Find("Canvas/MenuContainer");
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			GameObject val2 = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings");
			if ((Object)(object)val2 == (Object)null)
			{
				return null;
			}
			GameObject val3 = Object.Instantiate<GameObject>(val2, val2.transform.position, val2.transform.rotation, val.transform);
			((Object)val3).name = "LobbyJoinSettings";
			Transform val4 = val3.transform.Find("HostSettingsContainer");
			if ((Object)(object)val4 != (Object)null)
			{
				((Object)val4).name = "JoinSettingsContainer";
				((Object)((Component)val4).transform.Find("LobbyHostOptions")).name = "LobbyJoinOptions";
				Object.Destroy((Object)(object)((Component)val3.transform.Find("ChallengeLeaderboard")).gameObject);
				Object.Destroy((Object)(object)((Component)val3.transform.Find("FilesPanel")).gameObject);
				Object.Destroy((Object)(object)((Component)((Component)val4).transform.Find("LobbyJoinOptions/OptionsNormal")).gameObject);
				Object.Destroy((Object)(object)((Component)((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/AllowRemote")).gameObject);
				Object.Destroy((Object)(object)((Component)((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/Local")).gameObject);
				Transform val5 = ((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/Header");
				if ((Object)(object)val5 != (Object)null)
				{
					((TMP_Text)((Component)val5).GetComponent<TextMeshProUGUI>()).text = "Join LAN Server:";
				}
				Transform val6 = ((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/ServerNameField");
				if ((Object)(object)val6 != (Object)null)
				{
					((Component)val6).transform.localPosition = new Vector3(0f, 15f, -6.5f);
					((Component)val6).gameObject.SetActive(true);
				}
				TMP_InputField ip_field = ((Component)val6).GetComponent<TMP_InputField>();
				if ((Object)(object)ip_field != (Object)null)
				{
					TextMeshProUGUI ip_placeholder = ((Component)ip_field.placeholder).GetComponent<TextMeshProUGUI>();
					((TMP_Text)ip_placeholder).text = ES3.Load<string>("LANIPAddress", "LCGeneralSaveData", "127.0.0.1");
					Transform obj = ((Component)val4).transform.Find("Confirm");
					Button val7 = ((obj != null) ? ((Component)obj).GetComponent<Button>() : null);
					if ((Object)(object)val7 != (Object)null)
					{
						val7.onClick = new ButtonClickedEvent();
						((UnityEvent)val7.onClick).AddListener((UnityAction)delegate
						{
							string text = "127.0.0.1";
							text = ((!(ip_field.text != "")) ? ((TMP_Text)ip_placeholder).text : ip_field.text);
							ES3.Save<string>("LANIPAddress", text, "LCGeneralSaveData");
							GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings").gameObject.SetActive(false);
							((Component)NetworkManager.Singleton).GetComponent<UnityTransport>().ConnectionData.Address = text;
							MainClass.StaticLogger.LogInfo((object)("Listening to LAN server: " + text));
							GameObject.Find("MenuManager").GetComponent<MenuManager>().StartAClient();
						});
					}
				}
				TextMeshProUGUI component = ((Component)((Component)val4).transform.Find("PrivatePublicDescription")).GetComponent<TextMeshProUGUI>();
				if ((Object)(object)component != (Object)null)
				{
					((TMP_Text)component).text = "The mod will attempt to auto-detect the crew size however you can manually specify it to reduce chance of failure.";
				}
				((Component)((Component)val4).transform.Find("LobbyJoinOptions/LANOptions")).gameObject.SetActive(true);
			}
			return val3;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "SetConnectionDataBeforeConnecting")]
	public static class ConnectionDataPatch
	{
		public static void Postfix(ref GameNetworkManager __instance)
		{
			if (__instance.disableSteam)
			{
				NetworkManager.Singleton.NetworkConfig.ConnectionData = Encoding.ASCII.GetBytes(__instance.gameVersionNum + "," + MainClass.newPlayerCount);
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "OnLocalClientConnectionDisapproved")]
	public static class ConnectionDisapprovedPatch
	{
		private static int crewSizeMismatch;

		private static IEnumerator delayedReconnect()
		{
			yield return (object)new WaitForSeconds(0.5f);
			GameObject.Find("MenuManager").GetComponent<MenuManager>().StartAClient();
		}

		private static void Prefix(ref GameNetworkManager __instance, ulong clientId)
		{
			crewSizeMismatch = 0;
			if (!__instance.disableSteam)
			{
				return;
			}
			try
			{
				if (!string.IsNullOrEmpty(NetworkManager.Singleton.DisconnectReason) && NetworkManager.Singleton.DisconnectReason.StartsWith("Crew size mismatch!"))
				{
					crewSizeMismatch = int.Parse(NetworkManager.Singleton.DisconnectReason.Split("Their size: ")[1].Split(". ")[0]);
				}
			}
			catch
			{
			}
		}

		private static void Postfix(ref GameNetworkManager __instance, ulong clientId)
		{
			if (__instance.disableSteam && crewSizeMismatch != 0)
			{
				MainClass.newPlayerCount = Mathf.Clamp(crewSizeMismatch, MainClass.minPlayerCount, MainClass.maxPlayerCount);
				GameObject.Find("MenuManager").GetComponent<MenuManager>().menuNotification.SetActive(false);
				Object.FindObjectOfType<MenuManager>().SetLoadingScreen(true, (RoomEnter)5, "");
				((MonoBehaviour)__instance).StartCoroutine(delayedReconnect());
				crewSizeMismatch = 0;
			}
		}
	}
	public static class PluginInformation
	{
		public const string PLUGIN_NAME = "MoreCompany";

		public const string PLUGIN_VERSION = "1.8.1";

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

		public static int minPlayerCount = 4;

		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));
			}
			StaticLogger.LogInfo((object)"Loading MoreCompany...");
			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)("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);
			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);
				}
			}
		}

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

		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 = Mathf.Clamp(int.Parse(array[0]), minPlayerCount, maxPlayerCount);
					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_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b4: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			if (instance.allPlayerObjects.Length != newPlayerCount)
			{
				StaticLogger.LogInfo((object)$"ResizePlayerCache: {newPlayerCount}");
				playerIdsAndCosmetics.Clear();
				uint num = 10000u;
				int num2 = instance.allPlayerObjects.Length;
				int num3 = newPlayerCount - num2;
				Array.Resize(ref instance.allPlayerObjects, newPlayerCount);
				Array.Resize(ref instance.allPlayerScripts, newPlayerCount);
				Array.Resize(ref instance.gameStats.allPlayerStats, newPlayerCount);
				Array.Resize(ref instance.playerSpawnPositions, newPlayerCount);
				StaticLogger.LogInfo((object)$"Resizing player cache from {num2} to {newPlayerCount} with difference of {num3}");
				if (num3 > 0)
				{
					GameObject val = instance.allPlayerObjects[3];
					for (int i = 0; i < num3; i++)
					{
						uint num4 = num + (uint)i;
						GameObject val2 = Object.Instantiate<GameObject>(val, val.transform.parent);
						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})";
						PlayerControllerB componentInChildren = val2.GetComponentInChildren<PlayerControllerB>();
						notSupposedToExistPlayers.Add(componentInChildren);
						componentInChildren.playerClientId = (ulong)(4 + i);
						componentInChildren.playerUsername = $"Player #{componentInChildren.playerClientId}";
						componentInChildren.isPlayerControlled = false;
						componentInChildren.isPlayerDead = false;
						componentInChildren.DropAllHeldItems(false, false);
						componentInChildren.TeleportPlayer(instance.notSpawnedPosition.position, false, 0f, false, true);
						UnlockableSuit.SwitchSuitForPlayer(componentInChildren, 0, false);
						instance.allPlayerObjects[num2 + i] = val2;
						instance.gameStats.allPlayerStats[num2 + i] = new PlayerStats();
						instance.allPlayerScripts[num2 + i] = componentInChildren;
						instance.playerSpawnPositions[num2 + i] = instance.playerSpawnPositions[3];
					}
				}
			}
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val3 in allPlayerScripts)
			{
				((TMP_Text)val3.usernameBillboardText).text = val3.playerUsername;
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "Start")]
	public static class PlayerControllerBStartPatch
	{
		public static void Postfix(ref PlayerControllerB __instance)
		{
			Collider[] value = (Collider[])(object)new Collider[MainClass.newPlayerCount];
			ReflectionUtils.SetFieldValue(__instance, "nearByPlayers", value);
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesServerRpc")]
	public static class SendNewPlayerValuesServerRpcPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "callvirt virtual void System.Collections.Generic.List<ulong>::Add(ulong item)")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesClientRpc")]
	public static class SendNewPlayerValuesClientRpcPatch
	{
		public static void Prefix(PlayerControllerB __instance, ref ulong[] playerSteamIds)
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Expected O, but got Unknown
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening || StartOfRound.Instance.mapScreen.radarTargets.Count == StartOfRound.Instance.allPlayerScripts.Length)
			{
				return;
			}
			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));
		}
	}
	[HarmonyPatch(typeof(HUDManager), "SyncAllPlayerLevelsServerRpc", new Type[] { })]
	public static class SyncAllPlayerLevelsPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			foreach (CodeInstruction instruction in instructions)
			{
				if (((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch]
	public static class SyncShipUnlockablesPatch
	{
		[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesServerRpc")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> ServerTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			int num = 0;
			foreach (CodeInstruction instruction in instructions)
			{
				if (num != 2)
				{
					if (!flag && ((object)instruction).ToString() == "callvirt bool Unity.Netcode.NetworkManager::get_IsHost()")
					{
						flag = true;
					}
					else if (((object)instruction).ToString().StartsWith("ldc.i4.4 NULL"))
					{
						num++;
						CodeInstruction val = new CodeInstruction(instruction);
						val.opcode = OpCodes.Ldsfld;
						val.operand = AccessTools.Field(typeof(MainClass), "newPlayerCount");
						list.Add(val);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}

		[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> ClientTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "callvirt void UnityEngine.Renderer::set_sharedMaterial(UnityEngine.Material value)")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[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 IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "call int Steamworks.Data.Lobby::get_MemberCount()")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "maxPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(SteamMatchmaking), "CreateLobbyAsync")]
	public static class LobbyThingPatch
	{
		public static void Prefix(ref int maxMembers)
		{
			MainClass.ReadSettingsFromFile();
			maxMembers = MainClass.newPlayerCount;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "ConnectionApproval")]
	public static class ConnectionApproval
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "ldfld int GameNetworkManager::connectedPlayers")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}

		private static void Postfix(ref GameNetworkManager __instance, ref ConnectionApprovalRequest request, ref ConnectionApprovalResponse response)
		{
			if (response.Approved && __instance.disableSteam)
			{
				string @string = Encoding.ASCII.GetString(request.Payload);
				string[] array = @string.Split(",");
				if (!string.IsNullOrEmpty(@string) && (array.Length < 2 || array[1] != MainClass.newPlayerCount.ToString()))
				{
					response.Reason = $"Crew size mismatch! Their size: {MainClass.newPlayerCount}. Your size: {array[1]}";
					response.Approved = false;
				}
			}
		}
	}
	public class MimicPatches
	{
		[HarmonyPatch(typeof(MaskedPlayerEnemy), "SetEnemyOutside")]
		public class MaskedPlayerEnemyOnEnablePatch
		{
			public static void Postfix(MaskedPlayerEnemy __instance)
			{
				//IL_00dc: 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)
				if (!((Object)(object)__instance.mimickingPlayer != (Object)null) || !MainClass.showCosmetics)
				{
					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(ref 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
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			foreach (CodeInstruction instruction in instructions)
			{
				if (((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(SoundManager), "Start")]
	public static class SoundManagerStartPatch
	{
		public static void Postfix(ref SoundManager __instance)
		{
			Array.Resize(ref __instance.playerVoicePitchLerpSpeed, MainClass.newPlayerCount);
			Array.Resize(ref __instance.playerVoicePitchTargets, MainClass.newPlayerCount);
			Array.Resize(ref __instance.playerVoicePitches, MainClass.newPlayerCount);
			Array.Resize(ref __instance.playerVoiceVolumes, MainClass.newPlayerCount);
			Array.Resize(ref __instance.playerVoiceMixers, MainClass.newPlayerCount);
			AudioMixerGroup val = ((IEnumerable<AudioMixerGroup>)Resources.FindObjectsOfTypeAll<AudioMixerGroup>()).FirstOrDefault((Func<AudioMixerGroup, bool>)((AudioMixerGroup x) => ((Object)x).name.Contains("Voice")));
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				__instance.playerVoicePitchLerpSpeed[i] = 3f;
				__instance.playerVoicePitchTargets[i] = 1f;
				__instance.playerVoicePitches[i] = 1f;
				__instance.playerVoiceVolumes[i] = 0.5f;
				if (!Object.op_Implicit((Object)(object)__instance.playerVoiceMixers[i]))
				{
					__instance.playerVoiceMixers[i] = val;
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "GetPlayerSpawnPosition")]
	public static class SpawnPositionClampPatch
	{
		public static void Prefix(ref StartOfRound __instance, ref int playerNum, bool simpleTeleport = false)
		{
			if (!Object.op_Implicit((Object)(object)__instance.playerSpawnPositions[playerNum]))
			{
				playerNum = __instance.playerSpawnPositions.Length - 1;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnClientConnect")]
	public static class OnClientConnectedPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			bool flag = false;
			bool flag2 = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!flag2)
				{
					if (!flag && ((object)instruction).ToString() == "callvirt virtual bool System.Collections.Generic.List<int>::Contains(int item)")
					{
						flag = true;
					}
					else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL")
					{
						flag2 = true;
						CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
						list.Add(item);
						continue;
					}
				}
				list.Add(instruction);
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	public static class LoadLobbyListAndFilterPatch
	{
		private static void Postfix()
		{
			LobbySlot[] array = Object.FindObjectsOfType<LobbySlot>();
			LobbySlot[] array2 = array;
			foreach (LobbySlot val in array2)
			{
				((TMP_Text)val.playerCount).text = $"{((Lobby)(ref val.thisLobby)).MemberCount} / {((Lobby)(ref val.thisLobby)).MaxMembers}";
			}
		}
	}
	[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"))
				{
					continue;
				}
				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"));
					if (cosmeticInstances.ContainsKey(component.cosmeticId))
					{
						MainClass.StaticLogger.LogError((object)("Duplicate cosmetic id: " + component.cosmeticId));
					}
					else
					{
						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;
		}
	}
}

plugins/MoreEmotes1.3.3.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.Bootstrap;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using MoreEmotes.Patch;
using MoreEmotes.Scripts;
using RuntimeNetcodeRPCValidator;
using TMPro;
using Tools;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Animations.Rigging;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FuckYouMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FuckYouMod")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5ecc2bf2-af12-4e83-a6f1-cf2eacbf3060")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Tools
{
	public class Ref
	{
		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 Method(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;
		}
	}
	public class D : MonoBehaviour
	{
		public static bool Debug;

		public static void L(string msg)
		{
			if (Debug)
			{
				Debug.Log((object)msg);
			}
		}

		public static void W(string msg)
		{
			if (Debug)
			{
				Debug.LogWarning((object)msg);
			}
		}
	}
}
namespace MoreEmotes
{
	[BepInPlugin("MoreEmotes", "MoreEmotes-Sligili", "1.3.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class MoreEmotesInitialization : BaseUnityPlugin
	{
		private Harmony _harmony;

		private NetcodeValidator netcodeValidator;

		private ConfigEntry<string> config_KeyWheel;

		private ConfigEntry<string> config_KeyWheel_c;

		private ConfigEntry<bool> config_InventoryCheck;

		private ConfigEntry<bool> config_UseConfigFile;

		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<string> config_KeyEmote9;

		private ConfigEntry<string> config_KeyEmote10;

		private void Awake()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"MoreEmotes loaded");
			LoadAssetBundles();
			LoadAssets();
			ConfigFile();
			SearchForIncompatibleMods();
			_harmony = new Harmony("MoreEmotes");
			_harmony.PatchAll(typeof(EmotePatch));
			netcodeValidator = new NetcodeValidator("MoreEmotes");
			netcodeValidator.PatchAll();
			netcodeValidator.BindToPreExistingObjectByBehaviour<SignEmoteText, PlayerControllerB>();
			netcodeValidator.BindToPreExistingObjectByBehaviour<SyncAnimatorToOthers, PlayerControllerB>();
		}

		private void LoadAssetBundles()
		{
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animationsbundle");
			string text2 = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animatorbundle");
			try
			{
				EmotePatch.AnimationsBundle = AssetBundle.LoadFromFile(text);
				EmotePatch.AnimatorBundle = AssetBundle.LoadFromFile(text2);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Failed to load AssetBundles. Make sure \"animatorsbundle\" and \"animationsbundle\" are inside the MoreEmotes folder.\nError: " + ex.Message));
			}
		}

		private void LoadAssets()
		{
			string path = "Assets/MoreEmotes";
			EmotePatch.local = EmotePatch.AnimatorBundle.LoadAsset<RuntimeAnimatorController>(Path.Combine(path, "NEWmetarig.controller"));
			EmotePatch.others = EmotePatch.AnimatorBundle.LoadAsset<RuntimeAnimatorController>(Path.Combine(path, "NEWmetarigOtherPlayers.controller"));
			MoreEmotesEvents.ClapSounds[0] = EmotePatch.AnimationsBundle.LoadAsset<AudioClip>(Path.Combine(path, "SingleClapEmote1.wav"));
			MoreEmotesEvents.ClapSounds[1] = EmotePatch.AnimationsBundle.LoadAsset<AudioClip>(Path.Combine(path, "SingleClapEmote2.wav"));
			EmotePatch.SettingsPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/MoreEmotesPanel.prefab"));
			EmotePatch.ButtonPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/MoreEmotesButton.prefab"));
			EmotePatch.LegsPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/plegs.prefab"));
			EmotePatch.SignPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/Sign.prefab"));
			EmotePatch.SignUIPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/SignTextUI.prefab"));
			EmotePatch.WheelPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesMenu.prefab");
		}

		private void ConfigFile()
		{
			EmotePatch.ConfigFile_Keybinds = new string[32];
			config_KeyWheel = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL", "Key", "v", (ConfigDescription)null);
			EmotePatch.ConfigFile_WheelKeybind = config_KeyWheel.Value;
			config_KeyWheel_c = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL (Controller)", "Key", "leftshoulder", (ConfigDescription)null);
			EmotePatch.ConfigFile_WheelKeybind_controller = config_KeyWheel_c.Value;
			config_InventoryCheck = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "InventoryCheck", true, "Prevents some emotes from performing while holding any item/scrap");
			EmotePatch.ConfigFile_InventoryCheck = config_InventoryCheck.Value;
			config_UseConfigFile = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "ConfigFile", false, "Ignores all in-game saved settings and instead uses the config file");
			EmotePatch.UseConfigFile = config_UseConfigFile.Value;
			config_KeyEmote3 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Middle Finger", "3", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[2] = config_KeyEmote3.Value.Replace(" ", "");
			config_KeyEmote4 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "The Griddy", "6", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[5] = config_KeyEmote4.Value.Replace(" ", "");
			config_KeyEmote5 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Shy", "5", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[4] = config_KeyEmote5.Value.Replace(" ", "");
			config_KeyEmote6 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Clap", "4", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[3] = config_KeyEmote6.Value.Replace(" ", "");
			config_KeyEmote7 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Twerk", "7", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[6] = config_KeyEmote7.Value.Replace(" ", "");
			config_KeyEmote8 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Salute", "8", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[7] = config_KeyEmote8.Value.Replace(" ", "");
			config_KeyEmote9 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Prisyadka", "9", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[8] = config_KeyEmote9.Value.Replace(" ", "");
			config_KeyEmote10 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Sign", "0", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[9] = config_KeyEmote10.Value.Replace(" ", "");
		}

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

		public const string NAME = "MoreEmotes-Sligili";

		public const string VER = "1.3.3";
	}
}
namespace MoreEmotes.Patch
{
	public enum Emotes
	{
		D_Sign = 1010,
		D_Clap = 1004,
		D_Middle_Finger = 1003,
		Dance = 1,
		Point = 2,
		Middle_Finger = 3,
		Clap = 4,
		Shy = 5,
		The_Griddy = 6,
		Twerk = 7,
		Salute = 8,
		Prisyadka = 9,
		Sign = 10
	}
	public class EmotePatch
	{
		public static AssetBundle AnimationsBundle;

		public static AssetBundle AnimatorBundle;

		public static RuntimeAnimatorController local;

		public static RuntimeAnimatorController others;

		public static bool UseConfigFile;

		public static string[] ConfigFile_Keybinds;

		public static string ConfigFile_WheelKeybind;

		public static string ConfigFile_WheelKeybind_controller;

		public static bool ConfigFile_InventoryCheck;

		public static string EmoteWheelKeyboard;

		public static string EmoteWheelController;

		public static bool IncompatibleStuff;

		private static int s_currentEmoteID = 0;

		private static float s_defaultPlayerSpeed;

		private static bool[] s_wasPerformingEmote = new bool[32];

		public static bool IsEmoteWheelOpen;

		private static bool s_isPlayerFirstFrame;

		private static bool s_isFirstTimeOnMenu;

		private static bool s_isPlayerSpawning;

		public const int AlternateEmoteIDOffset = 1000;

		private static int[] s_doubleEmotesIDS = new int[2] { 3, 4 };

		public static bool LocalArmsSeparatedFromCamera;

		private static Transform s_freeArmsTarget;

		private static Transform s_lockedArmsTarget;

		private static CallbackContext emptyContext;

		public static GameObject ButtonPrefab;

		public static GameObject SettingsPrefab;

		public static GameObject LegsPrefab;

		public static GameObject SignPrefab;

		public static GameObject SignUIPrefab;

		public static GameObject WheelPrefab;

		private static GameObject s_localPlayerLevelBadge;

		private static GameObject s_localPlayerBetaBadge;

		private static Transform s_legsMesh;

		private static EmoteWheel s_selectionWheel;

		private static SignUI s_customSignInputField;

		private static SyncAnimatorToOthers s_syncAnimator;

		private static int _AlternateEmoteIDOffset => 1000;

		private static void InstantiateSettingsMenu(Transform container)
		{
			RebindButton.ConfigFile_Keybinds = ConfigFile_Keybinds;
			if (!PlayerPrefs.HasKey("InvCheck") || UseConfigFile)
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			ToggleButton.s_InventoryCheck = (UseConfigFile ? ConfigFile_InventoryCheck : (PlayerPrefs.GetInt("InvCheck") == 1));
			SetupUI.UseConfigFile = UseConfigFile;
			SetupUI.InventoryCheck = ToggleButton.s_InventoryCheck;
			GameObject gameObject = ((Component)((Component)container).transform.Find("SettingsPanel")).gameObject;
			Object.Instantiate<GameObject>(ButtonPrefab, gameObject.transform).transform.SetSiblingIndex(7);
			Object.Instantiate<GameObject>(SettingsPrefab, gameObject.transform);
			gameObject.AddComponent<SetupUI>();
		}

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

		private static void CheckWheelInput(string keybind, string controller, PlayerControllerB player)
		{
			//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_01b9: 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)
			bool flag = false;
			bool flag2 = false;
			if (Gamepad.all.Count != 0 && !controller.Equals(string.Empty))
			{
				flag = InputControlExtensions.IsPressed(((InputControl)Gamepad.current)[controller], 0f);
			}
			if (keybind != string.Empty)
			{
				flag2 = InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keybind], 0f) && !((ButtonControl)Keyboard.current[(Key)55]).wasPressedThisFrame;
			}
			bool flag3 = flag || flag2;
			if (flag3 && !IsEmoteWheelOpen && !player.isPlayerDead && !player.inTerminalMenu && !player.quickMenuManager.isMenuOpen && !player.isTypingChat && !s_customSignInputField.IsSignUIOpen)
			{
				IsEmoteWheelOpen = true;
				Cursor.visible = true;
				Cursor.lockState = (CursorLockMode)2;
				((Component)s_selectionWheel).gameObject.SetActive(IsEmoteWheelOpen);
				player.disableLookInput = true;
			}
			else
			{
				if (!IsEmoteWheelOpen || (flag3 && !player.quickMenuManager.isMenuOpen && !player.isTypingChat && !s_customSignInputField.IsSignUIOpen))
				{
					return;
				}
				int selectedEmoteID = s_selectionWheel.SelectedEmoteID;
				if (!player.quickMenuManager.isMenuOpen && !s_customSignInputField.IsSignUIOpen)
				{
					Cursor.visible = false;
					Cursor.lockState = (CursorLockMode)1;
				}
				if (!player.isPlayerDead && !player.quickMenuManager.isMenuOpen)
				{
					if (selectedEmoteID <= 3 || selectedEmoteID == 6 || !ConfigFile_InventoryCheck)
					{
						player.PerformEmote(emptyContext, selectedEmoteID);
					}
					else if (!player.isHoldingObject)
					{
						player.PerformEmote(emptyContext, selectedEmoteID);
					}
				}
				if (!s_customSignInputField.IsSignUIOpen)
				{
					player.disableLookInput = false;
				}
				IsEmoteWheelOpen = false;
				((Component)s_selectionWheel).gameObject.SetActive(IsEmoteWheelOpen);
			}
		}

		private static void OnFirstLocalPlayerFrameWithNewAnimator(PlayerControllerB player)
		{
			s_isPlayerFirstFrame = false;
			TurnControllerIntoAnOverrideController(player.playerBodyAnimator.runtimeAnimatorController);
			s_syncAnimator = ((Component)player).GetComponent<SyncAnimatorToOthers>();
			s_customSignInputField.Player = player;
			s_freeArmsTarget = Object.Instantiate<Transform>(player.localArmsRotationTarget, player.localArmsRotationTarget.parent.parent);
			s_lockedArmsTarget = player.localArmsRotationTarget;
			Transform val = ((Component)player).transform.Find("ScavengerModel").Find("metarig").Find("spine")
				.Find("spine.001")
				.Find("spine.002")
				.Find("spine.003");
			s_localPlayerLevelBadge = ((Component)val.Find("LevelSticker")).gameObject;
			s_localPlayerBetaBadge = ((Component)val.Find("BetaBadge")).gameObject;
			player.SpawnPlayerAnimation();
		}

		private static void SpawnSign(PlayerControllerB player)
		{
			//IL_005e: 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)
			GameObject val = Object.Instantiate<GameObject>(SignPrefab, ((Component)((Component)((Component)player).transform.Find("ScavengerModel")).transform.Find("metarig")).transform);
			val.transform.SetSiblingIndex(6);
			((Object)val).name = "Sign";
			val.transform.localPosition = new Vector3(0.029f, -0.45f, 1.3217f);
			val.transform.localRotation = Quaternion.Euler(65.556f, 180f, 180f);
		}

		private static void SpawnLegs(PlayerControllerB player)
		{
			//IL_00b4: 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)
			GameObject val = Object.Instantiate<GameObject>(LegsPrefab, ((Component)((Component)player.playerBodyAnimator).transform.parent).transform);
			s_legsMesh = val.transform.Find("Mesh");
			((Component)s_legsMesh).transform.parent = ((Component)player.playerBodyAnimator).transform.parent;
			((Object)s_legsMesh).name = "LEGS";
			GameObject gameObject = ((Component)val.transform.Find("Armature")).gameObject;
			gameObject.transform.parent = ((Component)player.playerBodyAnimator).transform;
			((Object)gameObject).name = "FistPersonLegs";
			gameObject.transform.position = new Vector3(0f, 0.197f, 0f);
			gameObject.transform.localScale = new Vector3(13.99568f, 13.99568f, 13.99568f);
			Object.Destroy((Object)(object)val);
		}

		private static void ResetIKWeights(PlayerControllerB player)
		{
			Transform val = ((Component)player.playerBodyAnimator).transform.Find("Rig 1");
			ChainIKConstraint component = ((Component)val.Find("RightArm")).GetComponent<ChainIKConstraint>();
			ChainIKConstraint component2 = ((Component)val.Find("LeftArm")).GetComponent<ChainIKConstraint>();
			TwoBoneIKConstraint component3 = ((Component)val.Find("RightLeg")).GetComponent<TwoBoneIKConstraint>();
			TwoBoneIKConstraint component4 = ((Component)val.Find("LeftLeg")).GetComponent<TwoBoneIKConstraint>();
			Transform val2 = ((Component)player.playerBodyAnimator).transform.Find("ScavengerModelArmsOnly").Find("metarig").Find("spine.003")
				.Find("RigArms");
			ChainIKConstraint component5 = ((Component)val2.Find("RightArm")).GetComponent<ChainIKConstraint>();
			ChainIKConstraint component6 = ((Component)val2.Find("LeftArm")).GetComponent<ChainIKConstraint>();
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component2).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component).weight = 1f;
			((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)component4).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component5).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component6).weight = 1f;
		}

		private static void UpdateLegsMaterial(PlayerControllerB player)
		{
			((Renderer)((Component)s_legsMesh).GetComponent<SkinnedMeshRenderer>()).material = ((Renderer)((Component)((Component)((Component)player.playerBodyAnimator).transform.parent).transform.Find("LOD1")).gameObject.GetComponent<SkinnedMeshRenderer>()).material;
		}

		private static void TogglePlayerBadges(bool enabled)
		{
			if ((Object)(object)s_localPlayerBetaBadge != (Object)null)
			{
				((Renderer)s_localPlayerBetaBadge.GetComponent<MeshRenderer>()).enabled = enabled;
			}
			if ((Object)(object)s_localPlayerLevelBadge != (Object)null)
			{
				((Renderer)s_localPlayerLevelBadge.GetComponent<MeshRenderer>()).enabled = enabled;
			}
			else
			{
				Debug.LogError((object)"[MoreEmotes-Sligili] Couldn't find the level badge");
			}
		}

		private static bool CheckIfTooManyEmotesIsPlaying(PlayerControllerB player)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			Animator playerBodyAnimator = player.playerBodyAnimator;
			AnimatorStateInfo currentAnimatorStateInfo = playerBodyAnimator.GetCurrentAnimatorStateInfo(1);
			return ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("Dance1") && player.performingEmote && GetAnimatorEmoteClipName(playerBodyAnimator) != "Dance1";
		}

		private static string GetAnimatorEmoteClipName(Animator animator)
		{
			AnimatorClipInfo[] currentAnimatorClipInfo = animator.GetCurrentAnimatorClipInfo(1);
			return ((Object)((AnimatorClipInfo)(ref currentAnimatorClipInfo[0])).clip).name;
		}

		private static void TurnControllerIntoAnOverrideController(RuntimeAnimatorController controller)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			if (!(controller is AnimatorOverrideController))
			{
				controller = (RuntimeAnimatorController)new AnimatorOverrideController(controller);
			}
		}

		public static void UpdateWheelKeybinds()
		{
			if (UseConfigFile)
			{
				EmoteWheelKeyboard = ConfigFile_WheelKeybind;
				EmoteWheelController = ConfigFile_WheelKeybind_controller;
				return;
			}
			if (!PlayerPrefs.HasKey("Emote_Wheel_c"))
			{
				PlayerPrefs.SetString("Emote_Wheel_c", ConfigFile_WheelKeybind_controller);
			}
			EmoteWheelController = PlayerPrefs.GetString("Emote_Wheel_c");
			if (!PlayerPrefs.HasKey("Emote_Wheel"))
			{
				PlayerPrefs.SetString("Emote_Wheel", ConfigFile_WheelKeybind);
			}
			EmoteWheelKeyboard = PlayerPrefs.GetString("Emote_Wheel");
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			ConfigFile_InventoryCheck = PlayerPrefs.GetInt("InvCheck") == 1;
		}

		[HarmonyPatch(typeof(MenuManager), "Start")]
		[HarmonyPostfix]
		private static void MenuStart(MenuManager __instance)
		{
			D.Debug = true;
			try
			{
				InstantiateSettingsMenu(((Component)((Component)__instance).transform.parent).transform.Find("MenuContainer"));
			}
			catch (Exception ex)
			{
				if (!s_isFirstTimeOnMenu)
				{
					s_isFirstTimeOnMenu = true;
				}
				else
				{
					Debug.LogError((object)(ex.Message + "\n[MoreEmotes-Sligili] Couldn't find MenuContainer"));
				}
			}
		}

		[HarmonyPatch(typeof(RoundManager), "Awake")]
		[HarmonyPostfix]
		private static void AwakePost(RoundManager __instance)
		{
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			UpdateWheelKeybinds();
			GameObject gameObject = ((Component)((Component)GameObject.Find("Systems").gameObject.transform.Find("UI")).gameObject.transform.Find("Canvas")).gameObject;
			InstantiateSettingsMenu(gameObject.transform.Find("QuickMenu"));
			s_selectionWheel = Object.Instantiate<GameObject>(WheelPrefab, gameObject.transform).AddComponent<EmoteWheel>();
			s_customSignInputField = Object.Instantiate<GameObject>(SignUIPrefab, gameObject.transform).AddComponent<SignUI>();
			EmoteWheel.Keybinds = new string[ConfigFile_Keybinds.Length + 1];
			EmoteWheel.Keybinds = ConfigFile_Keybinds;
			s_isPlayerFirstFrame = true;
		}

		[HarmonyPatch(typeof(HUDManager), "EnableChat_performed")]
		[HarmonyPrefix]
		private static bool OpenChatPrefix()
		{
			if (s_customSignInputField.IsSignUIOpen)
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(HUDManager), "SubmitChat_performed")]
		[HarmonyPrefix]
		private static bool SubmitChatPrefix()
		{
			if (s_customSignInputField.IsSignUIOpen)
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPostfix]
		private static void StartPostfix(PlayerControllerB __instance)
		{
			((Component)((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel")).transform.Find("metarig")).gameObject.AddComponent<MoreEmotesEvents>().Player = __instance;
			s_defaultPlayerSpeed = __instance.movementSpeed;
			((Component)__instance).gameObject.AddComponent<CustomAnimationObjects>();
			SpawnSign(__instance);
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(PlayerControllerB __instance)
		{
			if (!__instance.isPlayerControlled || !((NetworkBehaviour)__instance).IsOwner)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = others;
				TurnControllerIntoAnOverrideController(__instance.playerBodyAnimator.runtimeAnimatorController);
				return;
			}
			if ((Object)(object)__instance.playerBodyAnimator != (Object)(object)local)
			{
				if (s_isPlayerFirstFrame)
				{
					SpawnLegs(__instance);
				}
				__instance.playerBodyAnimator.runtimeAnimatorController = local;
				if (s_isPlayerFirstFrame)
				{
					OnFirstLocalPlayerFrameWithNewAnimator(__instance);
				}
				if (s_isPlayerSpawning)
				{
					__instance.SpawnPlayerAnimation();
					s_isPlayerSpawning = false;
				}
			}
			if (!IncompatibleStuff)
			{
				if ((bool)Ref.Method(__instance, "CheckConditionsForEmote") && __instance.performingEmote)
				{
					switch (s_currentEmoteID)
					{
					case 6:
						__instance.movementSpeed = s_defaultPlayerSpeed / 2f;
						break;
					case 9:
						__instance.movementSpeed = s_defaultPlayerSpeed / 3f;
						break;
					}
				}
				else
				{
					__instance.movementSpeed = s_defaultPlayerSpeed;
				}
			}
			__instance.localArmsRotationTarget = (LocalArmsSeparatedFromCamera ? (__instance.localArmsRotationTarget = s_freeArmsTarget) : (__instance.localArmsRotationTarget = s_lockedArmsTarget));
			CheckWheelInput(EmoteWheelKeyboard, EmoteWheelController, __instance);
			if (!__instance.quickMenuManager.isMenuOpen && !IsEmoteWheelOpen)
			{
				CheckEmoteInput(ConfigFile_Keybinds[2], needsEmptyHands: false, 3, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[3], needsEmptyHands: true, 4, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[4], needsEmptyHands: true, 5, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[5], needsEmptyHands: false, 6, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[6], needsEmptyHands: true, 7, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[7], needsEmptyHands: true, 8, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[8], needsEmptyHands: true, 9, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[9], needsEmptyHands: true, 10, __instance);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPrefix]
		private static void UpdatePrefix(PlayerControllerB __instance)
		{
			if (__instance.performingEmote)
			{
				s_wasPerformingEmote[__instance.playerClientId] = true;
			}
			if (!__instance.performingEmote && s_wasPerformingEmote[__instance.playerClientId])
			{
				s_wasPerformingEmote[__instance.playerClientId] = false;
				ResetIKWeights(__instance);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SpawnPlayerAnimation")]
		[HarmonyPrefix]
		private static void OnLocalPlayerSpawn(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled)
			{
				s_isPlayerSpawning = true;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "CheckConditionsForEmote")]
		[HarmonyPrefix]
		private static bool CheckConditionsPrefix(ref bool __result, PlayerControllerB __instance)
		{
			bool flag = (bool)Ref.GetInstanceField(typeof(PlayerControllerB), __instance, "isJumping");
			bool flag2 = (bool)Ref.GetInstanceField(typeof(PlayerControllerB), __instance, "isWalking");
			if (s_currentEmoteID == 6 || s_currentEmoteID == 9)
			{
				__result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && __instance.moveInputVector.x == 0f && !__instance.isSprinting && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu && !__instance.isTypingChat;
				return false;
			}
			if (s_currentEmoteID == 10 || s_currentEmoteID == 1010)
			{
				__result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && !flag2 && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "PerformEmote")]
		[HarmonyPrefix]
		private static bool PerformEmotePrefix(CallbackContext context, int emoteID, PlayerControllerB __instance)
		{
			if ((emoteID < 0 || CheckIfTooManyEmotesIsPlaying(__instance)) && emoteID > 2)
			{
				return false;
			}
			if ((!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || (((NetworkBehaviour)__instance).IsServer && !__instance.isHostPlayerObject)) && !__instance.isTestingPlayer)
			{
				return false;
			}
			if (s_customSignInputField.IsSignUIOpen && emoteID != 1010)
			{
				return false;
			}
			if (emoteID > 0 && emoteID < 3 && !IsEmoteWheelOpen && !((CallbackContext)(ref context)).performed)
			{
				return false;
			}
			int[] array = s_doubleEmotesIDS;
			foreach (int num in array)
			{
				int num2 = num + _AlternateEmoteIDOffset;
				bool flag = (UseConfigFile ? ConfigFile_InventoryCheck : (PlayerPrefs.GetInt("InvCheck") == 1));
				if (emoteID == num && s_currentEmoteID == emoteID && __instance.performingEmote && (!__instance.isHoldingObject || !flag))
				{
					if (emoteID == num)
					{
						emoteID += _AlternateEmoteIDOffset;
					}
					else
					{
						emoteID -= 1000;
					}
				}
			}
			if ((s_currentEmoteID != emoteID && emoteID < 3) || !__instance.performingEmote)
			{
				ResetIKWeights(__instance);
			}
			if (!(bool)Ref.Method(__instance, "CheckConditionsForEmote"))
			{
				return false;
			}
			if (__instance.timeSinceStartingEmote < 0.5f)
			{
				return false;
			}
			s_currentEmoteID = emoteID;
			Action action = delegate
			{
				__instance.timeSinceStartingEmote = 0f;
				__instance.playerBodyAnimator.SetInteger("emoteNumber", emoteID);
				__instance.performingEmote = true;
				__instance.StartPerformingEmoteServerRpc();
				s_syncAnimator.UpdateEmoteIDForOthers(emoteID);
				TogglePlayerBadges(enabled: false);
			};
			switch (emoteID)
			{
			case 9:
				action = (Action)Delegate.Combine(action, (Action)delegate
				{
					UpdateLegsMaterial(__instance);
				});
				break;
			case 10:
				action = (Action)Delegate.Combine(action, (Action)delegate
				{
					((Component)s_customSignInputField).gameObject.SetActive(true);
				});
				break;
			}
			action();
			return false;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "StopPerformingEmoteServerRpc")]
		[HarmonyPostfix]
		private static void StopPerformingEmoteServerPrefix(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled)
			{
				__instance.playerBodyAnimator.SetInteger("emoteNumber", 0);
			}
			TogglePlayerBadges(enabled: true);
			s_syncAnimator.UpdateEmoteIDForOthers(0);
			s_currentEmoteID = 0;
		}
	}
}
namespace MoreEmotes.Scripts
{
	public class MoreEmotesEvents : MonoBehaviour
	{
		private Animator _playerAnimator;

		private AudioSource _playerAudioSource;

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

		public PlayerControllerB Player;

		private void Start()
		{
			_playerAnimator = ((Component)this).GetComponent<Animator>();
			_playerAudioSource = Player.movementAudio;
		}

		public void PlayClapSound()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			if (Player.performingEmote)
			{
				int currentEmoteID = GetCurrentEmoteID();
				if (!((NetworkBehaviour)Player).IsOwner || !Player.isPlayerControlled || currentEmoteID == 4)
				{
					bool flag = Player.isInHangarShipRoom && Player.playersManager.hangarDoorsClosed;
					RoundManager.Instance.PlayAudibleNoise(((Component)Player).transform.position, 22f, 0.6f, 0, flag, 6);
					_playerAudioSource.pitch = Random.Range(0.59f, 0.79f);
					_playerAudioSource.PlayOneShot(ClapSounds[Random.Range(0, ClapSounds.Length)]);
				}
			}
		}

		public void PlayFootstepSound()
		{
			if (Player.performingEmote)
			{
				int currentEmoteID = GetCurrentEmoteID();
				if ((!((NetworkBehaviour)Player).IsOwner || !Player.isPlayerControlled || currentEmoteID == 6 || currentEmoteID == 8 || currentEmoteID == 9) && ((Vector2)(ref Player.moveInputVector)).sqrMagnitude == 0f)
				{
					Player.PlayFootstepLocal();
					Player.PlayFootstepServer();
				}
			}
		}

		private int GetCurrentEmoteID()
		{
			int num = _playerAnimator.GetInteger("emoteNumber");
			if (num >= 1000)
			{
				num -= 1000;
			}
			return num;
		}
	}
	public class SignEmoteText : NetworkBehaviour
	{
		private PlayerControllerB _playerInstance;

		private TextMeshPro _signModelText;

		public string Text => ((TMP_Text)_signModelText).text;

		private void Start()
		{
			_playerInstance = ((Component)this).GetComponent<PlayerControllerB>();
			_signModelText = ((Component)((Component)_playerInstance).transform.Find("ScavengerModel").Find("metarig").Find("Sign")
				.Find("Text")).GetComponent<TextMeshPro>();
		}

		public void UpdateSignText(string newText)
		{
			if (((NetworkBehaviour)_playerInstance).IsOwner && _playerInstance.isPlayerControlled)
			{
				UpdateSignTextServerRpc(newText);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void UpdateSignTextServerRpc(string newText)
		{
			UpdateSignTextClientRpc(newText);
		}

		[ClientRpc]
		private void UpdateSignTextClientRpc(string newText)
		{
			((TMP_Text)_signModelText).text = newText;
		}
	}
	public class EmoteWheel : MonoBehaviour
	{
		private RectTransform _graphics_selectedBlock;

		private RectTransform _graphics_selectionArrow;

		private Text _graphics_emoteInformation;

		private Text _graphics_pageInformation;

		private int _blocksNumber = 8;

		private int _selectedBlock = 1;

		private float _changePageCooldown = 0.1f;

		private float _selectionArrowLerpSpeed = 30f;

		private float _angle;

		private GameObject[] _pages;

		public float WheelMovementDeadzone = 3.3f;

		public float WheelMovementDeadzoneController = 0.7f;

		public static string[] Keybinds;

		private Vector2 _wheelCenter;

		private Vector2 _lastMouseCoords;

		public int SelectedPageNumber { get; private set; }

		public int SelectedEmoteID { get; private set; }

		public bool IsUsingController { get; private set; }

		private void Awake()
		{
			GetVanillaKeybinds();
			FindGraphics();
			FindPages(((Component)this).gameObject.transform.Find("FunctionalContent"));
			UpdatePageInfo();
		}

		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_0022: Unknown result type (might be due to invalid IL or missing references)
			_wheelCenter = new Vector2((float)(Screen.width / 2), (float)(Screen.height / 2));
			Mouse.current.WarpCursorPosition(_wheelCenter);
		}

		private void GetVanillaKeybinds()
		{
			PlayerInput component = GameObject.Find("PlayerSettingsObject").GetComponent<PlayerInput>();
			if ((Object)(object)component == (Object)null)
			{
				Debug.LogError((object)" MoreEmotes: PlayerSettingsObject is null");
				return;
			}
			Keybinds[0] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote1", false), 0, (DisplayStringOptions)0);
			Keybinds[1] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote2", false), 0, (DisplayStringOptions)0);
		}

		private void FindGraphics()
		{
			_graphics_selectionArrow = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("SelectionArrow")).gameObject.GetComponent<RectTransform>();
			_graphics_selectedBlock = ((Component)((Component)this).gameObject.transform.Find("SelectedEmote")).gameObject.GetComponent<RectTransform>();
			_graphics_emoteInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("EmoteInfo")).GetComponent<Text>();
			_graphics_pageInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("PageNumber")).GetComponent<Text>();
		}

		private void FindPages(Transform contentParent)
		{
			_pages = (GameObject[])(object)new GameObject[((Component)contentParent).transform.childCount];
			_graphics_pageInformation.text = "< Page " + (SelectedPageNumber + 1) + "/" + _pages.Length + " >";
			for (int i = 0; i < ((Component)contentParent).transform.childCount; i++)
			{
				_pages[i] = ((Component)((Component)contentParent).transform.GetChild(i)).gameObject;
			}
		}

		private void Update()
		{
			ControllerInput();
			if (!IsUsingController)
			{
				MouseInput();
			}
			Cursor.visible = !IsUsingController;
			UpdateSelectionArrow();
			PageSelection();
			SelectedEmoteID = _selectedBlock + Mathf.RoundToInt((float)(_blocksNumber / 4)) + _blocksNumber * SelectedPageNumber;
			UpdateEmoteInfo();
		}

		private unsafe void ControllerInput()
		{
			//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_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: 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 (Gamepad.all.Count == 0)
			{
				IsUsingController = false;
				return;
			}
			float num = ((InputControl<float>)(object)((Vector2Control)Gamepad.current.rightStick).x).ReadUnprocessedValue();
			float num2 = ((InputControl<float>)(object)((Vector2Control)Gamepad.current.rightStick).y).ReadUnprocessedValue();
			if (Mathf.Abs(num) < WheelMovementDeadzoneController && Mathf.Abs(num2) < WheelMovementDeadzoneController)
			{
				if (System.Runtime.CompilerServices.Unsafe.Read<Vector2>((void*)((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).value) != _lastMouseCoords)
				{
					IsUsingController = false;
				}
			}
			else
			{
				IsUsingController = true;
				_lastMouseCoords = System.Runtime.CompilerServices.Unsafe.Read<Vector2>((void*)((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).value);
				WheelSelection(Vector2.zero, num, num2);
			}
		}

		private void MouseInput()
		{
			//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_002b: Unknown result type (might be due to invalid IL or missing references)
			if (!(Vector2.Distance(_wheelCenter, ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue()) < WheelMovementDeadzone))
			{
				WheelSelection(_wheelCenter, ((InputControl<float>)(object)((Pointer)Mouse.current).position.x).ReadValue(), ((InputControl<float>)(object)((Pointer)Mouse.current).position.y).ReadValue());
			}
		}

		private void WheelSelection(Vector2 origin, float xAxisValue, float yAxisValue)
		{
			//IL_0002: 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_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: 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_00fd: Unknown result type (might be due to invalid IL or missing references)
			bool flag = xAxisValue > origin.x;
			bool flag2 = yAxisValue > origin.y;
			int num = ((!flag) ? (flag2 ? 2 : 3) : (flag2 ? 1 : 4));
			float num2 = (yAxisValue - origin.y) / (xAxisValue - origin.x);
			float num3 = 180 * (num - ((num <= 2) ? 1 : 2));
			_angle = Mathf.Atan(num2) * (180f / (float)Math.PI) + num3;
			if (_angle == 90f)
			{
				_angle = 270f;
			}
			else if (_angle == 270f)
			{
				_angle = 90f;
			}
			float num4 = 360 / _blocksNumber;
			_selectedBlock = Mathf.RoundToInt((_angle - num4 * 1.5f) / num4);
			((Transform)_graphics_selectedBlock).localRotation = Quaternion.Euler(((Component)this).transform.rotation.z, ((Component)this).transform.rotation.y, num4 * (float)_selectedBlock);
		}

		private void PageSelection()
		{
			UpdatePageInfo();
			if (_changePageCooldown > 0f)
			{
				_changePageCooldown -= Time.deltaTime;
				return;
			}
			int num;
			if (IsUsingController)
			{
				if (!Gamepad.current.dpad.left.isPressed && !Gamepad.current.dpad.right.isPressed)
				{
					return;
				}
				num = (Gamepad.current.dpad.left.isPressed ? 1 : (-1));
			}
			else
			{
				if (((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() == 0f)
				{
					return;
				}
				num = ((((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() > 0f) ? 1 : (-1));
			}
			GameObject[] pages = _pages;
			foreach (GameObject val in pages)
			{
				val.SetActive(false);
			}
			SelectedPageNumber = (SelectedPageNumber + num + _pages.Length) % _pages.Length;
			_pages[SelectedPageNumber].SetActive(true);
			_changePageCooldown = ((!IsUsingController) ? 0.1f : 0.3f);
		}

		private void UpdatePageInfo()
		{
			_graphics_pageInformation.text = $"<color=#fe6b02><</color> Page {SelectedPageNumber + 1}/{_pages.Length} <color=#fe6b02>></color>";
		}

		private void UpdateEmoteInfo()
		{
			string text = ((SelectedEmoteID > Keybinds.Length) ? "" : Keybinds[SelectedEmoteID - 1]);
			int num = 0;
			foreach (Emotes value in Enum.GetValues(typeof(Emotes)))
			{
				if (value >= Emotes.Dance && value < (Emotes)64)
				{
					num++;
				}
			}
			string text2 = ((SelectedEmoteID > num) ? "EMPTY" : ((Emotes)SelectedEmoteID).ToString().Replace("_", " "));
			if (SelectedEmoteID > 2 && SelectedEmoteID <= Keybinds.Length)
			{
				if (!PlayerPrefs.HasKey(text2.Replace(" ", "_")))
				{
					PlayerPrefs.SetString(text2.Replace(" ", "_"), (SelectedEmoteID > Keybinds.Length) ? "" : Keybinds[SelectedEmoteID - 1]);
				}
				else
				{
					text = PlayerPrefs.GetString(text2.Replace(" ", "_"));
				}
			}
			text = "<size=120>[" + text + "]</size>";
			_graphics_emoteInformation.text = text2 + "\n" + text.ToUpper();
		}

		private void UpdateSelectionArrow()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			float num = 360 / _blocksNumber;
			Quaternion val = Quaternion.Euler(0f, 0f, _angle - num * 2f);
			((Transform)_graphics_selectionArrow).localRotation = Quaternion.Lerp(((Transform)_graphics_selectionArrow).localRotation, val, Time.deltaTime * _selectionArrowLerpSpeed);
		}
	}
	public class RebindButton : MonoBehaviour
	{
		public static string[] ConfigFile_Keybinds;

		private string _defaultKey;

		private string _playerPrefsString;

		private Transform _waitingForInput;

		private Text _keyInfo;

		public bool IsControllerButton { get; private set; } = false;


		private void Start()
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			string text = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text;
			IsControllerButton = GetControllerFlag();
			_playerPrefsString = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text.Replace(" ", "_") + (IsControllerButton ? "_c" : "");
			_defaultKey = GetDefaultKey(text);
			FindComponents();
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener(new UnityAction(GetKey));
			if (!PlayerPrefs.HasKey(_playerPrefsString))
			{
				PlayerPrefs.SetString(_playerPrefsString, _defaultKey);
			}
			SetKeybind(PlayerPrefs.GetString(_playerPrefsString));
		}

		private string GetDefaultKey(string emoteName)
		{
			if (Enum.TryParse<Emotes>(emoteName.Replace(" ", "_"), out var result))
			{
				return ConfigFile_Keybinds[(int)(result - 1)];
			}
			return IsControllerButton ? "leftshoulder" : "V";
		}

		private bool GetControllerFlag()
		{
			Transform val = ((Component)this).gameObject.transform.Find("Description").Find("Subtext");
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			Text val2 = default(Text);
			if (((Component)val).TryGetComponent<Text>(ref val2))
			{
				return val2.text.Equals("(Controller)", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		private void FindComponents()
		{
			((Component)((Component)((Component)this).transform.parent).transform.Find("Delete")).gameObject.AddComponent<DeleteButton>();
			_keyInfo = ((Component)((Component)this).transform.Find("InputText")).GetComponent<Text>();
			_waitingForInput = ((Component)this).transform.Find("wait");
		}

		public void SetKeybind(string key)
		{
			List<string> list = new List<string> { "up", "down", "left", "right" };
			if (list.Contains(key.ToLower()) && key.Length < 5)
			{
				key = "dpad/" + key;
			}
			PlayerPrefs.SetString(_playerPrefsString, key);
			_keyInfo.text = key.ToUpper();
			((MonoBehaviour)this).StopAllCoroutines();
			((Component)_waitingForInput).gameObject.SetActive(false);
		}

		private void GetKey()
		{
			((Component)_waitingForInput).gameObject.SetActive(true);
			((MonoBehaviour)this).StartCoroutine(WaitForKey(delegate(string key)
			{
				SetKeybind(key);
			}));
		}

		private IEnumerator WaitForKey(Action<string> callback)
		{
			while (!((ButtonControl)Keyboard.current.anyKey).wasPressedThisFrame || (!((InputDevice)Gamepad.current).wasUpdatedThisFrame && !InputControlExtensions.IsActuated((InputControl)(object)Gamepad.current.leftStick, 0f) && !InputControlExtensions.IsActuated((InputControl)(object)Gamepad.current.rightStick, 0f)))
			{
				yield return (object)new WaitForEndOfFrame();
				Observable.CallOnce<InputControl>(InputSystem.onAnyButtonPress, (Action<InputControl>)delegate(InputControl ctrl)
				{
					callback(((ctrl.device == Gamepad.current && IsControllerButton) || (ctrl.device == Keyboard.current && !IsControllerButton)) ? ctrl.name : _defaultKey);
				});
			}
		}
	}
	public class DeleteButton : MonoBehaviour
	{
		private void Start()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			RebindButton _rebindButton = ((Component)((Component)((Component)this).transform.parent).transform.Find("Button")).GetComponent<RebindButton>();
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				_rebindButton.SetKeybind(string.Empty);
			});
		}
	}
	public class ToggleButton : MonoBehaviour
	{
		private Toggle _toggle;

		public static bool s_InventoryCheck;

		public string PlayerPrefsString;

		private void Start()
		{
			_toggle = ((Component)this).GetComponent<Toggle>();
			_toggle.isOn = s_InventoryCheck;
			((UnityEvent<bool>)(object)_toggle.onValueChanged).AddListener((UnityAction<bool>)SetNewValue);
			if (!PlayerPrefs.HasKey(PlayerPrefsString))
			{
				SetNewValue(s_InventoryCheck);
			}
		}

		public void SetNewValue(bool arg)
		{
			PlayerPrefs.SetInt(PlayerPrefsString, arg ? 1 : 0);
		}
	}
	public class EnableDisableButton : MonoBehaviour
	{
		public GameObject[] ToAlternateUI = (GameObject[])(object)new GameObject[1];

		private void Start()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				GameObject[] toAlternateUI = ToAlternateUI;
				foreach (GameObject val in toAlternateUI)
				{
					val.SetActive((!val.activeInHierarchy) ? true : false);
				}
			});
			if (((Object)((Component)this).gameObject).name.Equals("BackButton", StringComparison.OrdinalIgnoreCase))
			{
				ToAlternateUI[0] = ((Component)((Component)this).transform.parent).gameObject;
			}
			if (((Object)((Component)this).gameObject).name.Equals("MoreEmotesButton(Clone)", StringComparison.OrdinalIgnoreCase))
			{
				ToAlternateUI[0] = ((Component)((Component)((Component)this).transform.parent).gameObject.transform.Find("MoreEmotesPanel(Clone)")).gameObject;
			}
		}
	}
	public class SetupUI : MonoBehaviour
	{
		public static bool UseConfigFile;

		public static bool InventoryCheck;

		private void Awake()
		{
			Transform settingsUIPanel = ((Component)this).transform.Find("MoreEmotesPanel(Clone)");
			((Component)settingsUIPanel.Find("Version")).GetComponent<Text>().text = "1.3.3 - Sligili";
			SetupOpenSettingsButton();
			SetupBackButton();
			SetupRebindButtons(((Component)settingsUIPanel).transform.Find("KeybindButtons"));
			SetupRebindButtons(((Component)((Component)((Component)settingsUIPanel).transform.Find("Scroll View")).transform.Find("Viewport")).transform.Find("Content"));
			SetupInventoryCheckToggle();
			SetupUseConfigFileToggle();
			void SetupBackButton()
			{
				((Component)((Component)settingsUIPanel).transform.Find("BackButton")).gameObject.AddComponent<EnableDisableButton>();
			}
			void SetupInventoryCheckToggle()
			{
				((Component)((Component)settingsUIPanel).transform.Find("Inv")).gameObject.AddComponent<ToggleButton>().PlayerPrefsString = "InvCheck";
			}
			void SetupOpenSettingsButton()
			{
				((Component)((Component)this).transform.Find("MoreEmotesButton(Clone)")).gameObject.AddComponent<EnableDisableButton>();
			}
			static void SetupRebindButtons(Transform ButtonsParent)
			{
				Transform[] array = (Transform[])(object)new Transform[ButtonsParent.childCount];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = ButtonsParent.GetChild(i);
				}
				Transform[] array2 = array;
				foreach (Transform val in array2)
				{
					((Component)val.Find("Button")).gameObject.AddComponent<RebindButton>();
				}
			}
			void SetupUseConfigFileToggle()
			{
				((Component)((Component)settingsUIPanel).transform.Find("cfg")).gameObject.GetComponent<Toggle>().isOn = UseConfigFile;
			}
		}

		private void Update()
		{
			EmotePatch.UpdateWheelKeybinds();
		}
	}
	public class SignUI : MonoBehaviour
	{
		public PlayerControllerB Player;

		private TMP_InputField _inputField;

		private Text _charactersLeftText;

		private TMP_Text _previewText;

		private Button _submitButton;

		private Button _cancelButton;

		public bool IsSignUIOpen;

		private void Awake()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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
			FindComponents();
			((UnityEvent)_submitButton.onClick).AddListener(new UnityAction(SubmitText));
			((UnityEvent)_cancelButton.onClick).AddListener((UnityAction)delegate
			{
				Close(cancelAction: true);
			});
			((UnityEvent<string>)(object)_inputField.onValueChanged).AddListener((UnityAction<string>)delegate(string fieldText)
			{
				UpdatePreviewText(fieldText);
				UpdateCharactersLeftText();
			});
		}

		private void OnEnable()
		{
			Player.isTypingChat = true;
			IsSignUIOpen = true;
			((Selectable)_inputField).Select();
			_inputField.text = string.Empty;
			_previewText.text = "PREVIEW";
			Player.disableLookInput = true;
		}

		private void Update()
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			Cursor.visible = true;
			Cursor.lockState = (CursorLockMode)2;
			if (!Player.performingEmote)
			{
				Close(cancelAction: true);
			}
			if (((ButtonControl)Keyboard.current[(Key)2]).wasPressedThisFrame && !((ButtonControl)Keyboard.current[(Key)51]).isPressed)
			{
				SubmitText();
			}
			if (Player.quickMenuManager.isMenuOpen || EmotePatch.IsEmoteWheelOpen || InputControlExtensions.IsPressed(((InputControl)Mouse.current)["rightButton"], 0f))
			{
				Close(cancelAction: true);
			}
			if (Gamepad.all.Count != 0)
			{
				if (Gamepad.current.buttonWest.isPressed || Gamepad.current.startButton.isPressed)
				{
					SubmitText();
				}
				if (Gamepad.current.buttonEast.isPressed || Gamepad.current.selectButton.isPressed)
				{
					Close(cancelAction: true);
				}
			}
		}

		private void FindComponents()
		{
			_inputField = ((Component)((Component)this).transform.Find("InputField")).GetComponent<TMP_InputField>();
			_charactersLeftText = ((Component)((Component)this).transform.Find("CharsLeft")).GetComponent<Text>();
			_submitButton = ((Component)((Component)this).transform.Find("Submit")).GetComponent<Button>();
			_cancelButton = ((Component)((Component)this).transform.Find("Cancel")).GetComponent<Button>();
			_previewText = ((Component)((Component)((Component)this).transform.Find("Sign")).transform.Find("Text")).GetComponent<TMP_Text>();
		}

		private void UpdateCharactersLeftText()
		{
			_charactersLeftText.text = $"CHARACTERS LEFT: <color=yellow>{_inputField.characterLimit - _inputField.text.Length}</color>";
		}

		private void UpdatePreviewText(string text)
		{
			_previewText.text = text;
		}

		private void SubmitText()
		{
			//IL_007c: 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 (_inputField.text.Equals(string.Empty))
			{
				Close(cancelAction: true);
				return;
			}
			D.L("Submitted " + _inputField.text + " to server");
			((Component)Player).GetComponent<SignEmoteText>().UpdateSignText(_inputField.text);
			float num = 0.5f;
			if (Player.timeSinceStartingEmote > num)
			{
				Player.PerformEmote(default(CallbackContext), 1010);
			}
			Close(cancelAction: false);
		}

		private void Close(bool cancelAction)
		{
			Player.isTypingChat = false;
			IsSignUIOpen = false;
			if (cancelAction)
			{
				Player.performingEmote = false;
				Player.StopPerformingEmoteServerRpc();
			}
			if (!Player.quickMenuManager.isMenuOpen)
			{
				Cursor.visible = false;
				Cursor.lockState = (CursorLockMode)1;
			}
			Player.disableLookInput = false;
			((Component)this).gameObject.SetActive(false);
		}
	}
	public class SyncAnimatorToOthers : NetworkBehaviour
	{
		private PlayerControllerB _player;

		private void Start()
		{
			_player = ((Component)this).GetComponent<PlayerControllerB>();
		}

		public void UpdateEmoteIDForOthers(int newID)
		{
			if (((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				UpdateCurrentEmoteIDServerRpc(newID);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void UpdateCurrentEmoteIDServerRpc(int newID)
		{
			UpdateCurrentEmoteIDClientRpc(newID);
		}

		[ClientRpc]
		private void UpdateCurrentEmoteIDClientRpc(int newID)
		{
			if (!((NetworkBehaviour)_player).IsOwner)
			{
				_player.playerBodyAnimator.SetInteger("emoteNumber", newID);
			}
		}
	}
	public class CustomAnimationObjects : MonoBehaviour
	{
		private PlayerControllerB _player;

		private MeshRenderer _sign;

		private GameObject _signText;

		private SkinnedMeshRenderer _legs;

		private void Start()
		{
			_player = ((Component)this).GetComponent<PlayerControllerB>();
		}

		private void Update()
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_sign == (Object)null || (Object)(object)_signText == (Object)null)
			{
				FindSign();
				return;
			}
			((Component)_sign).transform.localPosition = ((Component)_sign).transform.parent.Find("spine").localPosition;
			if ((Object)(object)_legs == (Object)null && ((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				FindLegs();
				return;
			}
			DisableEverything();
			if (!_player.performingEmote)
			{
				return;
			}
			switch (_player.playerBodyAnimator.GetInteger("emoteNumber"))
			{
			case 10:
			case 1010:
				((Renderer)_sign).enabled = true;
				if (!_signText.activeSelf)
				{
					_signText.SetActive(true);
				}
				if (((NetworkBehaviour)_player).IsOwner)
				{
					EmotePatch.LocalArmsSeparatedFromCamera = true;
				}
				break;
			case 9:
				if ((Object)(object)_legs != (Object)null)
				{
					((Renderer)_legs).enabled = true;
				}
				if (((NetworkBehaviour)_player).IsOwner)
				{
					EmotePatch.LocalArmsSeparatedFromCamera = true;
				}
				break;
			}
		}

		private void DisableEverything()
		{
			if ((Object)(object)_legs != (Object)null)
			{
				((Renderer)_legs).enabled = false;
			}
			((Renderer)_sign).enabled = false;
			if (_signText.activeSelf)
			{
				_signText.SetActive(false);
			}
			if (((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				EmotePatch.LocalArmsSeparatedFromCamera = false;
			}
		}

		private void FindSign()
		{
			_sign = ((Component)((Component)_player).transform.Find("ScavengerModel").Find("metarig").Find("Sign")).GetComponent<MeshRenderer>();
			_signText = ((Component)((Component)_sign).transform.Find("Text")).gameObject;
		}

		private void FindLegs()
		{
			_legs = ((Component)((Component)_player).transform.Find("ScavengerModel").Find("LEGS")).GetComponent<SkinnedMeshRenderer>();
		}
	}
}

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.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2")]
[assembly: AssemblyProduct("MoreItems")]
[assembly: AssemblyTitle("MoreItems")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.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 MoreItems
{
	[BepInPlugin("MoreItems", "MoreItems", "1.0.2")]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("MoreItems");

		private void Awake()
		{
			try
			{
				harmony.PatchAll(typeof(GameNetworkManagerPatch));
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MoreItems is loaded!");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Plugin MoreItems failed to load and threw an exception:\n" + ex.Message));
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "MoreItems";

		public const string PLUGIN_NAME = "MoreItems";

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

		[HarmonyPatch("SaveItemsInShip")]
		[HarmonyPrefix]
		private static void IncreaseShipItemCapacity()
		{
			StartOfRound.Instance.maxShipItemCapacity = 999;
			Logger.CreateLogSource("MoreItems").LogInfo((object)$"Maximum amount of items that can be saved set to {999} just before saving.");
		}
	}
}

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

plugins/NicholaScott.BepInEx.RuntimeNetcodeRPCValidator.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.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using HarmonyLib;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: AssemblyCompany("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.5.0")]
[assembly: AssemblyInformationalVersion("0.2.5+6e2f89b3631ae55d2f51a00ccfd3f20fec9d2372")]
[assembly: AssemblyProduct("RuntimeNetcodeRPCValidator")]
[assembly: AssemblyTitle("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
namespace RuntimeNetcodeRPCValidator
{
	public class AlreadyRegisteredException : Exception
	{
		public AlreadyRegisteredException(string PluginGUID)
			: base("Can't register plugin " + PluginGUID + " until the other instance of NetcodeValidator is Disposed of!")
		{
		}
	}
	public class InvalidPluginGuidException : Exception
	{
		public InvalidPluginGuidException(string pluginGUID)
			: base("Can't patch plugin " + pluginGUID + " because it doesn't exist!")
		{
		}
	}
	public class NotNetworkBehaviourException : Exception
	{
		public NotNetworkBehaviourException(Type type)
			: base("Netcode Runtime RPC Validator tried to NetcodeValidator.Patch type " + type.Name + " that doesn't inherit from NetworkBehaviour!")
		{
		}
	}
	public class MustCallFromDeclaredTypeException : Exception
	{
		public MustCallFromDeclaredTypeException()
			: base("Netcode Runtime RPC Validator tried to run NetcodeValidator.PatchAll from a delegate! You must call PatchAll from a declared type.")
		{
		}
	}
	public static class FastBufferExtensions
	{
		private const BindingFlags BindingAll = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static void WriteSystemSerializable(this FastBufferWriter fastBufferWriter, object serializable)
		{
			//IL_0025: 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)
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream memoryStream = new MemoryStream();
			binaryFormatter.Serialize(memoryStream, serializable);
			byte[] array = memoryStream.ToArray();
			int num = array.Length;
			((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives));
			((FastBufferWriter)(ref fastBufferWriter)).WriteBytes(array, -1, 0);
		}

		private static void ReadSystemSerializable(this FastBufferReader fastBufferReader, out object serializable)
		{
			//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)
			int num = default(int);
			((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			byte[] buffer = new byte[num];
			((FastBufferReader)(ref fastBufferReader)).ReadBytes(ref buffer, num, 0);
			using MemoryStream memoryStream = new MemoryStream(buffer);
			memoryStream.Seek(0L, SeekOrigin.Begin);
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			serializable = binaryFormatter.Deserialize(memoryStream);
		}

		private static void WriteNetcodeSerializable(this FastBufferWriter fastBufferWriter, object networkSerializable)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(1024, (Allocator)2, -1);
			try
			{
				BufferSerializer<BufferSerializerWriter> val2 = default(BufferSerializer<BufferSerializerWriter>);
				val2..ctor(new BufferSerializerWriter(val));
				object obj = ((networkSerializable is INetworkSerializable) ? networkSerializable : null);
				if (obj != null)
				{
					((INetworkSerializable)obj).NetworkSerialize<BufferSerializerWriter>(val2);
				}
				byte[] array = ((FastBufferWriter)(ref val)).ToArray();
				int num = array.Length;
				((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref fastBufferWriter)).WriteBytes(array, -1, 0);
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		private static void ReadNetcodeSerializable(this FastBufferReader fastBufferReader, Type type, out object serializable)
		{
			//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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			int num = default(int);
			((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			byte[] array = new byte[num];
			((FastBufferReader)(ref fastBufferReader)).ReadBytes(ref array, num, 0);
			FastBufferReader val = default(FastBufferReader);
			((FastBufferReader)(ref val))..ctor(array, (Allocator)2, -1, 0);
			try
			{
				BufferSerializer<BufferSerializerReader> val2 = default(BufferSerializer<BufferSerializerReader>);
				val2..ctor(new BufferSerializerReader(val));
				serializable = Activator.CreateInstance(type);
				object obj = serializable;
				object obj2 = ((obj is INetworkSerializable) ? obj : null);
				if (obj2 != null)
				{
					((INetworkSerializable)obj2).NetworkSerialize<BufferSerializerReader>(val2);
				}
			}
			finally
			{
				((IDisposable)(FastBufferReader)(ref val)).Dispose();
			}
		}

		public static void WriteMethodInfoAndParameters(this FastBufferWriter fastBufferWriter, MethodBase methodInfo, object[] args)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe(methodInfo.Name, false);
			ParameterInfo[] parameters = methodInfo.GetParameters();
			int num = parameters.Length;
			((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives));
			for (int i = 0; i < parameters.Length; i++)
			{
				ParameterInfo parameterInfo = parameters[i];
				object obj = args[i];
				bool flag = obj == null || parameterInfo.ParameterType == typeof(ServerRpcParams) || parameterInfo.ParameterType == typeof(ClientRpcParams);
				((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					continue;
				}
				if (parameterInfo.ParameterType.GetInterfaces().Contains(typeof(INetworkSerializable)))
				{
					fastBufferWriter.WriteNetcodeSerializable(obj);
					continue;
				}
				if (parameterInfo.ParameterType.IsSerializable)
				{
					fastBufferWriter.WriteSystemSerializable(obj);
					continue;
				}
				throw new SerializationException(TextHandler.ObjectNotSerializable(parameterInfo));
			}
		}

		public static MethodInfo ReadMethodInfoAndParameters(this FastBufferReader fastBufferReader, Type methodDeclaringType, ref object[] args)
		{
			//IL_0010: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			string name = default(string);
			((FastBufferReader)(ref fastBufferReader)).ReadValueSafe(ref name, false);
			int num = default(int);
			((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			MethodInfo method = methodDeclaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (num != method?.GetParameters().Length)
			{
				throw new Exception(TextHandler.InconsistentParameterCount(method, num));
			}
			bool flag = default(bool);
			for (int i = 0; i < num; i++)
			{
				((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					continue;
				}
				ParameterInfo parameterInfo = method.GetParameters()[i];
				object serializable;
				if (parameterInfo.ParameterType.GetInterfaces().Contains(typeof(INetworkSerializable)))
				{
					fastBufferReader.ReadNetcodeSerializable(parameterInfo.ParameterType, out serializable);
				}
				else
				{
					if (!parameterInfo.ParameterType.IsSerializable)
					{
						throw new SerializationException(TextHandler.ObjectNotSerializable(parameterInfo));
					}
					fastBufferReader.ReadSystemSerializable(out serializable);
				}
				args[i] = serializable;
			}
			return method;
		}
	}
	public sealed class NetcodeValidator : IDisposable
	{
		private static readonly List<string> AlreadyRegistered = new List<string>();

		internal const string TypeCustomMessageHandlerPrefix = "Net";

		private static List<(NetcodeValidator validator, Type custom, Type native)> BoundNetworkObjects { get; } = new List<(NetcodeValidator, Type, Type)>();


		private List<string> CustomMessageHandlers { get; }

		private Harmony Patcher { get; }

		public string PluginGuid { get; }

		internal static event Action<NetcodeValidator, Type> AddedNewBoundBehaviour;

		private event Action<string> AddedNewCustomMessageHandler;

		public NetcodeValidator(string pluginGuid)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			if (!Chainloader.PluginInfos.TryGetValue(pluginGuid, out var _))
			{
				throw new InvalidPluginGuidException(pluginGuid);
			}
			if (AlreadyRegistered.Contains(pluginGuid))
			{
				throw new AlreadyRegisteredException(pluginGuid);
			}
			AlreadyRegistered.Add(pluginGuid);
			PluginGuid = pluginGuid;
			CustomMessageHandlers = new List<string>();
			Patcher = new Harmony(pluginGuid + "NicholaScott.BepInEx.RuntimeNetcodeRPCValidator");
			Plugin.NetworkManagerInitialized += NetworkManagerInitialized;
			Plugin.NetworkManagerShutdown += NetworkManagerShutdown;
		}

		internal static void TryLoadRelatedComponentsInOrder(NetworkBehaviour __instance, MethodBase __originalMethod)
		{
			foreach (var item in from obj in BoundNetworkObjects
				where obj.native == __originalMethod.DeclaringType
				select obj into it
				orderby it.validator.PluginGuid
				select it)
			{
				Plugin.Logger.LogInfo((object)TextHandler.CustomComponentAddedToExistingObject(item, __originalMethod));
				Component obj2 = ((Component)__instance).gameObject.AddComponent(item.custom);
				((NetworkBehaviour)(object)((obj2 is NetworkBehaviour) ? obj2 : null)).SyncWithNetworkObject();
			}
		}

		private bool Patch(MethodInfo rpcMethod, out bool isServerRpc, out bool isClientRpc)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			isServerRpc = ((MemberInfo)rpcMethod).GetCustomAttributes<ServerRpcAttribute>().Any();
			isClientRpc = ((MemberInfo)rpcMethod).GetCustomAttributes<ClientRpcAttribute>().Any();
			bool flag = rpcMethod.Name.EndsWith("ServerRpc");
			bool flag2 = rpcMethod.Name.EndsWith("ClientRpc");
			if (!isClientRpc && !isServerRpc && !flag2 && !flag)
			{
				return false;
			}
			if ((!isServerRpc && flag) || (!isClientRpc && flag2))
			{
				Plugin.Logger.LogError((object)TextHandler.MethodLacksRpcAttribute(rpcMethod));
				return false;
			}
			if ((isServerRpc && !flag) || (isClientRpc && !flag2))
			{
				Plugin.Logger.LogError((object)TextHandler.MethodLacksSuffix(rpcMethod));
				return false;
			}
			Patcher.Patch((MethodBase)rpcMethod, new HarmonyMethod(typeof(NetworkBehaviourExtensions), "MethodPatch", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return true;
		}

		public void BindToPreExistingObjectByBehaviour<TCustomBehaviour, TNativeBehaviour>() where TCustomBehaviour : NetworkBehaviour where TNativeBehaviour : NetworkBehaviour
		{
			if (Object.op_Implicit((Object)(object)NetworkManager.Singleton) && (NetworkManager.Singleton.IsListening || NetworkManager.Singleton.IsConnectedClient))
			{
				Plugin.Logger.LogError((object)TextHandler.PluginTriedToBindToPreExistingObjectTooLate(this, typeof(TCustomBehaviour), typeof(TNativeBehaviour)));
			}
			else
			{
				OnAddedNewBoundBehaviour(this, typeof(TCustomBehaviour), typeof(TNativeBehaviour));
			}
		}

		public void Patch(Type netBehaviourTyped)
		{
			if (netBehaviourTyped.BaseType != typeof(NetworkBehaviour))
			{
				throw new NotNetworkBehaviourException(netBehaviourTyped);
			}
			OnAddedNewCustomMessageHandler("Net." + netBehaviourTyped.Name);
			int num = 0;
			int num2 = 0;
			MethodInfo[] methods = netBehaviourTyped.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo rpcMethod in methods)
			{
				if (Patch(rpcMethod, out var isServerRpc, out var isClientRpc))
				{
					num += (isServerRpc ? 1 : 0);
					num2 += (isClientRpc ? 1 : 0);
				}
			}
			Plugin.Logger.LogInfo((object)TextHandler.SuccessfullyPatchedType(netBehaviourTyped, num, num2));
		}

		public void Patch(Assembly assembly)
		{
			Type[] types = assembly.GetTypes();
			foreach (Type type in types)
			{
				if (type.BaseType == typeof(NetworkBehaviour))
				{
					Patch(type);
				}
			}
		}

		public void PatchAll()
		{
			Assembly assembly = new StackTrace().GetFrame(1).GetMethod().ReflectedType?.Assembly;
			if (assembly == null)
			{
				throw new MustCallFromDeclaredTypeException();
			}
			Patch(assembly);
		}

		public void UnpatchSelf()
		{
			Plugin.Logger.LogInfo((object)TextHandler.PluginUnpatchedAllRPCs(this));
			Patcher.UnpatchSelf();
		}

		private static void RegisterMessageHandlerWithNetworkManager(string handler)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(handler, new HandleNamedMessageDelegate(NetworkBehaviourExtensions.ReceiveNetworkMessage));
		}

		private void NetworkManagerInitialized()
		{
			AddedNewCustomMessageHandler += RegisterMessageHandlerWithNetworkManager;
			foreach (string customMessageHandler in CustomMessageHandlers)
			{
				RegisterMessageHandlerWithNetworkManager(customMessageHandler);
			}
		}

		private void NetworkManagerShutdown()
		{
			AddedNewCustomMessageHandler -= RegisterMessageHandlerWithNetworkManager;
			foreach (string customMessageHandler in CustomMessageHandlers)
			{
				NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler(customMessageHandler);
			}
		}

		public void Dispose()
		{
			Plugin.NetworkManagerInitialized -= NetworkManagerInitialized;
			Plugin.NetworkManagerShutdown -= NetworkManagerShutdown;
			AlreadyRegistered.Remove(PluginGuid);
			if (Object.op_Implicit((Object)(object)NetworkManager.Singleton))
			{
				NetworkManagerShutdown();
			}
			if (Patcher.GetPatchedMethods().Any())
			{
				UnpatchSelf();
			}
		}

		private void OnAddedNewCustomMessageHandler(string obj)
		{
			CustomMessageHandlers.Add(obj);
			this.AddedNewCustomMessageHandler?.Invoke(obj);
		}

		private static void OnAddedNewBoundBehaviour(NetcodeValidator validator, Type custom, Type native)
		{
			BoundNetworkObjects.Add((validator, custom, native));
			NetcodeValidator.AddedNewBoundBehaviour?.Invoke(validator, native);
		}
	}
	public static class NetworkBehaviourExtensions
	{
		public enum RpcState
		{
			FromUser,
			FromNetworking
		}

		private static RpcState RpcSource;

		public static ClientRpcParams CreateSendToFromReceived(this ServerRpcParams senderId)
		{
			//IL_0002: 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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			ClientRpcParams result = default(ClientRpcParams);
			result.Send = new ClientRpcSendParams
			{
				TargetClientIds = new ulong[1] { senderId.Receive.SenderClientId }
			};
			return result;
		}

		public static void SyncWithNetworkObject(this NetworkBehaviour networkBehaviour)
		{
			if (!networkBehaviour.NetworkObject.ChildNetworkBehaviours.Contains(networkBehaviour))
			{
				networkBehaviour.NetworkObject.ChildNetworkBehaviours.Add(networkBehaviour);
			}
			networkBehaviour.UpdateNetworkProperties();
		}

		private static bool ValidateRPCMethod(NetworkBehaviour networkBehaviour, MethodBase method, RpcState state, out RpcAttribute rpcAttribute)
		{
			bool flag = ((MemberInfo)method).GetCustomAttributes<ServerRpcAttribute>().Any();
			bool flag2 = ((MemberInfo)method).GetCustomAttributes<ClientRpcAttribute>().Any();
			bool num = flag && ((MemberInfo)method).GetCustomAttribute<ServerRpcAttribute>().RequireOwnership;
			rpcAttribute = (RpcAttribute)(flag ? ((object)((MemberInfo)method).GetCustomAttribute<ServerRpcAttribute>()) : ((object)((MemberInfo)method).GetCustomAttribute<ClientRpcAttribute>()));
			if (num && networkBehaviour.OwnerClientId != NetworkManager.Singleton.LocalClientId)
			{
				Plugin.Logger.LogError((object)TextHandler.NotOwnerOfNetworkObject((state == RpcState.FromUser) ? "We" : "Client", method, networkBehaviour.NetworkObject));
				return false;
			}
			if (state == RpcState.FromUser && flag2 && !NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				Plugin.Logger.LogError((object)TextHandler.CantRunClientRpcFromClient(method));
				return false;
			}
			if (state == RpcState.FromUser && !flag && !flag2)
			{
				Plugin.Logger.LogError((object)TextHandler.MethodPatchedButLacksAttributes(method));
				return false;
			}
			if (state == RpcState.FromNetworking && !flag && !flag2)
			{
				Plugin.Logger.LogError((object)TextHandler.MethodPatchedAndNetworkCalledButLacksAttributes(method));
				return false;
			}
			if (state == RpcState.FromNetworking && flag && !networkBehaviour.IsServer && !networkBehaviour.IsHost)
			{
				Plugin.Logger.LogError((object)TextHandler.CantRunServerRpcAsClient(method));
				return false;
			}
			return true;
		}

		private static bool MethodPatchInternal(NetworkBehaviour networkBehaviour, MethodBase method, object[] args)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: 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_00e3: 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_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)NetworkManager.Singleton) || (!NetworkManager.Singleton.IsListening && !NetworkManager.Singleton.IsConnectedClient))
			{
				Plugin.Logger.LogError((object)TextHandler.NoNetworkManagerPresentToSendRpc(networkBehaviour));
				return false;
			}
			RpcState rpcSource = RpcSource;
			RpcSource = RpcState.FromUser;
			if (rpcSource == RpcState.FromNetworking)
			{
				return true;
			}
			if (!ValidateRPCMethod(networkBehaviour, method, rpcSource, out var rpcAttribute))
			{
				return false;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor((method.GetParameters().Length + 1) * 128, (Allocator)2, -1);
			ulong networkObjectId = networkBehaviour.NetworkObjectId;
			((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref networkObjectId, default(ForPrimitives));
			ushort networkBehaviourId = networkBehaviour.NetworkBehaviourId;
			((FastBufferWriter)(ref val)).WriteValueSafe<ushort>(ref networkBehaviourId, default(ForPrimitives));
			val.WriteMethodInfoAndParameters(method, args);
			string text = new StringBuilder("Net").Append(".").Append(method.DeclaringType.Name).ToString();
			NetworkDelivery val2 = (NetworkDelivery)(((int)rpcAttribute.Delivery == 0) ? 2 : 0);
			if (rpcAttribute is ServerRpcAttribute)
			{
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage(text, 0uL, val, val2);
			}
			else
			{
				ParameterInfo[] parameters = method.GetParameters();
				if (parameters.Length != 0 && parameters[^1].ParameterType == typeof(ClientRpcParams))
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage(text, ((ClientRpcParams)args[^1]).Send.TargetClientIds, val, val2);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(text, val, val2);
				}
			}
			return false;
		}

		internal static void ReceiveNetworkMessage(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_0100: 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_0126: 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_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			ulong key = default(ulong);
			((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref key, default(ForPrimitives));
			ushort num = default(ushort);
			((FastBufferReader)(ref reader)).ReadValueSafe<ushort>(ref num, default(ForPrimitives));
			int position = ((FastBufferReader)(ref reader)).Position;
			string text = default(string);
			((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
			((FastBufferReader)(ref reader)).Seek(position);
			if (!NetworkManager.Singleton.SpawnManager.SpawnedObjects.TryGetValue(key, out var value))
			{
				Plugin.Logger.LogError((object)TextHandler.RpcCalledBeforeObjectSpawned());
				return;
			}
			NetworkBehaviour networkBehaviourAtOrderIndex = value.GetNetworkBehaviourAtOrderIndex(num);
			MethodInfo method = ((object)networkBehaviourAtOrderIndex).GetType().GetMethod(text, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			RpcAttribute rpcAttribute;
			if (method == null)
			{
				Plugin.Logger.LogError((object)TextHandler.NetworkCalledNonExistentMethod(networkBehaviourAtOrderIndex, text));
			}
			else if (ValidateRPCMethod(networkBehaviourAtOrderIndex, method, RpcState.FromNetworking, out rpcAttribute))
			{
				RpcSource = RpcState.FromNetworking;
				ParameterInfo[] parameters = method.GetParameters();
				bool num2 = rpcAttribute is ServerRpcAttribute && parameters.Length != 0 && parameters[^1].ParameterType == typeof(ServerRpcParams);
				object[] args = null;
				if (parameters.Length != 0)
				{
					args = new object[parameters.Length];
				}
				reader.ReadMethodInfoAndParameters(method.DeclaringType, ref args);
				if (num2)
				{
					args[^1] = (object)new ServerRpcParams
					{
						Receive = new ServerRpcReceiveParams
						{
							SenderClientId = sender
						}
					};
				}
				method.Invoke(networkBehaviourAtOrderIndex, args);
			}
		}

		internal static bool MethodPatch(NetworkBehaviour __instance, MethodBase __originalMethod, object[] __args)
		{
			return MethodPatchInternal(__instance, __originalMethod, __args);
		}
	}
	[BepInPlugin("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator", "RuntimeNetcodeRPCValidator", "0.2.5")]
	public class Plugin : BaseUnityPlugin
	{
		private readonly Harmony _harmony = new Harmony("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator");

		private List<Type> AlreadyPatchedNativeBehaviours { get; } = new List<Type>();


		internal static ManualLogSource Logger { get; private set; }

		public static event Action NetworkManagerInitialized;

		public static event Action NetworkManagerShutdown;

		private void Awake()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			NetcodeValidator.AddedNewBoundBehaviour += NetcodeValidatorOnAddedNewBoundBehaviour;
			_harmony.Patch((MethodBase)AccessTools.Method(typeof(NetworkManager), "Initialize", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "OnNetworkManagerInitialized", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			_harmony.Patch((MethodBase)AccessTools.Method(typeof(NetworkManager), "Shutdown", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "OnNetworkManagerShutdown", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private void NetcodeValidatorOnAddedNewBoundBehaviour(NetcodeValidator validator, Type netBehaviour)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			if (!AlreadyPatchedNativeBehaviours.Contains(netBehaviour))
			{
				AlreadyPatchedNativeBehaviours.Add(netBehaviour);
				MethodBase methodBase = AccessTools.Method(netBehaviour, "Awake", (Type[])null, (Type[])null);
				if (methodBase == null)
				{
					methodBase = AccessTools.Method(netBehaviour, "Start", (Type[])null, (Type[])null);
				}
				if (methodBase == null)
				{
					methodBase = AccessTools.Constructor(netBehaviour, (Type[])null, false);
				}
				Logger.LogInfo((object)TextHandler.RegisteredPatchForType(validator, netBehaviour, methodBase));
				HarmonyMethod val = new HarmonyMethod(typeof(NetcodeValidator), "TryLoadRelatedComponentsInOrder", (Type[])null);
				_harmony.Patch(methodBase, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		protected static void OnNetworkManagerInitialized()
		{
			Plugin.NetworkManagerInitialized?.Invoke();
		}

		protected static void OnNetworkManagerShutdown()
		{
			Plugin.NetworkManagerShutdown?.Invoke();
		}
	}
	internal static class TextHandler
	{
		private const string NoNetworkManagerPresentToSendRpcConst = "NetworkBehaviour {0} tried to send a RPC but the NetworkManager is non-existant!";

		private const string MethodLacksAttributeConst = "Can't patch method {0}.{1} because it lacks a [{2}] attribute.";

		private const string MethodLacksSuffixConst = "Can't patch method {0}.{1} because it's name doesn't end with '{2}'!";

		private const string SuccessfullyPatchedTypeConst = "Patched {0} ServerRPC{1} & {2} ClientRPC{3} on NetworkBehaviour {4}.";

		private const string NotOwnerOfNetworkObjectConst = "{0} tried to run ServerRPC {1} but not the owner of NetworkObject {2}";

		private const string CantRunClientRpcFromClientConst = "Tried to run ClientRpc {0} but we're not a host! You should only call ClientRpc(s) from inside a ServerRpc OR if you've checked you're on the server with IsHost!";

		private const string CantRunServerRpcAsClientConst = "Received message to run ServerRPC {0}.{1} but we're a client!";

		private const string MethodPatchedButLacksAttributesConst = "Rpc Method {0} has been patched to attempt networking but lacks any RpcAttributes! This should never happen!";

		private const string MethodPatchedAndNetworkCalledButLacksAttributesConst = "Rpc Method {0} has been patched && even received a network call to execute but lacks any RpcAttributes! This should never happen! Something is VERY fucky!!!";

		private const string RpcCalledBeforeObjectSpawnedConst = "An RPC called on a NetworkObject that is not in the spawned objects list. Please make sure the NetworkObject is spawned before calling RPCs.";

		private const string NetworkCalledNonExistentMethodConst = "NetworkBehaviour {0} received RPC {1} but that method doesn't exist on {2}!";

		private const string ObjectNotSerializableConst = "[Network] Parameter ({0} {1}) is not marked [Serializable] nor does it implement INetworkSerializable!";

		private const string InconsistentParameterCountConst = "[Network] NetworkBehaviour received a RPC {0} but the number of parameters sent {1} != MethodInfo param count {2}";

		private const string PluginTriedToBindToPreExistingObjectTooLateConst = "Plugin '{0}' tried to bind {1} to {2} but it's too late! Make sure you bind to any pre-existing NetworkObjects before NetworkManager.IsListening || IsConnectedClient.";

		private const string RegisteredPatchForTypeConst = "Successfully registered first patch for type {0}.{1} | Triggered by {2}";

		private const string CustomComponentAddedToExistingObjectConst = "Successfully added {0} to {1} via {2}. Triggered by plugin {3}";

		private const string PluginUnpatchedAllRPCsConst = "Plugin {0} has unpatched all RPCs!";

		internal static string NoNetworkManagerPresentToSendRpc(NetworkBehaviour networkBehaviour)
		{
			return $"NetworkBehaviour {networkBehaviour.NetworkBehaviourId} tried to send a RPC but the NetworkManager is non-existant!";
		}

		internal static string MethodLacksRpcAttribute(MethodInfo method)
		{
			return string.Format("Can't patch method {0}.{1} because it lacks a [{2}] attribute.", method.DeclaringType?.Name, method.Name, method.Name.EndsWith("ServerRpc") ? "ServerRpc" : "ClientRpc");
		}

		internal static string MethodLacksSuffix(MethodBase method)
		{
			return string.Format("Can't patch method {0}.{1} because it's name doesn't end with '{2}'!", method.DeclaringType?.Name, method.Name, (((MemberInfo)method).GetCustomAttribute<ServerRpcAttribute>() != null) ? "ServerRpc" : "ClientRpc");
		}

		internal static string SuccessfullyPatchedType(Type networkType, int serverRpcCount, int clientRpcCount)
		{
			return string.Format("Patched {0} ServerRPC{1} & {2} ClientRPC{3} on NetworkBehaviour {4}.", serverRpcCount, (serverRpcCount == 1) ? "" : "s", clientRpcCount, (clientRpcCount == 1) ? "" : "s", networkType.Name);
		}

		internal static string NotOwnerOfNetworkObject(string whoIsNotOwner, MethodBase method, NetworkObject networkObject)
		{
			return $"{whoIsNotOwner} tried to run ServerRPC {method.Name} but not the owner of NetworkObject {networkObject.NetworkObjectId}";
		}

		internal static string CantRunClientRpcFromClient(MethodBase method)
		{
			return $"Tried to run ClientRpc {method.Name} but we're not a host! You should only call ClientRpc(s) from inside a ServerRpc OR if you've checked you're on the server with IsHost!";
		}

		internal static string CantRunServerRpcAsClient(MethodBase method)
		{
			return $"Received message to run ServerRPC {method.DeclaringType?.Name}.{method.Name} but we're a client!";
		}

		internal static string MethodPatchedButLacksAttributes(MethodBase method)
		{
			return $"Rpc Method {method.Name} has been patched to attempt networking but lacks any RpcAttributes! This should never happen!";
		}

		internal static string MethodPatchedAndNetworkCalledButLacksAttributes(MethodBase method)
		{
			return $"Rpc Method {method.Name} has been patched && even received a network call to execute but lacks any RpcAttributes! This should never happen! Something is VERY fucky!!!";
		}

		internal static string RpcCalledBeforeObjectSpawned()
		{
			return "An RPC called on a NetworkObject that is not in the spawned objects list. Please make sure the NetworkObject is spawned before calling RPCs.";
		}

		internal static string NetworkCalledNonExistentMethod(NetworkBehaviour networkBehaviour, string rpcName)
		{
			return $"NetworkBehaviour {networkBehaviour.NetworkBehaviourId} received RPC {rpcName} but that method doesn't exist on {((object)networkBehaviour).GetType().Name}!";
		}

		internal static string ObjectNotSerializable(ParameterInfo paramInfo)
		{
			return $"[Network] Parameter ({paramInfo.ParameterType.Name} {paramInfo.Name}) is not marked [Serializable] nor does it implement INetworkSerializable!";
		}

		internal static string InconsistentParameterCount(MethodBase method, int paramsSent)
		{
			return $"[Network] NetworkBehaviour received a RPC {method.Name} but the number of parameters sent {paramsSent} != MethodInfo param count {method.GetParameters().Length}";
		}

		internal static string PluginTriedToBindToPreExistingObjectTooLate(NetcodeValidator netcodeValidator, Type from, Type to)
		{
			return $"Plugin '{netcodeValidator.PluginGuid}' tried to bind {from.Name} to {to.Name} but it's too late! Make sure you bind to any pre-existing NetworkObjects before NetworkManager.IsListening || IsConnectedClient.";
		}

		internal static string RegisteredPatchForType(NetcodeValidator validator, Type netBehaviour, MethodBase method)
		{
			return $"Successfully registered first patch for type {netBehaviour.Name}.{method.Name} | Triggered by {validator.PluginGuid}";
		}

		internal static string CustomComponentAddedToExistingObject((NetcodeValidator validator, Type custom, Type native) it, MethodBase methodBase)
		{
			return $"Successfully added {it.custom.Name} to {it.native.Name} via {methodBase.Name}. Triggered by plugin {it.validator.PluginGuid}";
		}

		internal static string PluginUnpatchedAllRPCs(NetcodeValidator netcodeValidator)
		{
			return $"Plugin {netcodeValidator.PluginGuid} has unpatched all RPCs!";
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "NicholaScott.BepInEx.RuntimeNetcodeRPCValidator";

		public const string PLUGIN_NAME = "RuntimeNetcodeRPCValidator";

		public const string PLUGIN_VERSION = "0.2.5";
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}

plugins/NoSellLimit.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
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 BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("NoSellLimit")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Remove the limit of items that can be placed on the deposit desk")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("NoSellLimit")]
[assembly: AssemblyTitle("NoSellLimit")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace NoSellLimit
{
	[BepInPlugin("viviko.NoSellLimit", "NoSellLimit", "1.0.1")]
	public class NoSellLimit : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(DepositItemsDesk))]
		[HarmonyPatch("PlaceItemOnCounter")]
		public static class PlaceItemOnCounterPatch
		{
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Expected O, but got Unknown
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				//IL_0056: Expected O, but got Unknown
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Expected O, but got Unknown
				//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a6: Expected O, but got Unknown
				//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ce: Expected O, but got Unknown
				//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f6: Expected O, but got Unknown
				//IL_0118: Unknown result type (might be due to invalid IL or missing references)
				//IL_011e: Expected O, but got Unknown
				//IL_0121: Unknown result type (might be due to invalid IL or missing references)
				//IL_0126: Unknown result type (might be due to invalid IL or missing references)
				//IL_012d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0136: 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)
				CodeMatch[] array = (CodeMatch[])(object)new CodeMatch[7]
				{
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Ldarg_0), (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => CodeInstructionExtensions.LoadsField(i, AccessTools.Field(typeof(DepositItemsDesk), "deskObjectsContainer"), false)), (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Callvirt), (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Ldlen), (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Conv_I4), (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Ldc_I4_S), (string)null),
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Bge), (string)null)
				};
				CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null);
				val.Start();
				val.MatchForward(false, array);
				val.SetOpcodeAndAdvance(OpCodes.Nop);
				val.RemoveInstructions(array.Length - 1);
				return val.Instructions();
			}
		}

		private const string modGUID = "viviko.NoSellLimit";

		private const string modName = "NoSellLimit";

		private const string modVersion = "1.0.1";

		private readonly Harmony harmony = new Harmony("viviko.NoSellLimit");

		private static NoSellLimit Instance;

		public static ManualLogSource mls;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("NoSellLimit");
			harmony.PatchAll();
			mls.LogInfo((object)"Plugin NoSellLimit is loaded!");
		}
	}
	internal static class GeneratedPluginInfo
	{
		public const string Identifier = "viviko.NoSellLimit";

		public const string Name = "NoSellLimit";

		public const string Version = "1.0.1";
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class ExperimentalAttribute : Attribute
	{
		public string DiagnosticId { get; }

		public string? UrlFormat { get; set; }

		public ExperimentalAttribute(string diagnosticId)
		{
			DiagnosticId = diagnosticId;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class SetsRequiredMembersAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class StringSyntaxAttribute : Attribute
	{
		public const string CompositeFormat = "CompositeFormat";

		public const string DateOnlyFormat = "DateOnlyFormat";

		public const string DateTimeFormat = "DateTimeFormat";

		public const string EnumFormat = "EnumFormat";

		public const string GuidFormat = "GuidFormat";

		public const string Json = "Json";

		public const string NumericFormat = "NumericFormat";

		public const string Regex = "Regex";

		public const string TimeOnlyFormat = "TimeOnlyFormat";

		public const string TimeSpanFormat = "TimeSpanFormat";

		public const string Uri = "Uri";

		public const string Xml = "Xml";

		public string Syntax { get; }

		public object?[] Arguments { get; }

		public StringSyntaxAttribute(string syntax)
		{
			Syntax = syntax;
			Arguments = new object[0];
		}

		public StringSyntaxAttribute(string syntax, params object?[] arguments)
		{
			Syntax = syntax;
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class UnscopedRefAttribute : Attribute
	{
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiresPreviewFeaturesAttribute : Attribute
	{
		public string? Message { get; }

		public string? Url { get; set; }

		public RequiresPreviewFeaturesAttribute()
		{
		}

		public RequiresPreviewFeaturesAttribute(string? message)
		{
			Message = message;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CollectionBuilderAttribute : Attribute
	{
		public Type BuilderType { get; }

		public string MethodName { get; }

		public CollectionBuilderAttribute(Type builderType, string methodName)
		{
			BuilderType = builderType;
			MethodName = methodName;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CompilerFeatureRequiredAttribute : Attribute
	{
		public const string RefStructs = "RefStructs";

		public const string RequiredMembers = "RequiredMembers";

		public string FeatureName { get; }

		public bool IsOptional { get; set; }

		public CompilerFeatureRequiredAttribute(string featureName)
		{
			FeatureName = featureName;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute
	{
		public string[] Arguments { get; }

		public InterpolatedStringHandlerArgumentAttribute(string argument)
		{
			Arguments = new string[1] { argument };
		}

		public InterpolatedStringHandlerArgumentAttribute(params string[] arguments)
		{
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class InterpolatedStringHandlerAttribute : Attribute
	{
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	[ExcludeFromCodeCoverage]
	internal static class IsExternalInit
	{
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class ModuleInitializerAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiredMemberAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	[EditorBrowsable(EditorBrowsableState.Never)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiresLocationAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class SkipLocalsInitAttribute : Attribute
	{
	}
}

plugins/Pinger.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading.Tasks;
using BepInEx;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.ServerAPI;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Pinger.Overrider;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[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("Pinger")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Pings Player")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Pinger")]
[assembly: AssemblyTitle("Pinger")]
[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 Pinger
{
	internal struct CustomScanNode
	{
		public long created { get; set; }

		public ScanNodeProperties scanNode { get; set; }

		public string owner { get; set; }
	}
	[JsonObject(/*Could not decode attribute arguments.*/)]
	internal class PingData
	{
		[JsonProperty]
		public float x { get; set; }

		[JsonProperty]
		public float y { get; set; }

		[JsonProperty]
		public float z { get; set; }

		[JsonProperty]
		public long created { get; set; }

		[JsonProperty]
		public string owner { get; set; }

		[JsonProperty]
		public bool isDanger { get; set; }
	}
	[BepInPlugin("Pinger", "Pinger", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private const string SIGNATURE = "player_ping";

		private const int LIFESPAN = 10000;

		private Harmony _harmony;

		private ScanNodeProperties _scanNodeMaster;

		private LinkedList<CustomScanNode> _scanNodes = new LinkedList<CustomScanNode>();

		private static bool _isPatched;

		private static bool _isPatching;

		private static PlayerControllerB _mainPlayer;

		private static HUDManager _hudManager;

		public static Plugin Instance { get; private set; }

		private void Awake()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			Instance = this;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Pinger is loaded!");
			_harmony = new Harmony("Pinger");
			_harmony.PatchAll(typeof(StartOfRound_Awake));
			_harmony.PatchAll(typeof(KeyboardPing));
			StartLogicLoop();
		}

		private async void StartLogicLoop()
		{
			while ((Object)(object)StartOfRound.Instance == (Object)null)
			{
				await Task.Delay(1000);
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"StartOfRound.Instance found...");
			_mainPlayer = StartOfRound.Instance.localPlayerController;
			while ((Object)(object)_mainPlayer == (Object)null)
			{
				await Task.Delay(250);
				_mainPlayer = StartOfRound.Instance.localPlayerController;
			}
			while ((Object)(object)_hudManager == (Object)null)
			{
				await Task.Delay(250);
				_hudManager = HUDManager.Instance;
			}
			_isPatched = true;
			handleIncomingPings();
		}

		private void handleIncomingPings()
		{
			Networking.GetString = (Action<string, string>)Delegate.Combine(Networking.GetString, (Action<string, string>)delegate(string message, string signature)
			{
				//IL_009e: Unknown result type (might be due to invalid IL or missing references)
				if (signature.Equals("player_ping"))
				{
					PingData pingData = JsonConvert.DeserializeObject<PingData>(message);
					if (pingData == null)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)"Failed to parse ping data");
					}
					else
					{
						((BaseUnityPlugin)this).Logger.LogMessage((object)$"Received ping from {pingData.owner} at {pingData.x} {pingData.y} {pingData.z}");
						float x = pingData.x;
						float y = pingData.y;
						float z = pingData.z;
						RaycastHit hit = default(RaycastHit);
						createPing(x, y, z, in hit, pingData.isDanger, pingData.owner);
					}
				}
			});
		}

		private void DeletePings(string owner)
		{
			//IL_00ab: 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_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			ScanNodeProperties[] array = Object.FindObjectsByType<ScanNodeProperties>((FindObjectsSortMode)0);
			for (LinkedListNode<CustomScanNode> linkedListNode = _scanNodes.First; linkedListNode != null; linkedListNode = linkedListNode.Next)
			{
				if (!((Object)(object)linkedListNode.Value.scanNode == (Object)null))
				{
					if (linkedListNode.Value.owner != owner)
					{
						Debug.Log((object)$"Skipping ping at {((Component)linkedListNode.Value.scanNode).transform.position} (Predicate failed: {linkedListNode.Value.owner} != {owner})");
					}
					else
					{
						Debug.Log((object)$"Deleting ping at {((Component)linkedListNode.Value.scanNode).transform.position}");
						Object.Destroy((Object)(object)linkedListNode.Value.scanNode);
						for (int i = 0; i < array.Length; i++)
						{
							if (((Component)array[i]).transform.position == ((Component)linkedListNode.Value.scanNode).transform.position)
							{
								Object.Destroy((Object)(object)array[i]);
								break;
							}
						}
					}
				}
			}
		}

		private async void checkAndDeleteOldPings()
		{
			int lifespan = 10000;
			while (true)
			{
				await Task.Delay(1000);
				long now = DateTimeOffset.Now.ToUnixTimeMilliseconds();
				for (LinkedListNode<CustomScanNode> node = _scanNodes.First; node != null; node = node.Next)
				{
					if (!((Object)(object)node.Value.scanNode == (Object)null) && now - node.Value.created > lifespan)
					{
						((BaseUnityPlugin)this).Logger.LogMessage((object)$"Deleting ping at {((Component)node.Value.scanNode).transform.position}");
						Object.Destroy((Object)(object)node.Value.scanNode);
						_scanNodes.Remove(node);
					}
				}
			}
		}

		private void OnDestroy()
		{
			//IL_0038: 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)
			ScanNodeProperties[] array = Object.FindObjectsByType<ScanNodeProperties>((FindObjectsSortMode)0);
			for (LinkedListNode<CustomScanNode> linkedListNode = _scanNodes.First; linkedListNode != null; linkedListNode = linkedListNode.Next)
			{
				Object.Destroy((Object)(object)linkedListNode.Value.scanNode);
				for (int i = 0; i < array.Length; i++)
				{
					if (((Component)array[i]).transform.position == ((Component)linkedListNode.Value.scanNode).transform.position)
					{
						Object.Destroy((Object)(object)array[i]);
						break;
					}
				}
			}
		}

		public bool createPingWherePlayerIsLooking(bool is_danger = false)
		{
			//IL_005b: 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_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_mainPlayer == (Object)null || (Object)(object)_hudManager == (Object)null)
			{
				if (_isPatching)
				{
					return false;
				}
				StartLogicLoop();
				_isPatching = true;
				return false;
			}
			float x = ((Component)_mainPlayer.gameplayCamera).transform.position.x;
			float y = ((Component)_mainPlayer.gameplayCamera).transform.position.y;
			float z = ((Component)_mainPlayer.gameplayCamera).transform.position.z;
			RaycastHit hit = shootRay(x, y, z);
			float x2 = ((RaycastHit)(ref hit)).point.x;
			float y2 = ((RaycastHit)(ref hit)).point.y;
			float z2 = ((RaycastHit)(ref hit)).point.z;
			((BaseUnityPlugin)this).Logger.LogMessage((object)("Creating Ping on the surface of " + ((Object)((RaycastHit)(ref hit)).transform).name));
			CustomScanNode customScanNode = createPing(x2, y2, z2, in hit, is_danger);
			if ((Object)(object)customScanNode.scanNode == (Object)null)
			{
				return false;
			}
			string text = JsonConvert.SerializeObject((object)new PingData
			{
				x = x2,
				y = y2,
				z = z2,
				created = customScanNode.created,
				owner = _mainPlayer.playerUsername,
				isDanger = is_danger
			});
			Networking.Broadcast(text, "player_ping");
			return true;
		}

		private CustomScanNode createPing(float x, float y, float z, in RaycastHit hit)
		{
			return createPing(x, y, z, in hit, isDanger: false, _mainPlayer.playerUsername);
		}

		private CustomScanNode createPing(float x, float y, float z, in RaycastHit hit, bool isDanger)
		{
			return createPing(x, y, z, in hit, isDanger, _mainPlayer.playerUsername);
		}

		private CustomScanNode createPing(float x, float y, float z, in RaycastHit hit, string playerName)
		{
			return createPing(x, y, z, in hit, isDanger: false, playerName);
		}

		private CustomScanNode createPing(float x, float y, float z, in RaycastHit hit, bool isDanger, string playerName)
		{
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			if (hasPlayerPinged(playerName))
			{
				DeletePings(playerName);
			}
			string headerText = playerName + "'s ping";
			string subText = "Player Ping <!>";
			((BaseUnityPlugin)this).Logger.LogMessage((object)$"Creating Ping at : {x} {y} {z}");
			ScanNodeProperties[] array = Object.FindObjectsByType<ScanNodeProperties>((FindObjectsSortMode)0);
			if ((Object)(object)_scanNodeMaster == (Object)null)
			{
				if (array.Length == 0)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"No scan node master found");
					return default(CustomScanNode);
				}
				_scanNodeMaster = array[0];
				checkAndDeleteOldPings();
			}
			ScanNodeProperties val = Object.Instantiate<ScanNodeProperties>(_scanNodeMaster);
			((Object)val).name = "PlayerPing";
			val.headerText = headerText;
			val.subText = subText;
			((Component)val).transform.position = new Vector3(x, y, z);
			val.maxRange = 200;
			val.minRange = 0;
			val.requiresLineOfSight = true;
			if (isDanger)
			{
				val.nodeType = 1;
				val.subText = "DANGER <!>";
			}
			else
			{
				val.nodeType = 2;
			}
			CustomScanNode customScanNode = default(CustomScanNode);
			long created = DateTimeOffset.Now.ToUnixTimeMilliseconds();
			customScanNode.created = created;
			customScanNode.scanNode = val;
			customScanNode.owner = playerName;
			_scanNodes.AddLast(customScanNode);
			if ((Object)(object)_hudManager == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"HUDManager is null");
			}
			else if (customScanNode.owner == _mainPlayer.playerUsername)
			{
				_hudManager.UIAudio.PlayOneShot(_hudManager.scanSFX);
			}
			return customScanNode;
		}

		private bool hasPlayerPinged(string name)
		{
			for (LinkedListNode<CustomScanNode> linkedListNode = _scanNodes.First; linkedListNode != null; linkedListNode = linkedListNode.Next)
			{
				if (linkedListNode.Value.owner == name)
				{
					return true;
				}
			}
			return false;
		}

		private RaycastHit shootRay(float x, float y, float z)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: 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_0044: 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)
			float num = 2.5f;
			Transform transform = ((Component)_mainPlayer.gameplayCamera).transform;
			Vector3 val = transform.position + transform.forward * num;
			RaycastHit result = default(RaycastHit);
			Physics.Raycast(val, transform.forward, ref result, 1000f);
			return result;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "Pinger";

		public const string PLUGIN_NAME = "Pinger";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace Pinger.Overrider
{
	[HarmonyPatch(typeof(StartOfRound), "Awake")]
	internal class StartOfRound_Awake
	{
		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		private static bool Prefix()
		{
			Debug.Log((object)"StartOfRound.Awake() is called");
			return true;
		}
	}
	[HarmonyPatch]
	internal class KeyboardPing
	{
		private static float lastQPress;

		private const float PING_RESET = 0.3f;

		private static bool isWaiting;

		private static bool pingPressed;

		private static IEnumerator WaitForNextQ()
		{
			if (!isWaiting)
			{
				isWaiting = true;
				yield return (object)new WaitForSeconds(0.3f);
				if (!pingPressed)
				{
					Plugin.Instance.createPingWherePlayerIsLooking();
				}
				isWaiting = false;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void PingCommand(PlayerControllerB __instance)
		{
			long num = DateTimeOffset.Now.ToUnixTimeMilliseconds();
			bool flag = false;
			if (!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || __instance.inTerminalMenu || __instance.isTypingChat || __instance.isPlayerDead)
			{
				flag = true;
			}
			if (flag)
			{
				return;
			}
			if (((ButtonControl)Keyboard.current.qKey).wasPressedThisFrame)
			{
				if (!pingPressed)
				{
					pingPressed = true;
					((MonoBehaviour)__instance).StartCoroutine(WaitForNextQ());
				}
				else
				{
					bool flag2 = Plugin.Instance.createPingWherePlayerIsLooking(is_danger: true);
				}
			}
			else if (pingPressed)
			{
				lastQPress += Time.deltaTime;
				if (lastQPress >= 0.3f)
				{
					pingPressed = false;
					isWaiting = false;
					lastQPress = 0f;
				}
			}
		}
	}
}
namespace Pinger.CircleHelper
{
	public static class Helper
	{
		private const string TAG = "[Pinger::CircleHelper]";

		public static void debug_DisplayEntireComponentTree(Transform obj)
		{
			if ((Object)(object)obj == (Object)null)
			{
				return;
			}
			int childCount = obj.childCount;
			if (childCount > 0)
			{
				for (int i = 0; i < childCount; i++)
				{
					Transform child = obj.GetChild(i);
					Debug.Log((object)("[Pinger::CircleHelper]: " + ((Object)obj).name + "/" + ((Object)child).name));
					debug_DisplayComponent(obj);
					debug_DisplayEntireComponentTree(child);
				}
				Debug.Log((object)("EOF - " + ((Object)obj).name));
			}
		}

		private static void debug_DisplayComponent(Transform obj)
		{
			Debug.Log((object)string.Format("{0}: {1} :: typeof {2}", "[Pinger::CircleHelper]", ((Object)obj).name, ((object)obj).GetType()));
		}

		public static Transform debug_GrabInnerCircle(Transform obj)
		{
			if ((Object)(object)obj == (Object)null)
			{
				return null;
			}
			int childCount = obj.childCount;
			if (childCount <= 0)
			{
				return null;
			}
			Transform result = null;
			for (int i = 0; i < childCount; i++)
			{
				Transform child = obj.GetChild(i);
				if (((Object)child).name == "Inner")
				{
					result = child;
					break;
				}
			}
			return result;
		}
	}
}
namespace Pinger.Adder
{
	internal static class Adder
	{
		public static void AddToClass<T>(this T obj, Action action)
		{
			obj.GetType().GetMethod("AddToClass").Invoke(obj, new object[1] { action });
		}
	}
}

plugins/SecretLabs.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.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using SecretLabs.Patches;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SecretLabs")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("SecretLabs")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("SecretLabs")]
[assembly: AssemblyTitle("SecretLabs")]
[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 SecretLabs
{
	[Serializable]
	public class Config : SyncedInstance<Config>
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnRequestSync;

			public static HandleNamedMessageDelegate <1>__OnReceiveSync;
		}

		public bool customPriceEnabled;

		public int moonPrice;

		public Config(ConfigFile cfg)
		{
			InitInstance(this);
			customPriceEnabled = cfg.Bind<bool>("General", "CustomPriceEnabled", false, "Enable this if you wish to configure the moons route price below.").Value;
			moonPrice = cfg.Bind<int>("General", "MoonPrice", 700, "The route price of the Secret Labs moon.").Value;
		}

		public static void RequestSync()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<Config>.IsClient)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(SyncedInstance<Config>.IntSize, (Allocator)2, -1);
			try
			{
				SyncedInstance<Config>.MessageManager.SendNamedMessage("SecretLabs_OnRequestConfigSync", 0uL, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnRequestSync(ulong clientId, FastBufferReader _)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<Config>.IsHost)
			{
				return;
			}
			byte[] array = SyncedInstance<Config>.SerializeToBytes(SyncedInstance<Config>.Instance);
			int num = array.Length;
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(num + SyncedInstance<Config>.IntSize, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0);
				SyncedInstance<Config>.MessageManager.SendNamedMessage("SecretLabs_OnReceiveConfigSync", clientId, val, (NetworkDelivery)3);
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogDebug((object)$"Error occurred syncing config with client: {clientId}\n{arg}");
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnReceiveSync(ulong _, FastBufferReader reader)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<Config>.IntSize))
			{
				Plugin.Logger.LogError((object)"Config sync error: Could not begin reading buffer.");
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
			{
				Plugin.Logger.LogError((object)"Config sync error: Host could not sync.");
				return;
			}
			byte[] data = new byte[num];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
			SyncedInstance<Config>.SyncInstance(data);
			Plugin.Logger.LogDebug((object)"Successfully synced config with host.");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		public static void InitializeLocalPlayer()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			if (SyncedInstance<Config>.IsHost)
			{
				CustomMessagingManager messageManager = SyncedInstance<Config>.MessageManager;
				object obj = <>O.<0>__OnRequestSync;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = OnRequestSync;
					<>O.<0>__OnRequestSync = val;
					obj = (object)val;
				}
				messageManager.RegisterNamedMessageHandler("SecretLabs_OnRequestConfigSync", (HandleNamedMessageDelegate)obj);
				SyncedInstance<Config>.Synced = true;
				return;
			}
			SyncedInstance<Config>.Synced = false;
			CustomMessagingManager messageManager2 = SyncedInstance<Config>.MessageManager;
			object obj2 = <>O.<1>__OnReceiveSync;
			if (obj2 == null)
			{
				HandleNamedMessageDelegate val2 = OnReceiveSync;
				<>O.<1>__OnReceiveSync = val2;
				obj2 = (object)val2;
			}
			messageManager2.RegisterNamedMessageHandler("SecretLabs_OnReceiveConfigSync", (HandleNamedMessageDelegate)obj2);
			RequestSync();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		public static void PlayerLeave()
		{
			SyncedInstance<Config>.RevertSync();
		}
	}
	[Serializable]
	public class SyncedInstance<T>
	{
		[NonSerialized]
		protected static int IntSize = 4;

		internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;

		internal static bool IsClient => NetworkManager.Singleton.IsClient;

		internal static bool IsHost => NetworkManager.Singleton.IsHost;

		public static T Default { get; set; }

		public static T Instance { get; set; }

		public static bool Synced { get; internal set; }

		protected void InitInstance(T instance)
		{
			Default = instance;
			Instance = instance;
		}

		internal static void SyncInstance(byte[] data)
		{
			Instance = DeserializeFromBytes(data);
			Synced = true;
		}

		internal static void RevertSync()
		{
			Instance = Default;
			Synced = false;
		}

		public static byte[] SerializeToBytes(T val)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream memoryStream = new MemoryStream();
			try
			{
				binaryFormatter.Serialize(memoryStream, val);
				return memoryStream.ToArray();
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"Error serializing instance: {arg}");
				return null;
			}
		}

		public static T DeserializeFromBytes(byte[] data)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream serializationStream = new MemoryStream(data);
			try
			{
				return (T)binaryFormatter.Deserialize(serializationStream);
			}
			catch (Exception arg)
			{
				Plugin.Logger.LogError((object)$"Error deserializing instance: {arg}");
				return default(T);
			}
		}
	}
	[BepInPlugin("SecretLabs", "SecretLabs", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		public static ManualLogSource Logger;

		public static Config Config { get; internal set; }

		private void Awake()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			_harmony = new Harmony("SecretLabs");
			Config = new Config(((BaseUnityPlugin)this).Config);
			_harmony.PatchAll(typeof(RoutePatches));
			_harmony.PatchAll(typeof(Config));
			Logger.LogDebug((object)"Plugin SecretLabs is loaded!");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "SecretLabs";

		public const string PLUGIN_NAME = "SecretLabs";

		public const string PLUGIN_VERSION = "1.0.0";
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "SecretLabs";

		public const string PLUGIN_NAME = "SecretLabs";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace SecretLabs.Patches
{
	[HarmonyPatch(typeof(Terminal))]
	public class RoutePatches
	{
		[HarmonyPatch("LoadNewNode")]
		[HarmonyPrefix]
		private static void LoadNewNodePatchBefore(ref TerminalNode node)
		{
			if (!SyncedInstance<Config>.Instance.customPriceEnabled)
			{
				return;
			}
			Terminal obj = Object.FindObjectOfType<Terminal>();
			Plugin.Logger.LogDebug((object)((Object)node).name);
			CompatibleNoun[] compatibleNouns = obj.terminalNodes.allKeywords.First((TerminalKeyword terminalKeyword) => terminalKeyword.word == "route").compatibleNouns;
			foreach (CompatibleNoun val in compatibleNouns)
			{
				if (!((Object)(object)val.result == (Object)null) && ((Object)val.result).name == "secret labsRoute")
				{
					val.result.itemCost = SyncedInstance<Config>.Instance.moonPrice;
				}
			}
		}

		[HarmonyPatch("LoadNewNodeIfAffordable")]
		[HarmonyPrefix]
		private static void LoadNewNodeIfAffordablePatch(ref TerminalNode node)
		{
			if (SyncedInstance<Config>.Instance.customPriceEnabled)
			{
				Plugin.Logger.LogDebug((object)((Object)node).name);
				if (!((Object)(object)node == (Object)null) && !(((Object)node).name != "secret labsRouteConfirm"))
				{
					node.itemCost = Math.Abs(SyncedInstance<Config>.Instance.moonPrice);
				}
			}
		}
	}
}

plugins/SkinwalkerMod.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.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Dissonance;
using Dissonance.Config;
using HarmonyLib;
using SkinwalkerMod.Properties;
using Steamworks;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;
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("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
{
	internal class LogoManager : MonoBehaviour
	{
		private AssetBundle bundle;

		private readonly Logo[] logos = new Logo[6]
		{
			new Logo
			{
				fileName = "Teo",
				playerNames = new string[9] { "SAMMY", "paddy", "Ozias", "Teo", "Rugbug Redfern", "WuluKing", "Boolie", "TeaEditor", "FlashGamesNemesis" }
			},
			new Logo
			{
				fileName = "OfflineTV",
				playerNames = new string[3] { "Masayoshi", "QUARTERJADE", "DisguisedToast" }
			},
			new Logo
			{
				fileName = "Neuro",
				playerNames = new string[1] { "vedal" }
			},
			new Logo
			{
				fileName = "Mogul",
				playerNames = new string[2] { "ludwig", "AirCoots" }
			},
			new Logo
			{
				fileName = "Imp",
				playerNames = new string[1] { "camila" }
			},
			new Logo
			{
				fileName = "Iron",
				playerNames = new string[1] { "ironmouse" }
			}
		};

		private Image cachedHeader;

		private Image cachedLogoHeader;

		private void Awake()
		{
			try
			{
				bundle = AssetBundle.LoadFromMemory(Resources.logos);
				SceneManager.sceneLoaded += OnSceneLoaded;
			}
			catch (Exception ex)
			{
				SkinwalkerLogger.LogError("LogoManager Awake Error: " + ex.Message);
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			try
			{
				if (!(((Scene)(ref scene)).name == "MainMenu"))
				{
					return;
				}
				cachedHeader = GameObject.Find("HeaderImage").GetComponent<Image>();
				cachedLogoHeader = ((Component)GameObject.Find("Canvas/MenuContainer").transform.GetChild(0).GetChild(1)).GetComponent<Image>();
				string value = SteamClient.Name.ToString();
				Logo[] array = logos;
				foreach (Logo logo in array)
				{
					string[] playerNames = logo.playerNames;
					foreach (string text in playerNames)
					{
						if (text.Equals(value, StringComparison.OrdinalIgnoreCase))
						{
							((MonoBehaviour)this).StartCoroutine(I_ChangeLogo(bundle.LoadAsset<Sprite>("Assets/Logos/" + logo.fileName + ".png")));
							return;
						}
					}
				}
			}
			catch (Exception ex)
			{
				SkinwalkerLogger.LogError("LogoManager OnSceneLoaded Error: " + ex.Message + ". If you launched in LAN mode, then this is just gonna happen, it doesn't break anything so don't worry about it.");
			}
		}

		private IEnumerator I_ChangeLogo(Sprite sprite)
		{
			for (int i = 0; i < 20; i++)
			{
				if ((Object)(object)cachedHeader == (Object)null)
				{
					break;
				}
				if ((Object)(object)cachedLogoHeader == (Object)null)
				{
					break;
				}
				SetHeaderImage(sprite);
				yield return null;
			}
		}

		private void SetHeaderImage(Sprite sprite)
		{
			if (!((Object)(object)sprite == (Object)null))
			{
				cachedHeader.sprite = sprite;
				cachedLogoHeader.sprite = sprite;
			}
		}
	}
	internal class Logo
	{
		public string fileName;

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

		private const string modGUID = "RugbugRedfern.SkinwalkerMod";

		private const string modVersion = "2.0.7";

		private static bool initialized;

		public static PluginLoader Instance { get; private set; }

		private void Awake()
		{
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: 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 2.0.7");
			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);
			Logs.SetLogLevel((LogCategory)1, (LogLevel)4);
			Logs.SetLogLevel((LogCategory)3, (LogLevel)4);
			Logs.SetLogLevel((LogCategory)2, (LogLevel)4);
			GameObject val2 = new GameObject("Logo Manager");
			val2.AddComponent<LogoManager>();
			((Object)val2).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)val2);
		}

		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()
		{
			if (Time.time > nextTimeToPlayAudio)
			{
				SetNextTime();
				AttemptPlaySound();
			}
		}

		private void AttemptPlaySound()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: 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_0153: Unknown result type (might be due to invalid IL or missing references)
			float num = -1f;
			if (Object.op_Implicit((Object)(object)ai) && !ai.isEnemyDead)
			{
				if (((Object)((Component)ai).gameObject).name == "DressGirl(Clone)")
				{
					DressGirlAI val = (DressGirlAI)ai;
					if ((Object)(object)val.hauntingPlayer != (Object)(object)StartOfRound.Instance.localPlayerController)
					{
						SkinwalkerLogger.Log(((Object)this).name + " played voice line no (not haunted) EnemyAI: " + (object)ai);
						return;
					}
					if (!val.staringInHaunt && !((EnemyAI)val).moveTowardsDestination)
					{
						SkinwalkerLogger.Log(((Object)this).name + " played voice line no (not visible) EnemyAI: " + (object)ai);
						return;
					}
				}
				Vector3 val2 = (StartOfRound.Instance.localPlayerController.isPlayerDead ? ((Component)StartOfRound.Instance.spectateCamera).transform.position : ((Component)StartOfRound.Instance.localPlayerController).transform.position);
				if ((Object)(object)StartOfRound.Instance == (Object)null || (Object)(object)StartOfRound.Instance.localPlayerController == (Object)null || (num = Vector3.Distance(val2, ((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<bool> VoiceEnabled_OtherEnemies;

		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);
			PluginLoader.Instance.BindConfig(ref VoiceEnabled_OtherEnemies, "Monster Voices", "Other Enemies (Including Modded)", 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("VoiceEnabled_OtherEnemies" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_OtherEnemies.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, 
				_ => SkinwalkerNetworkManager.Instance.VoiceEnabled_OtherEnemies.Value, 
			};
		}

		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()
		{
			while (cachedAudio.Count > 200)
			{
				cachedAudio.RemoveAt(Random.Range(0, cachedAudio.Count));
			}
			if (cachedAudio.Count > 0)
			{
				int index = Random.Range(0, cachedAudio.Count - 1);
				AudioClip result = cachedAudio[index];
				cachedAudio.RemoveAt(index);
				return result;
			}
			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<bool> VoiceEnabled_OtherEnemies = 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;
				VoiceEnabled_OtherEnemies.Value = SkinwalkerConfig.VoiceEnabled_OtherEnemies.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 (VoiceEnabled_OtherEnemies == null)
			{
				throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_OtherEnemies cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)VoiceEnabled_OtherEnemies).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_OtherEnemies, "VoiceEnabled_OtherEnemies");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_OtherEnemies);
			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";
		}
	}
}
namespace SkinwalkerMod.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					ResourceManager resourceManager = new ResourceManager("SkinwalkerMod.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[] logos
		{
			get
			{
				object @object = ResourceManager.GetObject("logos", resourceCulture);
				return (byte[])@object;
			}
		}

		internal Resources()
		{
		}
	}
}

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.3")]
	public class YippeeModBase : BaseUnityPlugin
	{
		private const string modGUID = "sunnobunno.YippeeMod";

		private const string modName = "Yippee tbh mod";

		private const string modVersion = "1.2.3";

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