Decompiled source of ModpackFuerBuben v1.0.0

plugins/AinaVT-LethalConfig/LethalConfig/LethalConfig.dll

Decompiled 3 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LethalConfig.AutoConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using LethalConfig.Mods;
using LethalConfig.MonoBehaviours;
using LethalConfig.MonoBehaviours.Components;
using LethalConfig.MonoBehaviours.Managers;
using LethalConfig.Utils;
using Newtonsoft.Json;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.Serialization;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
[CompilerGenerated]
[EditorBrowsable(EditorBrowsableState.Never)]
[GeneratedCode("Unity.MonoScriptGenerator.MonoScriptInfoGenerator", null)]
internal class UnitySourceGeneratedAssemblyMonoScriptTypes_v1
{
	private struct MonoScriptData
	{
		public byte[] FilePathsData;

		public byte[] TypesData;

		public int TotalTypes;

		public int TotalFiles;

		public bool IsEditorOnly;
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	private static MonoScriptData Get()
	{
		MonoScriptData result = default(MonoScriptData);
		result.FilePathsData = new byte[3877]
		{
			0, 0, 0, 3, 0, 0, 0, 49, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 65, 117, 116, 111, 67, 111,
			110, 102, 105, 103, 92, 65, 117, 116, 111, 67,
			111, 110, 102, 105, 103, 71, 101, 110, 101, 114,
			97, 116, 111, 114, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 45, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 65, 117, 116, 111, 67, 111, 110, 102, 105,
			103, 92, 67, 111, 110, 102, 105, 103, 69, 110,
			116, 114, 121, 80, 97, 116, 104, 46, 99, 115,
			0, 0, 0, 2, 0, 0, 0, 45, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 115, 92, 66, 97, 115, 101,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			53, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 92, 66,
			111, 111, 108, 67, 104, 101, 99, 107, 66, 111,
			120, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 53, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 115, 92,
			69, 110, 117, 109, 68, 114, 111, 112, 68, 111,
			119, 110, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 56, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			92, 70, 108, 111, 97, 116, 73, 110, 112, 117,
			116, 70, 105, 101, 108, 100, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 52, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 115, 92, 70, 108, 111, 97, 116,
			83, 108, 105, 100, 101, 114, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 56, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 115, 92, 70, 108, 111, 97, 116,
			83, 116, 101, 112, 83, 108, 105, 100, 101, 114,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			54, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 92, 71,
			101, 110, 101, 114, 105, 99, 66, 117, 116, 116,
			111, 110, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 54, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			92, 73, 110, 116, 73, 110, 112, 117, 116, 70,
			105, 101, 108, 100, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 50, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 115, 92, 73, 110, 116, 83, 108, 105, 100,
			101, 114, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 50, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			92, 79, 112, 116, 105, 111, 110, 115, 92, 66,
			97, 115, 101, 79, 112, 116, 105, 111, 110, 115,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			55, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 92, 79,
			112, 116, 105, 111, 110, 115, 92, 66, 97, 115,
			101, 82, 97, 110, 103, 101, 79, 112, 116, 105,
			111, 110, 115, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 58, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			115, 92, 79, 112, 116, 105, 111, 110, 115, 92,
			66, 111, 111, 108, 67, 104, 101, 99, 107, 66,
			111, 120, 79, 112, 116, 105, 111, 110, 115, 46,
			99, 115, 0, 0, 0, 1, 0, 0, 0, 54,
			92, 65, 115, 115, 101, 116, 115, 92, 83, 99,
			114, 105, 112, 116, 115, 92, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 115, 92, 79, 112,
			116, 105, 111, 110, 115, 92, 67, 97, 110, 77,
			111, 100, 105, 102, 121, 82, 101, 115, 117, 108,
			116, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 58, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 115, 92,
			79, 112, 116, 105, 111, 110, 115, 92, 69, 110,
			117, 109, 68, 114, 111, 112, 68, 111, 119, 110,
			79, 112, 116, 105, 111, 110, 115, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 61, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 115, 92, 79, 112, 116, 105,
			111, 110, 115, 92, 70, 108, 111, 97, 116, 73,
			110, 112, 117, 116, 70, 105, 101, 108, 100, 79,
			112, 116, 105, 111, 110, 115, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 57, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 115, 92, 79, 112, 116, 105, 111,
			110, 115, 92, 70, 108, 111, 97, 116, 83, 108,
			105, 100, 101, 114, 79, 112, 116, 105, 111, 110,
			115, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 61, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 115, 92,
			79, 112, 116, 105, 111, 110, 115, 92, 70, 108,
			111, 97, 116, 83, 116, 101, 112, 83, 108, 105,
			100, 101, 114, 79, 112, 116, 105, 111, 110, 115,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			59, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 92, 79,
			112, 116, 105, 111, 110, 115, 92, 71, 101, 110,
			101, 114, 105, 99, 66, 117, 116, 116, 111, 110,
			79, 112, 116, 105, 111, 110, 115, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 59, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 115, 92, 79, 112, 116, 105,
			111, 110, 115, 92, 73, 110, 116, 73, 110, 112,
			117, 116, 70, 105, 101, 108, 100, 79, 112, 116,
			105, 111, 110, 115, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 55, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 115, 92, 79, 112, 116, 105, 111, 110, 115,
			92, 73, 110, 116, 83, 108, 105, 100, 101, 114,
			79, 112, 116, 105, 111, 110, 115, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 58, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 115, 92, 79, 112, 116, 105,
			111, 110, 115, 92, 84, 101, 120, 116, 68, 114,
			111, 112, 68, 111, 119, 110, 79, 112, 116, 105,
			111, 110, 115, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 60, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			115, 92, 79, 112, 116, 105, 111, 110, 115, 92,
			84, 101, 120, 116, 73, 110, 112, 117, 116, 70,
			105, 101, 108, 100, 79, 112, 116, 105, 111, 110,
			115, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 53, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 115, 92,
			84, 101, 120, 116, 68, 114, 111, 112, 68, 111,
			119, 110, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 55, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			92, 84, 101, 120, 116, 73, 110, 112, 117, 116,
			70, 105, 101, 108, 100, 67, 111, 110, 102, 105,
			103, 73, 116, 101, 109, 46, 99, 115, 0, 0,
			0, 1, 0, 0, 0, 26, 92, 65, 115, 115,
			101, 116, 115, 92, 83, 99, 114, 105, 112, 116,
			115, 92, 67, 111, 110, 102, 105, 103, 115, 46,
			99, 115, 0, 0, 0, 1, 0, 0, 0, 38,
			92, 65, 115, 115, 101, 116, 115, 92, 83, 99,
			114, 105, 112, 116, 115, 92, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 77, 97,
			110, 97, 103, 101, 114, 46, 99, 115, 0, 0,
			0, 2, 0, 0, 0, 37, 92, 65, 115, 115,
			101, 116, 115, 92, 83, 99, 114, 105, 112, 116,
			115, 92, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 80, 108, 117, 103, 105, 110,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			27, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 77, 111, 100,
			115, 92, 77, 111, 100, 46, 99, 115, 0, 0,
			0, 1, 0, 0, 0, 31, 92, 65, 115, 115,
			101, 116, 115, 92, 83, 99, 114, 105, 112, 116,
			115, 92, 77, 111, 100, 115, 92, 77, 111, 100,
			73, 110, 102, 111, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 44, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 77, 111, 100, 115, 92, 84, 104, 117, 110,
			100, 101, 114, 115, 116, 111, 114, 101, 77, 97,
			110, 105, 102, 101, 115, 116, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 67, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 77, 111, 110, 111, 66, 101, 104,
			97, 118, 105, 111, 117, 114, 115, 92, 67, 111,
			109, 112, 111, 110, 101, 110, 116, 115, 92, 66,
			111, 111, 108, 67, 104, 101, 99, 107, 66, 111,
			120, 67, 111, 110, 116, 114, 111, 108, 108, 101,
			114, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 67, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 77, 111,
			110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
			114, 115, 92, 67, 111, 109, 112, 111, 110, 101,
			110, 116, 115, 92, 69, 110, 117, 109, 68, 114,
			111, 112, 68, 111, 119, 110, 67, 111, 110, 116,
			114, 111, 108, 108, 101, 114, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 70, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 77, 111, 110, 111, 66, 101, 104,
			97, 118, 105, 111, 117, 114, 115, 92, 67, 111,
			109, 112, 111, 110, 101, 110, 116, 115, 92, 70,
			108, 111, 97, 116, 73, 110, 112, 117, 116, 70,
			105, 101, 108, 100, 67, 111, 110, 116, 114, 111,
			108, 108, 101, 114, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 66, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 92, 67, 111, 109, 112,
			111, 110, 101, 110, 116, 115, 92, 70, 108, 111,
			97, 116, 83, 108, 105, 100, 101, 114, 67, 111,
			110, 116, 114, 111, 108, 108, 101, 114, 46, 99,
			115, 0, 0, 0, 1, 0, 0, 0, 70, 92,
			65, 115, 115, 101, 116, 115, 92, 83, 99, 114,
			105, 112, 116, 115, 92, 77, 111, 110, 111, 66,
			101, 104, 97, 118, 105, 111, 117, 114, 115, 92,
			67, 111, 109, 112, 111, 110, 101, 110, 116, 115,
			92, 70, 108, 111, 97, 116, 83, 116, 101, 112,
			83, 108, 105, 100, 101, 114, 67, 111, 110, 116,
			114, 111, 108, 108, 101, 114, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 68, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 77, 111, 110, 111, 66, 101, 104,
			97, 118, 105, 111, 117, 114, 115, 92, 67, 111,
			109, 112, 111, 110, 101, 110, 116, 115, 92, 71,
			101, 110, 101, 114, 105, 99, 66, 117, 116, 116,
			111, 110, 67, 111, 110, 116, 114, 111, 108, 108,
			101, 114, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 68, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 77,
			111, 110, 111, 66, 101, 104, 97, 118, 105, 111,
			117, 114, 115, 92, 67, 111, 109, 112, 111, 110,
			101, 110, 116, 115, 92, 73, 110, 116, 73, 110,
			112, 117, 116, 70, 105, 101, 108, 100, 67, 111,
			110, 116, 114, 111, 108, 108, 101, 114, 46, 99,
			115, 0, 0, 0, 1, 0, 0, 0, 64, 92,
			65, 115, 115, 101, 116, 115, 92, 83, 99, 114,
			105, 112, 116, 115, 92, 77, 111, 110, 111, 66,
			101, 104, 97, 118, 105, 111, 117, 114, 115, 92,
			67, 111, 109, 112, 111, 110, 101, 110, 116, 115,
			92, 73, 110, 116, 83, 108, 105, 100, 101, 114,
			67, 111, 110, 116, 114, 111, 108, 108, 101, 114,
			46, 99, 115, 0, 0, 0, 2, 0, 0, 0,
			64, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 77, 111, 110,
			111, 66, 101, 104, 97, 118, 105, 111, 117, 114,
			115, 92, 67, 111, 109, 112, 111, 110, 101, 110,
			116, 115, 92, 77, 111, 100, 67, 111, 110, 102,
			105, 103, 67, 111, 110, 116, 114, 111, 108, 108,
			101, 114, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 67, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 77,
			111, 110, 111, 66, 101, 104, 97, 118, 105, 111,
			117, 114, 115, 92, 67, 111, 109, 112, 111, 110,
			101, 110, 116, 115, 92, 84, 101, 120, 116, 68,
			114, 111, 112, 68, 111, 119, 110, 67, 111, 110,
			116, 114, 111, 108, 108, 101, 114, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 69, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 92, 67,
			111, 109, 112, 111, 110, 101, 110, 116, 115, 92,
			84, 101, 120, 116, 73, 110, 112, 117, 116, 70,
			105, 101, 108, 100, 67, 111, 110, 116, 114, 111,
			108, 108, 101, 114, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 47, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 92, 67, 111, 110, 102,
			105, 103, 73, 110, 102, 111, 66, 111, 120, 46,
			99, 115, 0, 0, 0, 1, 0, 0, 0, 44,
			92, 65, 115, 115, 101, 116, 115, 92, 83, 99,
			114, 105, 112, 116, 115, 92, 77, 111, 110, 111,
			66, 101, 104, 97, 118, 105, 111, 117, 114, 115,
			92, 67, 111, 110, 102, 105, 103, 76, 105, 115,
			116, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 44, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 77, 111,
			110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
			114, 115, 92, 67, 111, 110, 102, 105, 103, 77,
			101, 110, 117, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 56, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			77, 111, 110, 111, 66, 101, 104, 97, 118, 105,
			111, 117, 114, 115, 92, 67, 111, 110, 102, 105,
			103, 77, 101, 110, 117, 78, 111, 116, 105, 102,
			105, 99, 97, 116, 105, 111, 110, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 48, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 92, 68,
			101, 115, 99, 114, 105, 112, 116, 105, 111, 110,
			66, 111, 120, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 65, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			77, 111, 110, 111, 66, 101, 104, 97, 118, 105,
			111, 117, 114, 115, 92, 77, 97, 110, 97, 103,
			101, 114, 115, 92, 67, 111, 110, 102, 105, 103,
			77, 101, 110, 117, 65, 117, 100, 105, 111, 77,
			97, 110, 97, 103, 101, 114, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 60, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 77, 111, 110, 111, 66, 101, 104,
			97, 118, 105, 111, 117, 114, 115, 92, 77, 97,
			110, 97, 103, 101, 114, 115, 92, 67, 111, 110,
			102, 105, 103, 77, 101, 110, 117, 77, 97, 110,
			97, 103, 101, 114, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 44, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 92, 77, 111, 100, 73,
			110, 102, 111, 66, 111, 120, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 41, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 77, 111, 110, 111, 66, 101, 104,
			97, 118, 105, 111, 117, 114, 115, 92, 77, 111,
			100, 76, 105, 115, 116, 46, 99, 115, 0, 0,
			0, 1, 0, 0, 0, 45, 92, 65, 115, 115,
			101, 116, 115, 92, 83, 99, 114, 105, 112, 116,
			115, 92, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 92, 77, 111, 100,
			76, 105, 115, 116, 73, 116, 101, 109, 46, 99,
			115, 0, 0, 0, 1, 0, 0, 0, 47, 92,
			65, 115, 115, 101, 116, 115, 92, 83, 99, 114,
			105, 112, 116, 115, 92, 77, 111, 110, 111, 66,
			101, 104, 97, 118, 105, 111, 117, 114, 115, 92,
			83, 101, 99, 116, 105, 111, 110, 72, 101, 97,
			100, 101, 114, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 41, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			77, 111, 110, 111, 66, 101, 104, 97, 118, 105,
			111, 117, 114, 115, 92, 84, 111, 111, 108, 116,
			105, 112, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 47, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 77,
			111, 110, 111, 66, 101, 104, 97, 118, 105, 111,
			117, 114, 115, 92, 84, 111, 111, 108, 116, 105,
			112, 83, 121, 115, 116, 101, 109, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 48, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 92, 84,
			111, 111, 108, 116, 105, 112, 84, 114, 105, 103,
			103, 101, 114, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 46, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			77, 111, 110, 111, 66, 101, 104, 97, 118, 105,
			111, 117, 114, 115, 92, 86, 101, 114, 115, 105,
			111, 110, 76, 97, 98, 101, 108, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 45, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 80, 97, 116, 99, 104, 101,
			115, 92, 77, 101, 110, 117, 77, 97, 110, 97,
			103, 101, 114, 80, 97, 116, 99, 104, 101, 115,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			50, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 80, 97, 116,
			99, 104, 101, 115, 92, 81, 117, 105, 99, 107,
			77, 101, 110, 117, 77, 97, 110, 97, 103, 101,
			114, 80, 97, 116, 99, 104, 101, 115, 46, 99,
			115, 0, 0, 0, 1, 0, 0, 0, 43, 92,
			65, 115, 115, 101, 116, 115, 92, 83, 99, 114,
			105, 112, 116, 115, 92, 85, 116, 105, 108, 115,
			92, 65, 115, 115, 101, 109, 98, 108, 121, 69,
			120, 116, 101, 110, 115, 105, 111, 110, 115, 46,
			99, 115, 0, 0, 0, 1, 0, 0, 0, 31,
			92, 65, 115, 115, 101, 116, 115, 92, 83, 99,
			114, 105, 112, 116, 115, 92, 85, 116, 105, 108,
			115, 92, 65, 115, 115, 101, 116, 115, 46, 99,
			115, 0, 0, 0, 1, 0, 0, 0, 33, 92,
			65, 115, 115, 101, 116, 115, 92, 83, 99, 114,
			105, 112, 116, 115, 92, 85, 116, 105, 108, 115,
			92, 76, 111, 103, 85, 116, 105, 108, 115, 46,
			99, 115, 0, 0, 0, 1, 0, 0, 0, 35,
			92, 65, 115, 115, 101, 116, 115, 92, 83, 99,
			114, 105, 112, 116, 115, 92, 85, 116, 105, 108,
			115, 92, 77, 101, 110, 117, 115, 85, 116, 105,
			108, 115, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 34, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 85,
			116, 105, 108, 115, 92, 80, 97, 116, 104, 85,
			116, 105, 108, 115, 46, 99, 115
		};
		result.TypesData = new byte[3566]
		{
			0, 0, 0, 0, 43, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 46, 65, 117,
			116, 111, 67, 111, 110, 102, 105, 103, 124, 65,
			117, 116, 111, 67, 111, 110, 102, 105, 103, 71,
			101, 110, 101, 114, 97, 116, 111, 114, 0, 0,
			0, 0, 58, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 65, 117, 116, 111,
			67, 111, 110, 102, 105, 103, 46, 65, 117, 116,
			111, 67, 111, 110, 102, 105, 103, 71, 101, 110,
			101, 114, 97, 116, 111, 114, 124, 65, 117, 116,
			111, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 0, 0, 0, 0, 66, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 65,
			117, 116, 111, 67, 111, 110, 102, 105, 103, 46,
			65, 117, 116, 111, 67, 111, 110, 102, 105, 103,
			71, 101, 110, 101, 114, 97, 116, 111, 114, 124,
			67, 111, 110, 102, 105, 103, 70, 105, 108, 101,
			65, 115, 115, 101, 109, 98, 108, 121, 80, 97,
			105, 114, 0, 0, 0, 0, 39, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			65, 117, 116, 111, 67, 111, 110, 102, 105, 103,
			124, 67, 111, 110, 102, 105, 103, 69, 110, 116,
			114, 121, 80, 97, 116, 104, 0, 0, 0, 0,
			39, 76, 101, 116, 104, 97, 108, 67, 111, 110,
			102, 105, 103, 46, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 115, 124, 66, 97, 115, 101,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			0, 0, 0, 0, 44, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 46, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 115, 124,
			66, 97, 115, 101, 86, 97, 108, 117, 101, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 0,
			0, 0, 0, 47, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 124, 66,
			111, 111, 108, 67, 104, 101, 99, 107, 66, 111,
			120, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 0, 0, 0, 0, 47, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			124, 69, 110, 117, 109, 68, 114, 111, 112, 68,
			111, 119, 110, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 0, 0, 0, 0, 50, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 115, 124, 70, 108, 111, 97, 116, 73, 110,
			112, 117, 116, 70, 105, 101, 108, 100, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 0, 0,
			0, 0, 46, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 115, 124, 70, 108,
			111, 97, 116, 83, 108, 105, 100, 101, 114, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 0,
			0, 0, 0, 50, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 124, 70,
			108, 111, 97, 116, 83, 116, 101, 112, 83, 108,
			105, 100, 101, 114, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 0, 0, 0, 0, 48, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 115, 124, 71, 101, 110, 101, 114, 105,
			99, 66, 117, 116, 116, 111, 110, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 0, 0, 0,
			0, 48, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 46, 67, 111, 110, 102, 105,
			103, 73, 116, 101, 109, 115, 124, 73, 110, 116,
			73, 110, 112, 117, 116, 70, 105, 101, 108, 100,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			0, 0, 0, 0, 44, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 46, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 115, 124,
			73, 110, 116, 83, 108, 105, 100, 101, 114, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 0,
			0, 0, 0, 44, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 46, 79,
			112, 116, 105, 111, 110, 115, 124, 66, 97, 115,
			101, 79, 112, 116, 105, 111, 110, 115, 0, 0,
			0, 0, 49, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 115, 46, 79, 112,
			116, 105, 111, 110, 115, 124, 66, 97, 115, 101,
			82, 97, 110, 103, 101, 79, 112, 116, 105, 111,
			110, 115, 0, 0, 0, 0, 52, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			115, 46, 79, 112, 116, 105, 111, 110, 115, 124,
			66, 111, 111, 108, 67, 104, 101, 99, 107, 66,
			111, 120, 79, 112, 116, 105, 111, 110, 115, 0,
			0, 0, 0, 48, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 46, 79,
			112, 116, 105, 111, 110, 115, 124, 67, 97, 110,
			77, 111, 100, 105, 102, 121, 82, 101, 115, 117,
			108, 116, 0, 0, 0, 0, 52, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			115, 46, 79, 112, 116, 105, 111, 110, 115, 124,
			69, 110, 117, 109, 68, 114, 111, 112, 68, 111,
			119, 110, 79, 112, 116, 105, 111, 110, 115, 0,
			0, 0, 0, 55, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 46, 79,
			112, 116, 105, 111, 110, 115, 124, 70, 108, 111,
			97, 116, 73, 110, 112, 117, 116, 70, 105, 101,
			108, 100, 79, 112, 116, 105, 111, 110, 115, 0,
			0, 0, 0, 51, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 46, 79,
			112, 116, 105, 111, 110, 115, 124, 70, 108, 111,
			97, 116, 83, 108, 105, 100, 101, 114, 79, 112,
			116, 105, 111, 110, 115, 0, 0, 0, 0, 55,
			76, 101, 116, 104, 97, 108, 67, 111, 110, 102,
			105, 103, 46, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 115, 46, 79, 112, 116, 105, 111,
			110, 115, 124, 70, 108, 111, 97, 116, 83, 116,
			101, 112, 83, 108, 105, 100, 101, 114, 79, 112,
			116, 105, 111, 110, 115, 0, 0, 0, 0, 53,
			76, 101, 116, 104, 97, 108, 67, 111, 110, 102,
			105, 103, 46, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 115, 46, 79, 112, 116, 105, 111,
			110, 115, 124, 71, 101, 110, 101, 114, 105, 99,
			66, 117, 116, 116, 111, 110, 79, 112, 116, 105,
			111, 110, 115, 0, 0, 0, 0, 53, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 115, 46, 79, 112, 116, 105, 111, 110, 115,
			124, 73, 110, 116, 73, 110, 112, 117, 116, 70,
			105, 101, 108, 100, 79, 112, 116, 105, 111, 110,
			115, 0, 0, 0, 0, 49, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			46, 79, 112, 116, 105, 111, 110, 115, 124, 73,
			110, 116, 83, 108, 105, 100, 101, 114, 79, 112,
			116, 105, 111, 110, 115, 0, 0, 0, 0, 52,
			76, 101, 116, 104, 97, 108, 67, 111, 110, 102,
			105, 103, 46, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 115, 46, 79, 112, 116, 105, 111,
			110, 115, 124, 84, 101, 120, 116, 68, 114, 111,
			112, 68, 111, 119, 110, 79, 112, 116, 105, 111,
			110, 115, 0, 0, 0, 0, 54, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			115, 46, 79, 112, 116, 105, 111, 110, 115, 124,
			84, 101, 120, 116, 73, 110, 112, 117, 116, 70,
			105, 101, 108, 100, 79, 112, 116, 105, 111, 110,
			115, 0, 0, 0, 0, 47, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			124, 84, 101, 120, 116, 68, 114, 111, 112, 68,
			111, 119, 110, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 0, 0, 0, 0, 49, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 115, 124, 84, 101, 120, 116, 73, 110, 112,
			117, 116, 70, 105, 101, 108, 100, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 0, 0, 0,
			0, 20, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 124, 67, 111, 110, 102, 105,
			103, 115, 0, 0, 0, 0, 32, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 124,
			76, 101, 116, 104, 97, 108, 67, 111, 110, 102,
			105, 103, 77, 97, 110, 97, 103, 101, 114, 0,
			0, 0, 0, 23, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 124, 80, 108, 117,
			103, 105, 110, 73, 110, 102, 111, 0, 0, 0,
			0, 31, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 124, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 80, 108, 117,
			103, 105, 110, 0, 0, 0, 0, 21, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 77, 111, 100, 115, 124, 77, 111, 100, 0,
			0, 0, 0, 25, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 77, 111, 100,
			115, 124, 77, 111, 100, 73, 110, 102, 111, 0,
			0, 0, 0, 38, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 77, 111, 100,
			115, 124, 84, 104, 117, 110, 100, 101, 114, 115,
			116, 111, 114, 101, 77, 97, 110, 105, 102, 101,
			115, 116, 0, 0, 0, 0, 61, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			77, 111, 110, 111, 66, 101, 104, 97, 118, 105,
			111, 117, 114, 115, 46, 67, 111, 109, 112, 111,
			110, 101, 110, 116, 115, 124, 66, 111, 111, 108,
			67, 104, 101, 99, 107, 66, 111, 120, 67, 111,
			110, 116, 114, 111, 108, 108, 101, 114, 0, 0,
			0, 0, 61, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 77, 111, 110, 111,
			66, 101, 104, 97, 118, 105, 111, 117, 114, 115,
			46, 67, 111, 109, 112, 111, 110, 101, 110, 116,
			115, 124, 69, 110, 117, 109, 68, 114, 111, 112,
			68, 111, 119, 110, 67, 111, 110, 116, 114, 111,
			108, 108, 101, 114, 0, 0, 0, 0, 64, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 46, 67, 111, 109,
			112, 111, 110, 101, 110, 116, 115, 124, 70, 108,
			111, 97, 116, 73, 110, 112, 117, 116, 70, 105,
			101, 108, 100, 67, 111, 110, 116, 114, 111, 108,
			108, 101, 114, 0, 0, 0, 0, 60, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 46, 67, 111, 109, 112,
			111, 110, 101, 110, 116, 115, 124, 70, 108, 111,
			97, 116, 83, 108, 105, 100, 101, 114, 67, 111,
			110, 116, 114, 111, 108, 108, 101, 114, 0, 0,
			0, 0, 64, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 77, 111, 110, 111,
			66, 101, 104, 97, 118, 105, 111, 117, 114, 115,
			46, 67, 111, 109, 112, 111, 110, 101, 110, 116,
			115, 124, 70, 108, 111, 97, 116, 83, 116, 101,
			112, 83, 108, 105, 100, 101, 114, 67, 111, 110,
			116, 114, 111, 108, 108, 101, 114, 0, 0, 0,
			0, 62, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 46, 77, 111, 110, 111, 66,
			101, 104, 97, 118, 105, 111, 117, 114, 115, 46,
			67, 111, 109, 112, 111, 110, 101, 110, 116, 115,
			124, 71, 101, 110, 101, 114, 105, 99, 66, 117,
			116, 116, 111, 110, 67, 111, 110, 116, 114, 111,
			108, 108, 101, 114, 0, 0, 0, 0, 62, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 46, 67, 111, 109,
			112, 111, 110, 101, 110, 116, 115, 124, 73, 110,
			116, 73, 110, 112, 117, 116, 70, 105, 101, 108,
			100, 67, 111, 110, 116, 114, 111, 108, 108, 101,
			114, 0, 0, 0, 0, 58, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 77,
			111, 110, 111, 66, 101, 104, 97, 118, 105, 111,
			117, 114, 115, 46, 67, 111, 109, 112, 111, 110,
			101, 110, 116, 115, 124, 73, 110, 116, 83, 108,
			105, 100, 101, 114, 67, 111, 110, 116, 114, 111,
			108, 108, 101, 114, 1, 0, 0, 0, 58, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 46, 67, 111, 109,
			112, 111, 110, 101, 110, 116, 115, 124, 77, 111,
			100, 67, 111, 110, 102, 105, 103, 67, 111, 110,
			116, 114, 111, 108, 108, 101, 114, 1, 0, 0,
			0, 58, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 46, 77, 111, 110, 111, 66,
			101, 104, 97, 118, 105, 111, 117, 114, 115, 46,
			67, 111, 109, 112, 111, 110, 101, 110, 116, 115,
			124, 77, 111, 100, 67, 111, 110, 102, 105, 103,
			67, 111, 110, 116, 114, 111, 108, 108, 101, 114,
			0, 0, 0, 0, 61, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 46, 77, 111,
			110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
			114, 115, 46, 67, 111, 109, 112, 111, 110, 101,
			110, 116, 115, 124, 84, 101, 120, 116, 68, 114,
			111, 112, 68, 111, 119, 110, 67, 111, 110, 116,
			114, 111, 108, 108, 101, 114, 0, 0, 0, 0,
			63, 76, 101, 116, 104, 97, 108, 67, 111, 110,
			102, 105, 103, 46, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 46, 67,
			111, 109, 112, 111, 110, 101, 110, 116, 115, 124,
			84, 101, 120, 116, 73, 110, 112, 117, 116, 70,
			105, 101, 108, 100, 67, 111, 110, 116, 114, 111,
			108, 108, 101, 114, 0, 0, 0, 0, 41, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 124, 67, 111, 110,
			102, 105, 103, 73, 110, 102, 111, 66, 111, 120,
			0, 0, 0, 0, 38, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 46, 77, 111,
			110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
			114, 115, 124, 67, 111, 110, 102, 105, 103, 76,
			105, 115, 116, 0, 0, 0, 0, 38, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 124, 67, 111, 110, 102,
			105, 103, 77, 101, 110, 117, 0, 0, 0, 0,
			50, 76, 101, 116, 104, 97, 108, 67, 111, 110,
			102, 105, 103, 46, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 124, 67,
			111, 110, 102, 105, 103, 77, 101, 110, 117, 78,
			111, 116, 105, 102, 105, 99, 97, 116, 105, 111,
			110, 0, 0, 0, 0, 42, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 77,
			111, 110, 111, 66, 101, 104, 97, 118, 105, 111,
			117, 114, 115, 124, 68, 101, 115, 99, 114, 105,
			112, 116, 105, 111, 110, 66, 111, 120, 0, 0,
			0, 0, 59, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 77, 111, 110, 111,
			66, 101, 104, 97, 118, 105, 111, 117, 114, 115,
			46, 77, 97, 110, 97, 103, 101, 114, 115, 124,
			67, 111, 110, 102, 105, 103, 77, 101, 110, 117,
			65, 117, 100, 105, 111, 77, 97, 110, 97, 103,
			101, 114, 0, 0, 0, 0, 54, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			77, 111, 110, 111, 66, 101, 104, 97, 118, 105,
			111, 117, 114, 115, 46, 77, 97, 110, 97, 103,
			101, 114, 115, 124, 67, 111, 110, 102, 105, 103,
			77, 101, 110, 117, 77, 97, 110, 97, 103, 101,
			114, 0, 0, 0, 0, 38, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 77,
			111, 110, 111, 66, 101, 104, 97, 118, 105, 111,
			117, 114, 115, 124, 77, 111, 100, 73, 110, 102,
			111, 66, 111, 120, 0, 0, 0, 0, 35, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 124, 77, 111, 100,
			76, 105, 115, 116, 0, 0, 0, 0, 39, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 124, 77, 111, 100,
			76, 105, 115, 116, 73, 116, 101, 109, 0, 0,
			0, 0, 41, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 77, 111, 110, 111,
			66, 101, 104, 97, 118, 105, 111, 117, 114, 115,
			124, 83, 101, 99, 116, 105, 111, 110, 72, 101,
			97, 100, 101, 114, 0, 0, 0, 0, 35, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 124, 84, 111, 111,
			108, 116, 105, 112, 0, 0, 0, 0, 41, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 124, 84, 111, 111,
			108, 116, 105, 112, 83, 121, 115, 116, 101, 109,
			0, 0, 0, 0, 42, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 46, 77, 111,
			110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
			114, 115, 124, 84, 111, 111, 108, 116, 105, 112,
			84, 114, 105, 103, 103, 101, 114, 0, 0, 0,
			0, 40, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 46, 77, 111, 110, 111, 66,
			101, 104, 97, 118, 105, 111, 117, 114, 115, 124,
			86, 101, 114, 115, 105, 111, 110, 76, 97, 98,
			101, 108, 0, 0, 0, 0, 39, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			80, 97, 116, 99, 104, 101, 115, 124, 77, 101,
			110, 117, 77, 97, 110, 97, 103, 101, 114, 80,
			97, 116, 99, 104, 101, 115, 0, 0, 0, 0,
			44, 76, 101, 116, 104, 97, 108, 67, 111, 110,
			102, 105, 103, 46, 80, 97, 116, 99, 104, 101,
			115, 124, 81, 117, 105, 99, 107, 77, 101, 110,
			117, 77, 97, 110, 97, 103, 101, 114, 80, 97,
			116, 99, 104, 101, 115, 0, 0, 0, 0, 37,
			76, 101, 116, 104, 97, 108, 67, 111, 110, 102,
			105, 103, 46, 85, 116, 105, 108, 115, 124, 65,
			115, 115, 101, 109, 98, 108, 121, 69, 120, 116,
			101, 110, 115, 105, 111, 110, 115, 0, 0, 0,
			0, 25, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 46, 85, 116, 105, 108, 115,
			124, 65, 115, 115, 101, 116, 115, 0, 0, 0,
			0, 27, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 46, 85, 116, 105, 108, 115,
			124, 76, 111, 103, 85, 116, 105, 108, 115, 0,
			0, 0, 0, 29, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 85, 116, 105,
			108, 115, 124, 77, 101, 110, 117, 115, 85, 116,
			105, 108, 115, 0, 0, 0, 0, 28, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 85, 116, 105, 108, 115, 124, 80, 97, 116,
			104, 85, 116, 105, 108, 115
		};
		result.TotalFiles = 65;
		result.TotalTypes = 70;
		result.IsEditorOnly = false;
		return result;
	}
}
namespace LethalConfig
{
	internal static class Configs
	{
		private enum TestEnum
		{
			None,
			First,
			Second
		}

		internal static ConfigEntry<bool> IsLethalConfigHidden { get; private set; }

		internal static void Initialize(ConfigFile config)
		{
			CreateConfigs(config);
			CreateExampleConfigs(config);
		}

		private static void CreateConfigs(ConfigFile config)
		{
			IsLethalConfigHidden = config.Bind<bool>("General", "Hide Lethal Config", false, "Hides the LethalConfig menu in the game. This setting will not show up in LethalConfig itself.");
			LethalConfigManager.SkipAutoGenFor((ConfigEntryBase)(object)IsLethalConfigHidden);
		}

		private static void CreateExampleConfigs(ConfigFile config)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: 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_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Expected O, but got Unknown
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			ConfigEntry<int> configEntry = config.Bind<int>("Example", "Int Slider", 30, new ConfigDescription("This is an integer slider. You can also type a value in the input field to the right of the slider.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			ConfigEntry<float> configEntry2 = config.Bind<float>("Example", "Float Slider", 0f, new ConfigDescription("This is a float slider. You can also type a value in the input field to the right of the slider.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-1f, 1f), Array.Empty<object>()));
			ConfigEntry<float> configEntry3 = config.Bind<float>("Example", "Float Step Slider", 0f, new ConfigDescription("This is a float step slider. It set values in increments. You can also type a value in the input field to the right of the slider.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-1f, 1f), Array.Empty<object>()));
			ConfigEntry<bool> configEntry4 = config.Bind<bool>("Example", "Bool Checkbox", false, new ConfigDescription("This is a bool checkbox.", (AcceptableValueBase)null, Array.Empty<object>()));
			ConfigEntry<TestEnum> configEntry5 = config.Bind<TestEnum>("Example", "Enum Dropdown", TestEnum.None, new ConfigDescription("This is a enum dropdown.", (AcceptableValueBase)null, Array.Empty<object>()));
			ConfigEntry<string> configEntry6 = config.Bind<string>("Example", "Text Input", "Example", "This is a text input field. It can have a limit of characters too.");
			ConfigEntry<string> configEntry7 = config.Bind<string>("Example", "Multiline Text Input", "Example", "This is a text input field. It can have a limit of characters too.");
			ConfigEntry<string> configEntry8 = config.Bind<string>("Example", "Text Input Dropdown", "Two", new ConfigDescription("This is a text input with an acceptable value list.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "One", "Two", "HL:Alyx" }), Array.Empty<object>()));
			ConfigEntry<int> configEntry9 = config.Bind<int>("Example", "Int Input", 50, "This is an integer input field.");
			ConfigEntry<float> configEntry10 = config.Bind<float>("Example", "Float Input", 0.5f, "This is a float input field.");
			LethalConfigManager.AddConfigItem(new IntSliderConfigItem(configEntry, requiresRestart: false));
			LethalConfigManager.AddConfigItem(new FloatSliderConfigItem(configEntry2, requiresRestart: false));
			LethalConfigManager.AddConfigItem(new FloatStepSliderConfigItem(configEntry3, new FloatStepSliderOptions
			{
				Step = 0.1f,
				RequiresRestart = false,
				Min = -1f,
				Max = 1f
			}));
			LethalConfigManager.AddConfigItem(new BoolCheckBoxConfigItem(configEntry4, requiresRestart: false));
			LethalConfigManager.AddConfigItem(new EnumDropDownConfigItem<TestEnum>(configEntry5, requiresRestart: false));
			LethalConfigManager.AddConfigItem(new TextInputFieldConfigItem(configEntry6, requiresRestart: false));
			LethalConfigManager.AddConfigItem(new TextInputFieldConfigItem(configEntry7, new TextInputFieldOptions
			{
				NumberOfLines = 0,
				TrimText = true
			}));
			LethalConfigManager.AddConfigItem(new GenericButtonConfigItem("Example", "Button", "This is a test button with a callback", "Open", delegate
			{
				if (Object.op_Implicit((Object)(object)ConfigMenuManager.Instance))
				{
					ConfigMenuManager.DisplayNotification("This is a test notification", "OK");
				}
			}));
			LethalConfigManager.AddConfigItem(new IntInputFieldConfigItem(configEntry9, new IntInputFieldOptions
			{
				Max = 150
			}));
			LethalConfigManager.AddConfigItem(new FloatInputFieldConfigItem(configEntry10, new FloatInputFieldOptions
			{
				Max = 2.5f
			}));
			LethalConfigManager.AddConfigItem(new TextDropDownConfigItem(configEntry8, new TextDropDownOptions
			{
				RequiresRestart = false
			}));
		}
	}
	public static class LethalConfigManager
	{
		private static readonly List<AutoConfigGenerator.ConfigFileAssemblyPair> CustomConfigFiles = new List<AutoConfigGenerator.ConfigFileAssemblyPair>();

		private static bool _hasGeneratedMissingConfigs;

		internal static Dictionary<string, Mod> Mods { get; } = new Dictionary<string, Mod>();


		private static Dictionary<Mod, Assembly> ModToAssemblyMap { get; } = new Dictionary<Mod, Assembly>();


		internal static void AutoGenerateMissingConfigsIfNeeded()
		{
			if (_hasGeneratedMissingConfigs)
			{
				return;
			}
			Mod[] second = Mods.Values.ToArray();
			IEnumerable<BaseConfigItem> existingConfigsFlat = Mods.SelectMany((KeyValuePair<string, Mod> kv) => kv.Value.ConfigItems);
			AutoConfigGenerator.AutoConfigItem[] array = AutoConfigGenerator.AutoGenerateConfigs(CustomConfigFiles.ToArray());
			Dictionary<Mod, IEnumerable<BaseConfigItem>> dictionary = (from c in array
				group c.ConfigItem by ModForAssembly(c.Assembly) into kv
				where kv.Key != null
				select kv).SelectMany((IGrouping<Mod, BaseConfigItem> kv) => from c in kv.Select(delegate(BaseConfigItem c)
				{
					c.Owner = kv.Key;
					return c;
				})
				where !kv.Key.EntriesToSkipAutoGen.Any((ConfigEntryPath path) => path.Matches(c))
				where existingConfigsFlat.FirstOrDefault(c.IsSameConfig) == null
				group c by c.Owner).ToDictionary((IGrouping<Mod, BaseConfigItem> kv) => kv.Key, (IGrouping<Mod, BaseConfigItem> kv) => kv.Select((BaseConfigItem c) => c));
			Mod[] array2 = dictionary.Keys.Except(second).ToArray();
			Mod[] array3 = array2;
			foreach (Mod obj in array3)
			{
				obj.IsAutoGenerated = true;
				obj.ModInfo.Description += "\n*This mod entry was automatically generated as it does not use LethalConfig directly.";
			}
			foreach (KeyValuePair<Mod, IEnumerable<BaseConfigItem>> item in dictionary)
			{
				Assembly valueOrDefault = ModToAssemblyMap.GetValueOrDefault(item.Key);
				if (valueOrDefault == null)
				{
					continue;
				}
				foreach (BaseConfigItem item2 in item.Value)
				{
					AddConfigItemForAssembly(item2, valueOrDefault);
				}
			}
			LogUtils.LogInfo($"Generated {array2.Length} mod entries.");
			LogUtils.LogInfo($"Generated {array.Length} configs, of which {dictionary.SelectMany((KeyValuePair<Mod, IEnumerable<BaseConfigItem>> kv) => kv.Value).Count()} were missing and registered.");
			_hasGeneratedMissingConfigs = true;
		}

		public static void AddConfigItem(BaseConfigItem configItem)
		{
			if (AddConfigItemForAssembly(configItem, Assembly.GetCallingAssembly()))
			{
				LogUtils.LogInfo($"Registered config \"{configItem}\"");
			}
		}

		public static void AddConfigItem(BaseConfigItem configItem, Assembly assembly)
		{
			if (AddConfigItemForAssembly(configItem, assembly))
			{
				LogUtils.LogInfo($"Registered config \"{configItem}\"");
			}
		}

		private static bool AddConfigItemForAssembly(BaseConfigItem configItem, Assembly assembly)
		{
			Mod mod = ModForAssembly(assembly);
			if (mod == null)
			{
				LogUtils.LogWarning("Mod for assembly not found.");
				return false;
			}
			configItem.Owner = mod;
			if (mod.ConfigItems.Any((BaseConfigItem c) => c.IsSameConfig(configItem)))
			{
				LogUtils.LogWarning($"Ignoring duplicated config \"{configItem}\"");
				return false;
			}
			mod.AddConfigItem(configItem);
			return true;
		}

		private static Mod ModForAssembly(Assembly assembly)
		{
			if (!assembly.TryGetModInfo(out var modInfo))
			{
				return null;
			}
			if (Mods.TryGetValue(modInfo.Guid, out var value))
			{
				return value;
			}
			Mod mod = new Mod(modInfo);
			Mods.Add(modInfo.Guid, mod);
			ModToAssemblyMap.Add(mod, assembly);
			return mod;
		}

		public static void SetModIcon(Sprite sprite)
		{
			if (!((Object)(object)sprite == (Object)null))
			{
				Mod mod = ModForAssembly(Assembly.GetCallingAssembly());
				if (mod != null)
				{
					mod.ModInfo.Icon = sprite;
				}
			}
		}

		public static void SetModDescription(string description)
		{
			if (description != null)
			{
				Mod mod = ModForAssembly(Assembly.GetCallingAssembly());
				if (mod != null)
				{
					mod.ModInfo.Description = description;
				}
			}
		}

		public static void SkipAutoGenFor(string configSection)
		{
			ModForAssembly(Assembly.GetCallingAssembly())?.EntriesToSkipAutoGen.Add(new ConfigEntryPath(configSection, "*"));
		}

		public static void SkipAutoGenFor(ConfigEntryBase configEntryBase)
		{
			ModForAssembly(Assembly.GetCallingAssembly())?.EntriesToSkipAutoGen.Add(new ConfigEntryPath(configEntryBase.Definition.Section, configEntryBase.Definition.Key));
		}

		public static void SkipAutoGen()
		{
			ModForAssembly(Assembly.GetCallingAssembly())?.EntriesToSkipAutoGen.Add(new ConfigEntryPath("*", "*"));
		}

		public static void QueueCustomConfigFileForAutoGeneration(ConfigFile configFile)
		{
			CustomConfigFiles.Add(new AutoConfigGenerator.ConfigFileAssemblyPair
			{
				ConfigFile = configFile,
				Assembly = Assembly.GetCallingAssembly()
			});
		}
	}
	internal static class PluginInfo
	{
		public const string Guid = "ainavt.lc.lethalconfig";

		public const string Name = "LethalConfig";

		public const string Version = "1.4.2";
	}
	[BepInPlugin("ainavt.lc.lethalconfig", "LethalConfig", "1.4.2")]
	internal class LethalConfigPlugin : BaseUnityPlugin
	{
		private static LethalConfigPlugin _instance;

		private static Harmony _harmony;

		private void Awake()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			if ((Object)(object)_instance == (Object)null)
			{
				_instance = this;
			}
			LogUtils.Init("ainavt.lc.lethalconfig");
			Configs.Initialize(((BaseUnityPlugin)this).Config);
			if (Configs.IsLethalConfigHidden.Value)
			{
				LogUtils.LogInfo("LethalConfig is hidden and will not load.");
				return;
			}
			Assets.Init();
			_harmony = new Harmony("ainavt.lc.lethalconfig");
			_harmony.PatchAll();
			LogUtils.LogInfo("LethalConfig loaded!");
		}
	}
}
namespace LethalConfig.Utils
{
	internal static class AssemblyExtensions
	{
		internal static bool TryGetModInfo(this Assembly assembly, out ModInfo modInfo)
		{
			modInfo = new ModInfo();
			BepInPlugin val = assembly.FindPluginAttribute();
			if (val == null)
			{
				return false;
			}
			modInfo.Name = val.Name;
			modInfo.Guid = val.GUID;
			modInfo.Version = val.Version.ToString();
			return true;
		}

		private static BepInPlugin FindPluginAttribute(this Assembly assembly)
		{
			Type[] source;
			try
			{
				source = assembly.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				source = ex.Types.Where((Type t) => t != null).ToArray();
			}
			return source.Select((Type type) => ((MemberInfo)type).GetCustomAttribute<BepInPlugin>()).FirstOrDefault<BepInPlugin>((Func<BepInPlugin, bool>)((BepInPlugin plugin) => plugin != null));
		}
	}
	internal static class Assets
	{
		private static AssetBundle _assetBundle;

		internal static GameObject ConfigMenuManagerPrefab;

		internal static GameObject ConfigMenuNotificationPrefab;

		internal static GameObject ConfigMenuPrefab;

		internal static GameObject ModListItemPrefab;

		internal static GameObject SectionHeaderPrefab;

		internal static GameObject IntSliderPrefab;

		internal static GameObject FloatSliderPrefab;

		internal static GameObject FloatStepSliderPrefab;

		internal static GameObject BoolCheckBoxPrefab;

		internal static GameObject EnumDropDownPrefab;

		internal static GameObject TextDropDownPrefab;

		internal static GameObject TextInputFieldPrefab;

		internal static GameObject IntInputFieldPrefab;

		internal static GameObject FloatInputFieldPrefab;

		internal static GameObject GenericButtonPrefab;

		internal static Sprite DefaultModIcon;

		internal static Sprite LethalConfigModIcon;

		internal static void Init()
		{
			_assetBundle = AssetBundle.LoadFromFile(PathUtils.PathForResourceInAssembly("ainavt_lethalconfig"));
			if ((Object)(object)_assetBundle == (Object)null)
			{
				LogUtils.LogError("Failed to load LethalConfig bundle.");
				return;
			}
			LoadAsset<GameObject>("prefabs/ConfigMenuManager.prefab", out ConfigMenuManagerPrefab);
			LoadAsset<GameObject>("prefabs/ConfigMenuNotification.prefab", out ConfigMenuNotificationPrefab);
			LoadAsset<GameObject>("prefabs/ConfigMenu.prefab", out ConfigMenuPrefab);
			LoadAsset<GameObject>("prefabs/ModListItem.prefab", out ModListItemPrefab);
			LoadAsset<GameObject>("prefabs/components/SectionHeader.prefab", out SectionHeaderPrefab);
			LoadAsset<GameObject>("prefabs/components/IntSliderItem.prefab", out IntSliderPrefab);
			LoadAsset<GameObject>("prefabs/components/FloatSliderItem.prefab", out FloatSliderPrefab);
			LoadAsset<GameObject>("prefabs/components/FloatStepSliderItem.prefab", out FloatStepSliderPrefab);
			LoadAsset<GameObject>("prefabs/components/BoolCheckBoxItem.prefab", out BoolCheckBoxPrefab);
			LoadAsset<GameObject>("prefabs/components/EnumDropDownItem.prefab", out EnumDropDownPrefab);
			LoadAsset<GameObject>("prefabs/components/TextDropDownItem.prefab", out TextDropDownPrefab);
			LoadAsset<GameObject>("prefabs/components/TextInputFieldItem.prefab", out TextInputFieldPrefab);
			LoadAsset<GameObject>("prefabs/components/IntInputFieldItem.prefab", out IntInputFieldPrefab);
			LoadAsset<GameObject>("prefabs/components/FloatInputFieldItem.prefab", out FloatInputFieldPrefab);
			LoadAsset<GameObject>("prefabs/components/GenericButtonItem.prefab", out GenericButtonPrefab);
			LoadAsset<Sprite>("sprite/unknown-icon.png", out DefaultModIcon);
			LoadAsset<Sprite>("icon.png", out LethalConfigModIcon);
			LogUtils.LogInfo("Finished loading assets.");
		}

		private static void LoadAsset<T>(string assetName, out T asset) where T : Object
		{
			string text = "Assets/" + assetName;
			asset = _assetBundle.LoadAsset<T>(text);
			if ((Object)(object)asset == (Object)null)
			{
				LogUtils.LogError("Failed to load asset (" + text + ")");
			}
		}
	}
	internal static class LogUtils
	{
		private static ManualLogSource _logSource;

		public static void Init(string pluginGuid)
		{
			_logSource = Logger.CreateLogSource(pluginGuid);
		}

		public static void LogDebug(string message)
		{
			ManualLogSource logSource = _logSource;
			if (logSource != null)
			{
				logSource.LogDebug((object)message);
			}
		}

		public static void LogInfo(string message)
		{
			ManualLogSource logSource = _logSource;
			if (logSource != null)
			{
				logSource.LogInfo((object)message);
			}
		}

		public static void LogWarning(string message)
		{
			ManualLogSource logSource = _logSource;
			if (logSource != null)
			{
				logSource.LogWarning((object)message);
			}
		}

		public static void LogError(string message)
		{
			ManualLogSource logSource = _logSource;
			if (logSource != null)
			{
				logSource.LogError((object)message);
			}
		}

		public static void LogFatal(string message)
		{
			ManualLogSource logSource = _logSource;
			if (logSource != null)
			{
				logSource.LogFatal((object)message);
			}
		}
	}
	internal static class MenusUtils
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__0_0;

			public static Func<Button, GameObject> <>9__0_1;

			public static Func<GameObject, RectTransform> <>9__0_3;

			public static Func<RectTransform, float> <>9__0_4;

			public static Func<float, float, float> <>9__0_5;

			internal void <InjectMenu>b__0_0()
			{
				ConfigMenuManager.Instance.menuAudio.PlayConfirmSfx();
			}

			internal GameObject <InjectMenu>b__0_1(Button b)
			{
				return ((Component)b).gameObject;
			}

			internal RectTransform <InjectMenu>b__0_3(GameObject b)
			{
				Transform transform = b.transform;
				return (RectTransform)(object)((transform is RectTransform) ? transform : null);
			}

			internal float <InjectMenu>b__0_4(RectTransform t)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return t.anchoredPosition.y;
			}

			internal float <InjectMenu>b__0_5(float y1, float y2)
			{
				return Mathf.Abs(y2 - y1);
			}
		}

		internal static void InjectMenu(Transform parentTransform, Transform mainButtonsTransform, GameObject quitButton)
		{
			//IL_001e: 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_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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: 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_00e8: Expected O, but got Unknown
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Expected O, but got Unknown
			//IL_012d: 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_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: 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)
			Object.Instantiate<GameObject>(Assets.ConfigMenuManagerPrefab, parentTransform, true).transform.localPosition = Vector3.zero;
			GameObject obj = Object.Instantiate<GameObject>(Assets.ConfigMenuPrefab, parentTransform, false);
			obj.transform.localPosition = Vector3.zero;
			obj.transform.localScale = Vector3.one;
			obj.transform.localRotation = Quaternion.identity;
			obj.SetActive(false);
			GameObject obj2 = Object.Instantiate<GameObject>(Assets.ConfigMenuNotificationPrefab, parentTransform, false);
			obj2.transform.localPosition = Vector3.zero;
			obj2.transform.localScale = Vector3.one;
			obj2.transform.localRotation = Quaternion.identity;
			obj2.SetActive(false);
			GameObject clonedButton = Object.Instantiate<GameObject>(quitButton, mainButtonsTransform);
			((UnityEventBase)clonedButton.GetComponent<Button>().onClick).RemoveAllListeners();
			clonedButton.GetComponent<Button>().onClick = new ButtonClickedEvent();
			((UnityEvent)clonedButton.GetComponent<Button>().onClick).AddListener(new UnityAction(ConfigMenuManager.ShowConfigMenu));
			ButtonClickedEvent onClick = clonedButton.GetComponent<Button>().onClick;
			object obj3 = <>c.<>9__0_0;
			if (obj3 == null)
			{
				UnityAction val = delegate
				{
					ConfigMenuManager.Instance.menuAudio.PlayConfirmSfx();
				};
				<>c.<>9__0_0 = val;
				obj3 = (object)val;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj3);
			((TMP_Text)clonedButton.GetComponentInChildren<TextMeshProUGUI>()).text = "> LethalConfig";
			List<GameObject> source = (from b in ((Component)mainButtonsTransform).GetComponentsInChildren<Button>()
				select ((Component)b).gameObject).ToList();
			List<float> list = (from t in source.Where((GameObject b) => (Object)(object)b != (Object)(object)clonedButton).Select(delegate(GameObject b)
				{
					Transform transform = b.transform;
					return (RectTransform)(object)((transform is RectTransform) ? transform : null);
				})
				select t.anchoredPosition.y).ToList();
			float num = list.Zip(list.Skip(1), (float y1, float y2) => Mathf.Abs(y2 - y1)).Min();
			foreach (GameObject item in source.Where((GameObject g) => (Object)(object)g != (Object)(object)quitButton))
			{
				RectTransform component = item.GetComponent<RectTransform>();
				component.anchoredPosition += new Vector2(0f, num);
			}
			clonedButton.GetComponent<RectTransform>().anchoredPosition = quitButton.GetComponent<RectTransform>().anchoredPosition + new Vector2(0f, num);
		}
	}
	internal static class PathUtils
	{
		public static string PathForResourceInAssembly(string resourceName, Assembly assembly = null)
		{
			return Path.Combine(Path.GetDirectoryName((assembly ?? Assembly.GetCallingAssembly()).Location), resourceName);
		}
	}
}
namespace LethalConfig.Patches
{
	[HarmonyPatch(typeof(MenuManager))]
	internal class MenuManagerPatches
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void StartPostFix(MenuManager __instance)
		{
			((MonoBehaviour)__instance).StartCoroutine(DelayedMainMenuInjection());
		}

		private static IEnumerator DelayedMainMenuInjection()
		{
			yield return (object)new WaitForSeconds(0f);
			InjectToMainMenu();
		}

		private static void InjectToMainMenu()
		{
			LogUtils.LogInfo("Injecting mod config menu into main menu...");
			GameObject val = GameObject.Find("MenuContainer");
			if (!Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			Transform val2 = val.transform.Find("MainButtons");
			if (Object.op_Implicit((Object)(object)val2))
			{
				Transform val3 = val2.Find("QuitButton");
				if (Object.op_Implicit((Object)(object)val3))
				{
					MenusUtils.InjectMenu(val.transform, val2, ((Component)val3).gameObject);
				}
			}
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager))]
	internal class QuickMenuManagerPatches
	{
		[HarmonyPatch("CloseQuickMenuPanels")]
		[HarmonyPostfix]
		public static void CloseQuickMenuPanelsPostFix(QuickMenuManager __instance)
		{
			ConfigMenu componentInChildren = ((Component)__instance.menuContainer.transform).GetComponentInChildren<ConfigMenu>(true);
			if (Object.op_Implicit((Object)(object)componentInChildren))
			{
				componentInChildren.Close(animated: false);
			}
			ConfigMenuNotification componentInChildren2 = ((Component)__instance.menuContainer.transform).GetComponentInChildren<ConfigMenuNotification>(true);
			if (Object.op_Implicit((Object)(object)componentInChildren2))
			{
				componentInChildren2.Close(animated: false);
			}
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void StartPostFix(QuickMenuManager __instance)
		{
			LogUtils.LogInfo("Injecting mod config menu into quick menu...");
			GameObject menuContainer = __instance.menuContainer;
			if (!Object.op_Implicit((Object)(object)menuContainer))
			{
				return;
			}
			Transform val = menuContainer.transform.Find("MainButtons");
			if (Object.op_Implicit((Object)(object)val))
			{
				Transform val2 = val.Find("Quit");
				if (Object.op_Implicit((Object)(object)val2))
				{
					MenusUtils.InjectMenu(menuContainer.transform, val, ((Component)val2).gameObject);
				}
			}
		}
	}
}
namespace LethalConfig.MonoBehaviours
{
	internal class ConfigInfoBox : MonoBehaviour
	{
		public TextMeshProUGUI configInfoText;

		public void SetConfigInfo(string configInfo)
		{
			((TMP_Text)configInfoText).text = configInfo;
		}
	}
	internal class ConfigList : MonoBehaviour
	{
		public GameObject listContainerObject;

		public DescriptionBox descriptionBox;

		internal void LoadConfigsForMod(Mod mod)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			ClearConfigList();
			foreach (IGrouping<string, BaseConfigItem> item in from c in mod.ConfigItems
				group c by c.Section)
			{
				GameObject obj = Object.Instantiate<GameObject>(Assets.SectionHeaderPrefab, listContainerObject.transform, true);
				obj.GetComponent<SectionHeader>().SetSectionName(item.Key);
				obj.transform.localPosition = Vector3.zero;
				obj.transform.localScale = Vector3.one;
				obj.transform.localRotation = Quaternion.identity;
				foreach (BaseConfigItem item2 in item)
				{
					GameObject val = item2.CreateGameObjectForConfig();
					ModConfigController controller = val.GetComponent<ModConfigController>();
					if (!controller.SetConfigItem(item2))
					{
						Object.DestroyImmediate((Object)(object)val);
						return;
					}
					val.transform.SetParent(listContainerObject.transform);
					val.transform.localPosition = Vector3.zero;
					val.transform.localScale = Vector3.one;
					val.transform.localRotation = Quaternion.identity;
					controller.OnHoverEnter += delegate
					{
						descriptionBox.ShowConfigInfo(controller.GetDescription());
						ConfigMenuManager.Instance.menuAudio.PlayHoverSfx();
					};
				}
			}
		}

		private void ClearConfigList()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			foreach (Transform item in listContainerObject.transform)
			{
				Object.Destroy((Object)(object)((Component)item).gameObject);
			}
		}
	}
	internal class ConfigMenu : MonoBehaviour
	{
		private static readonly int TriggerIdOpen = Animator.StringToHash("Open");

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

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

		public ConfigList configList;

		public Animator menuAnimator;

		private void Awake()
		{
			LethalConfigManager.AutoGenerateMissingConfigsIfNeeded();
		}

		public void Open()
		{
			//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)
			AnimatorStateInfo currentAnimatorStateInfo = menuAnimator.GetCurrentAnimatorStateInfo(0);
			if (!((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("ConfigMenuNormal") && !((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("ConfigMenuAppear"))
			{
				((Component)this).gameObject.SetActive(true);
				menuAnimator.SetTrigger(TriggerIdOpen);
				((Component)this).transform.SetAsLastSibling();
			}
		}

		public void Close(bool animated = true)
		{
			//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)
			AnimatorStateInfo currentAnimatorStateInfo = menuAnimator.GetCurrentAnimatorStateInfo(0);
			if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("ConfigMenuClosed") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("ConfigMenuDisappear"))
			{
				return;
			}
			foreach (BaseConfigItem item in LethalConfigManager.Mods.SelectMany((KeyValuePair<string, Mod> m) => m.Value.ConfigItems))
			{
				item.CancelChanges();
			}
			UpdateAppearanceOfCurrentComponents();
			if (!animated)
			{
				((Component)this).gameObject.SetActive(false);
				menuAnimator.SetTrigger(TriggerIdForceClose);
			}
			else
			{
				menuAnimator.SetTrigger(TriggerIdClose);
			}
		}

		public void OnCloseAnimationEnd()
		{
			((Component)this).gameObject.SetActive(false);
		}

		public void OnCancelButtonClicked()
		{
			Close();
			ConfigMenuManager.Instance.menuAudio.PlayCancelSfx();
		}

		public void OnApplyButtonClicked()
		{
			List<BaseConfigItem> list = (from c in LethalConfigManager.Mods.SelectMany((KeyValuePair<string, Mod> m) => m.Value.ConfigItems)
				where c.HasValueChanged
				select c).ToList();
			List<BaseConfigItem> list2 = list.Where((BaseConfigItem c) => c.RequiresRestart).ToList();
			foreach (BaseConfigItem item in list)
			{
				item.ApplyChanges();
			}
			UpdateAppearanceOfCurrentComponents();
			ConfigMenuManager.Instance.menuAudio.PlayConfirmSfx();
			LogUtils.LogInfo($"Saved config values for {list.Count} items.");
			LogUtils.LogInfo($"Modified {list2.Count} item(s) that requires a restart.");
			if (list2.Count > 0)
			{
				ConfigMenuManager.DisplayNotification("Some of the modified settings may require a restart to take effect.", "OK");
			}
		}

		private void UpdateAppearanceOfCurrentComponents()
		{
			ModConfigController[] componentsInChildren = ((Component)configList).GetComponentsInChildren<ModConfigController>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].UpdateAppearance();
			}
		}
	}
	internal class ConfigMenuNotification : MonoBehaviour
	{
		private static readonly int TriggerIdOpen = Animator.StringToHash("Open");

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

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

		public TextMeshProUGUI messageTextComponent;

		public TextMeshProUGUI buttonTextComponent;

		public Animator notificationAnimator;

		public void SetNotificationContent(string text, string button)
		{
			((TMP_Text)messageTextComponent).text = text;
			((TMP_Text)buttonTextComponent).text = "[" + button + "]";
		}

		public void Open()
		{
			//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)
			AnimatorStateInfo currentAnimatorStateInfo = notificationAnimator.GetCurrentAnimatorStateInfo(0);
			if (!((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("NotificationNormal") && !((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("NotificationAppear"))
			{
				((Component)this).gameObject.SetActive(true);
				notificationAnimator.SetTrigger(TriggerIdOpen);
				((Component)this).transform.SetAsLastSibling();
			}
		}

		public void Close(bool animated = true)
		{
			//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)
			AnimatorStateInfo currentAnimatorStateInfo = notificationAnimator.GetCurrentAnimatorStateInfo(0);
			if (!((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("NotificationClosed") && !((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("NotificationDisappear"))
			{
				if (!animated)
				{
					((Component)this).gameObject.SetActive(false);
					notificationAnimator.SetTrigger(TriggerIdForceClose);
				}
				else
				{
					notificationAnimator.SetTrigger(TriggerIdClose);
				}
			}
		}

		public void OnButtonClick()
		{
			Close();
			ConfigMenuManager.Instance.menuAudio.PlayConfirmSfx();
		}

		public void OnCloseAnimationEnd()
		{
			((Component)this).gameObject.SetActive(false);
		}
	}
	internal class DescriptionBox : MonoBehaviour
	{
		public ModInfoBox modInfoBox;

		public ConfigInfoBox configInfoBox;

		private void Awake()
		{
			((Component)modInfoBox).gameObject.SetActive(false);
			((Component)configInfoBox).gameObject.SetActive(false);
		}

		public void ShowConfigInfo(string configInfo)
		{
			((Component)configInfoBox).gameObject.SetActive(true);
			configInfoBox.SetConfigInfo(configInfo);
			HideModInfo();
		}

		public void HideConfigInfo()
		{
			((Component)configInfoBox).gameObject.SetActive(false);
		}

		public void ShowModInfo(Mod mod)
		{
			((Component)modInfoBox).gameObject.SetActive(true);
			modInfoBox.SetModInfo(mod);
			HideConfigInfo();
		}

		public void HideModInfo()
		{
			((Component)modInfoBox).gameObject.SetActive(false);
		}
	}
	internal class ModInfoBox : MonoBehaviour
	{
		public Image modIconImage;

		public TextMeshProUGUI modInfoText;

		public void SetModInfo(Mod mod)
		{
			modIconImage.sprite = mod.ModInfo.Icon;
			((TMP_Text)modInfoText).text = $"{mod.ModInfo}";
		}
	}
	internal class ModList : MonoBehaviour
	{
		public GameObject modItemPrefab;

		public GameObject listContainerObject;

		public ConfigList configList;

		public DescriptionBox descriptionBox;

		private List<ModListItem> _items;

		private void Awake()
		{
			_items = new List<ModListItem>();
			BuildModList();
		}

		private void BuildModList()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			_items.Clear();
			foreach (Transform item in listContainerObject.transform)
			{
				Object.Destroy((Object)(object)((Component)item).gameObject);
			}
			foreach (Mod mod in from m in LethalConfigManager.Mods.Values
				orderby m.ModInfo.Guid != "ainavt.lc.lethalconfig", m.IsAutoGenerated, m.ModInfo.Name
				select m)
			{
				GameObject val = Object.Instantiate<GameObject>(modItemPrefab, listContainerObject.transform);
				val.transform.localScale = Vector3.one;
				val.transform.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity);
				ModListItem component = val.GetComponent<ModListItem>();
				component.Mod = mod;
				component.ModSelected += ModSelected;
				component.OnHoverEnter += delegate
				{
					descriptionBox.ShowModInfo(mod);
					ConfigMenuManager.Instance.menuAudio.PlayHoverSfx();
				};
				component.OnHoverExit += delegate
				{
					descriptionBox.HideModInfo();
				};
				_items.Add(val.GetComponent<ModListItem>());
			}
		}

		private void ModSelected(Mod mod)
		{
			ConfigMenuManager.Instance.menuAudio.PlayConfirmSfx();
			configList.LoadConfigsForMod(mod);
			_items.First((ModListItem i) => i.Mod == mod).SetSelected(selected: true);
			foreach (ModListItem item in _items.Where((ModListItem i) => i.Mod != mod))
			{
				item.SetSelected(selected: false);
			}
		}
	}
	internal class ModListItem : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public delegate void OnHoverHandler();

		internal delegate void ModSelectedHandler(Mod mod);

		public TextMeshProUGUI textMesh;

		public GameObject selectedBorder;

		public Image modIcon;

		private Mod _mod;

		internal Mod Mod
		{
			get
			{
				return _mod;
			}
			set
			{
				_mod = value;
				((TMP_Text)textMesh).text = _mod.ModInfo.Name;
				modIcon.sprite = _mod.ModInfo.Icon;
			}
		}

		public event OnHoverHandler OnHoverEnter;

		public event OnHoverHandler OnHoverExit;

		internal event ModSelectedHandler ModSelected;

		public void OnPointerEnter(PointerEventData eventData)
		{
			this.OnHoverEnter?.Invoke();
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			this.OnHoverExit?.Invoke();
		}

		public void OnClick()
		{
			this.ModSelected?.Invoke(_mod);
		}

		public void SetSelected(bool selected)
		{
			selectedBorder.SetActive(selected);
		}

		public string GetDescription()
		{
			return _mod.ModInfo.Name + "\n" + _mod.ModInfo.Guid + "\n" + _mod.ModInfo.Version;
		}
	}
	internal class SectionHeader : MonoBehaviour
	{
		public TextMeshProUGUI textMesh;

		public void SetSectionName(string sectionName)
		{
			((TMP_Text)textMesh).text = "[" + sectionName + "]";
		}
	}
	internal class Tooltip : MonoBehaviour
	{
		public TextMeshProUGUI textComponent;

		private RectTransform _rectTransform;

		private Camera _uiCamera;

		public void SetText(string text)
		{
			((TMP_Text)textComponent).text = text;
		}

		public void SetTarget(GameObject newTargetGameObject)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			((Component)this).transform.position = newTargetGameObject.transform.position;
		}
	}
	internal class TooltipSystem : MonoBehaviour
	{
		private static TooltipSystem _instance;

		public Tooltip tooltip;

		private void Awake()
		{
			_instance = this;
		}

		public static void Show(string content, GameObject target)
		{
			if (!((Object)(object)_instance == (Object)null))
			{
				((Component)_instance.tooltip).gameObject.SetActive(true);
				_instance.tooltip.SetText(content);
				_instance.tooltip.SetTarget(target);
			}
		}

		public static void Hide()
		{
			if (!((Object)(object)_instance == (Object)null))
			{
				((Component)_instance.tooltip).gameObject.SetActive(false);
			}
		}
	}
	internal class TooltipTrigger : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public string tooltipText;

		public void OnPointerEnter(PointerEventData eventData)
		{
			TooltipSystem.Show(tooltipText, ((Component)this).gameObject);
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			TooltipSystem.Hide();
		}
	}
	internal class VersionLabel : MonoBehaviour
	{
		private void Start()
		{
			((TMP_Text)((Component)this).GetComponent<TextMeshProUGUI>()).text = "LethalConfig v1.4.2";
		}
	}
}
namespace LethalConfig.MonoBehaviours.Managers
{
	internal class ConfigMenuAudioManager : MonoBehaviour
	{
		[FormerlySerializedAs("confirmSFX")]
		public AudioClip confirmSfx;

		[FormerlySerializedAs("cancelSFX")]
		public AudioClip cancelSfx;

		[FormerlySerializedAs("selectSFX")]
		public AudioClip selectSfx;

		[FormerlySerializedAs("hoverSFX")]
		public AudioClip hoverSfx;

		[FormerlySerializedAs("changeValueSFX")]
		public AudioClip changeValueSfx;

		public AudioSource audioSource;

		public void PlayConfirmSfx()
		{
			audioSource.PlayOneShot(confirmSfx);
		}

		public void PlayCancelSfx()
		{
			audioSource.PlayOneShot(cancelSfx);
		}

		public void PlayHoverSfx()
		{
			audioSource.PlayOneShot(hoverSfx);
		}

		public void PlaySelectSfx()
		{
			audioSource.PlayOneShot(selectSfx);
		}

		public void PlayChangeValueSfx()
		{
			audioSource.PlayOneShot(changeValueSfx);
		}
	}
	internal class ConfigMenuManager : MonoBehaviour
	{
		public ConfigMenuAudioManager menuAudio;

		public static ConfigMenuManager Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
		}

		private void OnDestroy()
		{
			Instance = null;
		}

		public static void ShowConfigMenu()
		{
			ConfigMenu configMenu = Object.FindObjectOfType<ConfigMenu>(true);
			if (!Object.op_Implicit((Object)(object)configMenu))
			{
				LogUtils.LogWarning("ConfigMenu object not found");
			}
			else
			{
				configMenu.Open();
			}
		}

		public static void DisplayNotification(string message, string button)
		{
			ConfigMenuNotification configMenuNotification = Object.FindObjectOfType<ConfigMenuNotification>(true);
			if (!Object.op_Implicit((Object)(object)configMenuNotification))
			{
				LogUtils.LogWarning("Notification object not found");
				return;
			}
			configMenuNotification.SetNotificationContent(message, button);
			configMenuNotification.Open();
			EventSystem.current.SetSelectedGameObject(((Component)((Component)configMenuNotification).GetComponentInChildren<Button>()).gameObject);
		}
	}
}
namespace LethalConfig.MonoBehaviours.Components
{
	internal class BoolCheckBoxController : ModConfigController<BoolCheckBoxConfigItem, bool>
	{
		public Toggle toggleComponent;

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			toggleComponent.SetIsOnWithoutNotify(base.ConfigItem.CurrentValue);
		}

		protected override void OnSetConfigItem()
		{
			toggleComponent.SetIsOnWithoutNotify(base.ConfigItem.CurrentValue);
			UpdateAppearance();
		}

		public void OnCheckBoxValueChanged(bool value)
		{
			base.ConfigItem.CurrentValue = value;
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}
	}
	internal class EnumDropDownController : ModConfigController
	{
		public TMP_Dropdown dropdownComponent;

		private List<string> _enumNames = new List<string>();

		private Type _enumType;

		private void OnDestroy()
		{
			BaseConfigItem.OnCurrentValueChanged -= OnCurrentValueChanged;
		}

		public override string GetDescription()
		{
			return base.GetDescription() + "\n\nDefault: " + Enum.GetName(_enumType, BaseConfigItem.BoxedDefaultValue);
		}

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			int valueWithoutNotify = _enumNames.FindIndex((string e) => e == Enum.GetName(_enumType, BaseConfigItem.CurrentBoxedValue));
			dropdownComponent.SetValueWithoutNotify(valueWithoutNotify);
		}

		protected override void OnSetConfigItem()
		{
			BaseConfigItem.OnCurrentValueChanged += OnCurrentValueChanged;
			_enumType = BaseConfigItem.BaseConfigEntry.SettingType;
			_enumNames = Enum.GetNames(_enumType).ToList();
			dropdownComponent.ClearOptions();
			dropdownComponent.AddOptions(_enumNames);
			int valueWithoutNotify = _enumNames.FindIndex((string e) => e == Enum.GetName(_enumType, BaseConfigItem.CurrentBoxedValue));
			dropdownComponent.SetValueWithoutNotify(valueWithoutNotify);
			UpdateAppearance();
		}

		public void OnDropDownValueChanged(int index)
		{
			BaseConfigItem.CurrentBoxedValue = Enum.Parse(_enumType, _enumNames[index]);
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}

		private void OnCurrentValueChanged()
		{
			UpdateAppearance();
		}
	}
	internal class FloatInputFieldController : ModConfigController<FloatInputFieldConfigItem, float>
	{
		public TMP_InputField textInputField;

		public override string GetDescription()
		{
			string text = base.GetDescription();
			if (base.ConfigItem.MinValue != float.MinValue)
			{
				text += $"\nMin: {base.ConfigItem.MinValue:0.0#}";
			}
			if (base.ConfigItem.MaxValue != float.MaxValue)
			{
				text += $"\nMax: {base.ConfigItem.MaxValue:0.0#}";
			}
			return text;
		}

		protected override void OnSetConfigItem()
		{
			textInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue}");
			UpdateAppearance();
		}

		public void OnInputFieldEndEdit(string value)
		{
			if (float.TryParse(value, out var result))
			{
				base.ConfigItem.CurrentValue = Math.Clamp(result, base.ConfigItem.MinValue, base.ConfigItem.MaxValue);
			}
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}

		public override void UpdateAppearance()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			base.UpdateAppearance();
			textInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue}");
			((Transform)textInputField.textComponent.rectTransform).localPosition = Vector3.zero;
		}
	}
	internal class FloatSliderController : ModConfigController<FloatSliderConfigItem, float>
	{
		public Slider sliderComponent;

		public TMP_InputField valueInputField;

		public override string GetDescription()
		{
			return $"{base.GetDescription()}\nMin: {base.ConfigItem.MinValue:0.0#}\nMax: {base.ConfigItem.MaxValue:0.0#}";
		}

		protected override void OnSetConfigItem()
		{
			sliderComponent.SetValueWithoutNotify(base.ConfigItem.CurrentValue);
			sliderComponent.maxValue = base.ConfigItem.MaxValue;
			sliderComponent.minValue = base.ConfigItem.MinValue;
			UpdateAppearance();
		}

		public void OnSliderValueChanged(float value)
		{
			base.ConfigItem.CurrentValue = value;
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}

		public void OnInputFieldEndEdit(string value)
		{
			if (float.TryParse(value, out var result))
			{
				base.ConfigItem.CurrentValue = Math.Clamp(result, base.ConfigItem.MinValue, base.ConfigItem.MaxValue);
			}
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			sliderComponent.SetValueWithoutNotify(base.ConfigItem.CurrentValue);
			valueInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue:0.0#}");
		}
	}
	internal class FloatStepSliderController : ModConfigController<FloatStepSliderConfigItem, float>
	{
		public Slider sliderComponent;

		public TMP_InputField valueInputField;

		public override string GetDescription()
		{
			return $"{base.GetDescription()}\nMin: {base.ConfigItem.MinValue:0.0#}\nMax: {base.ConfigItem.MaxValue:0.0#}";
		}

		protected override void OnSetConfigItem()
		{
			sliderComponent.SetValueWithoutNotify(base.ConfigItem.CurrentValue);
			int num = (int)MathF.Ceiling((base.ConfigItem.MaxValue - base.ConfigItem.MinValue) / MathF.Max(base.ConfigItem.Step, float.Epsilon));
			sliderComponent.maxValue = num;
			sliderComponent.minValue = 0f;
			sliderComponent.wholeNumbers = true;
			UpdateAppearance();
		}

		public void OnSliderValueChanged(float value)
		{
			base.ConfigItem.CurrentValue = MathF.Round(base.ConfigItem.MinValue + base.ConfigItem.Step * (float)(int)value, 4);
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}

		public void OnInputFieldEndEdit(string value)
		{
			if (float.TryParse(value, out var result))
			{
				base.ConfigItem.CurrentValue = Math.Clamp(result, base.ConfigItem.MinValue, base.ConfigItem.MaxValue);
			}
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			sliderComponent.SetValueWithoutNotify((base.ConfigItem.CurrentValue - base.ConfigItem.MinValue) / MathF.Max(base.ConfigItem.Step, float.Epsilon));
			valueInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue:0.0#}");
		}
	}
	internal class GenericButtonController : ModConfigController
	{
		public TextMeshProUGUI buttonTextComponent;

		private GenericButtonConfigItem ConfigItem => BaseConfigItem as GenericButtonConfigItem;

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			((TMP_Text)buttonTextComponent).text = ConfigItem?.ButtonOptions?.ButtonText ?? "Button";
		}

		protected override void OnSetConfigItem()
		{
			UpdateAppearance();
		}

		public void OnButtonClicked()
		{
			ConfigMenuManager.Instance.menuAudio.PlayConfirmSfx();
			ConfigItem?.ButtonOptions?.ButtonHandler?.Invoke();
		}
	}
	internal class IntInputFieldController : ModConfigController<IntInputFieldConfigItem, int>
	{
		public TMP_InputField textInputField;

		public override string GetDescription()
		{
			string text = base.GetDescription();
			if (base.ConfigItem.MinValue != int.MinValue)
			{
				text += $"\nMin: {base.ConfigItem.MinValue}";
			}
			if (base.ConfigItem.MaxValue != int.MaxValue)
			{
				text += $"\nMax: {base.ConfigItem.MaxValue}";
			}
			return text;
		}

		protected override void OnSetConfigItem()
		{
			textInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue}");
			UpdateAppearance();
		}

		public void OnInputFieldEndEdit(string value)
		{
			if (int.TryParse(value, out var result))
			{
				base.ConfigItem.CurrentValue = Math.Clamp(result, base.ConfigItem.MinValue, base.ConfigItem.MaxValue);
			}
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}

		public override void UpdateAppearance()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			base.UpdateAppearance();
			textInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue}");
			((Transform)textInputField.textComponent.rectTransform).localPosition = Vector3.zero;
		}
	}
	internal class IntSliderController : ModConfigController<IntSliderConfigItem, int>
	{
		public Slider sliderComponent;

		public TMP_InputField valueInputField;

		public override string GetDescription()
		{
			return $"{base.GetDescription()}\nMin: {base.ConfigItem.MinValue}\nMax: {base.ConfigItem.MaxValue}";
		}

		protected override void OnSetConfigItem()
		{
			sliderComponent.SetValueWithoutNotify((float)base.ConfigItem.CurrentValue);
			sliderComponent.maxValue = base.ConfigItem.MaxValue;
			sliderComponent.minValue = base.ConfigItem.MinValue;
			UpdateAppearance();
		}

		public void OnSliderValueChanged(float value)
		{
			base.ConfigItem.CurrentValue = (int)value;
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}

		public void OnInputFieldEndEdit(string value)
		{
			if (int.TryParse(value, out var result))
			{
				base.ConfigItem.CurrentValue = Math.Clamp(result, base.ConfigItem.MinValue, base.ConfigItem.MaxValue);
			}
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			sliderComponent.SetValueWithoutNotify((float)base.ConfigItem.CurrentValue);
			valueInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue}");
		}
	}
	internal abstract class ModConfigController : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public delegate void OnHoverHandler();

		public TextMeshProUGUI nameTextComponent;

		public TooltipTrigger tooltipTrigger;

		private readonly List<Selectable> _selectables = new List<Selectable>();

		protected BaseConfigItem BaseConfigItem;

		protected bool IsOnSetup;

		private CanModifyResult CanModify
		{
			get
			{
				if (BaseConfigItem.Options.CanModifyCallback == null)
				{
					return true;
				}
				return BaseConfigItem.Options.CanModifyCallback();
			}
		}

		public event OnHoverHandler OnHoverEnter;

		public event OnHoverHandler OnHoverExit;

		protected virtual void Awake()
		{
			((Behaviour)tooltipTrigger).enabled = false;
			if (_selectables.Count <= 0)
			{
				_selectables.AddRange(((Component)this).GetComponentsInChildren<Selectable>());
			}
		}

		public void OnPointerEnter(PointerEventData eventData)
		{
			this.OnHoverEnter?.Invoke();
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			this.OnHoverExit?.Invoke();
		}

		public virtual bool SetConfigItem(BaseConfigItem configItem)
		{
			BaseConfigItem = configItem;
			IsOnSetup = true;
			OnSetConfigItem();
			IsOnSetup = false;
			if (BaseConfigItem.Options.CanModifyCallback != null)
			{
				tooltipTrigger.tooltipText = "<b>Modifying this entry is currently disabled:</b>\n<b>" + CanModify.Reason + "</b>";
			}
			return true;
		}

		protected abstract void OnSetConfigItem();

		public virtual void UpdateAppearance()
		{
			((TMP_Text)nameTextComponent).text = (BaseConfigItem.HasValueChanged ? "* " : "") + BaseConfigItem.Name;
			CanModifyResult canModify = CanModify;
			foreach (Selectable selectable in _selectables)
			{
				selectable.interactable = canModify;
			}
			((Behaviour)tooltipTrigger).enabled = !canModify;
		}

		public virtual void ResetToDefault()
		{
			ConfigMenuManager.Instance.menuAudio.PlayConfirmSfx();
			BaseConfigItem.ChangeToDefault();
			UpdateAppearance();
		}

		public virtual string GetDescription()
		{
			string text = "<b>" + BaseConfigItem.Name + "</b>";
			if (BaseConfigItem.IsAutoGenerated)
			{
				text += "\n\n<b>*This config entry was automatically generated and may require a restart*</b>";
			}
			else if (BaseConfigItem.RequiresRestart)
			{
				text += "\n\n<b>*REQUIRES RESTART*</b>";
			}
			return text + "\n\n" + BaseConfigItem.Description;
		}
	}
	internal abstract class ModConfigController<T, TV> : ModConfigController where T : BaseValueConfigItem<TV>
	{
		protected T ConfigItem => (T)BaseConfigItem;

		private void OnDestroy()
		{
			ConfigItem.OnCurrentValueChanged -= OnCurrentValueChanged;
		}

		public override string GetDescription()
		{
			return $"{base.GetDescription()}\n\nDefault: {ConfigItem.DefaultValue}";
		}

		public override bool SetConfigItem(BaseConfigItem configItem)
		{
			if (!(configItem is T val))
			{
				LogUtils.LogError("Expected config item of type " + typeof(T).Name + ", but got " + configItem.GetType().Name + " instead.");
				return false;
			}
			val.OnCurrentValueChanged += OnCurrentValueChanged;
			return base.SetConfigItem(val);
		}

		private void OnCurrentValueChanged()
		{
			UpdateAppearance();
		}
	}
	internal class TextDropDownController : ModConfigController<TextDropDownConfigItem, string>
	{
		public TMP_Dropdown dropdownComponent;

		private List<string> _textValues = new List<string>();

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			int valueWithoutNotify = _textValues.FindIndex((string e) => e == (string)BaseConfigItem.CurrentBoxedValue);
			dropdownComponent.SetValueWithoutNotify(valueWithoutNotify);
		}

		protected override void OnSetConfigItem()
		{
			_textValues = base.ConfigItem.Values.ToList();
			dropdownComponent.ClearOptions();
			dropdownComponent.AddOptions(_textValues);
			int valueWithoutNotify = _textValues.FindIndex((string e) => e == (string)BaseConfigItem.CurrentBoxedValue);
			dropdownComponent.SetValueWithoutNotify(valueWithoutNotify);
			UpdateAppearance();
		}

		public void OnDropDownValueChanged(int index)
		{
			base.ConfigItem.CurrentValue = _textValues[index];
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}
	}
	internal class TextInputFieldController : ModConfigController<TextInputFieldConfigItem, string>
	{
		public TMP_InputField textInputField;

		private LayoutElement _layoutElement;

		protected override void Awake()
		{
			base.Awake();
			_layoutElement = ((Component)this).GetComponent<LayoutElement>();
		}

		private void Update()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (textInputField.isFocused && (int)textInputField.lineType != 0)
			{
				bool isPressed = Keyboard.current.shiftKey.isPressed;
				textInputField.lineType = (LineType)((!isPressed) ? 1 : 2);
			}
		}

		protected override void OnSetConfigItem()
		{
			textInputField.text = base.ConfigItem.CurrentValue;
			int num = Mathf.Clamp((base.ConfigItem.NumberOfLines <= 0) ? 4 : base.ConfigItem.NumberOfLines, 1, 4);
			float num2 = 16 + num * 19;
			_layoutElement.minHeight = num2;
			_layoutElement.preferredHeight = num2;
			textInputField.lineType = (LineType)(num != 1);
			textInputField.lineLimit = base.ConfigItem.NumberOfLines;
			UpdateAppearance();
		}

		public void OnInputFieldEndEdit(string value)
		{
			int caretPosition = textInputField.caretPosition;
			if (base.ConfigItem.NumberOfLines != 1)
			{
				((MonoBehaviour)this).StartCoroutine(RemoveNewLineFromSubmitDelayed(caretPosition));
			}
			base.ConfigItem.CurrentValue = (base.ConfigItem.TrimText ? value.Trim() : value);
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSfx();
		}

		public override void UpdateAppearance()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			base.UpdateAppearance();
			textInputField.text = base.ConfigItem.CurrentValue;
			((Transform)textInputField.textComponent.rectTransform).localPosition = Vector3.zero;
		}

		private IEnumerator RemoveNewLineFromSubmitDelayed(int caretPosition)
		{
			yield return null;
			textInputField.text = textInputField.text.Remove(Mathf.Clamp(caretPosition, 0, textInputField.text.Length - 1), 1);
		}
	}
}
namespace LethalConfig.Mods
{
	internal class Mod
	{
		public readonly List<BaseConfigItem> ConfigItems;

		public readonly List<ConfigEntryPath> EntriesToSkipAutoGen;

		public readonly ModInfo ModInfo;

		public bool IsAutoGenerated;

		internal Mod(ModInfo modInfo)
		{
			ConfigItems = new List<BaseConfigItem>();
			EntriesToSkipAutoGen = new List<ConfigEntryPath>();
			ModInfo = modInfo;
			TryResolveIconAndDesc();
		}

		private void TryResolveIconAndDesc()
		{
			if (ModInfo.TryGetPluginInfo(out var pluginInfo))
			{
				string text = Path.GetFullPath(pluginInfo.Location);
				DirectoryInfo parent = Directory.GetParent(text);
				while (parent != null && !string.Equals(parent.Name, "plugins", StringComparison.OrdinalIgnoreCase))
				{
					text = parent.FullName;
					parent = Directory.GetParent(text);
				}
				if (!text.EndsWith(".dll"))
				{
					string iconPath = Directory.EnumerateFiles(text, "icon.png", SearchOption.AllDirectories).FirstOrDefault();
					LoadIcon(iconPath);
					string manifestPath = Directory.EnumerateFiles(text, "manifest.json", SearchOption.AllDirectories).FirstOrDefault();
					LoadDesc(manifestPath);
				}
			}
		}

		private void LoadIcon(string iconPath)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_0045: 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)
			try
			{
				if (iconPath != null)
				{
					Texture2D val = new Texture2D(256, 256);
					if (ImageConversion.LoadImage(val, File.ReadAllBytes(iconPath), true))
					{
						ModInfo.Icon = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
					}
				}
			}
			catch
			{
			}
		}

		private void LoadDesc(string manifestPath)
		{
			try
			{
				if (manifestPath != null)
				{
					ThunderstoreManifest thunderstoreManifest = JsonConvert.DeserializeObject<ThunderstoreManifest>(File.ReadAllText(manifestPath));
					if (thunderstoreManifest != null)
					{
						ModInfo.Description = thunderstoreManifest.Description;
					}
				}
			}
			catch
			{
			}
		}

		internal void AddConfigItem(BaseConfigItem item)
		{
			ConfigItems.Add(item);
		}
	}
	internal class ModInfo
	{
		internal string Name { get; set; }

		internal string Guid { get; set; }

		internal string Version { get; set; }

		internal string Description { get; set; } = "";


		internal Sprite Icon { get; set; } = Assets.DefaultModIcon;


		public override string ToString()
		{
			return "<b>" + Name + "</b>\n" + Guid + "\nv" + Version + "\n\n" + Description;
		}

		public bool TryGetPluginInfo(out PluginInfo pluginInfo)
		{
			return Chainloader.PluginInfos.TryGetValue(Guid, out pluginInfo);
		}
	}
	internal class ThunderstoreManifest
	{
		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("version_number")]
		public string VersionNumber { get; set; }

		[JsonProperty("website_url")]
		public string WebsiteURL { get; set; }

		[JsonProperty("description")]
		public string Description { get; set; }

		[JsonProperty("dependencies")]
		public IList<string> Dependencies { get; set; }
	}
}
namespace LethalConfig.ConfigItems
{
	public abstract class BaseConfigItem
	{
		internal delegate void CurrentValueChangedHandler();

		private object _currentBoxedValue;

		internal ConfigEntryBase BaseConfigEntry { get; }

		internal BaseOptions Options { get; }

		internal bool RequiresRestart => Options.RequiresRestart;

		internal Mod Owner { get; set; }

		internal bool IsAutoGenerated { get; set; }

		private string UnderlyingSection
		{
			get
			{
				ConfigEntryBase baseConfigEntry = BaseConfigEntry;
				return ((baseConfigEntry != null) ? baseConfigEntry.Definition.Section : null) ?? string.Empty;
			}
		}

		private string UnderlyingName
		{
			get
			{
				ConfigEntryBase baseConfigEntry = BaseConfigEntry;
				return ((baseConfigEntry != null) ? baseConfigEntry.Definition.Key : null) ?? string.Empty;
			}
		}

		private string UnderlyingDescription
		{
			get
			{
				ConfigEntryBase baseConfigEntry = BaseConfigEntry;
				return ((baseConfigEntry != null) ? baseConfigEntry.Description.Description : null) ?? string.Empty;
			}
		}

		internal string Section => Options.Section ?? UnderlyingSection;

		internal string Name => Options.Name ?? UnderlyingName;

		internal string Description => Options.Description ?? UnderlyingDescription;

		private object OriginalBoxedValue
		{
			get
			{
				ConfigEntryBase baseConfigEntry = BaseConfigEntry;
				if (baseConfigEntry == null)
				{
					return null;
				}
				return baseConfigEntry.BoxedValue;
			}
		}

		internal object BoxedDefaultValue
		{
			get
			{
				ConfigEntryBase baseConfigEntry = BaseConfigEntry;
				if (baseConfigEntry == null)
				{
					return null;
				}
				return baseConfigEntry.DefaultValue;
			}
		}

		internal object CurrentBoxedValue
		{
			get
			{
				return _currentBoxedValue;
			}
			set
			{
				_currentBoxedValue = value;
				this.OnCurrentValueChanged?.Invoke();
			}
		}

		internal bool HasValueChanged
		{
			get
			{
				object currentBoxedValue = CurrentBoxedValue;
				if (currentBoxedValue == null)
				{
					return false;
				}
				return !currentBoxedValue.Equals(OriginalBoxedValue);
			}
		}

		internal event CurrentValueChangedHandler OnCurrentValueChanged;

		internal BaseConfigItem(BaseOptions options)
			: this(null, options)
		{
		}

		internal BaseConfigItem(ConfigEntryBase configEntry, BaseOptions options)
		{
			BaseConfigEntry = configEntry;
			Options = options;
			CurrentBoxedValue = OriginalBoxedValue;
		}

		internal abstract GameObject CreateGameObjectForConfig();

		public void ApplyChanges()
		{
			if (BaseConfigEntry != null)
			{
				BaseConfigEntry.BoxedValue = CurrentBoxedValue;
			}
		}

		public void CancelChanges()
		{
			CurrentBoxedValue = OriginalBoxedValue;
		}

		public void ChangeToDefault()
		{
			CurrentBoxedValue = BoxedDefaultValue;
		}

		internal virtual bool IsSameConfig(BaseConfigItem configItem)
		{
			bool num = configItem.UnderlyingSection == UnderlyingSection;
			bool flag = configItem.UnderlyingName == UnderlyingName;
			bool flag2 = configItem.Owner.ModInfo.Guid == Owner.ModInfo.Guid;
			return num && flag && flag2;
		}
	}
	public abstract class BaseValueConfigItem<T> : BaseConfigItem
	{
		private ConfigEntry<T> ConfigEntry => (ConfigEntry<T>)(object)base.BaseConfigEntry;

		internal T CurrentValue
		{
			get
			{
				return (T)base.CurrentBoxedValue;
			}
			set
			{
				base.CurrentBoxedValue = value;
			}
		}

		private T OriginalValue => ConfigEntry.Value;

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

		internal BaseValueConfigItem(ConfigEntry<T> configEntry, BaseOptions options)
			: base((ConfigEntryBase)(object)configEntry, options)
		{
			CurrentValue = OriginalValue;
			if (ConfigEntry != null)
			{
				ConfigEntry.SettingChanged += OnUnderlyingEntryChanged;
			}
		}

		~BaseValueConfigItem()
		{
			if (ConfigEntry != null)
			{
				ConfigEntry.SettingChanged -= OnUnderlyingEntryChanged;
			}
		}

		private void OnUnderlyingEntryChanged(object sender, EventArgs args)
		{
			CurrentValue = OriginalValue;
		}

		public override string ToString()
		{
			return base.Owner.ModInfo.Name + "/" + ((ConfigEntryBase)ConfigEntry).Definition.Section + "/" + ((ConfigEntryBase)ConfigEntry).Definition.Key;
		}
	}
	public class BoolCheckBoxConfigItem : BaseValueConfigItem<bool>
	{
		public BoolCheckBoxConfigItem(ConfigEntry<bool> configEntry)
			: this(configEntry, requiresRestart: true)
		{
		}

		public BoolCheckBoxConfigItem(ConfigEntry<bool> configEntry, bool requiresRestart)
			: this(configEntry, new BoolCheckBoxOptions
			{
				RequiresRestart = requiresRestart
			})
		{
		}

		public BoolCheckBoxConfigItem(ConfigEntry<bool> configEntry, BoolCheckBoxOptions options)
			: base(configEntry, (BaseOptions)options)
		{
		}

		internal override GameObject CreateGameObjectForConfig()
		{
			return Object.Instantiate<GameObject>(Assets.BoolCheckBoxPrefab);
		}
	}
	public class EnumDropDownConfigItem<T> : BaseValueConfigItem<T> where T : Enum
	{
		public EnumDropDownConfigItem(ConfigEntry<T> configEntry)
			: this(configEntry, requiresRestart: true)
		{
		}

		public EnumDropDown

plugins/Amlinde-WhistleJester/Assembly-CSharp.dll

Decompiled 3 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using DigitalRuby.ThunderAndLightning;
using Discord;
using Dissonance;
using Dissonance.Audio.Playback;
using Dissonance.Datastructures;
using Dissonance.Extensions;
using Dissonance.Integrations.Unity_NFGO;
using Dissonance.Networking;
using DunGen;
using DunGen.Analysis;
using DunGen.Graph;
using DunGen.Tags;
using GameNetcodeStuff;
using JetBrains.Annotations;
using Netcode.Transports.Facepunch;
using Steamworks;
using Steamworks.Data;
using Steamworks.ServerList;
using TMPro;
using Unity.AI.Navigation;
using Unity.Collections;
using Unity.Netcode;
using Unity.Netcode.Components;
using Unity.Netcode.Samples;
using Unity.Netcode.Transports.UTP;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Animations.Rigging;
using UnityEngine.Audio;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;
using UnityEngine.Serialization;
using UnityEngine.Tilemaps;
using UnityEngine.UI;
using UnityEngine.VFX;
using UnityEngine.Video;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
public class AlarmButton : MonoBehaviour
{
	private Animator buttonAnimator;

	public float timeSincePushing;

	public void PushAlarmButton()
	{
		if (!(timeSincePushing < 1f))
		{
			buttonAnimator.SetTrigger("press");
			HUDManager.Instance.TriggerAlarmHornEffect();
		}
	}

	private void Update()
	{
		if (timeSincePushing <= 5f)
		{
			timeSincePushing += Time.deltaTime;
		}
	}
}
public class AnimatedItem : GrabbableObject
{
	public string grabItemBoolString;

	public string dropItemTriggerString;

	public bool makeAnimationWhenDropping;

	public Animator itemAnimator;

	public AudioSource itemAudio;

	public AudioClip grabAudio;

	public AudioClip dropAudio;

	public bool loopGrabAudio;

	public bool loopDropAudio;

	[Range(0f, 100f)]
	public int chanceToTriggerAnimation = 100;

	public int chanceToTriggerAlternateMesh;

	public Mesh alternateMesh;

	private Mesh normalMesh;

	private Random itemRandomChance;

	public float noiseRange;

	public float noiseLoudness;

	private int timesPlayedInOneSpot;

	private float makeNoiseInterval;

	private Vector3 lastPosition;

	public AudioLowPassFilter itemAudioLowPassFilter;

	private bool wasInPocket;

	public override void Start()
	{
		base.Start();
		itemRandomChance = new Random(StartOfRound.Instance.randomMapSeed + StartOfRound.Instance.currentLevelID + itemProperties.itemId);
		if (chanceToTriggerAlternateMesh > 0)
		{
			normalMesh = ((Component)this).gameObject.GetComponent<MeshFilter>().mesh;
		}
	}

	public override void EquipItem()
	{
		base.EquipItem();
		if ((Object)(object)itemAudioLowPassFilter != (Object)null)
		{
			itemAudioLowPassFilter.cutoffFrequency = 20000f;
		}
		itemAudio.volume = 1f;
		if (chanceToTriggerAlternateMesh > 0)
		{
			if (itemRandomChance.Next(0, 100) < chanceToTriggerAlternateMesh)
			{
				((Component)this).gameObject.GetComponent<MeshFilter>().mesh = alternateMesh;
				itemAudio.Stop();
				return;
			}
			((Component)this).gameObject.GetComponent<MeshFilter>().mesh = normalMesh;
		}
		if (!wasInPocket)
		{
			if (itemRandomChance.Next(0, 100) > chanceToTriggerAnimation)
			{
				itemAudio.Stop();
				return;
			}
		}
		else
		{
			wasInPocket = false;
		}
		if ((Object)(object)itemAnimator != (Object)null)
		{
			itemAnimator.SetBool(grabItemBoolString, true);
		}
		if ((Object)(object)itemAudio != (Object)null)
		{
			itemAudio.clip = grabAudio;
			itemAudio.loop = loopGrabAudio;
			itemAudio.Play();
		}
	}

	public override void DiscardItem()
	{
		base.DiscardItem();
		if ((Object)(object)itemAnimator != (Object)null)
		{
			itemAnimator.SetBool(grabItemBoolString, false);
		}
		if (chanceToTriggerAlternateMesh > 0)
		{
			((Component)this).gameObject.GetComponent<MeshFilter>().mesh = normalMesh;
		}
		if (!makeAnimationWhenDropping)
		{
			itemAudio.Stop();
			return;
		}
		if (itemRandomChance.Next(0, 100) < chanceToTriggerAnimation)
		{
			itemAudio.Stop();
			return;
		}
		if ((Object)(object)itemAnimator != (Object)null)
		{
			itemAnimator.SetTrigger(dropItemTriggerString);
		}
		if ((Object)(object)itemAudio != (Object)null)
		{
			itemAudio.loop = loopDropAudio;
			itemAudio.clip = dropAudio;
			itemAudio.Play();
			if ((Object)(object)itemAudioLowPassFilter != (Object)null)
			{
				itemAudioLowPassFilter.cutoffFrequency = 20000f;
			}
			itemAudio.volume = 1f;
		}
	}

	public override void PocketItem()
	{
		base.PocketItem();
		wasInPocket = true;
		if ((Object)(object)itemAudio != (Object)null)
		{
			if ((Object)(object)itemAudioLowPassFilter != (Object)null)
			{
				itemAudioLowPassFilter.cutoffFrequency = 1700f;
			}
			itemAudio.volume = 0.5f;
		}
	}

	public override void Update()
	{
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: 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)
		base.Update();
		if ((Object)(object)itemAudio == (Object)null || !itemAudio.isPlaying)
		{
			return;
		}
		if (makeNoiseInterval <= 0f)
		{
			makeNoiseInterval = 0.75f;
			if (Vector3.Distance(lastPosition, ((Component)this).transform.position) < 4f)
			{
				timesPlayedInOneSpot++;
			}
			else
			{
				timesPlayedInOneSpot = 0;
			}
			if (isPocketed)
			{
				RoundManager.Instance.PlayAudibleNoise(((Component)this).transform.position, noiseRange / 2f, noiseLoudness / 2f, timesPlayedInOneSpot, isInElevator && StartOfRound.Instance.hangarDoorsClosed);
			}
			else
			{
				RoundManager.Instance.PlayAudibleNoise(((Component)this).transform.position, noiseRange, noiseLoudness, timesPlayedInOneSpot, isInElevator && StartOfRound.Instance.hangarDoorsClosed);
			}
		}
		else
		{
			makeNoiseInterval -= Time.deltaTime;
		}
	}

	protected override void __initializeVariables()
	{
		base.__initializeVariables();
	}

	protected internal override string __getTypeName()
	{
		return "AnimatedItem";
	}
}
public class AnimatedTextureUV : MonoBehaviour
{
	private Material[] setMaterials;

	public MeshRenderer meshRenderer;

	public SkinnedMeshRenderer skinnedMeshRenderer;

	public int materialIndex;

	public int columns = 1;

	public int rows = 1;

	public float waitFrameTime = 0.005f;

	private float horizontalOffset;

	private float verticalOffset;

	private Coroutine animateMaterial;

	private bool skinnedMesh;

	private void OnEnable()
	{
		if (animateMaterial == null)
		{
			Debug.Log((object)"Animating material now");
			animateMaterial = ((MonoBehaviour)this).StartCoroutine(AnimateUV());
		}
	}

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

	private IEnumerator AnimateUV()
	{
		yield return null;
		if ((Object)(object)skinnedMeshRenderer != (Object)null)
		{
			setMaterials = ((Renderer)skinnedMeshRenderer).materials;
			skinnedMesh = true;
		}
		else
		{
			setMaterials = ((Renderer)meshRenderer).materials;
		}
		float maxVertical = 1f - 1f / (float)columns;
		float maxHorizontal = 1f - 1f / (float)rows;
		while (((Behaviour)this).enabled)
		{
			yield return (object)new WaitForSeconds(waitFrameTime);
			horizontalOffset += 1f / (float)rows;
			if (horizontalOffset > maxHorizontal)
			{
				horizontalOffset = 0f;
				verticalOffset += 1f / (float)columns;
				if (verticalOffset > maxVertical)
				{
					verticalOffset = 0f;
				}
			}
			setMaterials[materialIndex].SetTextureOffset("_BaseColorMap", new Vector2(horizontalOffset, verticalOffset));
			if (skinnedMesh)
			{
				((Renderer)skinnedMeshRenderer).materials = setMaterials;
			}
			else
			{
				((Renderer)skinnedMeshRenderer).materials = setMaterials;
			}
		}
	}
}
public class AnimationStopPoints : MonoBehaviour
{
	public bool canAnimationStop;

	public int animationPosition = 1;

	public void SetAnimationStopPosition1()
	{
		canAnimationStop = true;
		animationPosition = 1;
	}

	public void SetAnimationGo()
	{
		canAnimationStop = false;
	}

	public void SetAnimationStopPosition2()
	{
		canAnimationStop = true;
		animationPosition = 2;
	}
}
public class AudioReverbPresets : MonoBehaviour
{
	public AudioReverbTrigger[] audioPresets;
}
public class AutoParentToShip : NetworkBehaviour
{
	public bool disableObject;

	public Vector3 positionOffset;

	public Vector3 rotationOffset;

	[HideInInspector]
	public Vector3 startingPosition;

	[HideInInspector]
	public Vector3 startingRotation;

	public bool overrideOffset;

	private void Awake()
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0043: 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_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: 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_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		if (!overrideOffset)
		{
			positionOffset = StartOfRound.Instance.elevatorTransform.InverseTransformPoint(((Component)this).transform.position);
			rotationOffset = StartOfRound.Instance.elevatorTransform.InverseTransformDirection(((Component)this).transform.eulerAngles);
		}
		MoveToOffset();
		PlaceableShipObject component = ((Component)this).gameObject.GetComponent<PlaceableShipObject>();
		if ((Object)(object)component != (Object)null && (Object)(object)component.parentObjectSecondary != (Object)null)
		{
			startingPosition = component.parentObjectSecondary.position;
			startingRotation = component.parentObjectSecondary.eulerAngles;
		}
		else
		{
			startingPosition = positionOffset;
			startingRotation = rotationOffset;
		}
	}

	private void LateUpdate()
	{
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		if (!StartOfRound.Instance.suckingFurnitureOutOfShip)
		{
			if (disableObject)
			{
				((Component)this).transform.position = new Vector3(800f, -100f, 0f);
			}
			else
			{
				MoveToOffset();
			}
		}
	}

	public void StartSuckingOutOfShip()
	{
		((MonoBehaviour)this).StartCoroutine(SuckObjectOutOfShip());
	}

	private IEnumerator SuckObjectOutOfShip()
	{
		Vector3 dir = Vector3.Normalize((StartOfRound.Instance.middleOfSpaceNode.position - ((Component)this).transform.position) * 10000f);
		Debug.Log((object)dir);
		Quaternion randomRotation = Random.rotation;
		while (StartOfRound.Instance.suckingFurnitureOutOfShip)
		{
			yield return null;
			((Component)this).transform.position = ((Component)this).transform.position + dir * (Time.deltaTime * Mathf.Clamp(StartOfRound.Instance.suckingPower, 1.1f, 100f) * 17f);
			((Component)this).transform.rotation = Quaternion.Lerp(((Component)this).transform.rotation, ((Component)this).transform.rotation * randomRotation, Time.deltaTime * StartOfRound.Instance.suckingPower);
			Debug.DrawRay(((Component)this).transform.position + Vector3.up * 0.2f, StartOfRound.Instance.middleOfSpaceNode.position - ((Component)this).transform.position, Color.blue);
			Debug.DrawRay(((Component)this).transform.position, dir, Color.green);
		}
	}

	public void MoveToOffset()
	{
		//IL_0010: 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_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		((Component)this).transform.rotation = StartOfRound.Instance.elevatorTransform.rotation;
		((Component)this).transform.Rotate(rotationOffset);
		((Component)this).transform.position = StartOfRound.Instance.elevatorTransform.position;
		Vector3 val = positionOffset;
		val = StartOfRound.Instance.elevatorTransform.rotation * val;
		Transform transform = ((Component)this).transform;
		transform.position += val;
	}

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

	protected internal override string __getTypeName()
	{
		return "AutoParentToShip";
	}
}
public class BaboonBirdAI : EnemyAI
{
	public Dictionary<Transform, Threat> threats = new Dictionary<Transform, Threat>();

	public Transform focusedThreatTransform;

	public Threat focusedThreat;

	public bool focusingOnThreat;

	public bool focusedThreatIsInView;

	private int focusLevel;

	private float fearLevel;

	private float fearLevelNoDistComparison;

	private Vector3 agentLocalVelocity;

	private float velX;

	private float velZ;

	private Vector3 previousPosition;

	public Transform animationContainer;

	public MultiAimConstraint headLookRig;

	public Transform headLookTarget;

	private Ray lookRay;

	public float fov;

	public float visionDistance;

	private int visibleThreatsMask = 524296;

	private int scrapMask = 64;

	private int leadershipLevel;

	private int previousBehaviourState = -1;

	public BaboonHawkGroup scoutingGroup;

	private float miscAnimationTimer;

	private int currentMiscAnimation;

	private Vector3 lookTarget;

	private Vector3 peekTarget;

	private float peekTimer;

	public AISearchRoutine scoutingSearchRoutine;

	public static Vector3 baboonCampPosition;

	public float scoutTimer;

	public float timeToScout;

	private float timeSinceRestWhileScouting;

	private float restingDuringScouting;

	private bool eyesClosed;

	private bool restingAtCamp;

	private float restAtCampTimer;

	private float chosenDistanceToCamp = 1f;

	private float timeSincePingingBirdInterest;

	private float timeSinceLastMiscAnimation;

	private int aggressiveMode;

	private int previousAggressiveMode;

	private float fightTimer;

	public AudioSource aggressionAudio;

	private Vector3 debugSphere;

	public Collider ownCollider;

	private float timeSinceAggressiveDisplay;

	private float timeSpentFocusingOnThreat;

	private float timeSinceFighting;

	private bool doingKillAnimation;

	private Coroutine killAnimCoroutine;

	private float timeSinceHitting;

	public Transform deadBodyPoint;

	public AudioClip[] cawScreamSFX;

	public AudioClip[] cawLaughSFX;

	private float noiseTimer;

	private float noiseInterval;

	public GrabbableObject focusedScrap;

	public GrabbableObject heldScrap;

	public bool movingToScrap;

	public Transform grabTarget;

	public TwoBoneIKConstraint leftArmRig;

	public TwoBoneIKConstraint rightArmRig;

	private bool oddAIInterval;

	private DeadBodyInfo killAnimationBody;

	private float timeSinceBeingAttackedByPlayer;

	private float timeSinceJoiningOrLeavingScoutingGroup;

	private BaboonBirdAI biggestBaboon;

	public override void Start()
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: 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_0078: 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_0107: Unknown result type (might be due to invalid IL or missing references)
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		base.Start();
		if (!((NetworkBehaviour)this).IsOwner)
		{
			return;
		}
		Random random = new Random(StartOfRound.Instance.randomMapSeed + thisEnemyIndex);
		leadershipLevel = random.Next(0, 500);
		if (baboonCampPosition == Vector3.zero)
		{
			List<GameObject> list = new List<GameObject>();
			for (int i = 0; i < RoundManager.Instance.outsideAINodes.Length - 2; i += 2)
			{
				if (Vector3.Distance(RoundManager.Instance.outsideAINodes[i].transform.position, StartOfRound.Instance.elevatorTransform.position) > 30f && !PathIsIntersectedByLineOfSight(RoundManager.Instance.outsideAINodes[i].transform.position, calculatePathDistance: false, avoidLineOfSight: false))
				{
					list.Add(RoundManager.Instance.outsideAINodes[i]);
				}
			}
			if (list.Count == 0)
			{
				baboonCampPosition = ((Component)this).transform.position;
			}
			else
			{
				baboonCampPosition = RoundManager.Instance.GetRandomNavMeshPositionInBoxPredictable(list[random.Next(0, list.Count)].transform.position, 15f, RoundManager.Instance.navHit, random);
			}
		}
		SyncInitialValuesServerRpc(leadershipLevel, baboonCampPosition);
	}

	[ServerRpc]
	public void SyncInitialValuesServerRpc(int syncLeadershipLevel, Vector3 campPosition)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Invalid comparison between Unknown and I4
		//IL_011d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: 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(3452382367u, val, (RpcDelivery)0);
			BytePacker.WriteValueBitPacked(val2, syncLeadershipLevel);
			((FastBufferWriter)(ref val2)).WriteValueSafe(ref campPosition);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3452382367u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			SyncInitialValuesClientRpc(syncLeadershipLevel, campPosition);
		}
	}

	[ClientRpc]
	public void SyncInitialValuesClientRpc(int syncLeadershipLevel, Vector3 campPosition)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: 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_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		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(3856685904u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, syncLeadershipLevel);
				((FastBufferWriter)(ref val2)).WriteValueSafe(ref campPosition);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3856685904u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				leadershipLevel = syncLeadershipLevel;
				baboonCampPosition = campPosition;
				((Component)this).transform.localScale = ((Component)this).transform.localScale * Mathf.Max((float)leadershipLevel / 200f * 0.6f, 0.9f);
			}
		}
	}

	public void LateUpdate()
	{
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		if ((!inSpecialAnimation && ((Object)(object)focusedThreatTransform == (Object)null || currentBehaviourStateIndex != 2) && peekTimer < 0f) || isEnemyDead)
		{
			agent.angularSpeed = 300f;
			((RigConstraint<MultiAimConstraintJob, MultiAimConstraintData, MultiAimConstraintJobBinder<MultiAimConstraintData>>)(object)headLookRig).weight = Mathf.Lerp(((RigConstraint<MultiAimConstraintJob, MultiAimConstraintData, MultiAimConstraintJobBinder<MultiAimConstraintData>>)(object)headLookRig).weight, 0f, Time.deltaTime * 10f);
			return;
		}
		agent.angularSpeed = 0f;
		((RigConstraint<MultiAimConstraintJob, MultiAimConstraintData, MultiAimConstraintJobBinder<MultiAimConstraintData>>)(object)headLookRig).weight = Mathf.Lerp(((RigConstraint<MultiAimConstraintJob, MultiAimConstraintData, MultiAimConstraintJobBinder<MultiAimConstraintData>>)(object)headLookRig).weight, 1f, Time.deltaTime * 10f);
		if (peekTimer >= 0f)
		{
			peekTimer -= Time.deltaTime;
			AnimateLooking(peekTarget);
		}
		else
		{
			AnimateLooking(lookTarget);
		}
	}

	public override void OnCollideWithPlayer(Collider other)
	{
		//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_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_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: 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_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_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_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_0087: 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_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_00a2: 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_00fa: 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_0181: Unknown result type (might be due to invalid IL or missing references)
		base.OnCollideWithPlayer(other);
		if (timeSinceHitting < 0.5f)
		{
			return;
		}
		Vector3 val = Vector3.Normalize(((Component)this).transform.position + Vector3.up * 0.7f - (((Component)other).transform.position + Vector3.up * 0.4f)) * 0.5f;
		if (Physics.Linecast(((Component)this).transform.position + Vector3.up * 0.7f + val, ((Component)other).transform.position + Vector3.up * 0.4f, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))
		{
			return;
		}
		PlayerControllerB playerControllerB = MeetsStandardPlayerCollisionConditions(other, inSpecialAnimation || doingKillAnimation);
		if ((Object)(object)playerControllerB != (Object)null)
		{
			timeSinceHitting = 0f;
			playerControllerB.DamagePlayer(30);
			if (playerControllerB.isPlayerDead)
			{
				StabPlayerDeathAnimServerRpc((int)playerControllerB.playerClientId);
				return;
			}
			creatureAnimator.ResetTrigger("Hit");
			creatureAnimator.SetTrigger("Hit");
			creatureSFX.PlayOneShot(enemyType.audioClips[5]);
			WalkieTalkie.TransmitOneShotAudio(creatureSFX, enemyType.audioClips[5]);
			RoundManager.Instance.PlayAudibleNoise(((Component)creatureSFX).transform.position, 8f, 0.7f);
		}
	}

	public override void OnCollideWithEnemy(Collider other, EnemyAI enemyScript = null)
	{
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		base.OnCollideWithEnemy(other);
		if (!((Object)(object)enemyScript.enemyType == (Object)(object)enemyType) && !(timeSinceHitting < 0.75f) && ((NetworkBehaviour)this).IsOwner && enemyScript.enemyType.canDie)
		{
			timeSinceHitting = 0f;
			creatureAnimator.ResetTrigger("Hit");
			creatureAnimator.SetTrigger("Hit");
			creatureSFX.PlayOneShot(enemyType.audioClips[5]);
			WalkieTalkie.TransmitOneShotAudio(creatureSFX, enemyType.audioClips[5]);
			RoundManager.Instance.PlayAudibleNoise(((Component)creatureSFX).transform.position, 8f, 0.7f);
			enemyScript.HitEnemy(1, null, playHitSFX: true);
		}
	}

	public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false)
	{
		base.HitEnemy(force, playerWhoHit, playHitSFX);
		if (isEnemyDead)
		{
			return;
		}
		creatureAnimator.SetTrigger("TakeDamage");
		if ((Object)(object)playerWhoHit != (Object)null)
		{
			timeSinceBeingAttackedByPlayer = 0f;
			if (threats.TryGetValue(((Component)playerWhoHit).transform, out var value))
			{
				value.hasAttacked = true;
				fightTimer = 7f;
			}
		}
		enemyHP -= force;
		if (((NetworkBehaviour)this).IsOwner && enemyHP <= 0 && !isEnemyDead)
		{
			KillEnemyOnOwnerClient();
		}
		StopKillAnimation();
	}

	public override void KillEnemy(bool destroy = false)
	{
		base.KillEnemy(destroy);
		creatureAnimator.SetBool("IsDead", true);
		if ((Object)(object)heldScrap != (Object)null && ((NetworkBehaviour)this).IsOwner)
		{
			DropHeldItemAndSync();
		}
		StopKillAnimation();
	}

	public void StopKillAnimation()
	{
		if (killAnimCoroutine != null)
		{
			((MonoBehaviour)this).StopCoroutine(killAnimCoroutine);
		}
		agent.acceleration = 17f;
		inSpecialAnimation = false;
		doingKillAnimation = false;
		if ((Object)(object)killAnimationBody != (Object)null)
		{
			killAnimationBody.attachedLimb = null;
			killAnimationBody.attachedTo = null;
			killAnimationBody = null;
		}
	}

	[ServerRpc(RequireOwnership = false)]
	public void StabPlayerDeathAnimServerRpc(int playerObject)
	{
		//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 != 1 && (networkManager.IsClient || networkManager.IsHost))
		{
			ServerRpcParams val = default(ServerRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2476579270u, val, (RpcDelivery)0);
			BytePacker.WriteValueBitPacked(val2, playerObject);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2476579270u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && !doingKillAnimation)
		{
			if (((NetworkBehaviour)this).IsOwner && (Object)(object)heldScrap != (Object)null)
			{
				DropHeldItemAndSync();
			}
			doingKillAnimation = true;
			StabPlayerDeathAnimClientRpc(playerObject);
		}
	}

	[ClientRpc]
	public void StabPlayerDeathAnimClientRpc(int playerObject)
	{
		//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(3749667856u, val, (RpcDelivery)0);
			BytePacker.WriteValueBitPacked(val2, playerObject);
			((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3749667856u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
		{
			doingKillAnimation = true;
			inSpecialAnimation = true;
			agent.acceleration = 70f;
			agent.speed = 0f;
			if (killAnimCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(killAnimCoroutine);
			}
			killAnimCoroutine = ((MonoBehaviour)this).StartCoroutine(killPlayerAnimation(playerObject));
		}
	}

	private IEnumerator killPlayerAnimation(int playerObject)
	{
		PlayerControllerB killedPlayer = StartOfRound.Instance.allPlayerScripts[playerObject];
		creatureAnimator.ResetTrigger("KillAnimation");
		creatureAnimator.SetTrigger("KillAnimation");
		creatureVoice.PlayOneShot(enemyType.audioClips[4]);
		WalkieTalkie.TransmitOneShotAudio(creatureVoice, enemyType.audioClips[4]);
		float startTime = Time.realtimeSinceStartup;
		yield return (object)new WaitUntil((Func<bool>)(() => Time.realtimeSinceStartup - startTime > 1f || (Object)(object)killedPlayer.deadBody != (Object)null));
		if ((Object)(object)killedPlayer.deadBody != (Object)null)
		{
			killAnimationBody = killedPlayer.deadBody;
			killAnimationBody.attachedLimb = killedPlayer.deadBody.bodyParts[5];
			killAnimationBody.attachedTo = deadBodyPoint;
			killAnimationBody.matchPositionExactly = true;
			killAnimationBody.canBeGrabbedBackByPlayers = false;
			yield return null;
			yield return (object)new WaitForSeconds(1.7f);
			killAnimationBody.attachedLimb = null;
			killAnimationBody.attachedTo = null;
		}
		agent.acceleration = 17f;
		inSpecialAnimation = false;
		doingKillAnimation = false;
	}

	private void InteractWithScrap()
	{
		//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_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_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: 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_00d7: 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_00ec: 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)
		if ((Object)(object)heldScrap != (Object)null)
		{
			focusedScrap = null;
			if (Vector3.Distance(((Component)this).transform.position, baboonCampPosition) < Random.Range(1f, 7f) || heldScrap.isHeld)
			{
				DropHeldItemAndSync();
			}
		}
		else if ((Object)(object)focusedScrap != (Object)null)
		{
			if (debugEnemyAI)
			{
				Debug.DrawRay(((Component)focusedScrap).transform.position, Vector3.up * 3f, Color.yellow);
			}
			if (!CanGrabScrap(focusedScrap))
			{
				focusedScrap = null;
			}
			else if (Vector3.Distance(((Component)this).transform.position, ((Component)focusedScrap).transform.position) < 0.4f && !Physics.Linecast(((Component)this).transform.position, ((Component)focusedScrap).transform.position + Vector3.up * 0.5f, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))
			{
				GrabItemAndSync(((NetworkBehaviour)focusedScrap).NetworkObject);
			}
		}
	}

	private bool CanGrabScrap(GrabbableObject scrap)
	{
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		if (scrap.itemProperties.itemId == 1531)
		{
			return false;
		}
		if (scrap.isInShipRoom && !isInsidePlayerShip)
		{
			return false;
		}
		if (isEnemyDead)
		{
			return false;
		}
		if (!scrap.heldByPlayerOnServer && !scrap.isHeld && ((Object)(object)scrap == (Object)(object)heldScrap || !scrap.isHeldByEnemy))
		{
			return Vector3.Distance(((Component)scrap).transform.position, baboonCampPosition) > 8f;
		}
		return false;
	}

	private void DropHeldItemAndSync()
	{
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)heldScrap == (Object)null)
		{
			Debug.LogError((object)$"Baboon #{thisEnemyIndex} Error: DropItemAndSync called when baboon has no scrap!");
		}
		NetworkObject networkObject = ((NetworkBehaviour)heldScrap).NetworkObject;
		if ((Object)(object)networkObject == (Object)null)
		{
			Debug.LogError((object)$"Baboon #{thisEnemyIndex} Error: No network object in held scrap {((Object)((Component)heldScrap).gameObject).name}");
		}
		Vector3 itemFloorPosition = heldScrap.GetItemFloorPosition();
		DropScrap(networkObject, itemFloorPosition);
		DropScrapServerRpc(NetworkObjectReference.op_Implicit(networkObject), itemFloorPosition, (int)GameNetworkManager.Instance.localPlayerController.playerClientId);
	}

	[ServerRpc]
	public void DropScrapServerRpc(NetworkObjectReference item, Vector3 targetFloorPosition, int clientWhoSentRPC)
	{
		//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_0138: 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_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_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(1418775270u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(ref item, default(ForNetworkSerializable));
			((FastBufferWriter)(ref val2)).WriteValueSafe(ref targetFloorPosition);
			BytePacker.WriteValueBitPacked(val2, clientWhoSentRPC);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1418775270u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			DropScrapClientRpc(item, targetFloorPosition, clientWhoSentRPC);
		}
	}

	[ClientRpc]
	public void DropScrapClientRpc(NetworkObjectReference item, Vector3 targetFloorPosition, int clientWhoSentRPC)
	{
		//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_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_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_0112: 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(1865475504u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(ref item, default(ForNetworkSerializable));
			((FastBufferWriter)(ref val2)).WriteValueSafe(ref targetFloorPosition);
			BytePacker.WriteValueBitPacked(val2, clientWhoSentRPC);
			((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1865475504u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && clientWhoSentRPC != (int)GameNetworkManager.Instance.localPlayerController.playerClientId)
		{
			NetworkObject item2 = default(NetworkObject);
			if (((NetworkObjectReference)(ref item)).TryGet(ref item2, (NetworkManager)null))
			{
				DropScrap(item2, targetFloorPosition);
			}
			else
			{
				Debug.LogError((object)$"Baboon #{thisEnemyIndex}; Error, was not able to get network object from dropped item client rpc");
			}
		}
	}

	private void DropScrap(NetworkObject item, Vector3 targetFloorPosition)
	{
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: 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_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)heldScrap == (Object)null)
		{
			Debug.LogError((object)"Baboon: my held item is null when attempting to drop it!!");
			return;
		}
		if (heldScrap.isHeld)
		{
			heldScrap.DiscardItemFromEnemy();
			heldScrap.isHeldByEnemy = false;
			heldScrap = null;
			Debug.Log((object)$"Baboon #{thisEnemyIndex}: Dropped item which was held by a player");
			return;
		}
		heldScrap.parentObject = null;
		((Component)heldScrap).transform.SetParent(StartOfRound.Instance.propsContainer, true);
		heldScrap.EnablePhysics(enable: true);
		heldScrap.fallTime = 0f;
		heldScrap.startFallingPosition = ((Component)heldScrap).transform.parent.InverseTransformPoint(((Component)heldScrap).transform.position);
		heldScrap.targetFloorPosition = ((Component)heldScrap).transform.parent.InverseTransformPoint(targetFloorPosition);
		heldScrap.floorYRot = -1;
		heldScrap.DiscardItemFromEnemy();
		heldScrap.isHeldByEnemy = false;
		heldScrap = null;
		Debug.Log((object)$"Baboon #{thisEnemyIndex}: Dropped item");
	}

	private void GrabItemAndSync(NetworkObject item)
	{
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)heldScrap != (Object)null)
		{
			Debug.LogError((object)$"Baboon #{thisEnemyIndex} Error: GrabItemAndSync called when baboon is already carrying scrap!");
		}
		GrabScrap(item);
		GrabScrapServerRpc(NetworkObjectReference.op_Implicit(item), (int)GameNetworkManager.Instance.localPlayerController.playerClientId);
	}

	[ServerRpc]
	public void GrabScrapServerRpc(NetworkObjectReference item, int clientWhoSentRPC)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: 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_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: 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_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Invalid comparison between Unknown and I4
		//IL_016b: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
		{
			if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
				return;
			}
			ServerRpcParams val = default(ServerRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(869682226u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(ref item, default(ForNetworkSerializable));
			BytePacker.WriteValueBitPacked(val2, clientWhoSentRPC);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 869682226u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			NetworkObject val3 = default(NetworkObject);
			if (!((NetworkObjectReference)(ref item)).TryGet(ref val3, (NetworkManager)null))
			{
				Debug.LogError((object)$"Baboon #{thisEnemyIndex} error: Could not get grabbed network object from reference on server");
			}
			else if (Object.op_Implicit((Object)(object)((Component)val3).GetComponent<GrabbableObject>()) && !((Component)val3).GetComponent<GrabbableObject>().heldByPlayerOnServer)
			{
				GrabScrapClientRpc(item, clientWhoSentRPC);
			}
		}
	}

	[ClientRpc]
	public void GrabScrapClientRpc(NetworkObjectReference item, int clientWhoSentRPC)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
		{
			ClientRpcParams val = default(ClientRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1564051222u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(ref item, default(ForNetworkSerializable));
			BytePacker.WriteValueBitPacked(val2, clientWhoSentRPC);
			((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1564051222u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && clientWhoSentRPC != (int)GameNetworkManager.Instance.localPlayerController.playerClientId)
		{
			NetworkObject item2 = default(NetworkObject);
			if (((NetworkObjectReference)(ref item)).TryGet(ref item2, (NetworkManager)null))
			{
				GrabScrap(item2);
			}
			else
			{
				Debug.LogError((object)$"Baboon #{thisEnemyIndex}; Error, was not able to get id from grabbed item client rpc");
			}
		}
	}

	private void GrabScrap(NetworkObject item)
	{
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)heldScrap != (Object)null)
		{
			Debug.Log((object)$"Baboon #{thisEnemyIndex}: Trying to grab another item ({((Object)((Component)item).gameObject).name}) while hands are already full with item ({((Object)((Component)heldScrap).gameObject).name}). Dropping the currently held one.");
			DropScrap(((Component)heldScrap).GetComponent<NetworkObject>(), heldScrap.GetItemFloorPosition());
		}
		GrabbableObject grabbableObject = (heldScrap = ((Component)item).gameObject.GetComponent<GrabbableObject>());
		grabbableObject.parentObject = grabTarget;
		grabbableObject.hasHitGround = false;
		grabbableObject.GrabItemFromEnemy(this);
		grabbableObject.isHeldByEnemy = true;
		grabbableObject.EnablePhysics(enable: false);
		Debug.Log((object)$"Baboon #{thisEnemyIndex}: Grabbing item!!! {((Object)((Component)heldScrap).gameObject).name}");
	}

	public override void ReachedNodeInSearch()
	{
		base.ReachedNodeInSearch();
		if (currentSearch.nodesEliminatedInCurrentSearch > 14 && timeSinceRestWhileScouting > 17f && timeSinceAggressiveDisplay > 6f)
		{
			timeSinceRestWhileScouting = 0f;
			restingDuringScouting = 12f;
		}
	}

	public override void DoAIInterval()
	{
		//IL_00b9: 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_0486: Unknown result type (might be due to invalid IL or missing references)
		//IL_0477: 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_049d: Unknown result type (might be due to invalid IL or missing references)
		//IL_066b: 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_0258: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0314: Unknown result type (might be due to invalid IL or missing references)
		//IL_0336: Unknown result type (might be due to invalid IL or missing references)
		//IL_034e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0363: Unknown result type (might be due to invalid IL or missing references)
		//IL_0398: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_08f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0904: Unknown result type (might be due to invalid IL or missing references)
		//IL_090e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0913: Unknown result type (might be due to invalid IL or missing references)
		//IL_0918: Unknown result type (might be due to invalid IL or missing references)
		//IL_091a: Unknown result type (might be due to invalid IL or missing references)
		//IL_091c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0926: Unknown result type (might be due to invalid IL or missing references)
		//IL_092b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0943: Unknown result type (might be due to invalid IL or missing references)
		//IL_0948: Unknown result type (might be due to invalid IL or missing references)
		//IL_0952: Unknown result type (might be due to invalid IL or missing references)
		//IL_0957: Unknown result type (might be due to invalid IL or missing references)
		//IL_0962: Unknown result type (might be due to invalid IL or missing references)
		//IL_0967: Unknown result type (might be due to invalid IL or missing references)
		//IL_0971: Unknown result type (might be due to invalid IL or missing references)
		//IL_0976: Unknown result type (might be due to invalid IL or missing references)
		//IL_097b: Unknown result type (might be due to invalid IL or missing references)
		//IL_097d: 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_098c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0996: Unknown result type (might be due to invalid IL or missing references)
		//IL_079f: Unknown result type (might be due to invalid IL or missing references)
		//IL_07af: Unknown result type (might be due to invalid IL or missing references)
		//IL_07b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_07be: Unknown result type (might be due to invalid IL or missing references)
		//IL_07c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_07c5: 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_07d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_07d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_07e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_09de: Unknown result type (might be due to invalid IL or missing references)
		//IL_09e8: 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_09f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_09b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_09c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_09cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_09d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_08df: Unknown result type (might be due to invalid IL or missing references)
		//IL_09fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_09fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0a01: Unknown result type (might be due to invalid IL or missing references)
		//IL_0a16: Unknown result type (might be due to invalid IL or missing references)
		//IL_0a2b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0a2d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0a21: Unknown result type (might be due to invalid IL or missing references)
		//IL_0a23: Unknown result type (might be due to invalid IL or missing references)
		base.DoAIInterval();
		if (isEnemyDead)
		{
			agent.speed = 0f;
			if (scoutingSearchRoutine.inProgress)
			{
				StopSearch(scoutingSearchRoutine, clear: false);
			}
			return;
		}
		if (stunNormalizedTimer > 0f || miscAnimationTimer > 0f)
		{
			agent.speed = 0f;
			if (doingKillAnimation && stunNormalizedTimer >= 0f)
			{
				StopKillAnimation();
			}
			if ((Object)(object)heldScrap != (Object)null && ((NetworkBehaviour)this).IsOwner)
			{
				DropHeldItemAndSync();
			}
			if ((Object)(object)stunnedByPlayer != (Object)null)
			{
				PingBaboonInterest(((Component)stunnedByPlayer.gameplayCamera).transform.position, 4);
			}
		}
		if (inSpecialAnimation)
		{
			agent.speed = 0f;
			return;
		}
		if (!eyesClosed)
		{
			DoLOSCheck();
		}
		InteractWithScrap();
		switch (currentBehaviourStateIndex)
		{
		case 0:
			if (previousBehaviourState != currentBehaviourStateIndex)
			{
				timeToScout = Random.Range(25, 70);
				scoutTimer = 0f;
				restingAtCamp = false;
				restAtCampTimer = 0f;
				SetAggressiveMode(0);
				previousBehaviourState = currentBehaviourStateIndex;
			}
			if (!((NetworkBehaviour)this).IsOwner)
			{
				break;
			}
			if ((Object)(object)focusedScrap != (Object)null)
			{
				SetDestinationToPosition(((Component)focusedScrap).transform.position);
			}
			if (scoutingGroup == null || (Object)(object)scoutingGroup.leader == (Object)(object)this || !scoutingGroup.members.Contains(this))
			{
				_ = scoutingGroup;
				if (restingDuringScouting >= 0f)
				{
					if (scoutingSearchRoutine.inProgress)
					{
						StopSearch(scoutingSearchRoutine, clear: false);
					}
					if (!creatureAnimator.GetBool("sit"))
					{
						EnemyEnterRestModeServerRpc(sleep: false, atCamp: false);
					}
					creatureAnimator.SetBool("sit", true);
					restingDuringScouting -= AIIntervalTime;
					agent.speed = 0f;
				}
				else
				{
					if (!scoutingSearchRoutine.inProgress && (Object)(object)focusedScrap == (Object)null)
					{
						StartSearch(baboonCampPosition, scoutingSearchRoutine);
					}
					if (creatureAnimator.GetBool("sit"))
					{
						EnemyGetUpServerRpc();
						creatureAnimator.SetBool("sit", false);
					}
					agent.speed = 10f;
				}
			}
			else
			{
				if (scoutingSearchRoutine.inProgress)
				{
					StopSearch(scoutingSearchRoutine);
				}
				if (creatureAnimator.GetBool("sit"))
				{
					EnemyGetUpServerRpc();
					creatureAnimator.SetBool("sit", false);
				}
				agent.speed = 12f;
				if (Vector3.Distance(((Component)this).transform.position, ((Component)scoutingGroup.leader).transform.position) > 60f || PathIsIntersectedByLineOfSight(((Component)scoutingGroup.leader).transform.position, calculatePathDistance: false, avoidLineOfSight: false))
				{
					LeaveCurrentScoutingGroup(sync: true);
				}
				else if (Vector3.Distance(destination, ((Component)scoutingGroup.leader).transform.position) > 8f && (Object)(object)focusedScrap == (Object)null)
				{
					SetDestinationToPosition(RoundManager.Instance.GetRandomNavMeshPositionInRadiusSpherical(((Component)scoutingGroup.leader).transform.position, 6f, RoundManager.Instance.navHit));
				}
			}
			if (scoutTimer < timeToScout && (Object)(object)heldScrap == (Object)null)
			{
				scoutTimer += AIIntervalTime;
			}
			else
			{
				SwitchToBehaviourState(1);
			}
			break;
		case 1:
			if (previousBehaviourState != currentBehaviourStateIndex)
			{
				restingDuringScouting = 0f;
				scoutTimer = 0f;
				chosenDistanceToCamp = Random.Range(1f, 7f);
				LeaveCurrentScoutingGroup(sync: true);
				SetAggressiveMode(0);
				previousBehaviourState = currentBehaviourStateIndex;
			}
			if (scoutingSearchRoutine.inProgress)
			{
				StopSearch(scoutingSearchRoutine);
			}
			if ((Object)(object)focusedScrap != (Object)null)
			{
				SetDestinationToPosition(((Component)focusedScrap).transform.position);
			}
			else
			{
				SetDestinationToPosition(baboonCampPosition);
			}
			if (Vector3.Distance(((Component)this).transform.position, baboonCampPosition) < chosenDistanceToCamp && peekTimer < 0f)
			{
				if (!restingAtCamp)
				{
					restingAtCamp = true;
					restAtCampTimer = Random.Range(15f, 30f);
					if ((Object)(object)heldScrap != (Object)null)
					{
						DropHeldItemAndSync();
					}
					bool sleep = false;
					if (Random.Range(0, 100) < 35)
					{
						sleep = true;
					}
					EnemyEnterRestModeServerRpc(sleep, atCamp: true);
				}
				else if (restAtCampTimer <= 0f)
				{
					SwitchToBehaviourState(0);
				}
				else
				{
					restAtCampTimer -= AIIntervalTime;
				}
				agent.speed = 0f;
			}
			else
			{
				if (restingAtCamp)
				{
					restingAtCamp = false;
					EnemyGetUpServerRpc();
				}
				creatureAnimator.SetBool("sit", false);
				creatureAnimator.SetBool("sleep", false);
				agent.speed = 9f;
			}
			break;
		case 2:
		{
			if (previousBehaviourState != currentBehaviourStateIndex)
			{
				timeSpentFocusingOnThreat = 0f;
				creatureAnimator.SetBool("sleep", false);
				creatureAnimator.SetBool("sit", false);
				EnemyGetUpServerRpc();
				previousBehaviourState = currentBehaviourStateIndex;
			}
			if (focusedThreat == null || !focusingOnThreat)
			{
				StopFocusingThreat();
			}
			if (scoutingSearchRoutine.inProgress)
			{
				StopSearch(scoutingSearchRoutine, clear: false);
			}
			agent.speed = 9f;
			float num = fearLevelNoDistComparison * 2f;
			if (focusedThreat.interestLevel <= 0 || enemyHP <= 3)
			{
				num = Mathf.Max(num, 1f);
			}
			float num2 = GetComfortableDistanceToThreat(focusedThreat) + num;
			float num3 = Vector3.Distance(((Component)this).transform.position, focusedThreat.lastSeenPosition);
			bool flag = false;
			float num4 = Time.realtimeSinceStartup - focusedThreat.timeLastSeen;
			if (num4 > 5f)
			{
				SetThreatInView(inView: false);
				focusLevel = 0;
				StopFocusingThreat();
				break;
			}
			if (num4 > 3f)
			{
				SetThreatInView(inView: false);
				focusLevel = 1;
				if (num2 - num3 > 2f)
				{
					StopFocusingThreat();
					break;
				}
			}
			else if (num4 > 1f)
			{
				flag = true;
				focusedThreatIsInView = false;
				SetThreatInView(inView: false);
				focusLevel = 2;
				SetAggressiveMode(0);
			}
			else if (num4 < 0.55f)
			{
				flag = true;
				SetThreatInView(inView: true);
			}
			bool flag2 = (fearLevel > 0f && fearLevel < 4f) || focusedThreat.interestLevel > 0 || fearLevel < -6f || focusedThreat.hasAttacked;
			if (aggressiveMode == 2)
			{
				focusLevel = 3;
				if ((Object)(object)heldScrap != (Object)null)
				{
					DropHeldItemAndSync();
					focusedScrap = heldScrap;
				}
				Vector3 val = focusedThreat.threatScript.GetThreatTransform().position + focusedThreat.threatScript.GetThreatVelocity() * 10f;
				Debug.DrawRay(val, Vector3.up * 5f, Color.red, AIIntervalTime);
				SetDestinationToPosition(val, checkForPath: true);
				if (fightTimer > 4f || timeSinceBeingAttackedByPlayer < 4f || (fightTimer > 2f && (fearLevel >= 1f || !flag2)) || (enemyHP <= 3 && !flag2))
				{
					scoutTimer = timeToScout - 20f;
					fightTimer = -7f;
					SetAggressiveMode(1);
				}
				else if (num3 > 4f)
				{
					fightTimer += AIIntervalTime * 2f;
				}
				else if (num3 > 1f)
				{
					fightTimer += AIIntervalTime;
				}
				else
				{
					fightTimer += AIIntervalTime / 2f;
				}
				break;
			}
			bool flag3 = false;
			if ((Object)(object)focusedScrap != (Object)null && (!flag || fearLevel <= 2f))
			{
				SetDestinationToPosition(((Component)focusedScrap).transform.position);
				flag3 = true;
			}
			Vector3 val2 = focusedThreat.lastSeenPosition + focusedThreat.threatScript.GetThreatVelocity() * -17f;
			Debug.DrawRay(val2, Vector3.up * 3f, Color.red, AIIntervalTime);
			Ray val3 = default(Ray);
			((Ray)(ref val3))..ctor(((Component)this).transform.position + Vector3.up * 0.5f, Vector3.Normalize((((Component)this).transform.position + Vector3.up * 0.5f - val2) * 100f));
			RaycastHit val4 = default(RaycastHit);
			Vector3 val5 = ((!Physics.Raycast(val3, ref val4, num2 - num3, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1)) ? RoundManager.Instance.GetNavMeshPosition(((Ray)(ref val3)).GetPoint(num2 - num3), RoundManager.Instance.navHit, 8f) : RoundManager.Instance.GetNavMeshPosition(((RaycastHit)(ref val4)).point, RoundManager.Instance.navHit, 8f));
			Debug.DrawRay(val5, Vector3.up, Color.blue, AIIntervalTime);
			if (!flag3)
			{
				if (SetDestinationToPosition(val5, checkForPath: true))
				{
					debugSphere = val5;
				}
				else
				{
					debugSphere = val5;
				}
			}
			if (fightTimer > 7f && timeSinceFighting > 4f)
			{
				fightTimer = -6f;
				SetAggressiveMode(2);
				break;
			}
			bool flag4 = false;
			if (scoutingGroup != null)
			{
				for (int i = 0; i < scoutingGroup.members.Count; i++)
				{
					if (scoutingGroup.members[i].aggressiveMode == 2)
					{
						flag4 = true;
					}
				}
			}
			float num5 = GetComfortableDistanceToThreat(focusedThreat) - num3;
			if (fearLevel <= -5f)
			{
				if (noiseTimer >= noiseInterval)
				{
					noiseInterval = Random.Range(0.2f, 0.7f);
					noiseTimer = 0f;
					RoundManager.PlayRandomClip(creatureVoice, cawLaughSFX, randomize: true, 1f, 1105);
				}
				else
				{
					noiseTimer += Time.deltaTime;
				}
			}
			if ((flag && ((num5 > 8f && flag2) || num3 < 5f)) || timeSinceBeingAttackedByPlayer < 4f)
			{
				if (timeSinceFighting > 5f)
				{
					fightTimer += AIIntervalTime * 10.6f / (focusedThreat.distanceToThreat * 0.3f);
				}
				SetAggressiveMode(1);
			}
			else if (num5 > 4f && fearLevel < 3f && flag2)
			{
				fightTimer += AIIntervalTime * 7.4f / (focusedThreat.distanceToThreat * 0.3f);
				SetAggressiveMode(1);
			}
			else
			{
				if (!(num5 < 2f))
				{
					break;
				}
				if (timeSinceAggressiveDisplay > 2.5f)
				{
					SetAggressiveMode(0);
				}
				fightTimer -= Mathf.Max(-6f, AIIntervalTime * 0.2f);
				if (timeSpentFocusingOnThreat > 4f + (float)focusedThreat.interestLevel * 8f && !flag4)
				{
					if (fightTimer > 4f)
					{
						fightTimer -= Mathf.Max(-6f, AIIntervalTime * 0.5f * (focusedThreat.distanceToThreat * 0.1f));
					}
					else
					{
						StopFocusingThreat();
					}
				}
			}
			break;
		}
		}
	}

	private void StopFocusingThreat()
	{
		if (currentBehaviourStateIndex == 2)
		{
			aggressiveMode = 0;
			focusingOnThreat = false;
			focusedThreatIsInView = false;
			focusedThreatTransform = null;
			focusedThreat = null;
			if ((Object)(object)heldScrap == (Object)null)
			{
				SwitchToBehaviourStateOnLocalClient(0);
			}
			else
			{
				SwitchToBehaviourStateOnLocalClient(1);
			}
			StopFocusingThreatServerRpc((Object)(object)heldScrap == (Object)null);
		}
	}

	[ServerRpc]
	public void StopFocusingThreatServerRpc(bool enterScoutingMode)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: 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_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: 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(1546030380u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref enterScoutingMode, default(ForPrimitives));
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1546030380u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			StopFocusingThreatClientRpc(enterScoutingMode);
		}
	}

	[ClientRpc]
	public void StopFocusingThreatClientRpc(bool enterScoutingMode)
	{
		//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(3360048400u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref enterScoutingMode, default(ForPrimitives));
			((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3360048400u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((NetworkBehaviour)this).IsOwner)
		{
			aggressiveMode = 0;
			focusedThreatTransform = null;
			focusedThreat = null;
			if (enterScoutingMode)
			{
				SwitchToBehaviourStateOnLocalClient(0);
			}
			else
			{
				SwitchToBehaviourStateOnLocalClient(1);
			}
		}
	}

	private void SetAggressiveMode(int mode)
	{
		if (aggressiveMode != mode)
		{
			aggressiveMode = mode;
			SetAggressiveModeServerRpc(mode);
		}
	}

	[ServerRpc]
	public void SetAggressiveModeServerRpc(int mode)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e9: Invalid comparison between Unknown and I4
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Invalid comparison between Unknown and I4
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((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(443869275u, val, (RpcDelivery)0);
			BytePacker.WriteValueBitPacked(val2, mode);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 443869275u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			SetAggressiveModeClientRpc(mode);
		}
	}

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

	private void SetThreatInView(bool inView)
	{
		if (focusedThreatIsInView != inView)
		{
			focusedThreatIsInView = inView;
			SetThreatInViewServerRpc(inView);
		}
	}

	[ServerRpc]
	public void SetThreatInViewServerRpc(bool inView)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: 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_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: 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(3428942850u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref inView, default(ForPrimitives));
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3428942850u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			SetThreatInViewClientRpc(inView);
		}
	}

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

	[ServerRpc]
	public void EnemyEnterRestModeServerRpc(bool sleep, bool atCamp)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_0112: 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_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: 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_00f8: 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(1806580287u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref sleep, default(ForPrimitives));
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref atCamp, default(ForPrimitives));
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1806580287u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			EnemyEnterRestModeClientRpc(sleep, atCamp);
		}
	}

	[ClientRpc]
	public void EnemyEnterRestModeClientRpc(bool sleep, bool atCamp)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
		{
			ClientRpcParams val = default(ClientRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1567928363u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref sleep, default(ForPrimitives));
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref atCamp, default(ForPrimitives));
			((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1567928363u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
		{
			restingAtCamp = atCamp;
			if (sleep)
			{
				eyesClosed = true;
				creatureAnimator.SetBool("sleep", true);
				creatureAnimator.SetBool("sit", false);
			}
			else
			{
				eyesClosed = false;
				creatureAnimator.SetBool("sleep", false);
				creatureAnimator.SetBool("sit", true);
			}
		}
	}

	[ServerRpc]
	public void EnemyGetUpServerRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Invalid comparison between Unknown and I4
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Invalid comparison between Unknown and I4
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager == null || !networkManager.IsListening)
		{
			return;
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
		{
			if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
			{
				if ((int)networkManager.LogLevel <= 1)
				{
					Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
				}
				return;
			}
			ServerRpcParams val = default(ServerRpcParams);
			FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3614203845u, val, (RpcDelivery)0);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3614203845u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			EnemyGetUpClientRpc();
		}
	}

	[ClientRpc]
	public void EnemyGetUpClientRpc()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
		if (networkManager != null && networkManager.IsListening)
		{
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1155909339u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1155909339u, val, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((NetworkBehaviour)this).IsOwner)
			{
				creatureAnimator.SetBool("sit", false);
			}
		}
	}

	public override void OnDrawGizmos()
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d3: 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_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		if (!debugEnemyAI)
		{
			return;
		}
		if (currentBehaviourStateIndex == 1)
		{
			Gizmos.DrawCube(((Component)this).transform.position + Vector3.up * 2f, new Vector3(0.2f, 0.2f, 0.2f));
		}
		else if (scoutingGroup != null)
		{
			if ((Object)(object)scoutingGroup.leader == (Object)(object)this)
			{
				Gizmos.DrawSphere(((Component)this).transform.position + Vector3.up * 2f, 0.6f);
				return;
			}
			Gizmos.DrawLine(((Component)scoutingGroup.leader).transform.position + Vector3.up * 2f, ((Component)this).transform.position + Vector3.up * 2f);
			Gizmos.DrawSphere(((Component)this).transform.position + Vector3.up * 2f, 0.1f);
		}
	}

	public override void DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot = 0, int noiseID = 0)
	{
		//IL_0013: 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_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: 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_0064: 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)
		if (!((NetworkBehaviour)this).IsOwner || isEnemyDead)
		{
			return;
		}
		base.DetectNoise(noisePosition, noiseLoudness, timesPlayedInOneSpot, noiseID);
		if (Vector3.Distance(noisePosition, ((Component)this).transform.position + Vector3.up * 0.4f) < 0.75f || noiseID == 1105 || noiseID == 24751)
		{
			return;
		}
		float num = Vector3.Distance(noisePosition, ((Component)this).transform.position);
		float num2 = noiseLoudness / num;
		if (eyesClosed)
		{
			num2 *= 0.75f;
		}
		if (num2 < 0.12f && peekTimer >= 0f && focusLevel > 0)
		{
			return;
		}
		if (focusLevel >= 3)
		{
			if (num > 3f || num2 <= 0.06f)
			{
				return;
			}
		}
		else if (focusLevel == 2)
		{
			if (num > 25f || num2 <= 0.05f)
			{
				return;
			}
		}
		else if (focusLevel == 1 && (num > 40f || num2 <= 0.05f))
		{
			return;
		}
		PingBaboonInterest(noisePosition, focusLevel);
	}

	private void AnimateLooking(Vector3 lookAtPosition)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0032: 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_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_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: 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_00ab: 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_00ca: 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_00f4: Unknown result type (might be due to invalid IL or missing references)
		headLookTarget.position = Vector3.Lerp(headLookTarget.position, lookAtPosition, 15f * Time.deltaTime);
		Vector3 position = headLookTarget.position;
		position.y = ((Component)this).transform.position.y;
		if (Vector3.Angle(((Component)this).transform.forward, position - ((Component)this).transform.position) > 30f)
		{
			RoundManager.Instance.tempTransform.position = ((Component)this).transform.position;
			RoundManager.Instance.tempTransform.LookAt(position);
			((Component)this).transform.rotation = Quaternion.Lerp(((Component)this).transform.rotation, RoundManager.Instance.tempTransform.rotation, 4f * Time.deltaTime);
			((Component)this).transform.eulerAngles = new Vector3(0f, ((Component)this).transform.eulerAngles.y, 0f);
		}
	}

	public override void Update()
	{
		//IL_0525: Unknown result type (might be due to invalid IL or missing references)
		//IL_052a: Unknown result type (might be due to invalid IL or missing references)
		base.Update();
		if (isEnemyDead)
		{
			return;
		}
		timeSinceHitting += Time.deltaTime;
		if (stunNormalizedTimer > 0f || miscAnimationTimer > 0f)
		{
			agent.speed = 0f;
		}
		creatureAnimator.SetBool("stunned", stunNormalizedTimer > 0f);
		if (miscAnimationTimer <= 0f)
		{
			currentMiscAnimation = -1;
		}
		else
		{
			miscAnimationTimer -= Time.deltaTime;
		}
		CalculateAnimationDirection(2f);
		timeSinceLastMiscAnimation += Time.deltaTime;
		timeSincePingingBirdInterest += Time.deltaTime;
		timeSinceBeingAttackedByPlayer += Time.deltaTime;
		timeSinceJoiningOrLeavingScoutingGroup += Time.deltaTime;
		if (debugEnemyAI)
		{
			if (focusedThreat != null && focusingOnThreat)
			{
				HUDManager.Instance.SetDebugText(string.Format("{0}; {1}; \n Focused threat level: {2}", fearLevel.ToString("0.0"), fearLevelNoDistComparison.ToString("0.0"), focusedThreat.threatLevel));
			}
			else
			{
				HUDManager.Instance.SetDebugText(fearLevel.ToString("0.0") + "; " + fearLevelNoDistComparison.ToString("0.0"));
			}
		}
		if ((Object)(object)heldScrap != (Object)null && !isEnemyDead)
		{
			creatureAnimator.SetLayerWeight(1, Mathf.Lerp(creatureAnimator.GetLayerWeight(1), 1f, 12f * Time.deltaTime));
			((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)rightArmRig).weight = Mathf.Lerp(((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)rightArmRig).weight, 0f, 12f * Time.deltaTime);
			((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)leftArmRig).weight = Mathf.Lerp(((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)leftArmRig).weight, 0f, 12f * Time.deltaTime);
		}
		else
		{
			creatureAnimator.SetLayerWeight(1, Mathf.Lerp(creatureAnimator.GetLayerWeight(1), 0f, 12f * Time.deltaTime));
			((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)rightArmRig).weight = Mathf.Lerp(((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)rightArmRig).weight, 1f, 12f * Time.deltaTime);
			((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)leftArmRig).weight = Mathf.Lerp(((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)leftArmRig).weight, 1f, 12f * Time.deltaTime);
		}
		switch (aggressiveMode)
		{
		case 0:
			if (previousAggressiveMode != aggressiveMode)
			{
				creatureAnimator.SetBool("aggressiveDisplay", false);
				creatureAnimator.SetBool("fighting", false);
				previousAggressiveMode = aggressiveMode;
			}
			if (aggressionAudio.volume <= 0f)
			{
				aggressionAudio.Stop();
			}
			else
			{
				aggressionAudio.volume = Mathf.Max(aggressionAudio.volume - Time.deltaTime * 5f, 0f);
			}
			timeSinceAggressiveDisplay = 0f;
			break;
		case 1:
			if (previousAggressiveMode != aggressiveMode)
			{
				creatureAnimator.SetBool("aggressiveDisplay", true);
				creatureAnimator.SetBool("fighting", false);
				RoundManager.PlayRandomClip(creatureVoice, cawScreamSFX, randomize: true, 1f, 1105);
				WalkieTalkie.TransmitOneShotAudio(creatureVoice, enemyType.audioClips[1]);
				aggressionAudio.clip = enemyType.audioClips[2];
				aggressionAudio.Play();
				previousAggressiveMode = aggressiveMode;
			}
			timeSinceAggressiveDisplay += Time.deltaTime;
			aggressionAudio.volume = Mathf.Min(aggressionAudio.volume + Time.deltaTime * 4f, 1f);
			break;
		case 2:
			if (previousAggressiveMode != aggressiveMode)
			{
				creatureAnimator.SetBool("fighting", true);
				aggressionAudio.clip = enemyType.audioClips[3];
				aggressionAudio.Play();
				previousAggressiveMode = aggressiveMode;
			}
			timeSinceAggressiveDisplay += Time.deltaTime;
			aggressionAudio.volume = Mathf.Min(aggressionAudio.volume + Time.deltaTime * 5f, 1f);
			break;
		}
		switch (currentBehaviourStateIndex)
		{
		case 0:
			creatureAnimator.SetBool("sleep", false);
			restingAtCamp = false;
			eyesClosed = false;
			focusedThreatTransform = null;
			break;
		case 1:
			focusedThreatTransform = null;
			break;
		case 2:
			if ((Object)(object)focusedThreatTransform != (Object)null && focusedThreatIsInView)
			{
				lookTarget = focusedThreatTransform.position;
			}
			timeSpentFocusingOnThreat += Time.deltaTime;
			timeSinceFighting += Time.deltaTime;
			break;
		}
	}

	private float GetComfortableDistanceToThreat(Threat focusedThreat)
	{
		return Mathf.Min((float)focusedThreat.threatLevel * 6f, 25f);
	}

	private void ReactToThreat(Threat closestThreat)
	{
		//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_0098: Unknown result type (might be due to invalid IL or missing references)
		if (Vector3.Distance(closestThreat.lastSeenPosition, baboonCampPosition) < 18f)
		{
			closestThreat.interestLevel++;
		}
		if (closestThreat != focusedThreat && (focusedThreat == null || focusedThreat.threatLevel <= closestThreat.threatLevel) && closestThreat.distanceToThreat < GetComfortableDistanceToThreat(closestThreat))
		{
			NetworkObject component = ((Component)closestThreat.threatScript.GetThreatTransform()).gameObject.GetComponent<NetworkObject>();
			if ((Object)(object)component == (Object)null)
			{
				Debug.LogError((object)"Baboon: Error, threat did not contain network object. All objects implementing IVisibleThreat must have a NetworkObject");
				return;
			}
			fightTimer = 0f;
			focusingOnThreat = true;
			StartFocusOnThreatServerRpc(NetworkObjectReference.op_Implicit(component));
			focusedThreat = closestThreat;
			focusedThreatTransform = closestThreat.threatScript.GetThreatLookTransform();
		}
	}

	[ServerRpc]
	public void StartFocusOnThreatServerRpc(NetworkObjectReference netObject)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Invalid comparison between Unknown and I4
		//IL_011d: 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_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: 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(3933590138u, val, (RpcDelivery)0);
			((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(ref netObject, default(ForNetworkSerializable));
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3933590138u, val, (RpcDelivery)0);
		}
		if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			StartFocusOnThreatClientRpc(netObject);
		}
	}

	[ClientRpc]
	public void StartFocusOnThreatClientRpc(NetworkObjectReference netObject)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00a7: Unk

plugins/Amlinde-WhistleJester/WhistleJester.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("WhistleJester")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Changes the Jester's wind up sound to an edited version of Whistle from the Josh Hutcherson Whistle Edit")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+019b160686a7c045d2a255a73b9e73662ce1bffa")]
[assembly: AssemblyProduct("WhistleJester")]
[assembly: AssemblyTitle("WhistleJester")]
[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 WhistleJester
{
	[BepInPlugin("WhistleJester", "WhistleJester", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public static AudioClip Audio;

		public static bool ConstTimer = true;

		private void Awake()
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Invalid comparison between Unknown and I4
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			ConstTimer = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ConstTimer", true, "Sets the Jester's popUpTimer field to line up with the song").Value;
			string text = ((BaseUnityPlugin)this).Info.Location.TrimEnd("WhistleJester.dll".ToCharArray());
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip("File://" + text + "WhatHaveIDone.mp3", (AudioType)13);
			audioClip.SendWebRequest();
			while (!audioClip.isDone)
			{
			}
			if ((int)audioClip.result == 1)
			{
				Audio = DownloadHandlerAudioClip.GetContent(audioClip);
				new Harmony("WhistleJester").PatchAll(typeof(JesterPatch));
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin WhistleJester is loaded!");
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Could not load audio file");
			}
		}
	}
	[HarmonyPatch(typeof(JesterAI))]
	internal class JesterPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void AudioPatch(JesterAI __instance)
		{
			__instance.popGoesTheWeaselTheme = Plugin.Audio;
		}

		[HarmonyPatch("SetJesterInitialValues")]
		[HarmonyPostfix]
		public static void ForceTime(JesterAI __instance)
		{
			if (Plugin.ConstTimer)
			{
				__instance.popUpTimer = 41.5f;
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "WhistleJester";

		public const string PLUGIN_NAME = "WhistleJester";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

plugins/Clementinise-CustomSounds/CustomSounds.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using CustomSounds.Networking;
using CustomSounds.Patches;
using HarmonyLib;
using LCSoundTool;
using TMPro;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("CustomSounds")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomSounds")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9e086160-a7fd-4721-ba09-3e8534cb7011")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace CustomSounds
{
	[BepInPlugin("CustomSounds", "Custom Sounds", "2.3.2")]
	public class Plugin : BaseUnityPlugin
	{
		public struct SoundData
		{
			public string SoundName;

			public float? RandomPercentage;

			public string CustomName;

			public string FilePath;

			public string FileExtension;

			public string PackName;

			public string AudioSource;

			public string DirectoryPath;

			public string RelativeDirectoryPath;
		}

		public class FolderTree
		{
			public Dictionary<string, FolderTree> SubFolders { get; set; }

			public List<SoundData> Files { get; set; }

			public FolderTree()
			{
				SubFolders = new Dictionary<string, FolderTree>();
				Files = new List<SoundData>();
			}
		}

		public static class SoundDataProcessor
		{
			public static FolderTree BuildFolderTree(List<SoundData> soundDataList)
			{
				FolderTree folderTree = new FolderTree();
				foreach (SoundData soundData in soundDataList)
				{
					string relativeDirectoryPath = soundData.RelativeDirectoryPath;
					string[] array = relativeDirectoryPath.Split(Path.DirectorySeparatorChar, '\u0001');
					FolderTree folderTree2 = folderTree;
					string[] array2 = array;
					foreach (string key in array2)
					{
						if (!folderTree2.SubFolders.ContainsKey(key))
						{
							folderTree2.SubFolders[key] = new FolderTree();
						}
						folderTree2 = folderTree2.SubFolders[key];
					}
					folderTree2.Files.Add(soundData);
				}
				return folderTree;
			}

			public static string DisplayTree(bool isListing, FolderTree tree, int indent = 0, bool isRoot = true, int soundCount = 0)
			{
				StringBuilder stringBuilder = new StringBuilder();
				if (isRoot)
				{
					soundCount = CountSounds(tree);
					string text = (isListing ? "Listing all currently loaded custom sounds:" : "Customsounds reloaded.");
					stringBuilder.AppendLine(text + $" ({soundCount} sounds)");
				}
				foreach (KeyValuePair<string, FolderTree> subFolder in tree.SubFolders)
				{
					if (isRoot)
					{
						stringBuilder.Append("\n");
					}
					string text2 = subFolder.Key;
					if (text2.EndsWith("-AS"))
					{
						text2 = subFolder.Key.Substring(0, subFolder.Key.Length - 3) + " (AudioSource)";
					}
					stringBuilder.AppendLine(new string(' ', indent * 2) + ((indent > 0) ? "∟ " : "") + text2 + " :");
					stringBuilder.Append(DisplayTree(isListing, subFolder.Value, indent + 1, isRoot: false));
				}
				foreach (SoundData file in tree.Files)
				{
					string text3 = ((!file.RandomPercentage.HasValue) ? "" : $" (Random: {file.RandomPercentage * 100f}%)");
					string text4 = ((file.CustomName == "") ? "" : (" [" + file.CustomName + "]"));
					stringBuilder.AppendLine(new string(' ', indent * 2) + "- " + file.SoundName + text3 + text4 + " [" + file.FileExtension.ToUpper() + "]");
				}
				return stringBuilder.ToString();
			}

			private static int CountSounds(FolderTree tree)
			{
				int num = tree.Files.Count;
				foreach (KeyValuePair<string, FolderTree> subFolder in tree.SubFolders)
				{
					num += CountSounds(subFolder.Value);
				}
				return num;
			}
		}

		private const string PLUGIN_GUID = "CustomSounds";

		private const string PLUGIN_NAME = "Custom Sounds";

		private const string PLUGIN_VERSION = "2.3.2";

		public static Plugin Instance;

		internal ManualLogSource logger;

		private Harmony harmony;

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

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

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

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

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

		public static bool hasAcceptedSync = false;

		public static List<SoundData> soundDataList = new List<SoundData>();

		public static bool Initialized { get; private set; }

		private void Awake()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			if (!((Object)(object)Instance == (Object)null))
			{
				return;
			}
			Instance = this;
			logger = Logger.CreateLogSource("CustomSounds");
			harmony = new Harmony("CustomSounds");
			harmony.PatchAll(typeof(TerminalParsePlayerSentencePatch));
			modifiedSounds = new HashSet<string>();
			string customSoundsFolderPath = GetCustomSoundsFolderPath();
			if (!Directory.Exists(customSoundsFolderPath))
			{
				logger.LogInfo((object)"\"CustomSounds\" folder not found. Creating it now.");
				string path = Path.Combine(customSoundsFolderPath, "YourOwnSoundPack");
				Directory.CreateDirectory(path);
				string contents = "If you're interested in creating your own sound pack, please refer to the 'For Sound Packs Creator' section on the CustomSounds Thunderstore page. If you simply wish to replace a few sounds on your own, you can drop the desired sounds into the 'YourOwnSoundPack' folder.";
				File.WriteAllText(Path.Combine(customSoundsFolderPath, "READ-ME-PLEASE.txt"), contents);
			}
			string path2 = Path.Combine(Paths.BepInExConfigPath);
			try
			{
				List<string> list = File.ReadAllLines(path2).ToList();
				int num = list.FindIndex((string line) => line.StartsWith("HideManagerGameObject"));
				if (num != -1 && list[num].Contains("false"))
				{
					logger.LogInfo((object)"\"HideManagerGameObject\" value not correctly set. Fixing it now.");
					list[num] = "HideManagerGameObject = true";
					File.WriteAllLines(path2, list);
					harmony.PatchAll(typeof(MenuPatcher));
				}
				else if (num != -1)
				{
					logger.LogInfo((object)"\"HideManagerGameObject\" is correctly set to true.");
				}
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Error modifying config file: " + ex.Message));
			}
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			logger.LogInfo((object)"Plugin CustomSounds is loaded!");
		}

		internal void Start()
		{
			Initialize();
		}

		internal void OnDestroy()
		{
			Initialize();
		}

		internal void Initialize()
		{
			if (!Initialized)
			{
				Initialized = true;
				ReloadSounds();
			}
		}

		private void OnApplicationQuit()
		{
		}

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

		public string GetCustomSoundsFolderPath()
		{
			return Path.Combine(Paths.PluginPath, "CustomSounds");
		}

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

		public void ReloadSounds()
		{
			oldSounds = new HashSet<string>(currentSounds);
			currentSounds.Clear();
			modifiedSounds.Clear();
			soundDataList.Clear();
			string directoryName = Path.GetDirectoryName(Paths.PluginPath);
			ProcessDirectory(directoryName);
		}

		private string GetRelativePathToCustomSounds(string filePath)
		{
			Debug.Log((object)("FilePath: " + filePath));
			string[] array = filePath.Split(new char[1] { Path.DirectorySeparatorChar });
			int num = Array.IndexOf(array, "CustomSounds");
			if (num == -1 || num == array.Length - 1)
			{
				return "";
			}
			string[] paths = array.Skip(num + 1).ToArray();
			return Path.Combine(paths);
		}

		private void ProcessDirectory(string directoryPath)
		{
			string[] directories = Directory.GetDirectories(directoryPath, "*", SearchOption.AllDirectories);
			foreach (string text in directories)
			{
				string fileName = Path.GetFileName(text);
				ProcessSoundFiles(text, fileName);
			}
		}

		private void ProcessSoundFiles(string directoryPath, string packName)
		{
			string[] array = new string[3] { "*.wav", "*.ogg", "*.mp3" };
			string[] array2 = array;
			foreach (string searchPattern in array2)
			{
				string[] files = Directory.GetFiles(directoryPath, searchPattern);
				foreach (string text in files)
				{
					if (text.Contains("CustomSounds"))
					{
						ProcessSingleFile(text, packName);
					}
				}
			}
		}

		private void ProcessSingleFile(string file, string packName)
		{
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
			(string soundName, float? percentage, string customName) tuple = ParseSoundFileName(fileNameWithoutExtension);
			string item = tuple.soundName;
			float? item2 = tuple.percentage;
			string item3 = tuple.customName;
			string fileExtension = Path.GetExtension(file).TrimStart(new char[1] { '.' }).ToLower();
			string relativePathToCustomSounds = GetRelativePathToCustomSounds(file);
			string fileName = Path.GetFileName(Path.GetDirectoryName(file));
			string text = (fileName.EndsWith("-AS") ? fileName.Substring(0, fileName.Length - 3) : null);
			SoundData soundData = default(SoundData);
			soundData.SoundName = item;
			soundData.RandomPercentage = item2;
			soundData.CustomName = item3;
			soundData.FilePath = file;
			soundData.FileExtension = fileExtension;
			soundData.PackName = packName;
			soundData.AudioSource = text;
			soundData.DirectoryPath = Path.GetDirectoryName(file);
			soundData.RelativeDirectoryPath = Path.GetDirectoryName(relativePathToCustomSounds);
			SoundData item4 = soundData;
			soundDataList.Add(item4);
			string text2 = "Sound replaced: " + item;
			if (item4.RandomPercentage.HasValue)
			{
				text2 += $" (Percentage = {item4.RandomPercentage.Value * 100f}%)";
			}
			if (!string.IsNullOrEmpty(item4.CustomName))
			{
				text2 = text2 + " (Custom Name = " + item4.CustomName + ")";
			}
			text2 = text2 + " (File Extension = " + item4.FileExtension + ")";
			Debug.Log((object)text2);
			AudioClip audioClip = SoundTool.GetAudioClip(Path.GetDirectoryName(file), file);
			((Object)audioClip).name = fileNameWithoutExtension;
			currentSounds.Add(item4.SoundName);
			if (item4.RandomPercentage.HasValue)
			{
				if (item4.AudioSource != null)
				{
					SoundTool.ReplaceAudioClip(item4.SoundName, audioClip, item4.RandomPercentage.Value, item4.AudioSource);
				}
				else
				{
					SoundTool.ReplaceAudioClip(item4.SoundName, audioClip, item4.RandomPercentage.Value);
				}
			}
			else if (text != null)
			{
				SoundTool.ReplaceAudioClip(item4.SoundName, audioClip, item4.AudioSource);
			}
			else
			{
				SoundTool.ReplaceAudioClip(item4.SoundName, audioClip);
			}
		}

		private (string soundName, float? percentage, string customName) ParseSoundFileName(string fullSoundName)
		{
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullSoundName);
			string[] array = fileNameWithoutExtension.Split(new char[1] { '-' });
			string s = array[^1];
			if (int.TryParse(s, out var result))
			{
				string item = array[0];
				string item2 = string.Join(" ", array.Skip(1).Take(array.Length - 2));
				float value = (float)result / 100f;
				return (item, value, item2);
			}
			return (array[0], null, string.Join(" ", array.Skip(1)));
		}
	}
}
namespace CustomSounds.Patches
{
	[HarmonyPatch]
	public class NetworkObjectManager
	{
		private static GameObject networkPrefab;

		private static GameObject networkHandlerHost;

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

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

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		private static void DestroyNetworkHandler()
		{
			try
			{
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					Plugin.Instance.logger.LogInfo((object)"Destroying network handler");
					Object.Destroy((Object)(object)networkHandlerHost);
					networkHandlerHost = null;
				}
			}
			catch
			{
				Plugin.Instance.logger.LogError((object)"Failed to destroy network handler");
			}
		}
	}
	[HarmonyPatch(typeof(MenuManager))]
	internal class MenuPatcher
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void StartPostFix(MenuManager __instance)
		{
			((MonoBehaviour)__instance).StartCoroutine(DelayedMainMenuModification());
		}

		private static IEnumerator DelayedMainMenuModification()
		{
			yield return (object)new WaitForSeconds(0f);
			ChangeHostButtonFromMainMenu();
		}

		private static void ChangeHostButtonFromMainMenu()
		{
			Debug.Log((object)"Attempting to add a description to the Host button...");
			GameObject val = GameObject.Find("MenuContainer");
			Transform val2 = ((val != null) ? val.transform.Find("MainButtons") : null);
			object obj;
			if (val2 == null)
			{
				obj = null;
			}
			else
			{
				Transform obj2 = val2.Find("HostButton");
				obj = ((obj2 != null) ? ((Component)obj2).gameObject : null);
			}
			GameObject val3 = (GameObject)obj;
			if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null) && !((Object)(object)val3 == (Object)null))
			{
				string text = ((TMP_Text)val3.GetComponentInChildren<TextMeshProUGUI>()).text;
				((TMP_Text)val3.GetComponentInChildren<TextMeshProUGUI>()).text = "<line-height=0.28em>" + text + "\n<size=8><color=#B0B0B0>     Please restart the game for <color=#E6B800>CustomSounds</color> to work properly!</color></size></line-height>";
			}
		}
	}
	[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
	public static class TerminalParsePlayerSentencePatch
	{
		public static bool Prefix(Terminal __instance, ref TerminalNode __result)
		{
			string[] array = __instance.screenText.text.Split(new char[1] { '\n' });
			if (array.Length == 0)
			{
				return true;
			}
			string[] array2 = array.Last().Trim().ToLower()
				.Split(new char[1] { ' ' });
			if (array2.Length == 0 || (array2[0] != "customsounds" && array2[0] != "cs"))
			{
				return true;
			}
			Plugin.Instance.logger.LogInfo((object)("Received terminal command: " + string.Join(" ", array2)));
			if (array2.Length > 1 && (array2[0] == "customsounds" || array2[0] == "cs"))
			{
				switch (array2[1])
				{
				case "reload":
				case "rl":
					Plugin.Instance.RevertSounds();
					Plugin.Instance.ReloadSounds();
					__result = CreateTerminalNode(Plugin.SoundDataProcessor.DisplayTree(isListing: false, Plugin.SoundDataProcessor.BuildFolderTree(Plugin.soundDataList)));
					return false;
				case "revert":
				case "rv":
					Plugin.Instance.RevertSounds();
					__result = CreateTerminalNode("Game sounds reverted to original.\n\n");
					return false;
				case "list":
				case "l":
					__result = CreateTerminalNode(Plugin.SoundDataProcessor.DisplayTree(isListing: true, Plugin.SoundDataProcessor.BuildFolderTree(Plugin.soundDataList)));
					return false;
				case "help":
				case "h":
					if (NetworkManager.Singleton.IsHost)
					{
						__result = CreateTerminalNode("CustomSounds commands \n(Can also be used with 'CS' as an alias).\n\n>CUSTOMSOUNDS LIST/L\nTo display all currently loaded sounds\n\n>CUSTOMSOUNDS RELOAD/RL\nTo reload and apply sounds from the 'CustomSounds' folder and its subfolders.\n\n>CUSTOMSOUNDS REVERT/RV\nTo unload all custom sounds and restore original game sounds\n\n");
					}
					else
					{
						__result = CreateTerminalNode("CustomSounds commands \n(Can also be used with 'CS' as an alias).\n\n>CUSTOMSOUNDS LIST/L\nTo display all currently loaded sounds\n\n>CUSTOMSOUNDS RELOAD/RL\nTo reload and apply sounds from the 'CustomSounds' folder and its subfolders.\n\n>CUSTOMSOUNDS REVERT/RV\nTo unload all custom sounds and restore original game sounds\n\n");
					}
					return false;
				case "sync":
				case "s":
					__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command is not supported in this version of CustomSounds\n\n");
					return false;
				case "unsync":
				case "u":
					__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command is not supported in this version of CustomSounds\n\n");
					return false;
				case "fu":
				case "force-unsync":
					__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command is not supported in this version of CustomSounds\n\n");
					return false;
				default:
					__result = CreateTerminalNode("Unknown customsounds command.\n\n");
					return false;
				}
			}
			return true;
		}

		private static TerminalNode CreateTerminalNode(string message)
		{
			TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
			val.displayText = message;
			val.clearPreviousText = true;
			return val;
		}
	}
}
namespace CustomSounds.Networking
{
	public class AudioNetworkHandler : NetworkBehaviour
	{
		public static AudioNetworkHandler Instance { get; private set; }

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

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

plugins/CodeEnder-Custom_Boombox_Fix/CustomBoomboxFix.dll

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

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

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

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

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

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

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

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

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

		public const string PLUGIN_NAME = "CustomBoomboxFix";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

plugins/ControlCompany-ControlCompany/ControlCompany.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ControlCompany.Core;
using ControlCompany.Core.Config;
using ControlCompany.Core.Enemy;
using ControlCompany.Core.Enemy.NonStandardEnemy;
using ControlCompany.Core.Extentions;
using ControlCompany.Core.Input;
using ControlCompany.Core.UI;
using ControlCompany.Patches;
using Dissonance;
using GameNetcodeStuff;
using HarmonyLib;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering.HighDefinition;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ControlCompany")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ControlCompany")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("dfed064e-ab44-4aa7-b361-7a59370d39a8")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ControlCompany
{
	[BepInPlugin("ControlCompany.ControlCompany", "ControlCompany", "1.3.0")]
	public class ControlCompanyPlugin : BaseUnityPlugin
	{
		private const string modGUID = "ControlCompany.ControlCompany";

		private const string modName = "ControlCompany";

		private const string modVersion = "1.3.0";

		private readonly Harmony harmony = new Harmony("ControlCompany.ControlCompany");

		public static ControlCompanyPlugin Instance;

		internal ManualLogSource logger;

		private bool isInitialized = false;

		private bool ranInitializationScripts = false;

		private void Awake()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			logger = Logger.CreateLogSource("ControlCompany.ControlCompany");
			logger.LogInfo((object)"Loaded ControlCompany. Patching.");
			ApplyPatches();
			logger.LogInfo((object)"Completed patching. Initializing.");
			GameObject val = new GameObject("control_company_config_manager");
			val.AddComponent<ConfigManager>();
			((Object)val).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)val);
			logger.LogInfo((object)"Completed initialization.");
			isInitialized = true;
		}

		private void ApplyPatches()
		{
			harmony.PatchAll(typeof(ControlCompanyPlugin));
			harmony.PatchAll(typeof(HUDManagerPatch));
			harmony.PatchAll(typeof(StartOfRoundPatch));
			harmony.PatchAll(typeof(PlayerControllerBPatch));
			harmony.PatchAll(typeof(EnemyAIPatch));
			harmony.PatchAll(typeof(TimeOfDayPatch));
			harmony.PatchAll(typeof(SoundManagerPatch));
			harmony.PatchAll(typeof(LobbyListPatch));
		}
	}
}
namespace ControlCompany.Patches
{
	[HarmonyPatch(typeof(EnemyAI))]
	internal class EnemyAIPatch
	{
		[HarmonyPatch("ChangeOwnershipOfEnemy")]
		[HarmonyPrefix]
		private static bool ChangeOwnershipOfEnemyPrefix(EnemyAI __instance, ref ulong newOwnerClientId)
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null && ControlCenter.Instance.CurrentMode == ControlCenter.Mode.ENEMY)
			{
				if ((Object)(object)ControlCenter.Instance.CurrentControlledEnemy != (Object)null)
				{
					ulong actualClientId = ControlCenter.Instance.GetHostPlayer().actualClientId;
					bool flag = actualClientId == newOwnerClientId || ControlCenter.Instance.CurrentControlledEnemy.IsAIControlled;
					EnemyController currentControlledEnemy = ControlCenter.Instance.CurrentControlledEnemy;
					if (((object)currentControlledEnemy).GetType() == typeof(EnemyAIController))
					{
						EnemyAIController enemyAIController = (EnemyAIController)ControlCenter.Instance.CurrentControlledEnemy;
						flag = flag || (Object)(object)enemyAIController.EnemyAI != (Object)(object)__instance;
					}
					return flag;
				}
				return true;
			}
			return true;
		}

		[HarmonyPatch("ChangeEnemyOwnerServerRpc")]
		[HarmonyPrefix]
		private static bool ChangeEnemyOwnerServerRpcPrefix(EnemyAI __instance, ref ulong clientId)
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null && ControlCenter.Instance.CurrentMode == ControlCenter.Mode.ENEMY)
			{
				if ((Object)(object)ControlCenter.Instance.CurrentControlledEnemy != (Object)null)
				{
					ulong actualClientId = ControlCenter.Instance.GetHostPlayer().actualClientId;
					bool flag = actualClientId == clientId || ControlCenter.Instance.CurrentControlledEnemy.IsAIControlled;
					EnemyController currentControlledEnemy = ControlCenter.Instance.CurrentControlledEnemy;
					if (((object)currentControlledEnemy).GetType() == typeof(EnemyAIController))
					{
						EnemyAIController enemyAIController = (EnemyAIController)ControlCenter.Instance.CurrentControlledEnemy;
						flag = flag || (Object)(object)enemyAIController.EnemyAI != (Object)(object)__instance;
					}
					return flag;
				}
				return true;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	internal class HUDManagerPatch
	{
		[HarmonyPatch("CanPlayerScan")]
		[HarmonyPostfix]
		private static void CanPlayerScanPostfix(ref bool __result)
		{
			if (__result && (Object)(object)ControlCenter.Instance != (Object)null)
			{
				__result = ControlCenter.Instance.CurrentMode == ControlCenter.Mode.HOST;
			}
		}

		[HarmonyPatch("UpdateHealthUI")]
		[HarmonyPrefix]
		private static bool UpdateHealthUIPrefix()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				return ControlCenter.Instance.CurrentMode == ControlCenter.Mode.HOST;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		[HarmonyPatch("PlayerLookInput")]
		[HarmonyPrefix]
		private static bool PlayerLookInputPrefix()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				return ControlCenter.Instance.CurrentMode == ControlCenter.Mode.HOST;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(SoundManager))]
	internal class SoundManagerPatch
	{
		[HarmonyPatch("SetEarsRinging")]
		[HarmonyPrefix]
		private static bool SetEarsRingingPrefix()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				return ControlCenter.Instance.CurrentMode == ControlCenter.Mode.HOST;
			}
			return true;
		}
	}
	internal class StartOfRoundPatch
	{
		[HarmonyPatch(typeof(StartOfRound), "ShipHasLeft")]
		[HarmonyPrefix]
		private static void ShipHasLeftPrefix()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				ControlCenter.Instance.EndOfRoundCleanUp();
			}
		}

		[HarmonyPatch(typeof(RoundManager), "RefreshEnemiesList")]
		[HarmonyPostfix]
		private static void StartGamePostfix()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				ControlCenter.Instance.StartOfRoundInitialization();
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPostfix]
		private static void CreateControlCenter()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			if (!ConfigManager.Instance.DisableModForSelf)
			{
				GameObject val = new GameObject("control_company_control_center");
				val.AddComponent<ControlCenter>();
				val.AddComponent<UIManager>();
			}
		}
	}
	internal class LobbyListPatch
	{
		public const char SERVER_NAME_FILTER = '\u200b';

		[HarmonyPatch(typeof(MenuManager), "ConfirmHostButton")]
		[HarmonyPrefix]
		private static void AddServerNameChar(MenuManager __instance)
		{
			string text = __instance.lobbyNameInputField.text;
			if (!ConfigManager.Instance.DisableModForSelf && __instance.hostSettings_LobbyPublic)
			{
				if (!Enumerable.Contains(text, '\u200b'))
				{
					text = ((text.Length > 3) ? text.Insert(text.Length - 2, '\u200b'.ToString()) : ("\u200b" + text));
				}
				if (!text.Trim().StartsWith("[MODDED]"))
				{
					text = "[MODDED] " + text;
				}
				__instance.lobbyNameInputField.text = text;
			}
			else
			{
				__instance.lobbyNameInputField.text = text.RemoveChar('\u200b');
			}
		}
	}
	[HarmonyPatch(typeof(TimeOfDay))]
	internal class TimeOfDayPatch
	{
		[HarmonyPatch("VoteShipToLeaveEarly")]
		[HarmonyPrefix]
		private static bool VoteToLeaveEarly()
		{
			if ((Object)(object)ControlCenter.Instance != (Object)null)
			{
				return ControlCenter.Instance.CurrentMode == ControlCenter.Mode.HOST;
			}
			return true;
		}
	}
}
namespace ControlCompany.Core
{
	internal static class Constants
	{
		public static Dictionary<int, string> ALL_LAYERS_DICT = (from index in Enumerable.Range(0, 32)
			where !string.IsNullOrEmpty(LayerMask.LayerToName(index))
			select index).ToDictionary((int index) => index, (int index) => LayerMask.LayerToName(index));

		public static string PLAYER_LOS_LAYERNAME = "LineOfSight";

		public static int PLAYER_LOS_LAYERINDEX = LayerMask.NameToLayer(PLAYER_LOS_LAYERNAME);

		public static LayerMask PLAYER_LOS_LAYERMASK = LayerMask.op_Implicit(LayerMask.GetMask(new string[1] { PLAYER_LOS_LAYERNAME }));

		public static string PLAYER_LAYERNAME = "Player";

		public static int PLAYER_LAYERINDEX = LayerMask.NameToLayer(PLAYER_LAYERNAME);

		public static LayerMask PLAYER_LAYERMASK = LayerMask.op_Implicit(LayerMask.GetMask(new string[1] { PLAYER_LAYERNAME }));

		public static string PLAYER_VISOR_LAYERNAME = "HelmetVisor";

		public static int PLAYER_VISOR_LAYERINDEX = LayerMask.NameToLayer(PLAYER_VISOR_LAYERNAME);

		public static LayerMask PLAYER_VISOR_LAYERMASK = LayerMask.op_Implicit(LayerMask.GetMask(new string[1] { PLAYER_VISOR_LAYERNAME }));

		public static string ITERACTABLE_OBJ_LAYERNAME = "InteractableObject";

		public static int ITERACTABLE_OBJ_LAYERINDEX = LayerMask.NameToLayer(ITERACTABLE_OBJ_LAYERNAME);

		public static LayerMask ITERACTABLE_OBJ_LAYERMASK = LayerMask.op_Implicit(LayerMask.GetMask(new string[1] { ITERACTABLE_OBJ_LAYERNAME }));

		public static string PROPS_OBJ_LAYERNAME = "Props";

		public static int PROPS_OBJ_LAYERINDEX = LayerMask.NameToLayer(PROPS_OBJ_LAYERNAME);

		public static LayerMask PROPS_LAYERMASK = LayerMask.op_Implicit(LayerMask.GetMask(new string[1] { PROPS_OBJ_LAYERNAME }));

		public static string ENEMIES_OBJ_LAYERNAME = "Enemies";

		public static int ENEMIES_OBJ_LAYERINDEX = LayerMask.NameToLayer(ENEMIES_OBJ_LAYERNAME);

		public static LayerMask ENEMIES_LAYERMASK = LayerMask.op_Implicit(LayerMask.GetMask(new string[1] { ENEMIES_OBJ_LAYERNAME }));

		public static string PLAYER_RAGDOLL_LAYERNAME = "PlayerRagdoll";

		public static int PLAYER_RAGDOLL_LAYERINDEX = LayerMask.NameToLayer(PLAYER_RAGDOLL_LAYERNAME);

		public static LayerMask PLAYER_RAGDOLL_LAYERMASK = LayerMask.op_Implicit(LayerMask.GetMask(new string[1] { PLAYER_RAGDOLL_LAYERNAME }));

		public static string PHYSICS_OBJECT_LAYERNAME = "PhysicsObject";

		public static int PHYSICS_OBJECT_LAYERINDEX = LayerMask.NameToLayer(PHYSICS_OBJECT_LAYERNAME);

		public static LayerMask PHYSICS_OBJECT_LAYERMASK = LayerMask.op_Implicit(LayerMask.GetMask(new string[1] { PHYSICS_OBJECT_LAYERNAME }));
	}
	internal class ControlCenter : MonoBehaviour
	{
		public enum Mode
		{
			HOST,
			GHOST,
			ENEMY
		}

		public static ControlCenter Instance;

		private CustomPlayerController ghostController;

		private GameObject ghost;

		private EnemyController currentControlledEnemy;

		private int currentTargetIndex = 0;

		private PlayerControllerB currentTarget;

		private Mode currentMode = Mode.HOST;

		private bool allowAllEnemies = false;

		private bool initialMicPushToTalkSetting = false;

		private bool isExtendedModeEnabled = false;

		private bool scrapSpawnMode = false;

		private int currentSpawnScrapPage = 0;

		private const int scrapSpawnPageSize = 10;

		private int currentSpawnEnemiesPage = 0;

		private const int spawnEnemiesPageSize = 12;

		private List<ControllableEnemy> currentSpawnableEnemyList = new List<ControllableEnemy>();

		private bool loadedConfig = false;

		private bool showUI = true;

		private float gameStartedTime = 0f;

		private bool inRoundEndPhase = false;

		private bool isGhostIndoors = false;

		private List<ControllableEnemy> allIndoorEnemies = new List<ControllableEnemy>();

		private List<ControllableEnemy> allOutdoorEnemies = new List<ControllableEnemy>();

		private List<ControllableEnemy> indoorEnemiesOfLevel = new List<ControllableEnemy>();

		private List<ControllableEnemy> outdoorEnemiesOfLevel = new List<ControllableEnemy>();

		public Mode CurrentMode => currentMode;

		public EnemyController CurrentControlledEnemy => currentControlledEnemy;

		public bool IsGhostIndoors
		{
			get
			{
				return isGhostIndoors;
			}
			set
			{
				isGhostIndoors = value;
			}
		}

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

		private void OnEnable()
		{
			if (!loadedConfig)
			{
				loadedConfig = true;
				ConfigManager.Instance.LoadPlayerConfig(reload: true);
			}
		}

		private void Update()
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			if (!IsGameStarted())
			{
				return;
			}
			if (((ButtonControl)InputKeys.TOGGLE_UI_KEY).wasPressedThisFrame)
			{
				showUI = !showUI;
			}
			gameStartedTime += Time.deltaTime;
			if (!IsHost() || inRoundEndPhase)
			{
				return;
			}
			if (((Object)(object)currentTarget == (Object)null || !currentTarget.isPlayerControlled || currentTarget.isPlayerDead) && GetAlivePlayers().Count > 0)
			{
				SetNextTargetPlayer(1);
			}
			if ((Object)(object)ghost == (Object)null)
			{
				GameObject val = new GameObject("ghost");
				ghostController = val.AddComponent<CustomPlayerController>();
				ghostController.Initialize(GetHostPlayer().playerActions, CustomPlayerController.CameraMode.FIRST_PERSON);
				ghost = val;
				ghost.SetActive(false);
				ControlCompanyPlugin.Instance.logger.LogInfo((object)"Creating ghost");
			}
			if (currentMode != 0)
			{
				GetHostPlayer().isTypingChat = true;
			}
			if (IsListeningFromHost() && !IsHostDead() && currentMode != 0)
			{
				if ((Object)(object)ghostController != (Object)null)
				{
					((Behaviour)ghostController.AudioListener).enabled = false;
				}
				if ((Object)(object)currentControlledEnemy != (Object)null)
				{
					((Behaviour)currentControlledEnemy.AudioListener).enabled = false;
				}
				((Behaviour)GetHostPlayer().activeAudioListener).enabled = true;
				ChangeAudioListener(GetHostPlayer().activeAudioListener);
			}
			else if (currentMode == Mode.GHOST)
			{
				if ((Object)(object)ghostController != (Object)null && ghostController.IsInitialized)
				{
					((Behaviour)GetHostPlayer().activeAudioListener).enabled = false;
					((Behaviour)ghostController.AudioListener).enabled = true;
					ChangeAudioListener(ghostController.AudioListener);
				}
			}
			else if (currentMode == Mode.ENEMY)
			{
				if (((Object)(object)currentControlledEnemy != (Object)null) & currentControlledEnemy.IsInitialized)
				{
					((Behaviour)GetHostPlayer().activeAudioListener).enabled = false;
					((Behaviour)currentControlledEnemy.AudioListener).enabled = true;
					ChangeAudioListener(currentControlledEnemy.AudioListener);
				}
			}
			else if (currentMode == Mode.HOST)
			{
				ChangeAudioListener(GetHostPlayer().activeAudioListener);
			}
			InputUpdate();
		}

		private void InputUpdate()
		{
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_048a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0415: 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_03e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ec: Unknown result type (might be due to invalid IL or missing references)
			if (!IsGameStarted() || !IsHost() || inRoundEndPhase || (ConfigManager.Instance.DisableWhileUsingTerminal && GetHostPlayer().inTerminalMenu))
			{
				return;
			}
			if (((ButtonControl)InputKeys.EXTENDED_MODE_KEY).wasPressedThisFrame)
			{
				isExtendedModeEnabled = !isExtendedModeEnabled;
				allowAllEnemies = isExtendedModeEnabled;
				SetNextSpawnEnemiesPage(0);
			}
			switch (currentMode)
			{
			case Mode.ENEMY:
				if (!currentControlledEnemy.IsAIControlled && currentControlledEnemy.CanControlEnemy())
				{
					if (InputKeys.ENEMY_PRIMARY_SKILL_BUTTON.wasPressedThisFrame)
					{
						currentControlledEnemy.UsePrimarySkill();
					}
					else if (InputKeys.ENEMY_PRIMARY_SKILL_BUTTON.wasReleasedThisFrame)
					{
						currentControlledEnemy.ReleasePrimarySkill();
					}
					else if (InputKeys.ENEMY_SECONDARY_SKILL_BUTTON.wasPressedThisFrame)
					{
						currentControlledEnemy.UseSecondarySkill();
					}
					else if (InputKeys.ENEMY_SECONDARY_SKILL_BUTTON.wasReleasedThisFrame)
					{
						currentControlledEnemy.ReleaseSecondarySkill();
					}
					currentControlledEnemy.SetLockEnemyRotation(((ButtonControl)InputKeys.LOCK_ENEMY_ROTATION_KEY).isPressed);
				}
				if (((ButtonControl)InputKeys.EXIT_KEY).wasPressedThisFrame)
				{
					EnableGhost(enable: true, ((Component)currentControlledEnemy).transform.position);
					ghostController.EnableLight(isGhostIndoors);
					currentControlledEnemy.DestroyAndCleanUp();
					currentMode = Mode.GHOST;
				}
				else if (((ButtonControl)InputKeys.ENEMY_TOGGLE_AI_KEY).wasPressedThisFrame)
				{
					currentControlledEnemy.ToggleAIControl();
				}
				else if (((ButtonControl)InputKeys.ENEMY_TOGGLE_LIGHT_KEY).wasPressedThisFrame)
				{
					currentControlledEnemy.ToggleLight();
				}
				break;
			case Mode.HOST:
				if (((ButtonControl)InputKeys.HOST_GHOST_MODE_KEY).wasPressedThisFrame)
				{
					isGhostIndoors = IsTargetInside();
					EnableGhost(enable: true, ((Component)currentTarget).gameObject.transform.position);
					ghostController.EnableLight(isGhostIndoors);
					EnableHostPlayer(enable: false);
					currentMode = Mode.GHOST;
				}
				else if (((ButtonControl)InputKeys.CYCLE_KEY_LEFT).wasPressedThisFrame)
				{
					SetNextTargetPlayer(-1);
				}
				else if (((ButtonControl)InputKeys.CYCLE_KEY_RIGHT).wasPressedThisFrame)
				{
					SetNextTargetPlayer(1);
				}
				if (!isExtendedModeEnabled)
				{
					break;
				}
				if (((ButtonControl)InputKeys.HOST_TELEPORT_TO_ENTRANCE_KEY).wasPressedThisFrame)
				{
					if (!GetHostPlayer().isPlayerDead)
					{
						EntranceTeleport mainEntrance = GetMainEntrance(getMainEntranceThatIsOutside: true);
						if ((Object)(object)mainEntrance != (Object)null)
						{
							mainEntrance.TeleportPlayer();
						}
					}
				}
				else if (((ButtonControl)InputKeys.HOST_GIVE_CREDITS_KEY).wasPressedThisFrame)
				{
					Terminal obj = Object.FindObjectOfType<Terminal>();
					obj.groupCredits += 100;
				}
				break;
			case Mode.GHOST:
				if (!scrapSpawnMode)
				{
					List<ControllableEnemy> pagedSpawnableEnemies = GetPagedSpawnableEnemies();
					for (int i = 0; i < InputKeys.GHOST_SPAWN_ENEMY_KEYS.Count && i < pagedSpawnableEnemies.Count; i++)
					{
						if (!((ButtonControl)InputKeys.GHOST_SPAWN_ENEMY_KEYS[i]).wasPressedThisFrame)
						{
							continue;
						}
						if (ConfigManager.Instance.UseEnemySpawningBehaviour)
						{
							Random random = new Random(StartOfRound.Instance.randomMapSeed + 888);
							if (isGhostIndoors)
							{
								RoundManager.Instance.RefreshEnemyVents();
								EnemyVent[] allEnemyVents = RoundManager.Instance.allEnemyVents;
								if (allEnemyVents.Count() > 0)
								{
									EnemyVent val = allEnemyVents[random.Next(allEnemyVents.Count())];
									currentControlledEnemy = SpawnControllableEnemy(pagedSpawnableEnemies[i], val.floorNode.position, val.floorNode.rotation);
								}
								else
								{
									currentControlledEnemy = SpawnControllableEnemy(pagedSpawnableEnemies[i], ghost.transform.position, ghost.transform.rotation);
								}
							}
							else
							{
								GameObject[] array = GameObject.FindGameObjectsWithTag("OutsideAINode");
								if (array.Count() > 0)
								{
									currentControlledEnemy = SpawnControllableEnemy(pagedSpawnableEnemies[i], array[random.Next(array.Count())].transform.position, ghost.transform.rotation);
								}
								else
								{
									currentControlledEnemy = SpawnControllableEnemy(pagedSpawnableEnemies[i], ghost.transform.position, ghost.transform.rotation);
								}
							}
						}
						else
						{
							currentControlledEnemy = SpawnControllableEnemy(pagedSpawnableEnemies[i], ghost.transform.position, ghost.transform.rotation);
						}
						EnableGhost(enable: false);
						currentMode = Mode.ENEMY;
						break;
					}
				}
				else
				{
					List<Item> list = ExtensionMethods.Chunk(GetSpawnableScraps(), 10).ToList()[currentSpawnScrapPage].ToList();
					for (int j = 0; j < InputKeys.GHOST_SPAWN_ENEMY_KEYS.Count && j < list.Count; j++)
					{
						if (((ButtonControl)InputKeys.GHOST_SPAWN_ENEMY_KEYS[j]).wasPressedThisFrame)
						{
							SpawnScrap(list[j], ghost.transform.position);
							break;
						}
					}
				}
				if (((ButtonControl)InputKeys.EXIT_KEY).wasPressedThisFrame)
				{
					EnableGhost(enable: false);
					EnableHostPlayer(enable: true);
					currentMode = Mode.HOST;
					GetHostPlayer().isTypingChat = false;
				}
				else if (((ButtonControl)InputKeys.CYCLE_KEY_LEFT).wasPressedThisFrame)
				{
					SetNextSpawnEnemiesPage(-1);
				}
				else if (((ButtonControl)InputKeys.CYCLE_KEY_RIGHT).wasPressedThisFrame)
				{
					SetNextSpawnEnemiesPage(1);
				}
				if (((ButtonControl)Keyboard.current.upArrowKey).wasPressedThisFrame)
				{
				}
				if (scrapSpawnMode && ((ButtonControl)Keyboard.current.downArrowKey).wasPressedThisFrame)
				{
					int num = Mathf.CeilToInt((float)GetSpawnableScraps().Count / 10f);
					ControlCompanyPlugin.Instance.logger.LogMessage((object)$"Total scraps: {GetSpawnableScraps().Count()}, final page of scrap: {num}");
					currentSpawnScrapPage++;
					if (currentSpawnScrapPage >= num)
					{
						currentSpawnScrapPage = 0;
					}
				}
				break;
			}
		}

		private void ChangeAudioListener(AudioListener audioListener)
		{
			StartOfRound.Instance.audioListener = audioListener;
		}

		private EntranceTeleport GetMainEntrance(bool getMainEntranceThatIsOutside)
		{
			EntranceTeleport[] array = Object.FindObjectsOfType<EntranceTeleport>(false);
			foreach (EntranceTeleport val in array)
			{
				if (val.entranceId != 0)
				{
					continue;
				}
				if (getMainEntranceThatIsOutside)
				{
					if (val.isEntranceToBuilding)
					{
						return val;
					}
				}
				else if (!val.isEntranceToBuilding)
				{
					return val;
				}
			}
			return null;
		}

		private bool IsTargetInside()
		{
			return (Object)(object)currentTarget != (Object)null && currentTarget.isInsideFactory;
		}

		private void OnGUI()
		{
			if (!IsGameStarted() || !showUI)
			{
				return;
			}
			if (!IsHost())
			{
				if (gameStartedTime < 30f)
				{
					UIManager.Instance.RenderNotHostLabel(((InputControl)InputKeys.TOGGLE_UI_KEY).displayName);
				}
			}
			else
			{
				if (inRoundEndPhase || (ConfigManager.Instance.DisableWhileUsingTerminal && GetHostPlayer().inTerminalMenu))
				{
					return;
				}
				switch (currentMode)
				{
				case Mode.ENEMY:
					UIManager.Instance.RenderEnemyControls(((InputControl)InputKeys.ENEMY_PRIMARY_SKILL_BUTTON).shortDisplayName, ((InputControl)InputKeys.ENEMY_SECONDARY_SKILL_BUTTON).shortDisplayName, ((InputControl)InputKeys.ENEMY_TOGGLE_AI_KEY).displayName, ((InputControl)InputKeys.EXIT_KEY).displayName, ((InputControl)InputKeys.HOST_LISTEN_KEY).displayName, currentControlledEnemy, GetHostPlayer());
					break;
				case Mode.HOST:
					UIManager.Instance.RenderHostControls(((InputControl)InputKeys.HOST_GHOST_MODE_KEY).displayName, ((InputControl)InputKeys.CYCLE_KEY_LEFT).displayName, ((InputControl)InputKeys.CYCLE_KEY_RIGHT).displayName, currentTarget, isExtendedModeEnabled, ((InputControl)InputKeys.HOST_GIVE_CREDITS_KEY).displayName, ((InputControl)InputKeys.HOST_TELEPORT_TO_ENTRANCE_KEY).displayName, ((InputControl)InputKeys.TOGGLE_UI_KEY).displayName);
					break;
				case Mode.GHOST:
				{
					bool showEnemyPaging = GetSpawnableEnemies(isGhostIndoors).Count > 12;
					List<IEnumerable<Item>> list = ExtensionMethods.Chunk(GetSpawnableScraps(), 10).ToList();
					List<Item> scraps = ((list.Count > 0) ? list[currentSpawnScrapPage].ToList() : new List<Item>());
					UIManager.Instance.RenderGhostControls(InputKeys.GHOST_SPAWN_ENEMY_KEYS.Select((KeyControl key) => ((InputControl)key).displayName).ToList(), ((InputControl)InputKeys.EXIT_KEY).displayName, ((InputControl)InputKeys.CYCLE_KEY_LEFT).displayName, ((InputControl)InputKeys.CYCLE_KEY_RIGHT).displayName, ((InputControl)InputKeys.HOST_LISTEN_KEY).displayName, showEnemyPaging, GetPagedSpawnableEnemies(), scraps, GetHostPlayer(), scrapSpawnMode);
					break;
				}
				}
			}
		}

		private bool IsHostDead()
		{
			return GetHostPlayer().isPlayerDead;
		}

		private void EnableGhost(bool enable)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			EnableGhost(enable, Vector3.zero);
		}

		private void EnableGhost(bool enable, Vector3 position)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if (enable)
			{
				ghost.transform.position = position + new Vector3(0f, 0.5f, 0f);
				ghost.transform.rotation = Quaternion.identity;
				ghost.SetActive(true);
				ChangeAudioListener(ghostController.AudioListener);
				SetNextSpawnEnemiesPage(0);
			}
			else
			{
				ghost.SetActive(false);
			}
		}

		private void EnableHostPlayer(bool enable)
		{
			//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_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)
			PlayerControllerB hostPlayer = GetHostPlayer();
			MovementActions movement;
			if (enable)
			{
				if (ConfigManager.Instance.ForcePushToTalkWhileInMonsterMode)
				{
					ResetMicPushToTalk();
				}
				((Behaviour)GetHostPlayer().activeAudioListener).enabled = true;
				movement = hostPlayer.playerActions.Movement;
				((MovementActions)(ref movement)).PingScan.Enable();
				ChangeAudioListener(hostPlayer.activeAudioListener);
				((Behaviour)StartOfRound.Instance.activeCamera).enabled = true;
			}
			else
			{
				if (ConfigManager.Instance.ForcePushToTalkWhileInMonsterMode)
				{
					ForceMicPushToTalk();
				}
				((Behaviour)GetHostPlayer().activeAudioListener).enabled = false;
				movement = hostPlayer.playerActions.Movement;
				((MovementActions)(ref movement)).PingScan.Disable();
				((Behaviour)StartOfRound.Instance.activeCamera).enabled = false;
			}
		}

		private void EnablePlayer2DMics(bool enable, List<PlayerControllerB> players)
		{
			foreach (PlayerControllerB player in players)
			{
				if (player.isHostPlayerObject)
				{
					continue;
				}
				AudioSource currentVoiceChatAudioSource = player.currentVoiceChatAudioSource;
				if (enable)
				{
					if ((Object)(object)currentVoiceChatAudioSource != (Object)null)
					{
						currentVoiceChatAudioSource.spatialBlend = 0f;
					}
					player.currentVoiceChatIngameSettings.set2D = true;
					player.voicePlayerState.Volume = 1f;
				}
				else
				{
					if ((Object)(object)currentVoiceChatAudioSource != (Object)null)
					{
						currentVoiceChatAudioSource.spatialBlend = 1f;
					}
					player.currentVoiceChatIngameSettings.set2D = false;
					player.voicePlayerState.Volume = 0f;
				}
			}
		}

		private void SetNextTargetPlayer(int direction)
		{
			List<PlayerControllerB> alivePlayers = GetAlivePlayers();
			if (alivePlayers.Count == 0)
			{
				SetCurrentTargetToHost();
				ControlCompanyPlugin.Instance.logger.LogMessage((object)"Alive player count is zero");
			}
			else
			{
				currentTargetIndex += direction;
				if (currentTargetIndex >= alivePlayers.Count)
				{
					currentTargetIndex = 0;
				}
				else if (currentTargetIndex < 0)
				{
					currentTargetIndex = alivePlayers.Count - 1;
				}
				currentTargetIndex = Mathf.Clamp(currentTargetIndex, 0, alivePlayers.Count - 1);
				currentTarget = alivePlayers[currentTargetIndex];
			}
			ControlCompanyPlugin.Instance.logger.LogMessage((object)$"Current target index: {currentTargetIndex}");
			ControlCompanyPlugin.Instance.logger.LogMessage((object)("Setting next target to: " + currentTarget?.playerUsername));
		}

		public void SetCurrentTargetToHost()
		{
			currentTargetIndex = 0;
			currentTarget = GetHostPlayer();
			ControlCompanyPlugin.Instance.logger.LogMessage((object)"Setting next target to host");
		}

		private void SetNextSpawnEnemiesPage(int direction)
		{
			List<ControllableEnemy> spawnableEnemies = GetSpawnableEnemies(isGhostIndoors);
			if (spawnableEnemies == null || spawnableEnemies.Count == 0)
			{
				currentSpawnableEnemyList = new List<ControllableEnemy>();
				return;
			}
			if (spawnableEnemies.Count > 12)
			{
				List<IEnumerable<ControllableEnemy>> list = ExtensionMethods.Chunk(spawnableEnemies, 12).ToList();
				currentSpawnEnemiesPage += direction;
				if (currentSpawnEnemiesPage >= list.Count)
				{
					currentSpawnEnemiesPage = 0;
				}
				else if (currentSpawnEnemiesPage < 0)
				{
					currentSpawnEnemiesPage = list.Count - 1;
				}
				currentSpawnEnemiesPage = Mathf.Clamp(currentSpawnEnemiesPage, 0, list.Count - 1);
			}
			else
			{
				currentSpawnEnemiesPage = 0;
			}
			currentSpawnableEnemyList = ExtensionMethods.Chunk(GetSpawnableEnemies(isGhostIndoors), 12).ToList()[currentSpawnEnemiesPage].ToList();
		}

		public List<SpawnableEnemyWithRarity> GetDaytimeEnemies()
		{
			return new List<SpawnableEnemyWithRarity>(GetCurrentLevel().DaytimeEnemies);
		}

		public void StartOfRoundInitialization()
		{
			allIndoorEnemies = GetAllIndoorEnemiesAcrossAllMapsList();
			allOutdoorEnemies = GetAllOutdoorEnemiesAcrossAllMapsList();
			indoorEnemiesOfLevel = new List<ControllableEnemy>(GetCurrentLevel().Enemies.Select((SpawnableEnemyWithRarity enemy) => ControllableEnemy.FromSpawnableEnemy(enemy)));
			outdoorEnemiesOfLevel = new List<ControllableEnemy>(GetCurrentLevel().OutsideEnemies.Select((SpawnableEnemyWithRarity enemy) => ControllableEnemy.FromSpawnableEnemy(enemy)));
			ControllableEnemy maskedEnemy = GetMaskedEnemy();
			indoorEnemiesOfLevel.Add(maskedEnemy);
			outdoorEnemiesOfLevel.Add(maskedEnemy);
			allIndoorEnemies.Add(maskedEnemy);
			allOutdoorEnemies.Add(maskedEnemy);
			ControllableEnemy companyMonsterEnemy = GetCompanyMonsterEnemy();
			if (companyMonsterEnemy != null)
			{
				indoorEnemiesOfLevel.Add(companyMonsterEnemy);
				outdoorEnemiesOfLevel.Add(companyMonsterEnemy);
				allIndoorEnemies.Add(companyMonsterEnemy);
				allOutdoorEnemies.Add(companyMonsterEnemy);
			}
			ControllableEnemy secretEnemy = GetSecretEnemy();
			if (secretEnemy != null)
			{
				indoorEnemiesOfLevel.Insert(0, secretEnemy);
				allIndoorEnemies.Insert(0, secretEnemy);
			}
			indoorEnemiesOfLevel = indoorEnemiesOfLevel.DedupeBy((ControllableEnemy enemy) => enemy.EnemyName).ToList();
			outdoorEnemiesOfLevel = outdoorEnemiesOfLevel.DedupeBy((ControllableEnemy enemy) => enemy.EnemyName).ToList();
			allIndoorEnemies = allIndoorEnemies.DedupeBy((ControllableEnemy enemy) => enemy.EnemyName).ToList();
			allOutdoorEnemies = allOutdoorEnemies.DedupeBy((ControllableEnemy enemy) => enemy.EnemyName).ToList();
			gameStartedTime = 0f;
			SetCurrentTargetToHost();
			ResetToDefault();
			inRoundEndPhase = false;
			initialMicPushToTalkSetting = IngamePlayerSettings.Instance.settings.pushToTalk;
			ControlCompanyPlugin.Instance.logger.LogMessage((object)"Start of round initialization completed.");
		}

		public void EndOfRoundCleanUp()
		{
			ResetToDefault();
			inRoundEndPhase = true;
			ControlCompanyPlugin.Instance.logger.LogMessage((object)"End of round clean up completed.");
		}

		private void ResetToDefault()
		{
			StartOfRound.Instance.audioListener = GetHostPlayer().activeAudioListener;
			GetHostPlayer().isTypingChat = false;
			currentMode = Mode.HOST;
			if ((Object)(object)ghost != (Object)null)
			{
				Object.Destroy((Object)(object)ghost);
				ghost = null;
			}
			if ((Object)(object)currentControlledEnemy != (Object)null)
			{
				currentControlledEnemy.DestroyAndCleanUp();
			}
			currentSpawnableEnemyList = new List<ControllableEnemy>();
			currentSpawnEnemiesPage = 0;
			EnableHostPlayer(enable: true);
			ControlCompanyPlugin.Instance.logger.LogMessage((object)"Reset to default.");
		}

		public bool IsListeningFromHost()
		{
			return ((ButtonControl)InputKeys.HOST_LISTEN_KEY).isPressed;
		}

		public PlayerControllerB GetHostPlayer()
		{
			return RoundManager.Instance.playersManager.allPlayerObjects[0].GetComponentInChildren<PlayerControllerB>();
		}

		public List<PlayerControllerB> GetDeadPlayers()
		{
			return (from player in GetAllPlayers()
				where player.isPlayerDead
				select player).ToList();
		}

		public List<PlayerControllerB> GetAlivePlayers()
		{
			return (from player in GetAllPlayers()
				where !player.isPlayerDead
				select player).ToList();
		}

		public List<PlayerControllerB> GetAllPlayers()
		{
			List<PlayerControllerB> list = new List<PlayerControllerB>();
			GameObject[] allPlayerObjects = RoundManager.Instance.playersManager.allPlayerObjects;
			for (int i = 0; i < allPlayerObjects.Length; i++)
			{
				PlayerControllerB componentInChildren = allPlayerObjects[i].GetComponentInChildren<PlayerControllerB>();
				if ((Object)(object)componentInChildren != (Object)null && componentInChildren.isPlayerControlled)
				{
					list.Add(componentInChildren);
				}
			}
			return list;
		}

		public bool DoesCurrentLevelExist()
		{
			return (Object)(object)GetCurrentLevel() != (Object)null;
		}

		public bool IsGameStarted()
		{
			return (Object)(object)RoundManager.Instance != (Object)null && (Object)(object)RoundManager.Instance.currentLevel != (Object)null && (Object)(object)GameNetworkManager.Instance != (Object)null && GameNetworkManager.Instance.gameHasStarted && (Object)(object)StartOfRound.Instance != (Object)null && !StartOfRound.Instance.inShipPhase;
		}

		public SelectableLevel GetCurrentLevel()
		{
			return RoundManager.Instance.currentLevel;
		}

		public StartOfRound GetPlayersManager()
		{
			return RoundManager.Instance.playersManager;
		}

		private bool IsHost()
		{
			return ((NetworkBehaviour)RoundManager.Instance).IsHost;
		}

		public List<Item> GetSpawnableScraps()
		{
			return StartOfRound.Instance.allItemsList.itemsList;
		}

		public List<ControllableEnemy> GetPagedSpawnableEnemies()
		{
			return currentSpawnableEnemyList;
		}

		public List<ControllableEnemy> GetSpawnableEnemies(bool isIndoor)
		{
			List<ControllableEnemy> list = ((!isIndoor) ? GetSpawnableOutdoorEnemies() : GetSpawnableIndoorEnemies());
			if (list == null || list.Count == 0)
			{
				list = new List<ControllableEnemy>();
			}
			return list;
		}

		public List<ControllableEnemy> GetSpawnableIndoorEnemies()
		{
			return allowAllEnemies ? GetIndoorEnemyList() : GetAllowListedIndoorEnemies();
		}

		public List<ControllableEnemy> GetAllowListedIndoorEnemies()
		{
			return (from enemy in GetIndoorEnemyList()
				where enemy.Allowlisted
				select enemy).ToList();
		}

		public List<ControllableEnemy> GetIndoorEnemyList()
		{
			return allowAllEnemies ? allIndoorEnemies : indoorEnemiesOfLevel;
		}

		public List<ControllableEnemy> GetAllIndoorEnemiesAcrossAllMapsList()
		{
			HashSet<string> hashSet = new HashSet<string>();
			List<ControllableEnemy> list = new List<ControllableEnemy>();
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				if (!((Object)(object)val != (Object)null))
				{
					continue;
				}
				foreach (SpawnableEnemyWithRarity enemy in val.Enemies)
				{
					if ((Object)(object)enemy.enemyType != (Object)null && !hashSet.Contains(enemy.enemyType.enemyName))
					{
						hashSet.Add(enemy.enemyType.enemyName);
						list.Add(ControllableEnemy.FromSpawnableEnemy(enemy));
					}
				}
			}
			return list;
		}

		public List<ControllableEnemy> GetSpawnableOutdoorEnemies()
		{
			return allowAllEnemies ? GetOutdoorEnemyList() : GetAllowListedOutdoorEnemies();
		}

		public List<ControllableEnemy> GetAllowListedOutdoorEnemies()
		{
			return (from enemy in GetOutdoorEnemyList()
				where enemy.Allowlisted
				select enemy).ToList();
		}

		public List<ControllableEnemy> GetOutdoorEnemyList()
		{
			return allowAllEnemies ? allOutdoorEnemies : outdoorEnemiesOfLevel;
		}

		public List<ControllableEnemy> GetAllOutdoorEnemiesAcrossAllMapsList()
		{
			if (GetCurrentLevel().OutsideEnemies.Count == 0)
			{
				return new List<ControllableEnemy>();
			}
			HashSet<string> hashSet = new HashSet<string>();
			List<ControllableEnemy> list = new List<ControllableEnemy>();
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				if (!((Object)(object)val != (Object)null))
				{
					continue;
				}
				foreach (SpawnableEnemyWithRarity outsideEnemy in val.OutsideEnemies)
				{
					if ((Object)(object)outsideEnemy.enemyType != (Object)null && !hashSet.Contains(outsideEnemy.enemyType.enemyName))
					{
						hashSet.Add(outsideEnemy.enemyType.enemyName);
						list.Add(ControllableEnemy.FromSpawnableEnemy(outsideEnemy));
					}
				}
			}
			return list;
		}

		public ControllableEnemy GetMaskedEnemy()
		{
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				foreach (SpawnableEnemyWithRarity enemy in val.Enemies)
				{
					EnemyType enemyType = enemy.enemyType;
					object obj;
					if (enemyType == null)
					{
						obj = null;
					}
					else
					{
						GameObject enemyPrefab = enemyType.enemyPrefab;
						obj = ((enemyPrefab != null) ? enemyPrefab.GetComponent<EnemyAI>() : null);
					}
					EnemyAI val2 = (EnemyAI)obj;
					if ((Object)(object)val2 != (Object)null && ((object)val2).GetType() == typeof(MaskedPlayerEnemy))
					{
						return ControllableEnemy.FromSpawnableEnemy(enemy);
					}
				}
			}
			return null;
		}

		private ControllableEnemy GetSecretEnemy()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			Object[] array = Resources.FindObjectsOfTypeAll(typeof(EnemyAI));
			Object[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				EnemyAI val = (EnemyAI)array2[i];
				if (((object)val).GetType() == typeof(TestEnemy))
				{
					return ControllableEnemy.FromEnemyAI(val);
				}
			}
			return null;
		}

		private GameObject SpawnScrap(Item scrap, Vector3 position)
		{
			//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_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)
			GameObject val = Object.Instantiate<GameObject>(scrap.spawnPrefab, position, Quaternion.identity);
			GrabbableObject componentInChildren = val.GetComponentInChildren<GrabbableObject>();
			((Component)componentInChildren).transform.rotation = Quaternion.Euler(componentInChildren.itemProperties.restingRotation);
			val.GetComponentInChildren<NetworkObject>().Spawn(true);
			return val;
		}

		private EnemyController SpawnControllableEnemy(ControllableEnemy controllableEnemy, Vector3 position, Quaternion rotation)
		{
			//IL_0026: 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_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_002b: 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_003b: 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_0077: Expected O, but got Unknown
			//IL_007d: 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)
			Vector3 val = (controllableEnemy.OverrideEnemySpawnLocation ? controllableEnemy.EnemySpawnLocationOverride : (position + new Vector3(0f, 0.5f, 0f)));
			GameObject val2 = (controllableEnemy.OverrideEnemyPrefab ? controllableEnemy.EnemyGameObject : Object.Instantiate<GameObject>(controllableEnemy.EnemyPrefab, val, Quaternion.identity));
			if (!controllableEnemy.OverrideEnemyPrefab)
			{
				val2.GetComponentInChildren<NetworkObject>().Spawn(true);
			}
			GameObject val3 = new GameObject("enemy_controller");
			val3.transform.position = val;
			val3.transform.rotation = rotation;
			if (controllableEnemy.CreateAndAttachEnemyControllerFunc == null)
			{
				throw new Exception("Controllable enemy does not have a function defined to create and attach an enemy controller!");
			}
			EnemyController enemyController = controllableEnemy.CreateAndAttachEnemyControllerFunc(val2, val3);
			enemyController.InitializeEnemyController(GetHostPlayer().playerActions, val2);
			enemyController.EnableLight(isGhostIndoors);
			ChangeAudioListener(enemyController.AudioListener);
			return enemyController;
		}

		private GameObject GetTurretPrefab()
		{
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				SpawnableMapObject[] spawnableMapObjects = val.spawnableMapObjects;
				foreach (SpawnableMapObject val2 in spawnableMapObjects)
				{
					object obj;
					if (val2 == null)
					{
						obj = null;
					}
					else
					{
						GameObject prefabToSpawn = val2.prefabToSpawn;
						obj = ((prefabToSpawn != null) ? prefabToSpawn.GetComponentInChildren<Turret>() : null);
					}
					if ((Object)obj != (Object)null)
					{
						return val2.prefabToSpawn;
					}
				}
			}
			return null;
		}

		private EnemyController SpawnControllableTurret(Vector3 position, Quaternion rotation)
		{
			//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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0057: 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_006c: 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)
			GameObject turretPrefab = GetTurretPrefab();
			if ((Object)(object)turretPrefab == (Object)null)
			{
				ControlCompanyPlugin.Instance.logger.LogDebug((object)"Cannot find turret prefab in current level");
				return null;
			}
			GameObject val = Object.Instantiate<GameObject>(turretPrefab, position, rotation);
			val.GetComponentInChildren<NetworkObject>().Spawn(true);
			GameObject val2 = new GameObject("enemy_controller");
			val2.transform.position = position + new Vector3(0f, 0.5f, 0f);
			val2.transform.rotation = rotation;
			TurretEnemyController turretEnemyController = val2.AddComponent<TurretEnemyController>();
			turretEnemyController.InitializeEnemyController(GetHostPlayer().playerActions, val);
			turretEnemyController.EnableLight(enable: true);
			return turretEnemyController;
		}

		private ControllableEnemy GetCompanyMonsterEnemy()
		{
			//IL_0078: 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)
			DepositItemsDesk val = Object.FindObjectOfType<DepositItemsDesk>();
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			GameObject val2 = GameObject.Find("BellDinger");
			return new ControllableEnemy
			{
				EnemyName = "Company Monster",
				OverrideEnemyPrefab = true,
				EnemyGameObject = ((Component)val).gameObject,
				Allowlisted = true,
				OverrideEnemySpawnLocation = true,
				EnemySpawnLocationOverride = (((Object)(object)val2 != (Object)null) ? val2.transform.position : ((Component)val).transform.position),
				CreateAndAttachEnemyControllerFunc = (GameObject enemyGameObject, GameObject enemyController) => enemyController.AddComponent<CompanyMonsterController>()
			};
		}

		private DissonanceComms GetMic()
		{
			return StartOfRound.Instance.voiceChatModule;
		}

		private void ForceMicPushToTalk()
		{
			IngamePlayerSettings.Instance.settings.pushToTalk = true;
		}

		private void ResetMicPushToTalk()
		{
			IngamePlayerSettings.Instance.settings.pushToTalk = initialMicPushToTalkSetting;
		}
	}
	internal class DoorOpener : MonoBehaviour
	{
		public void DetectAndOpenDoors(float range)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(((Component)this).transform.position, range);
			for (int i = 0; i < array.Length; i++)
			{
				DoorLock componentInChildren = ((Component)array[i]).GetComponentInChildren<DoorLock>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					OpenDoor(componentInChildren);
				}
			}
		}

		public void OpenDoor(DoorLock doorLock)
		{
			if ((Object)(object)doorLock != (Object)null && !doorLock.GetFieldValue<bool>("isDoorOpened"))
			{
				doorLock.OpenDoorAsEnemyServerRpc();
				((Component)doorLock).gameObject.GetComponent<AnimatedObjectTrigger>().TriggerAnimationNonPlayer(false, true, false);
			}
		}
	}
	internal class EnemyController : CustomPlayerController
	{
		protected GameObject enemyGameObject;

		protected bool isAIControlled = false;

		protected bool controlEnemyRotation = true;

		protected bool controlEnemyMovement = true;

		protected bool lockEnemyRotationInput = false;

		public bool IsAIControlled => isAIControlled;

		public virtual void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
		}

		public virtual bool CanControlEnemy()
		{
			return true;
		}

		public void SetLockEnemyRotation(bool lockEnemyRotationInput)
		{
			this.lockEnemyRotationInput = lockEnemyRotationInput;
		}

		public void UsePrimarySkill()
		{
			CheckInitialized();
			if (!isAIControlled)
			{
				UsePrimarySkillAction();
			}
		}

		protected virtual void UsePrimarySkillAction()
		{
		}

		public void ReleasePrimarySkill()
		{
			CheckInitialized();
			if (!isAIControlled)
			{
				ReleasePrimarySkillAction();
			}
		}

		protected virtual void ReleasePrimarySkillAction()
		{
		}

		public void UseSecondarySkill()
		{
			CheckInitialized();
			if (!isAIControlled)
			{
				UseSecondarySkillAction();
			}
		}

		protected virtual void UseSecondarySkillAction()
		{
		}

		public void ReleaseSecondarySkill()
		{
			CheckInitialized();
			if (!isAIControlled)
			{
				ReleaseSecondarySkillAction();
			}
		}

		protected virtual void ReleaseSecondarySkillAction()
		{
		}

		protected virtual void EnableAIControl(bool enabled)
		{
			CheckInitialized();
			isAIControlled = enabled;
			ControlCompanyPlugin.Instance.logger.LogMessage((object)$"Enable AI control: {enabled}");
			if (IsAIControlled)
			{
				ToggleAIControlTrue();
			}
			else
			{
				ToggleAIControlFalse();
			}
		}

		protected virtual void ToggleAIControlTrue()
		{
		}

		protected virtual void ToggleAIControlFalse()
		{
		}

		public virtual void ToggleAIControl()
		{
			CheckInitialized();
			isAIControlled = !isAIControlled;
			EnableAIControl(isAIControlled);
		}

		public virtual void DestroyAndCleanUp()
		{
			if (ShouldDestroyEnemyGameObjectOnCleanUp())
			{
				Object.Destroy((Object)(object)enemyGameObject);
			}
			Object.Destroy((Object)(object)((Component)this).gameObject);
		}

		protected virtual bool ShouldDestroyEnemyGameObjectOnCleanUp()
		{
			return true;
		}

		public virtual string GetPrimarySkillName()
		{
			return "";
		}

		public virtual string GetSecondarySkillName()
		{
			return "";
		}

		protected void CheckInitialized()
		{
			if (!isInitialized)
			{
				throw new Exception("Not initialized yet.");
			}
		}

		protected virtual void OnControllerColliderHit(ControllerColliderHit hit)
		{
			DoorLock component = hit.gameObject.GetComponent<DoorLock>();
			if ((Object)(object)component != (Object)null)
			{
				doorOpener.OpenDoor(component);
			}
		}
	}
	internal class EnemyAIController : EnemyController
	{
		private EnemyAI enemyAI;

		private NavMeshAgent enemyAIAgent;

		private float originalAgentAngularSpeed;

		private float originalAgentSpeed;

		private Vector3 enemyPositionOffset = Vector3.zero;

		private bool useLerpRotation = false;

		public EnemyAI EnemyAI => enemyAI;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//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_0095: 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)
			if (!isInitialized)
			{
				List<Collider> list = enemyGameObject.GetComponentsInChildren<Collider>().ToList();
				Initialize(playerActions, CameraMode.THIRD_PERSON, list);
				CharacterController obj = characterController;
				((Collider)obj).excludeLayers = LayerMask.op_Implicit(LayerMask.op_Implicit(((Collider)obj).excludeLayers) & ~LayerMask.op_Implicit(Constants.ITERACTABLE_OBJ_LAYERMASK));
				enemyAI = GetEnemyAIFromEnemyGameObject(enemyGameObject);
				if ((Object)(object)enemyAI == (Object)null)
				{
					throw new Exception("Enemy gameobject does not have EnemyAI script attached.");
				}
				((Component)enemyAI).gameObject.LogLayer();
				enemyGameObject.transform.position = ((Component)this).transform.position;
				enemyGameObject.transform.rotation = ((Component)this).transform.rotation;
				base.enemyGameObject = enemyGameObject;
				enemyAIAgent = enemyGameObject.GetComponentInChildren<NavMeshAgent>();
				if ((Object)(object)enemyAIAgent != (Object)null)
				{
					originalAgentAngularSpeed = enemyAIAgent.angularSpeed;
					originalAgentSpeed = enemyAIAgent.speed;
				}
				ConfigureEnemyAttributes(enemyAI);
				EnableAIControl(enabled: false);
			}
		}

		protected override void LateUpdate()
		{
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_010b: 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_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)
			if (!isInitialized)
			{
				return;
			}
			base.LateUpdate();
			if (!isAIControlled)
			{
				if (!CanControlEnemy())
				{
					return;
				}
				if (controlEnemyMovement)
				{
					enemyGameObject.transform.position = ((Component)this).transform.position + enemyPositionOffset;
				}
				if (!controlEnemyRotation || lockEnemyRotationInput)
				{
					return;
				}
				Vector3 velocity = characterController.velocity;
				if (((Vector3)(ref velocity)).sqrMagnitude > 0.1f)
				{
					if (useLerpRotation)
					{
						enemyGameObject.transform.rotation = Quaternion.Lerp(enemyGameObject.transform.rotation, ((Component)this).transform.rotation, 8f * Time.deltaTime);
					}
					else
					{
						enemyGameObject.transform.rotation = ((Component)this).transform.rotation;
					}
				}
			}
			else
			{
				((Component)this).transform.position = enemyGameObject.transform.position;
			}
		}

		protected EnemyAI GetEnemyAIFromEnemyGameObject(GameObject enemyObj)
		{
			return enemyObj.GetComponentInChildren<EnemyAI>();
		}

		private void ConfigureEnemyAttributes(EnemyAI enemyAI)
		{
			//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)
			EnemyAttributes enemyAttributes = enemyAI.GetEnemyAttributes();
			base.WalkSpeed = enemyAttributes.WalkSpeed;
			base.RunSpeed = enemyAttributes.RunSpeed;
			SetCamDistance(enemyAttributes.CamDistance);
			SetCamHeight(enemyAttributes.CamHeight);
			controlEnemyRotation = enemyAttributes.PlayerControlsRotation;
			controlEnemyMovement = true;
			enemyPositionOffset = enemyAttributes.EnemyPositionOffset;
			useLerpRotation = enemyAttributes.UseLerpRotation;
		}

		protected virtual void ConfigureEnemyHandicap(EnemyAI enemyAI)
		{
		}

		public override bool CanControlEnemy()
		{
			return !enemyAI.isEnemyDead;
		}

		protected override void Move()
		{
			if (!enemyAI.isEnemyDead)
			{
				base.Move();
			}
		}

		public void SwitchAIState(int stateIndex)
		{
			CheckInitialized();
			if (!isAIControlled)
			{
				enemyAI.SwitchToBehaviourState(stateIndex);
			}
		}

		protected override void ToggleAIControlTrue()
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)enemyAIAgent != (Object)null)
			{
				enemyAIAgent.angularSpeed = originalAgentAngularSpeed;
				enemyAIAgent.speed = originalAgentSpeed;
				enemyAIAgent.isStopped = false;
				enemyAIAgent.Warp(enemyGameObject.transform.position);
				enemyAIAgent.updatePosition = true;
			}
		}

		protected override void ToggleAIControlFalse()
		{
			if ((Object)(object)enemyAI != (Object)null)
			{
				try
				{
					enemyAI.ChangeOwnershipOfEnemy(ControlCenter.Instance.GetHostPlayer().actualClientId);
				}
				catch (Exception ex)
				{
					ControlCompanyPlugin.Instance.logger.LogDebug((object)("Cannot give host control: " + ex.Message));
				}
			}
			if ((Object)(object)enemyAIAgent != (Object)null)
			{
				enemyAIAgent.angularSpeed = 0f;
				enemyAIAgent.speed = 0f;
				enemyAIAgent.isStopped = true;
				enemyAIAgent.updatePosition = false;
			}
			((Component)this).transform.SetParent((Transform)null);
		}

		protected override bool ShouldDestroyEnemyGameObjectOnCleanUp()
		{
			return !enemyAI.isEnemyDead;
		}

		public override string GetSecondarySkillName()
		{
			return "Secondary Skill";
		}

		protected override void UseSecondarySkillAction()
		{
			enemyAI.SwitchToBehaviourState(1);
		}

		protected override void EnableAIControl(bool enabled)
		{
			base.EnableAIControl(enabled);
			canMove = !isAIControlled;
		}
	}
	internal class CustomPlayerController : MonoBehaviour
	{
		public enum CameraMode
		{
			THIRD_PERSON,
			FIRST_PERSON
		}

		protected bool isInitialized = false;

		protected bool hasControl = false;

		protected bool canMove = false;

		protected bool canRotate = false;

		protected bool canJump = false;

		protected CameraMode camMode;

		protected CharacterController characterController;

		protected GameObject cameraGameObjectParent;

		protected GameObject cameraGameObject;

		protected Camera camera;

		protected Light light;

		protected PlayerActions playerActions;

		protected DoorOpener doorOpener;

		private AudioListener audioListener;

		private float runSpeed = 9f;

		private float walkSpeed = 7f;

		private float camDistance = -3.5f;

		private float camHeight = 2f;

		private float gravity = -20f;

		private float jumpHeight = 4.5f;

		private float currentYVelocity;

		private List<Collider> collidersToIgnore = new List<Collider>();

		public float RunSpeed
		{
			get
			{
				return runSpeed;
			}
			set
			{
				runSpeed = value;
			}
		}

		public float WalkSpeed
		{
			get
			{
				return walkSpeed;
			}
			set
			{
				walkSpeed = value;
			}
		}

		public float Gravity
		{
			get
			{
				return gravity;
			}
			set
			{
				gravity = value;
			}
		}

		public AudioListener AudioListener
		{
			get
			{
				return audioListener;
			}
			set
			{
				audioListener = value;
			}
		}

		public bool IsInitialized
		{
			get
			{
				return isInitialized;
			}
			set
			{
				isInitialized = value;
			}
		}

		public void Initialize(PlayerActions playerActions, CameraMode camMode, List<Collider> collidersToIgnore = null)
		{
			if (!isInitialized)
			{
				this.playerActions = playerActions;
				this.camMode = camMode;
				if (collidersToIgnore != null)
				{
					this.collidersToIgnore = collidersToIgnore;
				}
				characterController = InitializeCharacterController();
				camera = InitializeCamera();
				light = InitializeLight(((Component)camera).gameObject);
				doorOpener = ((Component)this).gameObject.AddComponent<DoorOpener>();
				EnableControl(enable: true);
				isInitialized = true;
			}
		}

		public void EnableLight(bool enable)
		{
			((Behaviour)light).enabled = enable;
		}

		public void EnableCamera(bool enable)
		{
			((Behaviour)camera).enabled = enable;
		}

		public void ToggleLight()
		{
			((Behaviour)light).enabled = !((Behaviour)light).enabled;
		}

		public void EnableControl(bool enable)
		{
			hasControl = enable;
			canMove = enable;
			canRotate = enable;
			canJump = enable;
		}

		public bool IsMoving()
		{
			//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)
			Vector3 velocity = characterController.velocity;
			return ((Vector3)(ref velocity)).sqrMagnitude > 0f;
		}

		public void SetCamHeight(float camHeight)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			this.camHeight = camHeight;
			cameraGameObjectParent.transform.localPosition = new Vector3(0f, camHeight, 0f);
		}

		public void SetCamDistance(float camDistance)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			this.camDistance = camDistance;
			cameraGameObject.transform.localPosition = new Vector3(0f, 0f, (camMode == CameraMode.THIRD_PERSON) ? camDistance : 0f);
		}

		protected virtual void LateUpdate()
		{
			if (isInitialized && hasControl)
			{
				if (canMove)
				{
					Move();
				}
				if (canRotate)
				{
					Rotate();
				}
				if (((ButtonControl)InputKeys.CONTROLLER_USE_KEY).wasPressedThisFrame)
				{
					doorOpener.DetectAndOpenDoors(3f);
				}
			}
		}

		protected virtual Vector3 MoveInput()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			return Vector2.op_Implicit(IngamePlayerSettings.Instance.playerInput.actions.FindAction("Move", false).ReadValue<Vector2>());
		}

		protected virtual bool IsSprinting()
		{
			return IngamePlayerSettings.Instance.playerInput.actions.FindAction("Sprint", false).ReadValue<float>() > 0f;
		}

		protected virtual void Move()
		{
			//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_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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_00d0: 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_00d2: 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_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			bool flag = IsSprinting();
			Vector3 val = MoveInput();
			Vector3 val2 = ((Component)this).transform.right * val.x;
			Vector3 val3 = ((Component)this).transform.forward * val.y;
			bool isGrounded = characterController.isGrounded;
			if (isGrounded && currentYVelocity < 0f)
			{
				currentYVelocity = 0f;
			}
			if (canJump && isGrounded && ((ButtonControl)InputKeys.CONTROLLER_JUMP_KEY).wasPressedThisFrame)
			{
				currentYVelocity += Mathf.Sqrt(jumpHeight * (0f - gravity));
			}
			currentYVelocity += gravity * Time.deltaTime;
			characterController.Move(((val2 + val3) * (flag ? runSpeed : walkSpeed) + new Vector3(0f, currentYVelocity, 0f)) * Time.deltaTime);
		}

		protected virtual void Rotate()
		{
			//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_0014: 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_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			MovementActions movement = playerActions.Movement;
			Vector2 val = ((MovementActions)(ref movement)).Look.ReadValue<Vector2>() * 0.008f * (float)IngamePlayerSettings.Instance.settings.lookSensitivity;
			if (IngamePlayerSettings.Instance.settings.invertYAxis)
			{
				val.y *= -1f;
			}
			((Component)this).transform.Rotate(new Vector3(0f, val.x, 0f));
			cameraGameObjectParent.transform.Rotate(new Vector3(0f - val.y, 0f, 0f));
		}

		private Light InitializeLight(GameObject lightParent)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0033: 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)
			GameObject val = new GameObject("controller_light");
			val.transform.SetParent(lightParent.transform);
			val.transform.localPosition = new Vector3(0f, 0.5f, 0f);
			val.transform.localRotation = Quaternion.identity;
			Light val2 = val.AddComponent<Light>();
			val2.range = 15f;
			val2.intensity = 225f;
			val2.cullingMask = -1;
			return val2;
		}

		private CharacterController InitializeCharacterController()
		{
			//IL_001e: 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_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			CharacterController controller = ((Component)this).gameObject.AddComponent<CharacterController>();
			((Collider)controller).excludeLayers = LayerMask.op_Implicit(LayerMask.op_Implicit(Constants.PLAYER_LOS_LAYERMASK) | LayerMask.op_Implicit(Constants.ITERACTABLE_OBJ_LAYERMASK) | LayerMask.op_Implicit(Constants.ENEMIES_LAYERMASK) | LayerMask.op_Implicit(Constants.PROPS_LAYERMASK) | LayerMask.op_Implicit(Constants.PLAYER_RAGDOLL_LAYERMASK));
			controller.center = new Vector3(0f, 0.55f, 0f);
			controller.height = 0.4f;
			ControlCenter.Instance.GetAllPlayers().ForEach(delegate(PlayerControllerB p)
			{
				if ((Object)(object)p != (Object)null)
				{
					((Component)p).GetComponentsInChildren<Collider>().ToList().ForEach(delegate(Collider c)
					{
						Physics.IgnoreCollision(c, (Collider)(object)controller);
					});
				}
			});
			if (collidersToIgnore.Count() > 0)
			{
				foreach (Collider item in collidersToIgnore)
				{
					Physics.IgnoreCollision(item, (Collider)(object)controller);
				}
			}
			controller.slopeLimit = 60f;
			controller.stepOffset = 0.4f;
			return controller;
		}

		private Camera InitializeCamera()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			//IL_0073: 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)
			GameObject val = new GameObject("controller_cam_parent");
			val.transform.SetParent(((Component)this).transform);
			val.transform.localRotation = Quaternion.identity;
			val.transform.localPosition = new Vector3(0f, camHeight, 0f);
			GameObject val2 = new GameObject("controller_cam");
			val2.transform.SetParent(val.transform);
			val2.transform.localRotation = Quaternion.identity;
			val2.transform.localPosition = new Vector3(0f, 0f, (camMode == CameraMode.THIRD_PERSON) ? camDistance : 0f);
			Camera val3 = val2.AddComponent<Camera>();
			audioListener = val2.AddComponent<AudioListener>();
			cameraGameObject = val2;
			cameraGameObjectParent = val;
			Camera gameplayCamera = ControlCenter.Instance.GetHostPlayer().gameplayCamera;
			val3.cullingMask = gameplayCamera.cullingMask;
			val3.farClipPlane = gameplayCamera.farClipPlane;
			HDAdditionalCameraData component = ((Component)gameplayCamera).gameObject.GetComponent<HDAdditionalCameraData>();
			CopyHDCameraData(val3, component);
			return val3;
		}

		private void CopyHDCameraData(Camera cam, HDAdditionalCameraData dataToCopy)
		{
			//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)
			if ((Object)(object)dataToCopy != (Object)null)
			{
				HDAdditionalCameraData val = ((Component)cam).gameObject.GetComponent<HDAdditionalCameraData>();
				if ((Object)(object)val == (Object)null)
				{
					val = ((Component)cam).gameObject.AddComponent<HDAdditionalCameraData>();
				}
				if ((Object)(object)val != (Object)null)
				{
					val.customRenderingSettings = true;
					val.renderingPathCustomFrameSettingsOverrideMask.mask = dataToCopy.renderingPathCustomFrameSettingsOverrideMask.mask;
					SetCustomPass(val, dataToCopy);
					SetVolumetricFog(val, dataToCopy);
					SetLOD(val, dataToCopy);
					SetAliasing(val, dataToCopy);
					SetShadowQuality(val, dataToCopy);
				}
			}
		}

		private void SetCustomPass(HDAdditionalCameraData camData, HDAdditionalCameraData dataToCopy)
		{
			((FrameSettings)(ref camData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)6, ((FrameSettings)(ref dataToCopy.renderingPathCustomFrameSettings)).IsEnabled((FrameSettingsField)6));
		}

		private void SetVolumetricFog(HDAdditionalCameraData camData, HDAdditionalCameraData dataToCopy)
		{
			((FrameSettings)(ref camData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)28, ((FrameSettings)(ref dataToCopy.renderingPathCustomFrameSettings)).IsEnabled((FrameSettingsField)28));
		}

		private void SetLOD(HDAdditionalCameraData camData, HDAdditionalCameraData dataToCopy)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			camData.renderingPathCustomFrameSettings.lodBiasMode = dataToCopy.renderingPathCustomFrameSettings.lodBiasMode;
			camData.renderingPathCustomFrameSettings.lodBias = dataToCopy.renderingPathCustomFrameSettings.lodBias;
		}

		private void SetAliasing(HDAdditionalCameraData camData, HDAdditionalCameraData dataToCopy)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			camData.antialiasing = dataToCopy.antialiasing;
		}

		private void SetShadowQuality(HDAdditionalCameraData camData, HDAdditionalCameraData dataToCopy)
		{
			((FrameSettings)(ref camData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)20, ((FrameSettings)(ref dataToCopy.renderingPathCustomFrameSettings)).IsEnabled((FrameSettingsField)20));
		}
	}
}
namespace ControlCompany.Core.UI
{
	public class UIInstruction
	{
		public string InputKey { get; set; }

		public string ActionText { get; set; }
	}
	internal class UIManager : MonoBehaviour
	{
		private const float GUI_LABEL_HEIGHT = 36f;

		private const float GUI_LABEL_WIDTH = 750f;

		private const float GUI_PADDING = 32f;

		private const int GUI_FONT_SIZE = 28;

		private const FontStyle GUI_FONT_WEIGHT = 0;

		public static UIManager Instance;

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

		public void RenderNotHostLabel(string toggleUIKey)
		{
			//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)
			//IL_0018: 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_002a: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			GUIStyle val = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)3,
				fontSize = 24,
				fontStyle = (FontStyle)0
			};
			val.normal.textColor = Color.red;
			RenderTextTopLeftCorner("Not hosting. ControlCompany mod is disabled. Press " + toggleUIKey + " to hide.", 0f, val, 1000f);
		}

		public void RenderEnemyControls(string primaryKey, string secondaryKey, string aiControlKey, string exitKey, string listenFromHostKey, EnemyController enemyController, PlayerControllerB hostPlayer)
		{
			string primarySkillName = enemyController.GetPrimarySkillName();
			string secondarySkillName = enemyController.GetSecondarySkillName();
			List<UIInstruction> list = new List<UIInstruction>();
			if (enemyController.IsAIControlled)
			{
				list.Add(new UIInstruction
				{
					InputKey = aiControlKey,
					ActionText = "Take control"
				});
			}
			else
			{
				if (!Utility.IsNullOrWhiteSpace(primarySkillName))
				{
					list.Add(new UIInstruction
					{
						InputKey = primaryKey,
						ActionText = primarySkillName
					});
				}
				if (!Utility.IsNullOrWhiteSpace(secondarySkillName))
				{
					list.Add(new UIInstruction
					{
						InputKey = secondaryKey,
						ActionText = secondarySkillName
					});
				}
				list.Add(new UIInstruction
				{
					InputKey = aiControlKey,
					ActionText = "AI control"
				});
			}
			list.Add(new UIInstruction
			{
				InputKey = exitKey,
				ActionText = "Exit"
			});
			RenderPlayerStatus(hostPlayer, listenFromHostKey);
			float height = 0f;
			height = RenderEnemyStatus(enemyController, height);
			RenderEnemySkills(list, height);
		}

		public void RenderHostControls(string ghostModeKey, string cycleLeftKey, string cycleRightKey, PlayerControllerB currentTarget, bool isExtendedModeEnabled, string creditsKey, string entranceTeleportKey, string toggleUIKey)
		{
			List<UIInstruction> list = new List<UIInstruction>();
			list.Add(new UIInstruction
			{
				InputKey = ghostModeKey,
				ActionText = "Ghost mode"
			});
			list.Add(new UIInstruction
			{
				InputKey = $"{cycleLeftKey}/{cycleRightKey}",
				ActionText = "Change target"
			});
			list.Add(new UIInstruction
			{
				InputKey = toggleUIKey,
				ActionText = "Hide UI"
			});
			if (isExtendedModeEnabled)
			{
				list.Add(new UIInstruction
				{
					InputKey = creditsKey,
					ActionText = "Give credits"
				});
				list.Add(new UIInstruction
				{
					InputKey = entranceTeleportKey,
					ActionText = "Teleport to entrance"
				});
			}
			RenderHostControlList(list, currentTarget);
		}

		public void RenderGhostControls(List<string> enemySpawnKeys, string exitKey, string cycleLeftKey, string cycleRightKey, string listenFromHostKey, bool showEnemyPaging, List<ControllableEnemy> enemies, List<Item> scraps, PlayerControllerB hostPlayer, bool scrapSpawnMode)
		{
			List<UIInstruction> list = new List<UIInstruction>();
			if (!scrapSpawnMode)
			{
				if (enemies != null && enemies.Count > 0)
				{
					if (showEnemyPaging)
					{
						list.Add(new UIInstruction
						{
							InputKey = $"{cycleLeftKey}/{cycleRightKey}",
							ActionText = "Change page"
						});
					}
					for (int i = 0; i < enemies.Count && i < enemySpawnKeys.Count; i++)
					{
						GameObject enemyPrefab = enemies[i].EnemyPrefab;
						list.Add(new UIInstruction
						{
							InputKey = enemySpawnKeys[i],
							ActionText = $"Control {enemies[i].EnemyName}"
						});
					}
				}
			}
			else
			{
				for (int j = 0; j < scraps.Count && j < enemySpawnKeys.Count; j++)
				{
					list.Add(new UIInstruction
					{
						InputKey = enemySpawnKeys[j],
						ActionText = $"Spawn {scraps[j].itemName}"
					});
				}
			}
			list.Add(new UIInstruction
			{
				InputKey = exitKey,
				ActionText = "Exit"
			});
			RenderPlayerStatus(hostPlayer, listenFromHostKey);
			RenderGhostControlList(list);
		}

		private void RenderGhostControlList(List<UIInstruction> ghostControls)
		{
			//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_0029: 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_003b: Expected O, but got Unknown
			if (ghostControls.Count <= 0)
			{
				return;
			}
			GUIStyle style = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)5,
				fontSize = 28,
				fontStyle = (FontStyle)0
			};
			float num = 0f;
			foreach (UIInstruction ghostControl in ghostControls)
			{
				RenderTextTopRightCorner($"{ghostControl.InputKey}: {ghostControl.ActionText}", num, style);
				num += 36f;
			}
		}

		private float RenderMicStatus(float height, PlayerControllerB hostPlayer)
		{
			//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)
			//IL_0018: 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_002a: Expected O, but got Unknown
			//IL_00bb: 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)
			GUIStyle val = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)3,
				fontSize = 28,
				fontStyle = (FontStyle)0
			};
			float num = height;
			if (IngamePlayerSettings.Instance.settings.micEnabled && (Object)(object)StartOfRound.Instance.voiceChatModule != (Object)null)
			{
				if (!StartOfRound.Instance.voiceChatModule.IsMuted)
				{
					val.normal.textColor = Color.green;
					RenderTextTopLeftCorner(string.Format("{0} mic enabled", hostPlayer.isPlayerDead ? "Dead" : "Player"), num, val);
				}
				else
				{
					val.normal.textColor = Color.red;
					RenderTextTopLeftCorner(string.Format("{0} mic disabled (push to talk)", hostPlayer.isPlayerDead ? "Dead" : "Player"), num, val);
				}
				num += 36f;
			}
			return num;
		}

		private float RenderPlayerStatus(PlayerControllerB hostPlayer, string listenFromHostKey)
		{
			//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)
			//IL_0018: 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_002a: Expected O, but got Unknown
			//IL_0050: 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_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)
			//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_00d1: Expected O, but got Unknown
			//IL_0103: 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_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_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Expected O, but got Unknown
			//IL_019c: 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)
			GUIStyle val = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)3,
				fontSize = 28,
				fontStyle = (FontStyle)0
			};
			if (hostPlayer.isPlayerDead)
			{
				val.normal.textColor = Color.red;
			}
			else
			{
				val.normal.textColor = Color.green;
			}
			float num = 0f;
			RenderTextTopLeftCorner(string.Format("Player status: {0}", hostPlayer.isPlayerDead ? "Dead" : "Alive"), num, val);
			num += 36f;
			if (!hostPlayer.isPlayerDead)
			{
				GUIStyle val2 = new GUIStyle(GUI.skin.label)
				{
					alignment = (TextAnchor)3,
					fontSize = 28,
					fontStyle = (FontStyle)0
				};
				bool flag = !HostIsNearOtherPlayers(hostPlayer);
				if (flag)
				{
					val2.normal.textColor = Color.green;
				}
				else
				{
					val2.normal.textColor = Color.red;
				}
				RenderTextTopLeftCorner(string.Format("Player proximity: {0}", flag ? "Alone" : "Near others"), num, val2);
				num += 36f;
				GUIStyle val3 = new GUIStyle(GUI.skin.label)
				{
					alignment = (TextAnchor)3,
					fontSize = 28,
					fontStyle = (FontStyle)0
				};
				bool flag2 = ControlCenter.Instance.IsListeningFromHost();
				if (flag2)
				{
					val3.normal.textColor = Color.green;
				}
				else
				{
					val3.normal.textColor = Color.red;
				}
				RenderTextTopLeftCorner(string.Format("Listening from host: {0}", flag2 ? "Yes" : ("No (hold " + listenFromHostKey + ")")), num, val3);
				num += 36f;
			}
			return num + RenderMicStatus(num, hostPlayer);
		}

		private void RenderHostControlList(List<UIInstruction> hostControls, PlayerControllerB currentTarget)
		{
			//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_0029: 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_003b: Expected O, but got Unknown
			if (hostControls.Count <= 0)
			{
				return;
			}
			GUIStyle style = new GUIStyle(GUI.skin.label)
			{
				alignment = (TextAnchor)5,
				fontSize = 28,
				fontStyle = (FontStyle)0
			};
			float num = 0f;
			if ((Object)(object)currentTarget != (Object)null)
			{
				RenderTextTopRightCorner($"Spawn target: {currentTarget.playerUsername}", num, style);
				num += 36f;
			}
			foreach (UIInstruction hostControl in hostControls)
			{
				RenderTextTopRightCorner($"{hostControl.InputKey}: {hostControl.ActionText}", num, style);
				num += 36f;
			}
		}

		private float RenderEnemyStatus(EnemyController enemyController, float height)
		{
			//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_0025: 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_0037: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			float num = height;
			if (enemyController.IsAIControlled)
			{
				GUIStyle val = new GUIStyle(GUI.skin.label)
				{
					alignment = (TextAnchor)5,
					fontSize = 28,
					fontStyle = (FontStyle)0
				};
				val.normal.textColor = Color.red;
				RenderTextTopRightCorner("AI controlled", num, val);
				num += 36f;
			}
			return num;
		}

		private float RenderEnemySkills(List<UIInstruction> playerEnemyControls, float height)
		{
			//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_002b: 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_003d: Expected O, but got Unknown
			float num = height;
			if (playerEnemyControls.Count > 0)
			{
				GUIStyle style = new GUIStyle(GUI.skin.label)
				{
					alignment = (TextAnchor)5,
					fontSize = 28,
					fontStyle = (FontStyle)0
				};
				foreach (UIInstruction playerEnemyControl in playerEnemyControls)
				{
					RenderTextTopRightCorner($"{playerEnemyControl.InputKey}: {playerEnemyControl.ActionText}", num, style);
					num += 36f;
				}
			}
			return num;
		}

		private void RenderTextMiddle(string text, float yPos, GUIStyle style)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			GUI.Label(new Rect((float)Screen.width / 2f - 375f, yPos + 32f, 750f, 36f), text, style);
		}

		private void RenderTextTopRightCorner(string text, float yPos, GUIStyle style)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			GUI.Label(new Rect((float)Screen.width - 750f - 32f, yPos + 32f, 750f, 36f), text, style);
		}

		private void RenderTextTopLeftCorner(string text, float yPos, GUIStyle style, float widthOverride = -1f)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			GUI.Label(new Rect(32f, yPos + 32f, (widthOverride > 0f) ? widthOverride : 750f, 36f), text, style);
		}

		private bool HostIsNearOtherPlayers(PlayerControllerB hostPlayer)
		{
			return (bool)hostPlayer.Call("NearOtherPlayers", hostPlayer, 17f);
		}
	}
}
namespace ControlCompany.Core.Input
{
	public static class InputKeys
	{
		public static KeyControl EXIT_KEY = Keyboard.current.escapeKey;

		public static KeyControl EXTENDED_MODE_KEY = Keyboard.current.digit0Key;

		public static KeyControl TOGGLE_UI_KEY = Keyboard.current.uKey;

		public static KeyControl CYCLE_KEY_LEFT = Keyboard.current.oKey;

		public static KeyControl CYCLE_KEY_RIGHT = Keyboard.current.pKey;

		public static KeyControl HOST_LISTEN_KEY = Keyboard.current.leftAltKey;

		public static KeyControl HOST_GHOST_MODE_KEY = Keyboard.current.f1Key;

		public static KeyControl HOST_GIVE_CREDITS_KEY = Keyboard.current.digit8Key;

		public static KeyControl HOST_TELEPORT_TO_ENTRANCE_KEY = Keyboard.current.digit9Key;

		public static KeyControl GHOST_SPAWN_ENEMY_1 = Keyboard.current.f1Key;

		public static KeyControl GHOST_SPAWN_ENEMY_2 = Keyboard.current.f2Key;

		public static KeyControl GHOST_SPAWN_ENEMY_3 = Keyboard.current.f3Key;

		public static KeyControl GHOST_SPAWN_ENEMY_4 = Keyboard.current.f4Key;

		public static KeyControl GHOST_SPAWN_ENEMY_5 = Keyboard.current.f5Key;

		public static KeyControl GHOST_SPAWN_ENEMY_6 = Keyboard.current.f6Key;

		public static KeyControl GHOST_SPAWN_ENEMY_7 = Keyboard.current.f7Key;

		public static KeyControl GHOST_SPAWN_ENEMY_8 = Keyboard.current.f8Key;

		public static KeyControl GHOST_SPAWN_ENEMY_9 = Keyboard.current.f9Key;

		public static KeyControl GHOST_SPAWN_ENEMY_10 = Keyboard.current.f10Key;

		public static KeyControl GHOST_SPAWN_ENEMY_11 = Keyboard.current.f11Key;

		public static KeyControl GHOST_SPAWN_ENEMY_12 = Keyboard.current.f12Key;

		public static List<KeyControl> GHOST_SPAWN_ENEMY_KEYS = new List<KeyControl>();

		public static KeyControl ENEMY_TOGGLE_AI_KEY = Keyboard.current.f1Key;

		public static ButtonControl ENEMY_PRIMARY_SKILL_BUTTON = Mouse.current.leftButton;

		public static ButtonControl ENEMY_SECONDARY_SKILL_BUTTON = Mouse.current.rightButton;

		public static KeyControl LOCK_ENEMY_ROTATION_KEY = Keyboard.current.rightAltKey;

		public static KeyControl ENEMY_TOGGLE_LIGHT_KEY = Keyboard.current.lKey;

		public static KeyControl CONTROLLER_USE_KEY = Keyboard.current.eKey;

		public static KeyControl CONTROLLER_JUMP_KEY = Keyboard.current.spaceKey;
	}
}
namespace ControlCompany.Core.Extentions
{
	public static class ExtensionMethods
	{
		public static T GetFieldValue<T>(this object obj, string name)
		{
			return (T)(obj.GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(obj));
		}

		public static void SetFieldValue<T>(this object obj, string method, T value)
		{
			obj.GetType().GetField(method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetField | BindingFlags.SetProperty)?.SetValue(obj, value);
		}

		public static object Call(this object o, string methodName, params object[] args)
		{
			MethodInfo method = o.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
			if (method != null)
			{
				return method.Invoke(o, args);
			}
			return null;
		}

		public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
		{
			if (dictionary.TryGetValue(key, out var value))
			{
				return value;
			}
			return defaultValue;
		}

		public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunksize)
		{
			while (source.Any())
			{
				yield return source.Take(chunksize);
				source = source.Skip(chunksize);
			}
		}

		public static IEnumerable<T> DedupeBy<T>(this IEnumerable<T> source, Func<T, string> dedupeFunc)
		{
			return from t in source
				group t by dedupeFunc(t) into t
				select t.First();
		}

		public static void LogLayer(this GameObject gameObject)
		{
			ControlCompanyPlugin.Instance.logger.LogMessage((object)$"Enemy layer ({LayerMask.LayerToName(gameObject.layer)}): {gameObject.layer}");
		}

		public static void LogGameObjectName(this GameObject gameObject)
		{
			ControlCompanyPlugin.Instance.logger.LogMessage((object)string.Format("GameObject name: {0}, parent: {1}", ((Object)gameObject).name, ((Object)(object)gameObject.transform.parent != (Object)null) ? ((Object)gameObject.transform.parent).name : "null"));
		}

		public static void LogAllComponents(this GameObject gameObject)
		{
			Component[] components = gameObject.GetComponents<Component>();
			foreach (Component val in components)
			{
				_ = $"GameObject ({((Object)gameObject).name}) component: {((Object)val).name}";
			}
		}

		public static void LogPosition(this GameObject gameObject)
		{
			//IL_001c: 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)
			ControlCompanyPlugin.Instance.logger.LogMessage((object)$"GameObject ({((Object)gameObject).name}) position: {gameObject.transform.position}, local position: {gameObject.transform.localPosition}");
		}

		public static string RemoveChar(this string input, char charToRemove)
		{
			int num = input.IndexOf(charToRemove);
			if (num < 0)
			{
				return input;
			}
			return input.Remove(num, 1).RemoveChar(charToRemove);
		}

		public static bool IsObjectWithinAngle(this Transform transform, Transform other, Vector3 direction, float angleBounds)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = other.position - transform.position;
			float num = Vector3.Angle(val, direction);
			return Mathf.Abs(num) <= angleBounds;
		}
	}
}
namespace ControlCompany.Core.Enemy
{
	internal class RadMechEnemyController : EnemyAIController
	{
		private RadMechAI radMechAI;

		private float originalRunSpeed = 0f;

		private float originalWalkSpeed = 0f;

		private float scanTargetRange = 200f;

		private float fireRate;

		private float shootTimer = 0f;

		private bool isFiring = false;

		private int visibleThreatsMask;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			radMechAI = (RadMechAI)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
			originalRunSpeed = base.RunSpeed;
			originalWalkSpeed = base.WalkSpeed;
			visibleThreatsMask = radMechAI.GetFieldValue<int>("visibleThreatsMask");
			fireRate = radMechAI.fireRate;
			AdjustAudio();
		}

		protected override void LateUpdate()
		{
			//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)
			if (!isInitialized)
			{
				return;
			}
			base.LateUpdate();
			if (isAIControlled || !hasControl)
			{
				return;
			}
			radMechAI.SetFieldValue("shootTimer", 0f);
			Vector3 val = MoveInput();
			if (((Vector3)(ref val)).sqrMagnitude <= 0.1f)
			{
				radMechAI.SetFieldValue("walkStepTimer", 0.1f);
				radMechAI.SetFieldValue("takingStep", value: false);
			}
			else
			{
				if (radMechAI.aimingGun)
				{
					radMechAI.SetAimingGun(false);
				}
				bool fieldValue = radMechAI.GetFieldValue<bool>("takingStep");
				float fieldValue2 = radMechAI.GetFieldValue<float>("walkStepTimer");
				radMechAI.SetFieldValue("walkStepTimer", Mathf.Min(fieldValue2, 0.7f));
				if (!fieldValue)
				{
					base.RunSpeed = 0f;
					base.WalkSpeed = 0f;
					if (IsSprinting())
					{
						radMechAI.SetFieldValue("walkStepTimer", Mathf.Min(fieldValue2, 0.2f));
					}
				}
				else
				{
					base.RunSpeed = originalRunSpeed;
					base.WalkSpeed = originalWalkSpeed;
				}
			}
			if (isFiring)
			{
				shootTimer += Time.deltaTime;
				if (!radMechAI.aimingGun)
				{
					radMechAI.SetAimingGun(true);
				}
				if (shootTimer >= fireRate)
				{
					shootTimer = 0f;
					radMechAI.StartShootGun();
				}
			}
		}

		protected override void UsePrimarySkillAction()
		{
			ScanAndSetTargetIfNotExists();
			if ((Object)(object)radMechAI.focusedThreatTransform != (Object)null)
			{
				((EnemyAI)radMechAI).SwitchToBehaviourState(1);
				isFiring = true;
			}
		}

		protected override void ReleasePrimarySkillAction()
		{
			isFiring = false;
			shootTimer = 0f;
			radMechAI.SetAimingGun(false);
			((EnemyAI)radMechAI).SwitchToBehaviourState(0);
		}

		protected override void UseSecondarySkillAction()
		{
		}

		protected override void ReleaseSecondarySkillAction()
		{
		}

		public override void DestroyAndCleanUp()
		{
			((MonoBehaviour)this).StartCoroutine(DelayedDestroyAndCleanUp());
		}

		private IEnumerator DelayedDestroyAndCleanUp()
		{
			EnableControl(enable: false);
			EnableCamera(enable: false);
			yield return (object)new WaitForSeconds(3f);
			base.DestroyAndCleanUp();
		}

		public override string GetPrimarySkillName()
		{
			return "Fire";
		}

		public override string GetSecondarySkillName()
		{
			return "";
		}

		private void AdjustAudio()
		{
			AudioSource creatureSFX = ((EnemyAI)radMechAI).creatureSFX;
			creatureSFX.volume *= 0.25f;
			AudioSource localLRADAudio = radMechAI.LocalLRADAudio;
			localLRADAudio.volume *= 0.25f;
			AudioSource localLRADAudio2 = radMechAI.LocalLRADAudio2;
			localLRADAudio2.volume *= 0.25f;
			AudioSource explosionAudio = radMechAI.explosionAudio;
			explosionAudio.volume *= 0.25f;
			AudioSource blowtorchAudio = radMechAI.blowtorchAudio;
			blowtorchAudio.volume *= 0.25f;
			AudioSource flyingDistantAudio = radMechAI.flyingDistantAudio;
			flyingDistantAudio.volume *= 0.25f;
			AudioSource spotlightOnAudio = radMechAI.spotlightOnAudio;
			spotlightOnAudio.volume *= 0.25f;
			AudioSource chargeForwardAudio = radMechAI.chargeForwardAudio;
			chargeForwardAudio.volume *= 0.25f;
			AudioSource engineSFX = radMechAI.engineSFX;
			engineSFX.volume *= 0.25f;
			AudioSource chargeForwardAudio2 = radMechAI.chargeForwardAudio;
			chargeForwardAudio2.volume *= 0.25f;
			AudioSource chargeForwardAudio3 = radMechAI.chargeForwardAudio;
			chargeForwardAudio3.volume *= 0.25f;
		}

		private void FireGun()
		{
		}

		private void ReloadGun()
		{
		}

		private void ScanAndSetTargetIfNotExists()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: 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_0165: 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_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_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)radMechAI.focusedThreatTransform != (Object)null)
			{
				return;
			}
			float num = float.MaxValue;
			Transform eye = ((EnemyAI)radMechAI).eye;
			IVisibleThreat val = null;
			Transform val2 = null;
			Collider[] array = Physics.OverlapSphere(eye.position + eye.forward * 58f + -eye.up * 10f, scanTargetRange, visibleThreatsMask, (QueryTriggerInteraction)2);
			Collider[] array2 = array;
			foreach (Collider val3 in array2)
			{
				if ((Object)(object)val3 == (Object)(object)radMechAI.ownCollider)
				{
					continue;
				}
				IVisibleThreat componentInChildren = ((Component)val3).GetComponentInChildren<IVisibleThreat>();
				if (componentInChildren != null && ((Component)this).transform.IsObjectWithinAngle(((Component)val3).transform, ((Component)this).transform.forward, 180f))
				{
					Vector3 val4 = ((Component)val3).transform.position - eye.position;
					float magnitude = ((Vector3)(ref val4)).magnitude;
					if (magnitude < num)
					{
						num = magnitude;
						val = componentInChildren;
						val2 = ((Component)val3).transform;
					}
				}
			}
			if (val != null)
			{
				float num2 = Vector3.Distance(eye.position, val2.position);
				radMechAI.SetTargetedThreat(val, val2.position + Vector3.up * 0.5f, num2);
				radMechAI.focusedThreatTransform = val.GetThreatTransform();
				NetworkObject component = ((Component)radMechAI.focusedThreatTransform).gameObject.GetComponent<NetworkObject>();
				((EnemyAI)radMechAI).SwitchToBehaviourStateOnLocalClient(1);
				radMechAI.SetTargetToThreatClientRpc(NetworkObjectReference.op_Implicit(component), radMechAI.targetedThreat.lastSeenPosition);
			}
			else
			{
				radMechAI.EnableSpotlight();
			}
		}
	}
	internal class SecretTestEnemyController : EnemyAIController
	{
		private TestEnemy testEnemy;

		public override void InitializeEnemyController(PlayerActions playerActions, GameObject enemyGameObject)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			testEnemy = (TestEnemy)GetEnemyAIFromEnemyGameObject(enemyGameObject);
			base.InitializeEnemyController(playerActions, enemyGameObject);
		}

		protected override void UseSecondarySkillAction()
		{
		}

		public override string GetSecondarySkillName()
		{
			return "";
		}
	}
	internal class ControllableEnemy
	{
		public GameObject EnemyPrefab { get; set; }

		public string EnemyName { get; set; }

		public bool OverrideEnemyPrefab { get; set; }

		public GameObject EnemyGameObject { get; set; }

		public bool OverrideEnemySpawnLocation { get; set; }

		public bool Allowlisted { get; set; }

		public Vector3 EnemySpawnLocationOverride { get; set; }

		public Func<GameObject, GameObject, EnemyController> CreateAndAttachEnemyControllerFunc { get; set; }

		public static ControllableEnemy FromSpawnableEnemy(SpawnableEnemyWithRarity spawnableEnemy)
		{
			GameObject enemyPrefab = spawnableEnemy.enemyType.enemyPrefab;
			EnemyAI componentInChildren = enemyPrefab.GetComponentInChildren<EnemyAI>();
			string enemyName = (((Object)(object)componentInChildren == (Object)null) ? spawnableEnemy.enemyType.enemyName : componentInChildren.GetEnemyName());
			return new ControllableEnemy
			{
				EnemyName = enemyName,
				EnemyPrefab = enemyPrefab,
				OverrideEnemyPrefab = false,
				OverrideEnemySpawnLocation = false,
				Allowlisted = componentInChildren.IsEnemyAllowlisted(),
				CreateAndAttachEnemyControllerFunc = delegate(GameObject enemyGameObject, GameObject enemyController)
				{
					EnemyAI compone

plugins/ControlCompany-ControlCompanyFilter/ControlCompanyFilter.dll

Decompiled 3 months ago
using System;
using System.Collections;
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.Logging;
using ControlCompanyFilter.Patches;
using HarmonyLib;
using Steamworks.Data;
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: AssemblyTitle("ControlCompanyFilter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ControlCompanyFilter")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("dfed064e-ab44-4aa7-b361-7a59370d39a8")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ControlCompanyFilter
{
	[BepInPlugin("ControlCompany.ControlCompanyFilter", "ControlCompanyFilter", "1.0.0")]
	public class ControlCompanyFilterPlugin : BaseUnityPlugin
	{
		private const string modGUID = "ControlCompany.ControlCompanyFilter";

		private const string modName = "ControlCompanyFilter";

		private const string modVersion = "1.0.0";

		private readonly Harmony harmony = new Harmony("ControlCompany.ControlCompanyFilter");

		public static ControlCompanyFilterPlugin Instance;

		internal ManualLogSource logger;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			logger = Logger.CreateLogSource("ControlCompany.ControlCompanyFilter");
			ApplyPatches();
		}

		private void ApplyPatches()
		{
			harmony.PatchAll(typeof(ControlCompanyFilterPlugin));
			harmony.PatchAll(typeof(LobbyListPatch));
		}
	}
}
namespace ControlCompanyFilter.Patches
{
	internal class LobbyListPatch
	{
		public const char SERVER_NAME_FILTER = '\u200b';

		[HarmonyPatch(typeof(LobbySlot), "Awake")]
		[HarmonyPostfix]
		private static void LobbySlotPostfix(LobbySlot __instance)
		{
			if ((Object)(object)__instance != (Object)null)
			{
				((MonoBehaviour)__instance).StartCoroutine(MarkLobbySlot(__instance));
			}
		}

		private static IEnumerator MarkLobbySlot(LobbySlot lobbySlot)
		{
			yield return (object)new WaitForEndOfFrame();
			string lobbyName = ((Lobby)(ref lobbySlot.thisLobby)).GetData("name");
			if (!string.IsNullOrEmpty(lobbyName) && Enumerable.Contains(lobbyName, '\u200b'))
			{
				Transform obj = ((Component)lobbySlot).transform.Find("Outline");
				Image outlineImage = ((obj != null) ? ((Component)obj).GetComponent<Image>() : null);
				Transform obj2 = ((Component)lobbySlot).transform.Find("JoinButton/SelectionHighlight");
				Image joinButtonSelectionHighlight = ((obj2 != null) ? ((Component)obj2).GetComponent<Image>() : null);
				if (Object.op_Implicit((Object)(object)outlineImage))
				{
					((Graphic)outlineImage).color = GetColorFromRGBA(202, 181, 0, 255);
				}
				if (Object.op_Implicit((Object)(object)joinButtonSelectionHighlight))
				{
					((Graphic)joinButtonSelectionHighlight).color = GetColorFromRGBA(255, 178, 0, 9);
				}
				TextMeshProUGUI serverNameText = lobbySlot.LobbyName;
				TextMeshProUGUI numPlayersText = lobbySlot.playerCount;
				Color textColor = (((Graphic)serverNameText).color = GetColorFromRGBA(219, 181, 0, 255));
				((Graphic)numPlayersText).color = textColor;
				Image lobbySlotImage = ((Component)lobbySlot).GetComponent<Image>();
				((Graphic)lobbySlotImage).color = GetColorFromRGBA(77, 67, 0, 255);
				if (!((Object)((Component)lobbySlot).transform).name.Contains("Challenge"))
				{
					GameObject rectTransformGO = new GameObject("cc", new Type[1] { typeof(RectTransform) });
					RectTransform rectTransform = rectTransformGO.GetComponent<RectTransform>();
					TextMeshProUGUI ccText = ((Component)rectTransform).gameObject.AddComponent<TextMeshProUGUI>();
					((TMP_Text)ccText).fontSize = 26f;
					((TMP_Text)ccText).text = "CONTROL COMPANY";
					((TMP_Text)ccText).alignment = (TextAlignmentOptions)4097;
					((TMP_Text)ccText).font = ((TMP_Text)numPlayersText).font;
					((Graphic)ccText).color = GetColorFromRGBA(89, 89, 0, 255);
					((Transform)rectTransform).SetParent(((Component)lobbySlot).transform);
					rectTransform.anchorMin = new Vector2(0f, 1f);
					rectTransform.anchorMax = new Vector2(0f, 1f);
					rectTransform.pivot = new Vector2(0f, 1f);
					((Transform)rectTransform).localScale = new Vector3(0.8497399f, 0.8497399f, 0.8497399f);
					((Transform)rectTransform).localPosition = new Vector3(130f, -10f, -7f);
					rectTransform.sizeDelta = new Vector2(269f, 24f);
				}
			}
		}

		private static Color GetColorFromRGBA(int r, int b, int g, int a)
		{
			//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_0029: Unknown result type (might be due to invalid IL or missing references)
			return new Color((float)r / 255f, (float)b / 255f, (float)g / 255f, (float)a / 255f);
		}
	}
}

plugins/FlipMods-ReservedFlashlightSlot/ReservedFlashlightSlot.dll

Decompiled 3 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.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using ReservedFlashlightSlot.Config;
using ReservedFlashlightSlot.Patches;
using ReservedItemSlotCore;
using ReservedItemSlotCore.Config;
using ReservedItemSlotCore.Data;
using ReservedItemSlotCore.Networking;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ReservedFlashlightSlot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReservedFlashlightSlot")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5b7d6563-4e51-4a69-bcf9-fa1dea6eff75")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ReservedFlashlightSlot
{
	[BepInPlugin("FlipMods.ReservedFlashlightSlot", "ReservedFlashlightSlot", "2.0.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		private static ManualLogSource logger;

		private Harmony _harmony;

		public static ReservedItemSlotData flashlightSlotData;

		public static ReservedItemData flashlightData;

		public static ReservedItemData proFlashlightData;

		public static ReservedItemData laserPointerData;

		public static List<ReservedItemData> additionalItemData = new List<ReservedItemData>();

		private void Awake()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			instance = this;
			CreateCustomLogger();
			ConfigSettings.BindConfigSettings();
			CreateReservedItemSlots();
			CreateAdditionalReservedItemSlots();
			_harmony = new Harmony("ReservedFlashlightSlot");
			PatchAll();
			Log("ReservedFlashlightSlot loaded");
		}

		private void CreateReservedItemSlots()
		{
			//IL_003e: 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_0061: Expected O, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			//IL_00c2: 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_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			flashlightSlotData = ReservedItemSlotData.CreateReservedItemSlotData("flashlight", ConfigSettings.overrideItemSlotPriority.Value, ConfigSettings.overridePurchasePrice.Value);
			flashlightData = flashlightSlotData.AddItemToReservedItemSlot(new ReservedItemData("Flashlight", (PlayerBone)4, new Vector3(0.2f, 0.25f, 0f), new Vector3(90f, 0f, 0f)));
			proFlashlightData = flashlightSlotData.AddItemToReservedItemSlot(new ReservedItemData("Pro-flashlight", (PlayerBone)4, new Vector3(0.2f, 0.25f, 0f), new Vector3(90f, 0f, 0f)));
			laserPointerData = flashlightSlotData.AddItemToReservedItemSlot(new ReservedItemData("Laser pointer", (PlayerBone)4, new Vector3(0.2f, 0.25f, 0f), new Vector3(90f, 0f, 0f)));
		}

		private void CreateAdditionalReservedItemSlots()
		{
			//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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			string[] array = ConfigSettings.ParseAdditionalItems();
			string[] array2 = array;
			foreach (string text in array2)
			{
				if (!flashlightSlotData.ContainsItem(text))
				{
					LogWarning("Adding additional item to reserved item slot. Item: " + text);
					ReservedItemData val = new ReservedItemData(text, (PlayerBone)0, default(Vector3), default(Vector3));
					additionalItemData.Add(val);
					flashlightSlotData.AddItemToReservedItemSlot(val);
				}
			}
		}

		private void PatchAll()
		{
			IEnumerable<Type> enumerable;
			try
			{
				enumerable = Assembly.GetExecutingAssembly().GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				enumerable = ex.Types.Where((Type t) => t != null);
			}
			foreach (Type item in enumerable)
			{
				_harmony.PatchAll(item);
			}
		}

		private void CreateCustomLogger()
		{
			try
			{
				logger = Logger.CreateLogSource($"{((BaseUnityPlugin)this).Info.Metadata.Name}-{((BaseUnityPlugin)this).Info.Metadata.Version}");
			}
			catch
			{
				logger = ((BaseUnityPlugin)this).Logger;
			}
		}

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

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

		public static void LogWarning(string message)
		{
			logger.LogWarning((object)message);
		}

		public static bool IsModLoaded(string guid)
		{
			return Chainloader.PluginInfos.ContainsKey(guid);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FlipMods.ReservedFlashlightSlot";

		public const string PLUGIN_NAME = "ReservedFlashlightSlot";

		public const string PLUGIN_VERSION = "2.0.3";
	}
}
namespace ReservedFlashlightSlot.Patches
{
	[HarmonyPatch]
	public static class FlashlightPatcher
	{
		public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController;

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

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

		public static FlashlightItem GetReservedFlashlight(PlayerControllerB playerController)
		{
			ReservedItemSlotData val = default(ReservedItemSlotData);
			ReservedPlayerData value;
			return (FlashlightItem)((SessionManager.TryGetUnlockedItemSlotData(Plugin.flashlightSlotData.slotName, ref val) && ReservedPlayerData.allPlayerData.TryGetValue(playerController, out value)) ? /*isinst with value type is only supported in some contexts*/: null);
		}

		public static FlashlightItem GetCurrentlySelectedFlashlight(PlayerControllerB playerController)
		{
			return (FlashlightItem)((playerController.currentItemSlot >= 0 && playerController.currentItemSlot < playerController.ItemSlots.Length) ? /*isinst with value type is only supported in some contexts*/: null);
		}

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

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

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

		[HarmonyPatch(typeof(FlashlightItem), "PocketFlashlightClientRpc")]
		[HarmonyPrefix]
		public static void OnPocketFlashlightClientRpc(bool stillUsingFlashlight, FlashlightItem __instance)
		{
			if (NetworkHelper.IsValidClientRpcExecStage((NetworkBehaviour)(object)__instance) && !((NetworkBehaviour)__instance).IsOwner && !((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null) && !((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController))
			{
				OnPocketFlashlight(__instance, stillUsingFlashlight);
			}
		}

		private static void OnPocketFlashlight(FlashlightItem flashlightItem, bool stillUsingFlashlight = false)
		{
			if (!((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)null))
			{
				FlashlightItem currentlySelectedFlashlight = GetCurrentlySelectedFlashlight(((GrabbableObject)flashlightItem).playerHeldBy);
				FlashlightItem reservedFlashlight = GetReservedFlashlight(((GrabbableObject)flashlightItem).playerHeldBy);
				bool flag = stillUsingFlashlight || ((Object)(object)currentlySelectedFlashlight != (Object)null && ((GrabbableObject)currentlySelectedFlashlight).isBeingUsed);
				if ((Object)(object)currentlySelectedFlashlight != (Object)null && ((GrabbableObject)currentlySelectedFlashlight).isBeingUsed)
				{
					((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = null;
				}
				else if (((GrabbableObject)flashlightItem).isBeingUsed)
				{
					((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)flashlightItem;
				}
				else if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight == (Object)null || !((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight.isBeingUsed))
				{
					((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight;
				}
			}
		}

		[HarmonyPatch(typeof(FlashlightItem), "EquipItem")]
		[HarmonyPostfix]
		public static void OnEquipFlashlight(FlashlightItem __instance)
		{
			if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null))
			{
				bool mainFlashlightActive = ((Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight != (Object)null && ((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight.isBeingUsed) || ((GrabbableObject)__instance).isBeingUsed;
				FlashlightItem reservedFlashlight = GetReservedFlashlight(((GrabbableObject)__instance).playerHeldBy);
				if (((GrabbableObject)__instance).isBeingUsed || (Object)(object)__instance == (Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight)
				{
					((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight = null;
				}
				else if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight == (Object)null || !((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight.isBeingUsed))
				{
					((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight;
				}
				UpdateAllFlashlightStates(((GrabbableObject)__instance).playerHeldBy, mainFlashlightActive);
			}
		}

		[HarmonyPatch(typeof(FlashlightItem), "DiscardItem")]
		[HarmonyPrefix]
		public static void ResetPocketedFlashlight(FlashlightItem __instance)
		{
			PlayerControllerB previousPlayerHeldBy = GetPreviousPlayerHeldBy(__instance);
			if (!((Object)(object)previousPlayerHeldBy == (Object)null))
			{
				FlashlightItem reservedFlashlight = GetReservedFlashlight(previousPlayerHeldBy);
				if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)__instance == (Object)(object)previousPlayerHeldBy.pocketedFlashlight || (Object)(object)previousPlayerHeldBy.pocketedFlashlight == (Object)null))
				{
					previousPlayerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight;
				}
			}
		}

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

		private static void UpdateFlashlightState(FlashlightItem flashlightItem, bool active)
		{
			if (!((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)null))
			{
				PlayerControllerB playerHeldBy = ((GrabbableObject)flashlightItem).playerHeldBy;
				((GrabbableObject)flashlightItem).isBeingUsed = active;
				bool flag = (Object)(object)playerHeldBy != (Object)(object)localPlayerController || (Object)(object)playerHeldBy.ItemSlots[playerHeldBy.currentItemSlot] == (Object)(object)flashlightItem;
				((Behaviour)flashlightItem.flashlightBulb).enabled = active && flag;
				((Behaviour)flashlightItem.flashlightBulbGlow).enabled = active && flag;
				flashlightItem.usingPlayerHelmetLight = active && !flag;
			}
		}
	}
}
namespace ReservedFlashlightSlot.Input
{
	internal class IngameKeybinds : LcInputActions
	{
		internal static IngameKeybinds Instance = new IngameKeybinds();

		[InputAction("<Keyboard>/f", Name = "[ReservedItemSlots]\nToggle flashlight")]
		public InputAction ToggleFlashlightHotkey { get; set; }

		internal static InputActionAsset GetAsset()
		{
			return ((LcInputActions)Instance).Asset;
		}
	}
	internal class InputUtilsCompat
	{
		internal static InputActionAsset Asset => IngameKeybinds.GetAsset();

		internal static bool Enabled => Plugin.IsModLoaded("com.rune580.LethalCompanyInputUtils");

		public static InputAction ToggleFlashlightHotkey => IngameKeybinds.Instance.ToggleFlashlightHotkey;
	}
	[HarmonyPatch]
	public static class KeybindDisplayNames
	{
		public static bool usingControllerPrevious = false;

		public static string[] keyboardKeywords = new string[2] { "keyboard", "mouse" };

		public static string[] controllerKeywords = new string[2] { "gamepad", "controller" };

		public static bool usingController => StartOfRound.Instance.localPlayerUsingController;

		public static string GetKeybindDisplayName(InputAction inputAction)
		{
			//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_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			if (inputAction == null || !inputAction.enabled)
			{
				return "";
			}
			int num = (usingController ? 1 : 0);
			InputBinding val = inputAction.bindings[num];
			string effectivePath = ((InputBinding)(ref val)).effectivePath;
			return GetKeybindDisplayName(effectivePath);
		}

		public static string GetKeybindDisplayName(string controlPath)
		{
			if (controlPath.Length <= 1)
			{
				return "";
			}
			string text = controlPath.ToLower();
			int num = text.IndexOf(">/");
			text = ((num >= 0) ? text.Substring(num + 2) : text);
			if (text.Contains("not-bound"))
			{
				return "";
			}
			text = text.Replace("leftalt", "Alt");
			text = text.Replace("rightalt", "Alt");
			text = text.Replace("leftctrl", "Ctrl");
			text = text.Replace("rightctrl", "Ctrl");
			text = text.Replace("leftshift", "Shift");
			text = text.Replace("rightshift", "Shift");
			text = text.Replace("leftbutton", "LMB");
			text = text.Replace("rightbutton", "RMB");
			text = text.Replace("middlebutton", "MMB");
			text = text.Replace("lefttrigger", "LT");
			text = text.Replace("righttrigger", "RT");
			text = text.Replace("leftshoulder", "LB");
			text = text.Replace("rightshoulder", "RB");
			text = text.Replace("leftstickpress", "LS");
			text = text.Replace("rightstickpress", "RS");
			text = text.Replace("dpad/", "DPad-");
			text = text.Replace("backquote", "`");
			try
			{
				text = char.ToUpper(text[0]) + text.Substring(1);
			}
			catch
			{
			}
			return text;
		}
	}
	[HarmonyPatch]
	internal static class Keybinds
	{
		public static InputActionAsset Asset;

		public static InputActionMap ActionMap;

		private static InputAction ActivateFlashlightAction;

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

		[HarmonyPatch(typeof(PreInitSceneScript), "Awake")]
		[HarmonyPrefix]
		public static void AddToKeybindMenu()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			Plugin.Log("Initializing hotkeys.");
			if (InputUtilsCompat.Enabled)
			{
				Asset = InputUtilsCompat.Asset;
				ActionMap = Asset.actionMaps[0];
				ActivateFlashlightAction = InputUtilsCompat.ToggleFlashlightHotkey;
			}
			else
			{
				Asset = ScriptableObject.CreateInstance<InputActionAsset>();
				ActionMap = new InputActionMap("ReservedItemSlots");
				InputActionSetupExtensions.AddActionMap(Asset, ActionMap);
				ActivateFlashlightAction = InputActionSetupExtensions.AddAction(ActionMap, "ReservedItemSlots.ToggleFlashlight", (InputActionType)0, "<keyboard>/f", (string)null, (string)null, (string)null, (string)null);
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "OnEnable")]
		[HarmonyPostfix]
		public static void OnEnable()
		{
			Asset.Enable();
			ActivateFlashlightAction.performed += OnActivateFlashlightPerformed;
		}

		[HarmonyPatch(typeof(StartOfRound), "OnDisable")]
		[HarmonyPostfix]
		public static void OnDisable()
		{
			Asset.Disable();
			ActivateFlashlightAction.performed -= OnActivateFlashlightPerformed;
		}

		private static void OnActivateFlashlightPerformed(CallbackContext context)
		{
			if (!((Object)(object)localPlayerController == (Object)null) && localPlayerController.isPlayerControlled && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject))
			{
				FlashlightItem mainFlashlight = FlashlightPatcher.GetMainFlashlight(localPlayerController);
				if (((CallbackContext)(ref context)).performed && !((Object)(object)mainFlashlight == (Object)null) && !ShipBuildModeManager.Instance.InBuildMode && !localPlayerController.inTerminalMenu && !(ReservedPlayerData.localPlayerData.timeSinceSwitchingSlots < 0.075f) && !localPlayerController.isTypingChat && !localPlayerController.inTerminalMenu && !localPlayerController.quickMenuManager.isMenuOpen && !localPlayerController.isPlayerDead && !localPlayerController.isGrabbingObjectAnimation && !ReservedPlayerData.localPlayerData.isGrabbingReservedItem)
				{
					((GrabbableObject)mainFlashlight).UseItemOnClient(!((GrabbableObject)mainFlashlight).isBeingUsed);
					Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0);
				}
			}
		}
	}
}
namespace ReservedFlashlightSlot.Config
{
	public static class ConfigSettings
	{
		public static ConfigEntry<int> overrideItemSlotPriority;

		public static ConfigEntry<int> overridePurchasePrice;

		public static ConfigEntry<string> additionalItemsInSlot;

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

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			overrideItemSlotPriority = AddConfigEntry<int>(((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server-side", "FlashlightSlotPriorityOverride", 200, "[Host only] Manually set the priority for this item slot. Higher priority slots will come first in the reserved item slots, which will appear below the other slots. Negative priority items will appear on the left side of the screen, this is disabled in the core mod's config."));
			overridePurchasePrice = AddConfigEntry<int>(((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server-side", "FlashlightSlotPriceOverride", 200, "[Host only] Manually set the price for this item in the store. Setting 0 will force this item to be unlocked immediately after the game starts."));
			additionalItemsInSlot = AddConfigEntry<string>(((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Server-side", "AdditionalItemsInSlot", "", "[Host only] Syntax: \"Item1,Item name2\" (without quotes). When adding items, use the item's name as it appears in game. Include spaces if there are spaces in the item name. Adding items that do not exist, or that are from a mod which is not enabled will not cause any problems.\nNOTE: IF YOU ARE USING A TRANSLATION MOD, YOU MAY NEED TO ADD THE TRANSLATED NAME OF ANY ITEM YOU WANT IN THIS SLOT."));
			additionalItemsInSlot.Value = additionalItemsInSlot.Value.Replace(", ", ",");
			TryRemoveOldConfigSettings();
		}

		public static ConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			currentConfigEntries.Add(((ConfigEntryBase)configEntry).Definition.Key, (ConfigEntryBase)(object)configEntry);
			return configEntry;
		}

		public static string[] ParseAdditionalItems()
		{
			return ConfigSettings.ParseItemNames(additionalItemsInSlot.Value);
		}

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

plugins/FlipMods-ReservedItemSlotCore/ReservedItemSlotCore.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using ReservedItemSlotCore.Compatibility;
using ReservedItemSlotCore.Config;
using ReservedItemSlotCore.Data;
using ReservedItemSlotCore.Input;
using ReservedItemSlotCore.Networking;
using ReservedItemSlotCore.Patches;
using TMPro;
using TooManyEmotes;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ReservedItemSlotCore")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReservedItemSlotCore")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("238ce080-e339-46b6-9b08-992a950453a1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("ReservedFlashlightSlot")]
[assembly: InternalsVisibleTo("ReservedWalkieSlot")]
[assembly: InternalsVisibleTo("ReservedWeaponSlot")]
[assembly: InternalsVisibleTo("ReservedSprayPaintSlot")]
[assembly: InternalsVisibleTo("ReservedUtilitySlot")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ReservedItemSlotCore
{
	[HarmonyPatch]
	internal static class ItemNameMap
	{
		private static Dictionary<string, Item> originalNameToItemMap = new Dictionary<string, Item>();

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

		[HarmonyPatch(typeof(StartOfRound), "Start")]
		[HarmonyPostfix]
		private static void RecordOriginalItemNames(StartOfRound __instance)
		{
			foreach (Item items in __instance.allItemsList.itemsList)
			{
				string itemName = items.itemName;
				if ((Object)(object)items != (Object)null && itemName.Length > 0)
				{
					if (!itemToNameMap.ContainsKey(items))
					{
						itemToNameMap.Add(items, itemName);
					}
					if (!originalNameToItemMap.ContainsKey(itemName))
					{
						originalNameToItemMap.Add(itemName, items);
					}
				}
			}
		}

		internal static string GetItemName(GrabbableObject grabbableObject)
		{
			if ((Object)(object)grabbableObject?.itemProperties == (Object)null)
			{
				return "";
			}
			return GetItemName(grabbableObject.itemProperties);
		}

		internal static string GetItemName(Item item)
		{
			if ((Object)(object)item == (Object)null)
			{
				return "";
			}
			if (itemToNameMap.TryGetValue(item, out var value))
			{
				return value;
			}
			return "";
		}
	}
	[BepInPlugin("FlipMods.ReservedItemSlotCore", "ReservedItemSlotCore", "2.0.22")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		public static Plugin instance;

		private static ManualLogSource logger;

		public static List<ReservedItemSlotData> customItemSlots = new List<ReservedItemSlotData>();

		private void Awake()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			instance = this;
			CreateCustomLogger();
			ConfigSettings.BindConfigSettings();
			AddCustomItemSlots();
			if (InputUtilsCompat.Enabled)
			{
				InputUtilsCompat.Init();
			}
			_harmony = new Harmony("ReservedItemSlotCore");
			PatchAll();
			Log("ReservedItemSlotCore loaded");
		}

		private void AddCustomItemSlots()
		{
			//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)
			//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)
			foreach (CustomItemSlotConfigEntry customItemSlotConfig in ConfigSettings.customItemSlotConfigs)
			{
				if (!(customItemSlotConfig.customItemSlotName == "") && customItemSlotConfig.customItemSlotItems.Length != 0)
				{
					ReservedItemSlotData reservedItemSlotData = ReservedItemSlotData.CreateReservedItemSlotData(customItemSlotConfig.customItemSlotName, customItemSlotConfig.customItemSlotPriority, customItemSlotConfig.customItemSlotPrice);
					string[] customItemSlotItems = customItemSlotConfig.customItemSlotItems;
					foreach (string itemName in customItemSlotItems)
					{
						ReservedItemData itemData = new ReservedItemData(itemName);
						reservedItemSlotData.AddItemToReservedItemSlot(itemData);
						customItemSlots.Add(reservedItemSlotData);
					}
				}
			}
		}

		private void PatchAll()
		{
			IEnumerable<Type> enumerable;
			try
			{
				enumerable = Assembly.GetExecutingAssembly().GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				enumerable = ex.Types.Where((Type t) => t != null);
			}
			foreach (Type item in enumerable)
			{
				_harmony.PatchAll(item);
			}
		}

		private void CreateCustomLogger()
		{
			try
			{
				logger = Logger.CreateLogSource($"{((BaseUnityPlugin)this).Info.Metadata.Name}-{((BaseUnityPlugin)this).Info.Metadata.Version}");
			}
			catch
			{
				logger = ((BaseUnityPlugin)this).Logger;
			}
		}

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

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

		public static void LogWarning(string message)
		{
			logger.LogWarning((object)message);
		}

		public static bool IsModLoaded(string guid)
		{
			return Chainloader.PluginInfos.ContainsKey(guid);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FlipMods.ReservedItemSlotCore";

		public const string PLUGIN_NAME = "ReservedItemSlotCore";

		public const string PLUGIN_VERSION = "2.0.22";
	}
	[HarmonyPatch]
	public static class ReservedHotbarManager
	{
		public static int indexInHotbar = 0;

		public static int indexInReservedHotbar = 0;

		internal static List<ReservedItemSlotData> currentlyToggledItemSlots = new List<ReservedItemSlotData>();

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

		public static ReservedPlayerData localPlayerData => ReservedPlayerData.localPlayerData;

		public static int reservedHotbarSize => SessionManager.numReservedItemSlotsUnlocked;

		public static bool isToggledInReservedSlots
		{
			get
			{
				ReservedItemSlotData currentlySelectedReservedItemSlot = localPlayerData.GetCurrentlySelectedReservedItemSlot();
				return ConfigSettings.toggleFocusReservedHotbar.Value || (currentlyToggledItemSlots != null && currentlySelectedReservedItemSlot != null && currentlyToggledItemSlots.Contains(currentlySelectedReservedItemSlot));
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		public static void InitSession(StartOfRound __instance)
		{
			currentlyToggledItemSlots = new List<ReservedItemSlotData>();
			ReservedPlayerData.allPlayerData.Clear();
			indexInHotbar = 0;
			indexInReservedHotbar = -1;
		}

		public static void ForceToggleReservedHotbar(params ReservedItemSlotData[] reservedItemSlots)
		{
			if (((NetworkBehaviour)localPlayerController).IsOwner && localPlayerController.isPlayerControlled && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject) && HUDPatcher.hasReservedItemSlotsAndEnabled && reservedHotbarSize > 0 && CanSwapHotbars() && reservedItemSlots != null && reservedItemSlots.Length != 0 && !((Object)(object)localPlayerController == (Object)null))
			{
				currentlyToggledItemSlots = new List<ReservedItemSlotData>(reservedItemSlots);
				int num = currentlyToggledItemSlots.First().GetReservedItemSlotIndex() + localPlayerData.reservedHotbarStartIndex;
				bool active = ReservedPlayerData.localPlayerData.IsReservedItemSlot(num);
				if (currentlyToggledItemSlots.Contains(localPlayerData.GetCurrentlySelectedReservedItemSlot()))
				{
					FocusReservedHotbarSlots(active: false);
					return;
				}
				HUDPatcher.UpdateToggledReservedItemSlotsUI();
				FocusReservedHotbarSlots(active, num);
			}
		}

		public static void FocusReservedHotbarSlots(bool active, int forceSlot = -1)
		{
			if (!HUDPatcher.hasReservedItemSlotsAndEnabled || (reservedHotbarSize <= 0 && active) || (ReservedPlayerData.localPlayerData.currentItemSlotIsReserved == active && (forceSlot == -1 || localPlayerData.currentItemSlot == forceSlot)))
			{
				return;
			}
			if (forceSlot != -1)
			{
				active = localPlayerData.IsReservedItemSlot(forceSlot);
			}
			ReservedPlayerData reservedPlayerData = ReservedPlayerData.localPlayerData;
			indexInHotbar = Mathf.Clamp(indexInHotbar, 0, localPlayerController.ItemSlots.Length - 1);
			indexInHotbar = ((!reservedPlayerData.IsReservedItemSlot(indexInHotbar)) ? indexInHotbar : 0);
			indexInReservedHotbar = Mathf.Clamp(indexInReservedHotbar, reservedPlayerData.reservedHotbarStartIndex, reservedPlayerData.reservedHotbarEndIndexExcluded - 1);
			int num = Mathf.Clamp(localPlayerController.currentItemSlot, 0, localPlayerController.ItemSlots.Length);
			int i = num;
			bool flag = active;
			if (flag && (!reservedPlayerData.IsReservedItemSlot(num) || forceSlot != -1))
			{
				indexInHotbar = num;
				indexInHotbar = ((!reservedPlayerData.IsReservedItemSlot(indexInHotbar)) ? indexInHotbar : 0);
				if (forceSlot != -1 && reservedPlayerData.IsReservedItemSlot(forceSlot))
				{
					indexInReservedHotbar = forceSlot;
				}
				i = indexInReservedHotbar;
				if ((Object)(object)localPlayerController.ItemSlots[i] == (Object)null && reservedPlayerData.GetNumHeldReservedItems() > 0)
				{
					for (i = reservedPlayerData.reservedHotbarStartIndex; i < reservedPlayerData.reservedHotbarEndIndexExcluded && !((Object)(object)localPlayerController.ItemSlots[i] != (Object)null); i++)
					{
					}
				}
				Plugin.Log("Focusing reserved hotbar slots. NewIndex: " + i + " OldIndex: " + num + " ReservedStartIndex: " + ReservedPlayerData.localPlayerData.reservedHotbarStartIndex);
			}
			else if (!flag && (ReservedPlayerData.localPlayerData.IsReservedItemSlot(num) || forceSlot != -1))
			{
				indexInReservedHotbar = Mathf.Clamp(num, reservedPlayerData.reservedHotbarStartIndex, reservedPlayerData.reservedHotbarEndIndexExcluded - 1);
				if (forceSlot != -1 && !reservedPlayerData.IsReservedItemSlot(forceSlot))
				{
					indexInHotbar = forceSlot;
				}
				i = indexInHotbar;
				Plugin.Log("Unfocusing reserved hotbar slots. NewIndex: " + i + " OldIndex: " + num + " ReservedStartIndex: " + ReservedPlayerData.localPlayerData.reservedHotbarStartIndex);
			}
			if (i < 0)
			{
				Plugin.LogError("Swapping to hotbar slot: " + i + ". Maybe send these logs to Flip? :)");
			}
			else if (i >= localPlayerController.ItemSlots.Length)
			{
				Plugin.LogError("Swapping to hotbar slot: " + i + " InventorySize: " + localPlayerController.ItemSlots.Length + ". Maybe send these logs to Flip? :)");
			}
			SyncManager.SwapHotbarSlot(i);
			if (localPlayerController.currentItemSlot != i)
			{
				Plugin.LogWarning("OnFocusReservedHotbarSlots - New hotbar index does not match target hotbar index. Tried to swap to index: " + i + " Current index: " + localPlayerController.currentItemSlot + " Tried swapping to reserved hotbar: " + active);
			}
		}

		public static bool CanSwapHotbars()
		{
			if (!HUDPatcher.hasReservedItemSlotsAndEnabled)
			{
				return false;
			}
			if (TooManyEmotes_Compat.Enabled && TooManyEmotes_Compat.IsLocalPlayerPerformingCustomEmote() && !TooManyEmotes_Compat.CanMoveWhileEmoting())
			{
				return false;
			}
			return ReservedPlayerData.localPlayerData.grabbingReservedItemData == null && !localPlayerController.isGrabbingObjectAnimation && !localPlayerController.quickMenuManager.isMenuOpen && !localPlayerController.inSpecialInteractAnimation && !localPlayerData.throwingObject && !localPlayerController.isTypingChat && !localPlayerController.twoHanded && !localPlayerController.activatingItem && !localPlayerController.jetpackControls && !localPlayerController.disablingJetpackControls && !localPlayerController.inTerminalMenu && !localPlayerController.isPlayerDead && !(localPlayerData.timeSinceSwitchingSlots < 0.3f);
		}

		internal static void OnSwapToReservedHotbar()
		{
			if (!localPlayerData.currentItemSlotIsReserved)
			{
				return;
			}
			if (localPlayerData.currentItemSlotIsReserved)
			{
				indexInReservedHotbar = localPlayerController.currentItemSlot;
			}
			ReservedItemSlotData currentlySelectedReservedItemSlot = localPlayerData.GetCurrentlySelectedReservedItemSlot();
			if (isToggledInReservedSlots && currentlyToggledItemSlots != null && !currentlyToggledItemSlots.Contains(currentlySelectedReservedItemSlot))
			{
				currentlyToggledItemSlots = null;
			}
			if (HUDPatcher.reservedItemSlots == null)
			{
				return;
			}
			foreach (Image reservedItemSlot in HUDPatcher.reservedItemSlots)
			{
				CanvasGroup component = ((Component)reservedItemSlot).GetComponent<CanvasGroup>();
				if ((Object)(object)component != (Object)null)
				{
					component.ignoreParentGroups = true;
				}
			}
		}

		internal static void OnSwapToVanillaHotbar()
		{
			if (localPlayerData.currentItemSlotIsReserved)
			{
				return;
			}
			if (!localPlayerData.currentItemSlotIsReserved)
			{
				indexInHotbar = localPlayerController.currentItemSlot;
			}
			currentlyToggledItemSlots = null;
			if (HUDPatcher.reservedItemSlots == null)
			{
				return;
			}
			foreach (Image reservedItemSlot in HUDPatcher.reservedItemSlots)
			{
				CanvasGroup component = ((Component)reservedItemSlot).GetComponent<CanvasGroup>();
				if ((Object)(object)component != (Object)null)
				{
					component.ignoreParentGroups = ConfigSettings.preventReservedItemSlotFade.Value;
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")]
		[HarmonyPrefix]
		private static void RefocusReservedHotbarAfterAnimation(PlayerControllerB __instance)
		{
			if (HUDPatcher.hasReservedItemSlotsAndEnabled && !((Object)(object)__instance != (Object)(object)localPlayerController) && !ConfigSettings.toggleFocusReservedHotbar.Value && Keybinds.holdingModifierKey != ReservedPlayerData.localPlayerData.currentItemSlotIsReserved && !isToggledInReservedSlots && CanSwapHotbars())
			{
				FocusReservedHotbarSlots(Keybinds.holdingModifierKey);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "UpdateSpecialAnimationValue")]
		[HarmonyPostfix]
		private static void UpdateReservedHotbarAfterAnimation(bool specialAnimation, PlayerControllerB __instance)
		{
			if (HUDPatcher.hasReservedItemSlotsAndEnabled && !((Object)(object)__instance != (Object)(object)localPlayerController) && !specialAnimation && !ConfigSettings.toggleFocusReservedHotbar.Value && ReservedPlayerData.localPlayerData.currentItemSlotIsReserved != Keybinds.holdingModifierKey)
			{
				FocusReservedHotbarSlots(Keybinds.holdingModifierKey);
			}
		}
	}
	[HarmonyPatch]
	public static class SessionManager
	{
		internal static List<ReservedItemSlotData> unlockedReservedItemSlots = new List<ReservedItemSlotData>();

		internal static Dictionary<string, ReservedItemSlotData> unlockedReservedItemSlotsDict = new Dictionary<string, ReservedItemSlotData>();

		internal static List<ReservedItemSlotData> pendingUnlockedReservedItemSlots = new List<ReservedItemSlotData>();

		internal static Dictionary<string, ReservedItemSlotData> pendingUnlockedReservedItemSlotsDict = new Dictionary<string, ReservedItemSlotData>();

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

		internal static bool gameStarted = false;

		internal static List<ReservedItemSlotData> allUnlockableReservedItemSlots => SyncManager.unlockableReservedItemSlots;

		internal static Dictionary<string, ReservedItemSlotData> allUnlockableReservedItemSlotsDict => SyncManager.unlockableReservedItemSlotsDict;

		public static int numReservedItemSlotsUnlocked => (unlockedReservedItemSlots != null) ? unlockedReservedItemSlots.Count : 0;

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		private static void InitSession()
		{
			unlockedReservedItemSlots.Clear();
			unlockedReservedItemSlotsDict.Clear();
			pendingUnlockedReservedItemSlots.Clear();
			pendingUnlockedReservedItemSlotsDict.Clear();
			allReservedItemData.Clear();
		}

		public static void UnlockReservedItemSlot(ReservedItemSlotData itemSlotData)
		{
			Plugin.Log("Unlocking reserved item slot: " + itemSlotData.slotName);
			if (!SyncManager.isSynced)
			{
				if (!pendingUnlockedReservedItemSlotsDict.ContainsKey(itemSlotData.slotName))
				{
					pendingUnlockedReservedItemSlotsDict.Add(itemSlotData.slotName, itemSlotData);
					pendingUnlockedReservedItemSlots.Add(itemSlotData);
				}
				return;
			}
			if (!unlockedReservedItemSlotsDict.ContainsKey(itemSlotData.slotName))
			{
				unlockedReservedItemSlotsDict.Add(itemSlotData.slotName, itemSlotData);
				if (!unlockedReservedItemSlots.Contains(itemSlotData))
				{
					int num = -1;
					for (int i = 0; i < unlockedReservedItemSlots.Count; i++)
					{
						if (itemSlotData.slotPriority > unlockedReservedItemSlots[i].slotPriority)
						{
							num = i;
							break;
						}
					}
					if (num == -1)
					{
						num = unlockedReservedItemSlots.Count;
					}
					unlockedReservedItemSlots.Insert(num, itemSlotData);
					foreach (ReservedPlayerData value in ReservedPlayerData.allPlayerData.Values)
					{
						if (unlockedReservedItemSlots.Count == 1)
						{
							value.reservedHotbarStartIndex = value.itemSlots.Length;
						}
						int index = value.reservedHotbarStartIndex + num;
						List<GrabbableObject> list = new List<GrabbableObject>(value.itemSlots);
						list.Insert(index, null);
						value.playerController.ItemSlots = list.ToArray();
						value.hotbarSize = list.Count;
					}
				}
			}
			if (ReservedHotbarManager.indexInReservedHotbar < ReservedPlayerData.localPlayerData.reservedHotbarStartIndex || ReservedHotbarManager.indexInReservedHotbar >= ReservedPlayerData.localPlayerData.reservedHotbarEndIndexExcluded)
			{
				ReservedHotbarManager.indexInReservedHotbar = ReservedPlayerData.localPlayerData.reservedHotbarStartIndex;
			}
			UpdateReservedItemsList();
			HUDPatcher.OnUpdateReservedItemSlots();
		}

		internal static void UnlockAllPendingItemSlots()
		{
			foreach (ReservedItemSlotData pendingUnlockedReservedItemSlot in pendingUnlockedReservedItemSlots)
			{
				UnlockReservedItemSlot(pendingUnlockedReservedItemSlot);
			}
			pendingUnlockedReservedItemSlots.Clear();
			pendingUnlockedReservedItemSlotsDict.Clear();
		}

		public static ReservedItemSlotData GetUnlockedReservedItemSlot(int indexInUnlockedItemSlots)
		{
			return (unlockedReservedItemSlots != null && indexInUnlockedItemSlots >= 0 && indexInUnlockedItemSlots < unlockedReservedItemSlots.Count) ? unlockedReservedItemSlots[indexInUnlockedItemSlots] : null;
		}

		public static ReservedItemSlotData GetUnlockedReservedItemSlot(string itemSlotName)
		{
			if (TryGetUnlockedItemSlotData(itemSlotName, out var itemSlotData))
			{
				return itemSlotData;
			}
			return null;
		}

		public static bool IsItemSlotUnlocked(ReservedItemSlotData itemSlotData)
		{
			return itemSlotData != null && IsItemSlotUnlocked(itemSlotData.slotName);
		}

		public static bool IsItemSlotUnlocked(string itemSlotName)
		{
			return unlockedReservedItemSlotsDict.ContainsKey(itemSlotName);
		}

		internal static void UpdateReservedItemsList()
		{
			if (unlockedReservedItemSlots == null)
			{
				return;
			}
			allReservedItemData.Clear();
			foreach (ReservedItemSlotData unlockedReservedItemSlot in unlockedReservedItemSlots)
			{
				if (unlockedReservedItemSlot.reservedItemData == null)
				{
					continue;
				}
				foreach (ReservedItemData value in unlockedReservedItemSlot.reservedItemData.Values)
				{
					if (!allReservedItemData.ContainsKey(value.itemName))
					{
						allReservedItemData.Add(value.itemName, value);
					}
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "ResetShip")]
		[HarmonyPostfix]
		private static void OnResetShip()
		{
			if (SyncManager.enablePurchasingItemSlots)
			{
				ResetProgress();
			}
		}

		[HarmonyPatch(typeof(GameNetworkManager), "SaveGameValues")]
		[HarmonyPostfix]
		private static void OnSaveGameValues()
		{
			if (NetworkManager.Singleton.IsHost && StartOfRound.Instance.inShipPhase && SyncManager.enablePurchasingItemSlots)
			{
				SaveGameValues();
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "LoadUnlockables")]
		[HarmonyPostfix]
		private static void OnLoadGameValues()
		{
			if (NetworkManager.Singleton.IsServer && SyncManager.isSynced && SyncManager.enablePurchasingItemSlots)
			{
				LoadGameValues();
			}
		}

		internal static void ResetProgress(bool force = false)
		{
			if (!SyncManager.enablePurchasingItemSlots && !force)
			{
				return;
			}
			foreach (ReservedPlayerData value in ReservedPlayerData.allPlayerData.Values)
			{
				GrabbableObject[] itemSlots = value.playerController.ItemSlots;
				List<GrabbableObject> list = new List<GrabbableObject>();
				for (int i = 0; i < itemSlots.Length; i++)
				{
					if (i < value.reservedHotbarStartIndex || i >= value.reservedHotbarEndIndexExcluded)
					{
						list.Add(itemSlots[i]);
					}
				}
				value.playerController.ItemSlots = list.ToArray();
			}
			unlockedReservedItemSlots?.Clear();
			unlockedReservedItemSlotsDict?.Clear();
			pendingUnlockedReservedItemSlots?.Clear();
			pendingUnlockedReservedItemSlotsDict?.Clear();
			List<Image> list2 = new List<Image>();
			List<Image> list3 = new List<Image>();
			for (int j = 0; j < HUDManager.Instance.itemSlotIconFrames.Length; j++)
			{
				Image val = HUDManager.Instance.itemSlotIconFrames[j];
				Image item = HUDManager.Instance.itemSlotIcons[j];
				if (!HUDPatcher.reservedItemSlots.Contains(val))
				{
					list2.Add(val);
					list3.Add(item);
				}
				else
				{
					Object.Destroy((Object)(object)((Component)val).gameObject);
				}
			}
			HUDPatcher.reservedItemSlots.Clear();
			HUDManager.Instance.itemSlotIconFrames = list2.ToArray();
			HUDManager.Instance.itemSlotIcons = list3.ToArray();
			foreach (ReservedPlayerData value2 in ReservedPlayerData.allPlayerData.Values)
			{
				if (value2.playerController.currentItemSlot < 0 || value2.playerController.currentItemSlot >= value2.playerController.ItemSlots.Length)
				{
					PlayerPatcher.SwitchToItemSlot(value2.playerController, 0);
				}
				value2.reservedHotbarStartIndex = value2.itemSlots.Length;
			}
			foreach (ReservedItemSlotData allUnlockableReservedItemSlot in allUnlockableReservedItemSlots)
			{
				if (allUnlockableReservedItemSlot.purchasePrice <= 0)
				{
					UnlockReservedItemSlot(allUnlockableReservedItemSlot);
				}
			}
			HUDPatcher.OnUpdateReservedItemSlots();
			if (NetworkManager.Singleton.IsServer)
			{
				ES3.DeleteKey("ReservedItemSlots.UnlockedItemSlots", GameNetworkManager.Instance.currentSaveFileName);
			}
		}

		internal static void SaveGameValues()
		{
			if (!NetworkManager.Singleton.IsServer || unlockedReservedItemSlots == null)
			{
				return;
			}
			List<string> list = new List<string>();
			foreach (ReservedItemSlotData unlockedReservedItemSlot in unlockedReservedItemSlots)
			{
				if (!list.Contains(unlockedReservedItemSlot.slotName))
				{
					list.Add(unlockedReservedItemSlot.slotName);
				}
			}
			Plugin.LogWarning("Saving " + list.Count + " unlocked reserved item slots.");
			string[] array = list.ToArray();
			ES3.Save<string[]>("ReservedItemSlots.UnlockedItemSlots", array, GameNetworkManager.Instance.currentSaveFileName);
		}

		internal static void LoadGameValues()
		{
			if (!NetworkManager.Singleton.IsServer || SyncManager.unlockableReservedItemSlotsDict == null)
			{
				return;
			}
			string[] array = ES3.Load<string[]>("ReservedItemSlots.UnlockedItemSlots", GameNetworkManager.Instance.currentSaveFileName, new string[0]);
			Plugin.LogWarning("Loading " + array.Length + " unlocked reserved item slots.");
			string[] array2 = array;
			foreach (string key in array2)
			{
				if (SyncManager.unlockableReservedItemSlotsDict.TryGetValue(key, out var value))
				{
					UnlockReservedItemSlot(value);
					SyncManager.SendUnlockItemSlotToClients(value.slotId);
				}
			}
		}

		public static bool IsReservedItem(GrabbableObject grabbableObject)
		{
			string itemName = ItemNameMap.GetItemName(grabbableObject);
			return IsReservedItem(itemName) || ((Object)(object)grabbableObject?.itemProperties != (Object)null && IsReservedItem(grabbableObject.itemProperties.itemName));
		}

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

		public static bool TryGetUnlockedItemSlotData(string itemSlotName, out ReservedItemSlotData itemSlotData)
		{
			itemSlotData = null;
			unlockedReservedItemSlotsDict.TryGetValue(itemSlotName, out itemSlotData);
			return itemSlotData != null;
		}

		public static bool TryGetUnlockedItemData(GrabbableObject item, out ReservedItemData itemData)
		{
			itemData = null;
			string itemName = ItemNameMap.GetItemName(item);
			return TryGetUnlockedItemData(itemName, out itemData) || ((Object)(object)item?.itemProperties != (Object)null && TryGetUnlockedItemData(item.itemProperties.itemName, out itemData));
		}

		public static bool TryGetUnlockedItemData(string itemName, out ReservedItemData itemData)
		{
			itemData = null;
			return allReservedItemData.TryGetValue(itemName, out itemData);
		}
	}
}
namespace ReservedItemSlotCore.Patches
{
	[HarmonyPatch]
	internal static class DropReservedItemPatcher
	{
		private static HashSet<PlayerControllerB> discardingEndOfFrame = new HashSet<PlayerControllerB>();

		[HarmonyPatch(typeof(GrabbableObject), "DiscardItemOnClient")]
		[HarmonyPrefix]
		private static void OnDiscardItem(GrabbableObject __instance)
		{
			PlayerControllerB val = __instance?.playerHeldBy;
			if ((Object)(object)val != (Object)null && !discardingEndOfFrame.Contains(val))
			{
				int currentItemSlot = val.currentItemSlot;
				discardingEndOfFrame.Add(val);
				((MonoBehaviour)val).StartCoroutine(OnDiscardEndOfFrame(val, currentItemSlot));
			}
		}

		private static IEnumerator OnDiscardEndOfFrame(PlayerControllerB playerController, int currentIndex)
		{
			yield return (object)new WaitForEndOfFrame();
			discardingEndOfFrame.Remove(playerController);
			if (ReservedPlayerData.allPlayerData.TryGetValue(playerController, out var playerData) && playerData.currentItemSlotIsReserved && (Object)(object)playerData.currentlySelectedItem == (Object)null && playerData.GetNumHeldReservedItems() > 0)
			{
				int swapToIndex = playerData.CallGetNextItemSlot(forward: true);
				if (!playerData.IsReservedItemSlot(swapToIndex) && !playerData.IsReservedItemSlot(ReservedHotbarManager.indexInHotbar))
				{
					swapToIndex = ReservedHotbarManager.indexInHotbar;
				}
				playerData.CallSwitchToItemSlot(swapToIndex);
			}
			if ((Object)(object)playerController == (Object)(object)StartOfRound.Instance?.localPlayerController)
			{
				HUDPatcher.UpdateUI();
			}
		}
	}
	[HarmonyPatch]
	public static class HUDPatcher
	{
		private static bool usingController = false;

		private static float itemSlotWidth;

		private static float itemSlotSpacing;

		private static float xPos;

		private static float defaultItemSlotSpacing;

		private static Vector2 defaultItemSlotSize;

		private static TextMeshProUGUI hotkeyTooltip;

		public static List<Image> reservedItemSlots = new List<Image>();

		public static HashSet<ReservedItemSlotData> toggledReservedItemSlots = new HashSet<ReservedItemSlotData>();

		private static bool lerpToggledItemSlotFrames = false;

		private static float largestPositionDifference = 0f;

		private static bool currentApplyHotbarPlusFormatting;

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

		public static ReservedPlayerData localPlayerData => ReservedPlayerData.localPlayerData;

		public static bool localPlayerUsingController => (Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.localPlayerUsingController;

		public static bool hasReservedItemSlotsAndEnabled => reservedItemSlots != null && reservedItemSlots.Count > 0 && ((Component)reservedItemSlots[0]).gameObject.activeSelf && ((Behaviour)reservedItemSlots[0]).enabled;

		[HarmonyPatch(typeof(HUDManager), "Awake")]
		[HarmonyPostfix]
		public static void Initialize(HUDManager __instance)
		{
			//IL_002a: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			CanvasScaler componentInParent = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<CanvasScaler>();
			AspectRatioFitter componentInParent2 = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<AspectRatioFitter>();
			itemSlotWidth = ((Component)__instance.itemSlotIconFrames[0]).GetComponent<RectTransform>().sizeDelta.x;
			itemSlotSpacing = 1.125f * itemSlotWidth;
			xPos = componentInParent.referenceResolution.x / 2f / componentInParent2.aspectRatio - itemSlotWidth / 4f;
			defaultItemSlotSpacing = itemSlotSpacing;
			defaultItemSlotSize = ((Graphic)__instance.itemSlotIconFrames[0]).rectTransform.sizeDelta;
			reservedItemSlots.Clear();
		}

		[HarmonyPatch(typeof(StartOfRound), "Update")]
		[HarmonyPrefix]
		public static void UpdateUsingController(StartOfRound __instance)
		{
			if (!((Object)(object)__instance.localPlayerController == (Object)null) && !((Object)(object)hotkeyTooltip == (Object)null) && ((Component)hotkeyTooltip).gameObject.activeSelf && ((Behaviour)hotkeyTooltip).enabled)
			{
				if (__instance.localPlayerUsingController != usingController)
				{
					usingController = __instance.localPlayerUsingController;
					UpdateHotkeyTooltipText();
				}
				LerpItemSlotFrames();
			}
		}

		private static void LerpItemSlotFrames()
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: 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_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			if (!lerpToggledItemSlotFrames)
			{
				return;
			}
			if (largestPositionDifference < 2f && largestPositionDifference != -1f)
			{
				lerpToggledItemSlotFrames = false;
			}
			for (int i = 0; i < SessionManager.numReservedItemSlotsUnlocked; i++)
			{
				ReservedItemSlotData unlockedReservedItemSlot = SessionManager.GetUnlockedReservedItemSlot(i);
				Image val = HUDManager.Instance.itemSlotIconFrames[ReservedPlayerData.localPlayerData.reservedHotbarStartIndex + i];
				bool flag = unlockedReservedItemSlot.slotPriority >= 0 || !ConfigSettings.displayNegativePrioritySlotsLeftSideOfScreen.Value;
				Vector2 anchoredPosition = ((Graphic)val).rectTransform.anchoredPosition;
				anchoredPosition.x = (flag ? xPos : (0f - xPos));
				if (ReservedHotbarManager.isToggledInReservedSlots && ReservedHotbarManager.currentlyToggledItemSlots != null && ReservedHotbarManager.currentlyToggledItemSlots.Contains(unlockedReservedItemSlot))
				{
					anchoredPosition.x += itemSlotWidth / 2f * (float)((!flag) ? 1 : (-1));
				}
				float num = Mathf.Abs(anchoredPosition.x - ((Graphic)val).rectTransform.anchoredPosition.x);
				largestPositionDifference = Mathf.Max(largestPositionDifference, num);
				if (lerpToggledItemSlotFrames)
				{
					((Graphic)val).rectTransform.anchoredPosition = Vector2.Lerp(((Graphic)val).rectTransform.anchoredPosition, anchoredPosition, Time.deltaTime * 10f);
				}
				else
				{
					((Graphic)val).rectTransform.anchoredPosition = anchoredPosition;
				}
			}
		}

		public static void OnUpdateReservedItemSlots()
		{
			//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_00dd: 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_0119: 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)
			if (reservedItemSlots == null || SessionManager.numReservedItemSlotsUnlocked <= 0 || reservedItemSlots.Count == SessionManager.numReservedItemSlotsUnlocked)
			{
				return;
			}
			List<Image> list = new List<Image>(HUDManager.Instance.itemSlotIconFrames);
			List<Image> list2 = new List<Image>(HUDManager.Instance.itemSlotIcons);
			Animator component = ((Component)HUDManager.Instance.itemSlotIconFrames[0]).GetComponent<Animator>();
			RuntimeAnimatorController val = ((component != null) ? component.runtimeAnimatorController : null);
			AnimatorStateInfo currentAnimatorStateInfo = component.GetCurrentAnimatorStateInfo(0);
			for (int i = reservedItemSlots.Count; i < SessionManager.numReservedItemSlotsUnlocked; i++)
			{
				GameObject val2 = Object.Instantiate<GameObject>(((Component)list[0]).gameObject, ((Component)list[0]).transform.parent);
				Image component2 = val2.GetComponent<Image>();
				Image component3 = ((Component)((Component)component2).transform.GetChild(0)).GetComponent<Image>();
				((Component)component2).transform.localScale = ((Component)list[0]).transform.localScale;
				((Transform)((Graphic)component2).rectTransform).eulerAngles = ((Transform)((Graphic)list[0]).rectTransform).eulerAngles;
				((Transform)((Graphic)component3).rectTransform).eulerAngles = ((Transform)((Graphic)list2[0]).rectTransform).eulerAngles;
				CanvasGroup val3 = ((Component)component2).gameObject.AddComponent<CanvasGroup>();
				val3.ignoreParentGroups = ConfigSettings.preventReservedItemSlotFade.Value;
				val3.alpha = 1f;
				component2.fillMethod = list[0].fillMethod;
				component2.sprite = list[0].sprite;
				((Graphic)component2).material = ((Graphic)list[0]).material;
				if (Plugin.IsModLoaded("xuxiaolan.hotbarrd"))
				{
					component2.overrideSprite = list[0].overrideSprite;
				}
				int index = ReservedPlayerData.localPlayerData.reservedHotbarStartIndex + reservedItemSlots.Count;
				list.Insert(index, component2);
				list2.Insert(index, component3);
				reservedItemSlots.Add(component2);
			}
			HUDManager.Instance.itemSlotIconFrames = list.ToArray();
			HUDManager.Instance.itemSlotIcons = list2.ToArray();
			UpdateUI();
		}

		public static void UpdateUI()
		{
			//IL_0137: 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_0312: 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_0348: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Unknown result type (might be due to invalid IL or missing references)
			//IL_037b: 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_03a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: 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_0256: Unknown result type (might be due to invalid IL or missing references)
			if (reservedItemSlots.Count != SessionManager.numReservedItemSlotsUnlocked)
			{
				Plugin.LogError("Called UpdateUI with mismatched unlocked reserved item slots and reserved item slot hud elements.");
				return;
			}
			int num = 0;
			int num2 = 0;
			Transform val = null;
			Vector2 anchoredPosition = default(Vector2);
			for (int i = 0; i < SessionManager.numReservedItemSlotsUnlocked; i++)
			{
				ReservedItemSlotData unlockedReservedItemSlot = SessionManager.GetUnlockedReservedItemSlot(i);
				int num3 = Array.IndexOf(HUDManager.Instance.itemSlotIconFrames, reservedItemSlots[i]);
				Image val2 = HUDManager.Instance.itemSlotIconFrames[ReservedPlayerData.localPlayerData.reservedHotbarStartIndex + i];
				Image val3 = HUDManager.Instance.itemSlotIcons[ReservedPlayerData.localPlayerData.reservedHotbarStartIndex + i];
				float currentItemSlotSpacing = GetCurrentItemSlotSpacing();
				if (HotbarPlus_Compat.Enabled && !ConfigSettings.applyHotbarPlusFormatting.Value)
				{
					((Graphic)val2).rectTransform.sizeDelta = defaultItemSlotSize;
					currentItemSlotSpacing = defaultItemSlotSpacing;
				}
				GrabbableObject reservedItem = ReservedPlayerData.localPlayerData.GetReservedItem(unlockedReservedItemSlot);
				((Object)val2).name = "Slot" + i + " [ReservedItemSlot] (" + unlockedReservedItemSlot.slotName + ")";
				((Vector2)(ref anchoredPosition))..ctor(xPos, ((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.anchoredPosition.y);
				if (unlockedReservedItemSlot.slotPriority >= 0 || !ConfigSettings.displayNegativePrioritySlotsLeftSideOfScreen.Value)
				{
					anchoredPosition.x = xPos;
					anchoredPosition.y = ((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.anchoredPosition.y + currentItemSlotSpacing * (float)num;
					if (!ConfigSettings.hideEmptyReservedItemSlots.Value || (Object)(object)reservedItem != (Object)null)
					{
						if (!Object.op_Implicit((Object)(object)val))
						{
							val = ((Component)val2).transform;
						}
						num++;
					}
					else
					{
						anchoredPosition.y = -1000f;
					}
				}
				else
				{
					anchoredPosition.x = 0f - xPos;
					anchoredPosition.y = ((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.anchoredPosition.y + currentItemSlotSpacing * (float)num2;
					if (!ConfigSettings.hideEmptyReservedItemSlots.Value || (Object)(object)reservedItem != (Object)null)
					{
						num2++;
					}
					else
					{
						anchoredPosition.y = -1000f;
					}
				}
				((Graphic)val2).rectTransform.anchoredPosition = anchoredPosition;
				if ((Object)(object)reservedItem != (Object)null)
				{
					((Behaviour)val3).enabled = true;
					val3.sprite = reservedItem.itemProperties.itemIcon;
				}
				else
				{
					((Behaviour)val3).enabled = false;
					val3.sprite = null;
				}
			}
			if (SessionManager.numReservedItemSlotsUnlocked > 0 && !ConfigSettings.hideFocusHotbarTooltip.Value)
			{
				if ((Object)(object)hotkeyTooltip == (Object)null)
				{
					hotkeyTooltip = new GameObject("ReservedItemSlotTooltip", new Type[2]
					{
						typeof(RectTransform),
						typeof(TextMeshProUGUI)
					}).GetComponent<TextMeshProUGUI>();
				}
				RectTransform rectTransform = ((TMP_Text)hotkeyTooltip).rectTransform;
				((Transform)rectTransform).parent = val;
				if (Object.op_Implicit((Object)(object)val))
				{
					((Transform)rectTransform).localScale = Vector3.one;
					rectTransform.sizeDelta = new Vector2(((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.sizeDelta.x * 2f, 10f);
					rectTransform.pivot = Vector2.one / 2f;
					rectTransform.anchoredPosition3D = new Vector3(0f, (0f - rectTransform.sizeDelta.x / 2f) * 1.2f, 0f);
					((TMP_Text)hotkeyTooltip).font = ((TMP_Text)HUDManager.Instance.controlTipLines[0]).font;
					((TMP_Text)hotkeyTooltip).fontSize = 7f;
					((TMP_Text)hotkeyTooltip).alignment = (TextAlignmentOptions)514;
					UpdateHotkeyTooltipText();
				}
				else
				{
					((Transform)rectTransform).localScale = Vector3.zero;
				}
			}
			currentApplyHotbarPlusFormatting = ConfigSettings.applyHotbarPlusFormatting.Value;
		}

		public static void UpdateHotkeyTooltipText()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//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)
			if (!((Object)(object)localPlayerController == (Object)null) && !((Object)(object)hotkeyTooltip == (Object)null) && Keybinds.FocusReservedHotbarAction != null && !Plugin.IsModLoaded("com.potatoepet.AdvancedCompany"))
			{
				int num = (localPlayerUsingController ? 1 : 0);
				InputBinding val = Keybinds.FocusReservedHotbarAction.bindings[num];
				string keybindDisplayName = KeybindDisplayNames.GetKeybindDisplayName(((InputBinding)(ref val)).effectivePath);
				((TMP_Text)hotkeyTooltip).text = (ConfigSettings.toggleFocusReservedHotbar.Value ? $"Toggle: [{keybindDisplayName}]" : $"Hold: [{keybindDisplayName}]");
			}
		}

		public static void UpdateToggledReservedItemSlotsUI()
		{
			if (ReservedHotbarManager.currentlyToggledItemSlots != null)
			{
				toggledReservedItemSlots = new HashSet<ReservedItemSlotData>(ReservedHotbarManager.currentlyToggledItemSlots);
			}
			else
			{
				toggledReservedItemSlots.Clear();
			}
			lerpToggledItemSlotFrames = true;
			largestPositionDifference = -1f;
		}

		private static float GetCurrentItemSlotSpacing()
		{
			//IL_005d: 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)
			try
			{
				Image val = HUDManager.Instance.itemSlotIconFrames[0];
				Image val2 = HUDManager.Instance.itemSlotIconFrames[1];
				if (((Object)val).name.ToLower().Contains("reserved") || ((Object)val2).name.ToLower().Contains("reserved"))
				{
					return defaultItemSlotSpacing;
				}
				return Mathf.Abs(((Graphic)val2).rectTransform.anchoredPosition.x - ((Graphic)val).rectTransform.anchoredPosition.x);
			}
			catch
			{
			}
			return defaultItemSlotSpacing;
		}

		[HarmonyPatch(typeof(QuickMenuManager), "CloseQuickMenu")]
		[HarmonyPostfix]
		public static void OnCloseQuickMenu()
		{
			if (HotbarPlus_Compat.Enabled && currentApplyHotbarPlusFormatting != ConfigSettings.applyHotbarPlusFormatting.Value)
			{
				UpdateUI();
			}
		}
	}
	[HarmonyPatch]
	internal class MaskedEnemyPatcher
	{
		[HarmonyPatch(typeof(MaskedPlayerEnemy), "Awake")]
		[HarmonyPrefix]
		public static void InitMaskedEnemy(MaskedPlayerEnemy __instance)
		{
			if (ConfigSettings.showReservedItemsHolsteredMaskedEnemy.Value && !MaskedEnemyData.allMaskedEnemyData.ContainsKey(__instance))
			{
				MaskedEnemyData.allMaskedEnemyData.Add(__instance, new MaskedEnemyData(__instance));
			}
		}

		[HarmonyPatch(typeof(MaskedPlayerEnemy), "OnDestroy")]
		[HarmonyPrefix]
		public static void OnDestroy(MaskedPlayerEnemy __instance)
		{
			if (MaskedEnemyData.allMaskedEnemyData.TryGetValue(__instance, out var value))
			{
				value.DestroyEquippedItems();
				MaskedEnemyData.allMaskedEnemyData.Remove(__instance);
			}
		}

		[HarmonyPatch(typeof(MaskedPlayerEnemy), "Update")]
		[HarmonyPostfix]
		public static void Update(MaskedPlayerEnemy __instance)
		{
			if (ConfigSettings.showReservedItemsHolsteredMaskedEnemy.Value && MaskedEnemyData.allMaskedEnemyData.TryGetValue(__instance, out var value) && (Object)(object)value.originallyMimickingPlayer == (Object)null && (Object)(object)value.maskedEnemy.mimickingPlayer != (Object)null)
			{
				AddReservedItemsToMaskedEnemy(__instance);
			}
		}

		public static void AddReservedItemsToMaskedEnemy(MaskedPlayerEnemy maskedEnemy)
		{
			//IL_014a: 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_0177: Unknown result type (might be due to invalid IL or missing references)
			if (!ConfigSettings.showReservedItemsHolsteredMaskedEnemy.Value || !MaskedEnemyData.allMaskedEnemyData.TryGetValue(maskedEnemy, out var value))
			{
				return;
			}
			value.originallyMimickingPlayer = value.maskedEnemy.mimickingPlayer;
			if (!ReservedPlayerData.allPlayerData.TryGetValue(value.originallyMimickingPlayer, out var value2))
			{
				Plugin.LogWarning("Failed to mimic player's equipped reserved items. Could not retrieve player data from: " + value.originallyMimickingPlayer.playerUsername);
				return;
			}
			for (int i = value2.reservedHotbarStartIndex; i < value2.reservedHotbarEndIndexExcluded; i++)
			{
				GrabbableObject val = value2.playerController.ItemSlots[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				int index = i - value2.reservedHotbarStartIndex;
				ReservedItemSlotData reservedItemSlotData = SessionManager.unlockedReservedItemSlots[index];
				ReservedItemData reservedItemData = reservedItemSlotData.GetReservedItemData(val);
				if (reservedItemData.holsteredParentBone == PlayerBone.None)
				{
					continue;
				}
				Transform bone = value.boneMap.GetBone(reservedItemData.holsteredParentBone);
				if ((Object)(object)bone == (Object)null)
				{
					Plugin.LogWarning("Failed to get bone from masked enemy: " + reservedItemData.holsteredParentBone);
					continue;
				}
				GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, bone);
				val2.transform.localEulerAngles = reservedItemData.holsteredRotationOffset;
				val2.transform.localPosition = reservedItemData.holsteredPositionOffset;
				val2.transform.localScale = ((Component)val).transform.localScale;
				val2.layer = 6;
				MeshRenderer[] componentsInChildren = val2.GetComponentsInChildren<MeshRenderer>();
				foreach (MeshRenderer val3 in componentsInChildren)
				{
					if (!((Object)val3).name.Contains("ScanNode") && !((Component)val3).gameObject.CompareTag("DoNotSet") && !((Component)val3).gameObject.CompareTag("InteractTrigger"))
					{
						((Component)val3).gameObject.layer = 6;
					}
				}
				if (val is FlashlightItem)
				{
					Light[] componentsInChildren2 = val2.GetComponentsInChildren<Light>();
					foreach (Light val4 in componentsInChildren2)
					{
						((Behaviour)val4).enabled = false;
					}
				}
				else
				{
					Light[] componentsInChildren3 = val2.GetComponentsInChildren<Light>();
					foreach (Light val5 in componentsInChildren3)
					{
						((Behaviour)val5).enabled = true;
					}
				}
				GrabbableObject componentInChildren = val2.GetComponentInChildren<GrabbableObject>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					componentInChildren.playerHeldBy = null;
					FlashlightItem val6 = (FlashlightItem)(object)((componentInChildren is FlashlightItem) ? componentInChildren : null);
					if ((Object)(object)val6 != (Object)null)
					{
						((Behaviour)val6.flashlightBulb).enabled = true;
						((Behaviour)val6.flashlightBulbGlow).enabled = true;
						((Renderer)val6.flashlightMesh).sharedMaterials[1] = val6.bulbLight;
					}
					ReservedItemsPatcher.ForceEnableItemMesh(componentInChildren, enabled: true);
					componentInChildren.EnablePhysics(false);
				}
				Object.DestroyImmediate((Object)(object)val2.GetComponentInChildren<NetworkObject>());
				Collider[] componentsInChildren4 = val2.GetComponentsInChildren<Collider>();
				foreach (Collider val7 in componentsInChildren4)
				{
					Object.DestroyImmediate((Object)(object)val7);
				}
				MonoBehaviour[] componentsInChildren5 = val2.GetComponentsInChildren<MonoBehaviour>();
				foreach (MonoBehaviour val8 in componentsInChildren5)
				{
					Object.DestroyImmediate((Object)(object)val8);
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class MouseScrollPatcher
	{
		private static bool scrollingItemSlots;

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

		[HarmonyPatch(typeof(PlayerControllerB), "NextItemSlot")]
		[HarmonyPrefix]
		public static void CorrectReservedScrollDirectionNextItemSlot(ref bool forward)
		{
			if (Keybinds.scrollingReservedHotbar)
			{
				forward = Keybinds.RawScrollAction.ReadValue<float>() > 0f;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SwitchItemSlotsServerRpc")]
		[HarmonyPrefix]
		public static void CorrectReservedScrollDirectionServerRpc(ref bool forward)
		{
			if (Keybinds.scrollingReservedHotbar)
			{
				forward = Keybinds.RawScrollAction.ReadValue<float>() > 0f;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ScrollMouse_performed")]
		[HarmonyPrefix]
		public static bool PreventInvertedScrollingReservedHotbar(CallbackContext context)
		{
			if (StartOfRound.Instance.localPlayerUsingController || SessionManager.numReservedItemSlotsUnlocked <= 0 || HUDPatcher.reservedItemSlots == null || localPlayerController.inTerminalMenu)
			{
				return true;
			}
			if (ReservedPlayerData.localPlayerData.currentItemSlotIsReserved)
			{
				if (!HUDPatcher.hasReservedItemSlotsAndEnabled)
				{
					return true;
				}
				if (!Keybinds.scrollingReservedHotbar || (ReservedPlayerData.localPlayerData.GetNumHeldReservedItems() == 1 && (Object)(object)ReservedPlayerData.localPlayerData.currentlySelectedItem != (Object)null && !ReservedHotbarManager.isToggledInReservedSlots))
				{
					return false;
				}
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ScrollMouse_performed")]
		[HarmonyPostfix]
		public static void ScrollReservedItemSlots(CallbackContext context)
		{
			scrollingItemSlots = false;
		}
	}
	[HarmonyPatch]
	internal static class PlayerPatcher
	{
		private static int INTERACTABLE_OBJECT_MASK = 0;

		public static int vanillaHotbarSize = 4;

		private static bool initialized = false;

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

		public static Dictionary<PlayerControllerB, ReservedPlayerData> allPlayerData => ReservedPlayerData.allPlayerData;

		public static ReservedPlayerData localPlayerData => ReservedPlayerData.localPlayerData;

		public static int reservedHotbarSize => SessionManager.numReservedItemSlotsUnlocked;

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		public static void InitSession(StartOfRound __instance)
		{
			initialized = false;
			vanillaHotbarSize = 4;
			ReservedPlayerData.allPlayerData?.Clear();
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Awake")]
		[HarmonyPostfix]
		public static void InitializePlayerController(PlayerControllerB __instance)
		{
			if (!initialized)
			{
				vanillaHotbarSize = __instance.ItemSlots.Length;
				INTERACTABLE_OBJECT_MASK = (int)Traverse.Create((object)__instance).Field("interactableObjectsMask").GetValue();
				initialized = true;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPrefix]
		public static void InitializePlayerControllerLate(PlayerControllerB __instance)
		{
			ReservedPlayerData value = new ReservedPlayerData(__instance);
			if (!allPlayerData.ContainsKey(__instance))
			{
				Plugin.Log("Initializing ReservedPlayerData for player: " + ((Object)__instance).name);
				allPlayerData.Add(__instance, value);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")]
		[HarmonyPostfix]
		public static void CheckForChangedInventorySize(PlayerControllerB __instance)
		{
			if (!SyncManager.isSynced || !ReservedPlayerData.allPlayerData.TryGetValue(__instance, out var value) || !SyncManager.canUseModDisabledOnHost || (Object)(object)__instance != (Object)(object)localPlayerController || reservedHotbarSize <= 0 || value.hotbarSize == __instance.ItemSlots.Length)
			{
				return;
			}
			Plugin.LogWarning("On update inventory size for player: " + ((Object)__instance).name + " - Old hotbar size: " + value.hotbarSize + " - New hotbar size: " + __instance.ItemSlots.Length);
			value.hotbarSize = __instance.ItemSlots.Length;
			int num = -1;
			if ((Object)(object)__instance == (Object)(object)localPlayerController)
			{
				if (HUDPatcher.reservedItemSlots != null && HUDPatcher.reservedItemSlots.Count > 0)
				{
					num = Array.IndexOf(HUDManager.Instance.itemSlotIconFrames, HUDPatcher.reservedItemSlots[0]);
					Plugin.Log("OnUpdateInventorySize A for local player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num);
				}
				if (num == -1)
				{
					for (int i = 0; i < HUDManager.Instance.itemSlotIconFrames.Length; i++)
					{
						if (((Object)HUDManager.Instance.itemSlotIconFrames[i]).name.ToLower().Contains("reserved"))
						{
							num = i;
							Plugin.Log("OnUpdateInventorySize B for local player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num);
							break;
						}
					}
				}
			}
			if (num == -1)
			{
				num = value.reservedHotbarStartIndex;
				Plugin.Log("OnUpdateInventorySize C for player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num);
			}
			if (num == -1)
			{
				num = vanillaHotbarSize;
				Plugin.Log("OnUpdateInventorySize D for player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num);
			}
			value.reservedHotbarStartIndex = num;
			if (value.reservedHotbarStartIndex < 0)
			{
				Plugin.LogError("Set new reserved start index to slot: " + value.reservedHotbarStartIndex + ". Maybe share these logs with Flip? :)");
			}
			if (value.reservedHotbarEndIndexExcluded - 1 >= value.playerController.ItemSlots.Length)
			{
				Plugin.LogError("Set new reserved start index to slot: " + value.reservedHotbarStartIndex + " Last reserved slot index: " + (value.reservedHotbarEndIndexExcluded - 1) + " Inventory size: " + value.playerController.ItemSlots.Length + ". Maybe share these logs with Flip? :)");
			}
			if (value.isLocalPlayer)
			{
				HUDPatcher.UpdateUI();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "BeginGrabObject")]
		[HarmonyPrefix]
		public static bool BeginGrabReservedItemPrefix(PlayerControllerB __instance)
		{
			//IL_0083: 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_009d: Unknown result type (might be due to invalid IL or missing references)
			if ((!SyncManager.isSynced && !SyncManager.canUseModDisabledOnHost) || !HUDPatcher.hasReservedItemSlotsAndEnabled)
			{
				return true;
			}
			localPlayerData.grabbingReservedItemSlotData = null;
			localPlayerData.grabbingReservedItemData = null;
			localPlayerData.grabbingReservedItem = null;
			localPlayerData.previousHotbarIndex = -1;
			if (__instance.twoHanded || __instance.sinkingValue > 0.73f)
			{
				return true;
			}
			Ray val = default(Ray);
			((Ray)(ref val))..ctor(((Component)__instance.gameplayCamera).transform.position, ((Component)__instance.gameplayCamera).transform.forward);
			RaycastHit val2 = default(RaycastHit);
			if (Physics.Raycast(val, ref val2, __instance.grabDistance, INTERACTABLE_OBJECT_MASK) && ((Component)((RaycastHit)(ref val2)).collider).gameObject.layer != 8 && ((Component)((RaycastHit)(ref val2)).collider).tag == "PhysicsProp")
			{
				GrabbableObject component = ((Component)((Component)((RaycastHit)(ref val2)).collider).transform).gameObject.GetComponent<GrabbableObject>();
				if ((Object)(object)component != (Object)null && !__instance.inSpecialInteractAnimation && !component.isHeld && !component.isPocketed)
				{
					NetworkObject networkObject = ((NetworkBehaviour)component).NetworkObject;
					if ((Object)(object)networkObject != (Object)null && networkObject.IsSpawned && SessionManager.TryGetUnlockedItemData(component, out var itemData))
					{
						localPlayerData.grabbingReservedItemData = itemData;
						localPlayerData.grabbingReservedItem = component;
						localPlayerData.previousHotbarIndex = Mathf.Clamp(__instance.currentItemSlot, 0, __instance.ItemSlots.Length - 1);
						Plugin.Log("Beginning grab on reserved item: " + itemData.itemName + " Previous item slot: " + localPlayerData.previousHotbarIndex);
					}
				}
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "BeginGrabObject")]
		[HarmonyPostfix]
		public static void BeginGrabReservedItemPostfix(PlayerControllerB __instance)
		{
			if (localPlayerData != null && localPlayerData.isGrabbingReservedItem && !localPlayerData.IsReservedItemSlot(localPlayerData.previousHotbarIndex))
			{
				SetSpecialGrabAnimationBool(__instance, setTrue: false);
				SetSpecialGrabAnimationBool(__instance, (Object)(object)localPlayerData.previouslyHeldItem != (Object)null, localPlayerData.previouslyHeldItem);
				__instance.playerBodyAnimator.SetBool("GrabValidated", true);
				__instance.playerBodyAnimator.SetBool("GrabInvalidated", false);
				__instance.playerBodyAnimator.ResetTrigger("SwitchHoldAnimation");
				__instance.playerBodyAnimator.ResetTrigger("SwitchHoldAnimationTwoHanded");
				if ((Object)(object)localPlayerData.previouslyHeldItem != (Object)null)
				{
					__instance.playerBodyAnimator.ResetTrigger(localPlayerData.previouslyHeldItem.itemProperties.pocketAnim);
				}
				__instance.twoHanded = (Object)(object)localPlayerData.previouslyHeldItem != (Object)null && localPlayerData.previouslyHeldItem.itemProperties.twoHanded;
				__instance.twoHandedAnimation = (Object)(object)localPlayerData.previouslyHeldItem != (Object)null && localPlayerData.previouslyHeldItem.itemProperties.twoHandedAnimation;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")]
		[HarmonyPrefix]
		public static void GrabReservedItemClientRpcPrefix(bool grabValidated, NetworkObjectReference grabbedObject, PlayerControllerB __instance)
		{
			if ((!SyncManager.isSynced && !SyncManager.canUseModDisabledOnHost) || !NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance) || !ReservedPlayerData.allPlayerData.TryGetValue(__instance, out var value))
			{
				return;
			}
			NetworkObject val = default(NetworkObject);
			GrabbableObject val2 = default(GrabbableObject);
			if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsListening && grabValidated && ((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null) && ((Component)val).TryGetComponent<GrabbableObject>(ref val2) && SessionManager.TryGetUnlockedItemData(val2, out var itemData))
			{
				ReservedItemSlotData firstEmptySlotForReservedItem = value.GetFirstEmptySlotForReservedItem(itemData.itemName);
				if (firstEmptySlotForReservedItem != null)
				{
					value.grabbingReservedItemSlotData = firstEmptySlotForReservedItem;
					value.grabbingReservedItemData = itemData;
					value.grabbingReservedItem = val2;
					value.previousHotbarIndex = Mathf.Clamp(__instance.currentItemSlot, 0, __instance.ItemSlots.Length - 1);
					return;
				}
			}
			value.grabbingReservedItemSlotData = null;
			value.grabbingReservedItemData = null;
			value.grabbingReservedItem = null;
			value.previousHotbarIndex = -1;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")]
		[HarmonyPostfix]
		public static void GrabReservedItemClientRpcPostfix(bool grabValidated, NetworkObjectReference grabbedObject, PlayerControllerB __instance)
		{
			if ((!SyncManager.isSynced && !SyncManager.canUseModDisabledOnHost) || !NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance) || !ReservedPlayerData.allPlayerData.TryGetValue(__instance, out var value) || !value.isGrabbingReservedItem)
			{
				return;
			}
			if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsListening)
			{
				NetworkObject val = default(NetworkObject);
				GrabbableObject val2 = default(GrabbableObject);
				if (grabValidated && ((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null) && ((Component)val).TryGetComponent<GrabbableObject>(ref val2))
				{
					if (SessionManager.TryGetUnlockedItemData(val2, out var itemData))
					{
						if (!value.IsReservedItemSlot(value.previousHotbarIndex))
						{
							if ((Object)(object)value.previouslyHeldItem != (Object)null)
							{
								value.previouslyHeldItem.EnableItemMeshes(true);
							}
							ReservedItemsPatcher.ForceEnableItemMesh(value.grabbingReservedItem, enabled: false);
							Traverse.Create((object)val2).Field("previousPlayerHeldBy").SetValue((object)__instance);
							if (value.isLocalPlayer)
							{
								int num = value.reservedHotbarStartIndex + value.grabbingReservedItemSlotData.GetReservedItemSlotIndex();
								((Component)HUDManager.Instance.itemSlotIconFrames[num]).GetComponent<Animator>().SetBool("selectedSlot", false);
								((Component)HUDManager.Instance.itemSlotIconFrames[value.previousHotbarIndex]).GetComponent<Animator>().SetBool("selectedSlot", true);
								((Component)HUDManager.Instance.itemSlotIconFrames[num]).GetComponent<Animator>().Play("PanelLines", 0, 1f);
								((Component)HUDManager.Instance.itemSlotIconFrames[value.previousHotbarIndex]).GetComponent<Animator>().Play("PanelEnlarge", 0, 1f);
							}
							else
							{
								SwitchToItemSlot(__instance, value.previousHotbarIndex);
								if (itemData.showOnPlayerWhileHolstered)
								{
									val2.EnableItemMeshes(true);
								}
							}
							SetSpecialGrabAnimationBool(__instance, setTrue: false);
							SetSpecialGrabAnimationBool(__instance, (Object)(object)value.previouslyHeldItem != (Object)null, value.previouslyHeldItem);
							__instance.playerBodyAnimator.SetBool("GrabValidated", true);
							__instance.playerBodyAnimator.SetBool("GrabInvalidated", false);
							__instance.playerBodyAnimator.ResetTrigger("SwitchHoldAnimation");
							__instance.playerBodyAnimator.ResetTrigger("SwitchHoldAnimationTwoHanded");
							if ((Object)(object)value.previouslyHeldItem != (Object)null)
							{
								__instance.playerBodyAnimator.ResetTrigger(value.previouslyHeldItem.itemProperties.pocketAnim);
							}
							__instance.twoHanded = (Object)(object)value.previouslyHeldItem != (Object)null && value.previouslyHeldItem.itemProperties.twoHanded;
							__instance.twoHandedAnimation = (Object)(object)value.previouslyHeldItem != (Object)null && value.previouslyHeldItem.itemProperties.twoHandedAnimation;
						}
						if (value.isLocalPlayer)
						{
							HUDPatcher.UpdateUI();
							return;
						}
						value.grabbingReservedItemSlotData = null;
						value.grabbingReservedItemData = null;
						value.grabbingReservedItem = null;
						value.previousHotbarIndex = -1;
						return;
					}
				}
				else if (value.isLocalPlayer)
				{
					Plugin.LogWarning("Failed to validate ReservedItemGrab by the local player. Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + ". Internal error?");
					Traverse.Create((object)localPlayerController).Field("grabInvalidated").SetValue((object)true);
				}
				else
				{
					Plugin.LogWarning("Failed to validate ReservedItemGrab by player with id: " + ((Object)__instance).name + ". Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + ". Internal error?");
				}
			}
			value.grabbingReservedItemSlotData = null;
			value.grabbingReservedItemData = null;
			value.grabbingReservedItem = null;
			value.previousHotbarIndex = -1;
		}

		[HarmonyPatch(typeof(GrabbableObject), "GrabItemOnClient")]
		[HarmonyPrefix]
		public static void OnReservedItemGrabbed(GrabbableObject __instance)
		{
			if (localPlayerData.grabbingReservedItemData != null && (Object)(object)__instance == (Object)(object)GetCurrentlyGrabbingObject(localPlayerController))
			{
				((MonoBehaviour)localPlayerController).StartCoroutine(OnReservedItemGrabbedEndOfFrame());
			}
			IEnumerator OnReservedItemGrabbedEndOfFrame()
			{
				yield return (object)new WaitForEndOfFrame();
				if (localPlayerData.isGrabbingReservedItem)
				{
					if (localPlayerData.previousHotbarIndex < 0 || localPlayerData.previousHotbarIndex >= localPlayerController.ItemSlots.Length || localPlayerData.IsReservedItemSlot(localPlayerData.previousHotbarIndex))
					{
						localPlayerData.previousHotbarIndex = 0;
					}
					SwitchToItemSlot(localPlayerController, localPlayerData.previousHotbarIndex);
					GrabbableObject obj = __instance;
					if (obj != null)
					{
						obj.PocketItem();
					}
					SetSpecialGrabAnimationBool(localPlayerController, setTrue: false);
					SetSpecialGrabAnimationBool(localPlayerController, (Object)(object)localPlayerData.previouslyHeldItem != (Object)null, localPlayerData.previouslyHeldItem);
					localPlayerController.playerBodyAnimator.SetBool("GrabValidated", true);
					localPlayerController.playerBodyAnimator.SetBool("GrabInvalidated", false);
					localPlayerController.playerBodyAnimator.ResetTrigger("SwitchHoldAnimation");
					localPlayerController.isGrabbingObjectAnimation = false;
					localPlayerController.playerBodyAnimator.ResetTrigger("SwitchHoldAnimationTwoHanded");
					if ((Object)(object)localPlayerData.previouslyHeldItem != (Object)null)
					{
						localPlayerController.playerBodyAnimator.ResetTrigger(localPlayerData.previouslyHeldItem.itemProperties.pocketAnim);
					}
					localPlayerController.twoHanded = (Object)(object)localPlayerData.previouslyHeldItem != (Object)null && localPlayerData.previouslyHeldItem.itemProperties.twoHanded;
					localPlayerController.twoHandedAnimation = (Object)(object)localPlayerData.previouslyHeldItem != (Object)null && localPlayerData.previouslyHeldItem.itemProperties.twoHandedAnimation;
				}
				localPlayerData.grabbingReservedItemSlotData = null;
				localPlayerData.grabbingReservedItemData = null;
				localPlayerData.grabbingReservedItem = null;
				localPlayerData.previousHotbarIndex = -1;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SwitchToItemSlot")]
		[HarmonyPrefix]
		private static void UpdateLastSelectedHotbarIndex(int slot, PlayerControllerB __instance)
		{
			int currentItemSlot = __instance.currentItemSlot;
			if (ReservedPlayerData.allPlayerData.TryGetValue(__instance, out var value))
			{
				if (value.IsReservedItemSlot(currentItemSlot))
				{
					ReservedHotbarManager.indexInReservedHotbar = currentItemSlot;
				}
				else
				{
					ReservedHotbarManager.indexInHotbar = currentItemSlot;
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SwitchToItemSlot")]
		[HarmonyPostfix]
		private static void UpdateFocusReservedHotbar(int slot, PlayerControllerB __instance)
		{
			if (HUDPatcher.hasReservedItemSlotsAndEnabled && ReservedPlayerData.allPlayerData.TryGetValue(__instance, out var value))
			{
				bool inReservedHotbarSlots = value.inReservedHotbarSlots;
				value.inReservedHotbarSlots = value.IsReservedItemSlot(__instance.currentItemSlot);
				bool flag = false;
				if (inReservedHotbarSlots != value.inReservedHotbarSlots || (value.inReservedHotbarSlots && ReservedHotbarManager.isToggledInReservedSlots && ReservedHotbarManager.currentlyToggledItemSlots != null && !ReservedHotbarManager.currentlyToggledItemSlots.Contains(value.GetCurrentlySelectedReservedItemSlot())))
				{
					flag = true;
				}
				if (value.inReservedHotbarSlots)
				{
					ReservedHotbarManager.OnSwapToReservedHotbar();
				}
				else
				{
					ReservedHotbarManager.OnSwapToVanillaHotbar();
				}
				if (flag)
				{
					HUDPatcher.UpdateToggledReservedItemSlotsUI();
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "FirstEmptyItemSlot")]
		[HarmonyPostfix]
		private static void GetReservedItemSlotPlacementIndex(ref int __result, PlayerControllerB __instance)
		{
			if (reservedHotbarSize <= 0 || !HUDPatcher.hasReservedItemSlotsAndEnabled || !ReservedPlayerData.allPlayerData.TryGetValue(__instance, out var value))
			{
				return;
			}
			ReservedItemData grabbingReservedItemData = value.grabbingReservedItemData;
			if (grabbingReservedItemData != null)
			{
				ReservedItemSlotData firstEmptySlotForReservedItem = value.GetFirstEmptySlotForReservedItem(grabbingReservedItemData.itemName);
				if (firstEmptySlotForReservedItem != null)
				{
					__result = firstEmptySlotForReservedItem.GetIndexInInventory(__instance);
					return;
				}
				value.grabbingReservedItemSlotData = null;
				value.grabbingReservedItemData = null;
				value.grabbingReservedItem = null;
				value.previousHotbarIndex = -1;
			}
			if (!value.IsReservedItemSlot(__result))
			{
				return;
			}
			__result = -1;
			for (int i = 0; i < __instance.ItemSlots.Length; i++)
			{
				if (!value.IsReservedItemSlot(i) && (Object)(object)__instance.ItemSlots[i] == (Object)null)
				{
					__result = i;
					break;
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "NextItemSlot")]
		[HarmonyPostfix]
		private static void OnNextItemSlot(ref int __result, bool forward, PlayerControllerB __instance)
		{
			if (reservedHotbarSize <= 0 || !HUDPatcher.hasReservedItemSlotsAndEnabled || !ReservedPlayerData.allPlayerData.TryGetValue(__instance, out var value))
			{
				return;
			}
			bool inReservedHotbarSlots = value.inReservedHotbarSlots;
			bool flag = value.IsReservedItemSlot(__result);
			bool flag2 = inReservedHotbarSlots;
			if (inReservedHotbarSlots)
			{
				ReservedItemSlotData unlockedReservedItemSlot = SessionManager.GetUnlockedReservedItemSlot(__result - value.reservedHotbarStartIndex);
				if (ReservedHotbarManager.isToggledInReservedSlots && !ConfigSettings.toggleFocusReservedHotbar.Value && !Keybinds.holdingModifierKey && ReservedHotbarManager.currentlyToggledItemSlots != null && (!flag || (Object)(object)value.itemSlots[__result] == (Object)null || !ReservedHotbarManager.currentlyToggledItemSlots.Contains(unlockedReservedItemSlot)))
				{
					__result = ReservedHotbarManager.indexInHotbar;
					return;
				}
			}
			if (flag == flag2 && (!flag || (Object)(object)__instance.ItemSlots[__result] != (Object)null))
			{
				return;
			}
			int num = (forward ? 1 : (-1));
			__result = __instance.currentItemSlot + num;
			__result = ((__result < 0) ? (__instance.ItemSlots.Length - 1) : ((__result < __instance.ItemSlots.Length) ? __result : 0));
			flag = value.IsReservedItemSlot(__result);
			if (!flag2)
			{
				if (flag)
				{
					__result = (forward ? ((value.reservedHotbarStartIndex + reservedHotbarSize) % __instance.ItemSlots.Length) : (value.reservedHotbarStartIndex - 1));
				}
				return;
			}
			__result = (flag ? __result : (forward ? value.reservedHotbarStartIndex : (value.reservedHotbarStartIndex + reservedHotbarSize - 1)));
			int numHeldReservedItems = value.GetNumHeldReservedItems();
			while (numHeldReservedItems > 0 && __result != value.currentItemSlot && (Object)(object)__instance.ItemSlots[__result] == (Object)null)
			{
				__result += num;
				__result = ((!value.IsReservedItemSlot(__result)) ? (forward ? value.reservedHotbarStartIndex : (value.reservedHotbarStartIndex + reservedHotbarSize - 1)) : __result);
			}
		}

		[HarmonyPatch(typeof(HUDManager), "ClearControlTips")]
		[HarmonyPrefix]
		private static bool PreventClearControlTipsGrabbingReservedItem(HUDManager __instance)
		{
			return ReservedPlayerData.localPlayerData == null || (Object)(object)ReservedPlayerData.localPlayerData.grabbingReservedItem == (Object)null;
		}

		[HarmonyPatch(typeof(GrabbableObject), "SetControlTipsForItem")]
		[HarmonyPrefix]
		private static bool PreventUpdateControlTipsGrabbingReservedItem(GrabbableObject __instance)
		{
			return ReservedPlayerData.localPlayerData == null || (Object)(object)ReservedPlayerData.localPlayerData.grabbingReservedItem != (Object)(object)__instance;
		}

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

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

		public static bool ReservedItemIsBeingGrabbed(GrabbableObject grabbableObject)
		{
			if ((Object)(object)grabbableObject == (Object)null)
			{
				return false;
			}
			foreach (ReservedPlayerData value in ReservedPlayerData.allPlayerData.Values)
			{
				if ((Object)(object)grabbableObject == (Object)(object)value.grabbingReservedItem)
				{
					return true;
				}
			}
			return false;
		}

		public static void SetSpecialGrabAnimationBool(PlayerControllerB playerController, bool setTrue, GrabbableObject currentItem = null)
		{
			MethodInfo method = ((object)playerController).GetType().GetMethod("SetSpecialGrabAnimationBool", BindingFlags.Instance | BindingFlags.NonPublic);
			method.Invoke(playerController, new object[2] { setTrue, currentItem });
		}

		public static void SwitchToItemSlot(PlayerControllerB playerController, int slot, GrabbableObject fillSlotWithItem = null)
		{
			MethodInfo method = ((object)playerController).GetType().GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic);
			method.Invoke(playerController, new object[2] { slot, fillSlotWithItem });
			if (ReservedPlayerData.allPlayerData.TryGetValue(playerController, out var value))
			{
				value.timeSinceSwitchingSlots = 0f;
			}
		}
	}
	[HarmonyPatch]
	internal static class ReservedItemsPatcher
	{
		public static bool ignoreMeshOverride;

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

		[HarmonyPatch(typeof(GrabbableObject), "PocketItem")]
		[HarmonyPostfix]
		public static void OnPocketReservedItem(GrabbableObject __instance)
		{
			if (!ConfigSettings.showReservedItemsHolstered.Value || (Object)(object)__instance.playerHeldBy == (Object)null || !ReservedPlayerData.allPlayerData.TryGetValue(__instance.playerHeldBy, out var value) || !SessionManager.TryGetUnlockedItemData(__instance, out var itemData) || !value.IsItemInReservedItemSlot(__instance) || !itemData.showOnPlayerWhileHolstered)
			{
				return;
			}
			MeshRenderer[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<MeshRenderer>();
			foreach (MeshRenderer val in componentsInChildren)
			{
				if (!((Component)val).gameObject.CompareTag("DoNotSet") && !((Component)val).gameObject.CompareTag("InteractTrigger") && ((Component)val).gameObject.layer != 14 && ((Component)val).gameObject.layer != 22)
				{
					((Component)val).gameObject.layer = (value.isLocalPlayer ? 23 : 6);
				}
			}
			__instance.parentObject = value.boneMap.GetBone(itemData.holsteredParentBone);
			ForceEnableItemMesh(__instance, enabled: true);
		}

		[HarmonyPatch(typeof(GrabbableObject), "EquipItem")]
		[HarmonyPostfix]
		public static void OnEquipReservedItem(GrabbableObject __instance)
		{
			if (!ConfigSettings.showReservedItemsHolstered.Value || (Object)(object)__instance.playerHeldBy == (Object)null || !ReservedPlayerData.allPlayerData.TryGetValue(__instance.playerHeldBy, out var value) || !SessionManager.TryGetUnlockedItemData(__instance, out var itemData) || !value.IsItemInReservedItemSlot(__instance) || !itemData.showOnPlayerWhileHolstered)
			{
				return;
			}
			MeshRenderer[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<MeshRenderer>();
			foreach (MeshRenderer val in componentsInChildren)
			{
				if (!((Component)val).gameObject.CompareTag("DoNotSet") && !((Component)val).gameObject.CompareTag("InteractTrigger") && ((Component)val).gameObject.layer != 14 && ((Component)val).gameObject.layer != 22)
				{
					((Component)val).gameObject.layer = 6;
				}
			}
			__instance.parentObject = (value.isLocalPlayer ? __instance.playerHeldBy.localItemHolder : __instance.playerHeldBy.serverItemHolder);
		}

		[HarmonyPatch(typeof(GrabbableObject), "DiscardItem")]
		[HarmonyPostfix]
		public static void ResetReservedItemLayer(GrabbableObject __instance)
		{
			if (!SessionManager.TryGetUnlockedItemData(__instance, out var itemData) || !itemData.showOnPlayerWhileHolstered)
			{
				return;
			}
			MeshRenderer[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<MeshRenderer>();
			foreach (MeshRenderer val in componentsInChildren)
			{
				if (!((Component)val).gameObject.CompareTag("DoNotSet") && !((Component)val).gameObject.CompareTag("InteractTrigger") && ((Component)val).gameObject.layer != 14 && ((Component)val).gameObject.layer != 22)
				{
					((Component)val).gameObject.layer = 6;
				}
			}
		}

		[HarmonyPatch(typeof(GrabbableObject), "LateUpdate")]
		[HarmonyPostfix]
		public static void SetHolsteredPositionRotation(GrabbableObject __instance)
		{
			//IL_00ab: 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)
			//IL_00bb: 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_00d5: 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_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)
			if (ConfigSettings.showReservedItemsHolstered.Value && !((Object)(object)__instance.playerHeldBy == (Object)null) && !((Object)(object)__instance.parentObject == (Object)null) && ReservedPlayerData.allPlayerData.TryGetValue(__instance.playerHeldBy, out var value) && SessionManager.TryGetUnlockedItemData(__instance, out var itemData) && value.IsItemInReservedItemSlot(__instance) && itemData.showOnPlayerWhileHolstered && (Object)(object)__instance != (Object)(object)value.currentlySelectedItem)
			{
				Transform transform = ((Component)__instance.parentObject).transform;
				((Component)__instance).transform.rotation = ((Component)__instance.parentObject).transform.rotation * Quaternion.Euler(itemData.holsteredRotationOffset);
				((Component)__instance).transform.position = transform.position + transform.rotation * itemData.holsteredPositionOffset;
			}
		}

		[HarmonyPatch(typeof(GrabbableObject), "EnableItemMeshes")]
		[HarmonyPrefix]
		public static void OnEnableItemMeshes(ref bool enable, GrabbableObject __instance)
		{
			if (ConfigSettings.showReservedItemsHolstered.Value)
			{
				if ((Object)(object)__instance.playerHeldBy != (Object)null && !ignoreMeshOverride && ReservedPlayerData.allPlayerData.TryGetValue(__instance.playerHeldBy, out var value) && SessionManager.TryGetUnlockedItemData(__instance, out var itemData) && value.IsItemInReservedItemSlot(__instance) && itemData.showOnPlayerWhileHolstered && (Object)(object)value.currentlySelectedItem != (Object)(object)__instance && !PlayerPatcher.ReservedItemIsBeingGrabbed(__instance))
				{
					enable = true;
				}
				ignoreMeshOverride = false;
			}
		}

		public static void ForceEnableItemMesh(GrabbableObject grabbableObject, bool enabled)
		{
			ignoreMeshOverride = true;
			grabbableObject.EnableItemMeshes(enabled);
		}
	}
	[HarmonyPatch]
	internal static class SyncAlreadyHeldObjectsPatcher
	{
		[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesServerRpc")]
		[HarmonyPrefix]
		private static void SyncAlreadyHeldReservedObjectsClientRpc()
		{
		}

		[HarmonyPatch(typeof(StartOfRound), "SyncAlreadyHeldObjectsClientRpc")]
		[HarmonyPrefix]
		private static bool SyncAlreadyHeldReservedObjectsClientRpc(ref NetworkObjectReference[] gObjects, ref int[] playersHeldBy, ref int[] itemSlotNumbers, ref int[] isObjectPocketed, int syncWithClient, StartOfRound __instance)
		{
			if ((Object)(object)NetworkManager.Singleton == (Object)null || !NetworkManager.Singleton.IsListening)
			{
				return true;
			}
			if ((NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance) || (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)) && (!NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance) || (!NetworkManager.Singleton.IsClient && !NetworkManager.Singleton.IsHost) || syncWithClient != (int)NetworkManager.Singleton.LocalClientId))
			{
				return false;
			}
			bool flag = false;
			List<NetworkObjectReference> list = new List<NetworkObjectReference>(gObjects);
			List<int> list2 = new List<int>(playersHeldBy);
			List<int> list3 = new List<int>(itemSlotNumbers);
			List<int> list4 = new List<int>(isObjectPocketed);
			for (int num = itemSlotNumbers.Length - 1; num >= 0; num--)
			{
				if (itemSlotNumbers[num] >= __instance.localPlayerController.ItemSlots.Length)
				{
					list.RemoveAt(num);
					list2.RemoveAt(num);
					list3.RemoveAt(num);
					list4.Remove(num);
					flag = true;
				}
			}
			if (flag)
			{
				gObjects = list.ToArray();
				playersHeldBy = list2.ToArray();
				itemSlotNumbers = list3.ToArray();
				isObjectPocketed = list4.ToArray();
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class TerminalPatcher
	{
		public static Terminal terminalInstance;

		public static bool initializedTerminalNodes;

		public static ReservedItemSlotData purchasingItemSlot;

		[HarmonyPatch(typeof(Terminal), "Awake")]
		[HarmonyPrefix]
		public static void InitializeTerminal(Terminal __instance)
		{
			terminalInstance = __instance;
			initializedTerminalNodes = false;
			EditExistingTerminalNodes();
		}

		[HarmonyPatch(typeof(Terminal), "BeginUsingTerminal")]
		[HarmonyPrefix]
		public static void OnBeginUsingTerminal(Terminal __instance)
		{
			if (!initializedTerminalNodes && SyncManager.isSynced)
			{
				EditExistingTerminalNodes();
			}
		}

		public static void EditExistingTerminalNodes()
		{
			if (!SyncManager.isSynced)
			{
				return;
			}
			initializedTerminalNodes = true;
			if (!SyncManager.enablePurchasingItemSlots)
			{
				return;
			}
			foreach (TerminalNode specialNode in terminalInstance.terminalNodes.specialNodes)
			{
				if (((Object)specialNode).name == "Start" && !specialNode.displayText.Contains("[ReservedItemSlots]"))
				{
					string text = "Type \"Help\" for a list of commands.";
					int num = specialNode.displayText.IndexOf(text);
					if (num != -1)
					{
						num += text.Length;
						string value = "\n\n[ReservedItemSlots]\nType \"Reserved\" to purchase reserved item slots.";
						specialNode.displayText = specialNode.displayText.Insert(num, value);
					}
					else
					{
						Debug.LogError((object)"Failed to add reserved item slots tip to terminal. Maybe an update broke it?");
					}
				}
				else if (((Object)specialNode).name == "HelpCommands" && !specialNode.displayText.Contains(">RESERVED"))
				{
					string value2 = "[numberOfItemsOnRoute]";
					int num2 = specialNode.displayText.IndexOf(value2);
					if (num2 != -1)
					{
						string text2 = ">RESERVED\n";
						text2 += "Purchase reserved item slots.\n\n";
						specialNode.displayText = specialNode.displayText.Insert(num2, text2);
					}
				}
			}
		}

		[HarmonyPatch(typeof(Terminal), "TextPostProcess")]
		[HarmonyPrefix]
		public static void TextPostProcess(ref string modifiedDisplayText, TerminalNode node)
		{
			if (modifiedDisplayText.Length <= 0)
			{
				return;
			}
			string text = "[[[reservedItemSlotsSelectionList]]]";
			if (!modifiedDisplayText.Contains(text))
			{
				return;
			}
			int num = modifiedDisplayText.IndexOf(text);
			int num2 = num + text.Length;
			string oldValue = modifiedDisplayText.Substring(num, num2 - num);
			string text2 = "";
			if (!SyncManager.enablePurchasingItemSlots)
			{
				text2 += "Every reserved item slot is unlocked!\n\n";
			}
			else
			{
				text2 += "Reserved Item Slots\n------------------------------\n\n";
				text2 += "To purchase a reserved item slot, type the following command.\n> RESERVED [item_slot]\n\n";
				int num3 = 0;
				foreach (ReservedItemSlotData value in SyncManager.unlockableReservedItemSlotsDict.Values)
				{
					num3 = Mathf.Max(num3, value.slotName.Length);
				}
				foreach (ReservedItemSlotData value2 in SyncManager.unlockableReservedItemSlotsDict.Values)
				{
					string arg = (SessionManager.IsItemSlotUnlocked(value2) ? "[Purchased]" : ("$" + value2.purchasePrice));
					text2 += $"* {value2.slotDisplayName}{new string(' ', num3 - value2.slotDisplayName.Length)}   //   {arg}\n";
				}
			}
			modifiedDisplayText = modifiedDisplayText.Replace(oldValue, text2);
		}

		[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
		[HarmonyPrefix]
		public static bool ParsePlayerSentence(ref TerminalNode __result, Terminal __instance)
		{
			if (__instance.screenText.text.Length <= 0)
			{
				return true;
			}
			string text = __instance.screenText.text.Substring(__instance.screenText.text.Length - __instance.textAdded).ToLower();
			string[] array = text.Split(new char[1] { ' ' });
			ReservedItemSlotData reservedItemSlotData = null;
			if (!SyncManager.isSynced)
			{
				if (text.StartsWith("reserved"))
				{
					__result = BuildTerminalNodeHostDoesNotHaveMod();
					return false;
				}
				return true;
			}
			if (purchasingItemSlot != null)
			{
				if ("confirm".StartsWith(text))
				{
					if (purchasingItemSlot.isUnlocked)
					{
						Debug.LogWarning((object)("Attempted to confirm purchase on reserved item slot that was already unlocked. Item slot: " + purchasingItemSlot.slotDisplayName));
						__result = BuildTerminalNodeAlreadyUnlocked(purchasingItemSlot);
					}
					else if (terminalInstance.groupCredits < purchasingItemSlot.purchasePrice)
					{
						Debug.LogWarning((object)("Attempted to confirm purchase with insufficient credits. Current credits: " + terminalInstance.groupCredits + " Required credits: " + purchasingItemSlot.purchasePrice));
						__result = BuildTerminalNodeInsufficientFunds(purchasingItemSlot);
					}
					else
					{
						Debug.Log((object)("Purchasing reserved item slot: " + purchasingItemSlot.slotDisplayName + ". Price: " + purchasingItemSlot.purchasePrice));
						Terminal obj = terminalInstance;
						obj.groupCredits -= purchasingItemSlot.purchasePrice;
						terminalInstance.BuyItemsServerRpc(new int[0], terminalInstance.groupCredits, terminalInstance.numberOfItemsInDropship);
						SyncManager.SendUnlockItemSlotUpdateToServer(purchasingItemSlot.slotId);
						__result = BuildTerminalNodeOnPurchased(purchasingItemSlot, terminalInstance.groupCredits);
					}
				}
				else
				{
					Plugin.Log("Canceling order.");
					__result = BuildCustomTerminalNode("Canceled order.\n\n");
				}
				purchasingItemSlot = null;
				return false;
			}
			purchasingItemSlot = null;
			if (array.Length == 0 || array[0] != "reserved")
			{
				return true;
			}
			if (array.Length == 1)
			{
				__result = BuildTerminalNodeHome();
				return false;
			}
			string text2 = text.Substring(9);
			reservedItemSlotData = TryGetReservedItemSlot(text2);
			if (reservedItemSlotData != null)
			{
				if (SessionManager.IsItemSlotUnlocked(reservedItemSlotData))
				{
					Plugin.LogWarning("Attempted to start purchase on reserved item slot that was already unlocked. Item slot: " + reservedItemSlotData.slotName);
					__result = BuildTerminalNodeAlreadyUnlocked(reservedItemSlotData);
				}
				else if (terminalInstance.groupCredits < reservedItemSlotData.purchasePrice)
				{
					Plugin.LogWarning("Attempted to start purchase with insufficient credits. Current credits: " + terminalInstance.groupCredits + ". Item slot price: " + reservedItemSlotData.purchasePrice);
					__result = BuildTerminalNodeInsufficientFunds(reservedItemSlotData);
				}
				else
				{
					Plugin.Log("Started purchasing reserved item slot: " + reservedItemSlotData.slotName);
					purchasingItemSlot = reservedItemSlotData;
					__result = BuildTerminalNodeConfirmDenyPurchase(reservedItemSlotData);
				}
				return false;
			}
			Plugin.LogWarning("Attempted to start purchase on invalid reserved item slot. Item slot: " + text2);
			__result = BuildTerminalNodeInvalidReservedItemSlot(text2);
			return false;
		}

		private static TerminalNode BuildTerminalNodeHome()
		{
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			return new TerminalNode
			{
				displayText = "[ReservedItemSlots]\n\nStore\n------------------------------\n[[[reservedItemSlotsSelectionList]]]\n\n",
				clearPreviousText = true,
				acceptAnything = false
			};
		}

		private static TerminalNode BuildTerminalNodeConfirmDenyPurchase(ReservedItemSlotData itemSlotData)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			TerminalNode val = new TerminalNode();
			val.displayText = "You have requested to purchase a reserved item slot for $" + itemSlotData.purchasePrice + " credits.\n> [" + itemSlotData.slotDisplayName + "]\n\n";
			val.isConfirmationNode = true;
			val.acceptAnything = false;
			val.clearPreviousText = true;
			TerminalNode val2 = val;
			val2.displayText = val2.displayText + "Credit balance: $" + terminalInstance.groupCredits + "\n";
			val2.displayText += "\n";
			val2.displayText += "Please CONFIRM or DENY.\n\n";
			return val2;
		}

		private static TerminalNode BuildTerminalNodeOnPurchased(ReservedItemSlotData itemSlotData, int newGroupCredits)
		{
			//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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			TerminalNode val = new TerminalNode
			{
				displayText = "You have successfully purchased a new reserved item slot!\n> [" + itemSlotData.slotDisplayName + "]\n\n",
				buyUnlockable = true,
				clearPreviousText = true,
				acceptAnything = false,
				playSyncedClip = 0
			};
			val.displayText = val.displayText + "New credit balance: $" + newGroupCredits + "\n\n";
			return val;
		}

		private static TerminalNode BuildTerminalNodeAlreadyUnlocked(ReservedItemSlotData itemSlot)
		{
			//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_0021: 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_0030: Expected O, but got Unknown
			return new TerminalNode
			{
				displayText = "You have already purchased this reserved item slot!\n> [" + itemSlot.slotDisplayName + "]\n\n",
				clearPreviousText = false,
				acceptAnything = false
			};
		}

		private static TerminalNode BuildTerminalNodeInsufficientFunds(ReservedItemSlotData itemSlot)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			TerminalNode val = new TerminalNode();
			val.displayText = "You could not afford this reserved item slot!\n> [" + itemSlot.slotDisplayName + "]\n\nCredit balance is $" + terminalInstance.groupCredits + "\n";
			val.clearPreviousText = true;
			val.acceptAnything = false;
			TerminalNode val2 = val;
			val2.displayText = val2.displayText + "Price of reserved item slot is $" + itemSlot.purchasePrice + "\n\n";
			return val2;
		}

		private static TerminalNode BuildTerminalNodeInvalidReservedItemSlot(string reservedItemSlotName = "")
		{
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			TerminalNode val = new TerminalNode
			{
				displayText = "Reserved item slot does not exist.",
				clearPreviousText = false,
				acceptAnything = false
			};
			if (reservedItemSlotName != "")
			{
				val.displayText = val.displayText + "\n\"" + reservedItemSlotName + "\"";
			}
			val.displayText += "\n";
			return val;
		}

		private static TerminalNode BuildTerminalNodeHostDoesNotHaveMod(string itemSlotName = "")
		{
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			TerminalNode val = new TerminalNode
			{
				displayText = "You cannot use the reserved item slot commands until you have synced with the host.\n\nYou may also be seeing this because the host does not have this mod.\n\n",
				clearPreviousText = true,
				acceptAnything = false
			};
			if (itemSlotName != "")
			{
				val.displayText = val.displayText + "\n\"" + itemSlotName + "\"";
			}
			val.displayText += "\n";
			return val;
		}

		private static TerminalNode BuildCustomTerminalNode(string displayText, bool clearPreviousText = false, bool acceptAnything = false, bool isConfirmationNode = false)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			return new TerminalNode
			{
				displayText = displayText,
				clearPreviousText = clearPreviousText,
				acceptAnything = false,
				isConfirmationNode = isConfirmationNode
			};
		}

		private static ReservedItemSlotData TryGetReservedItemSlot(string itemSlotNameInput)
		{
			ReservedItemSlotData reservedItemSlotData = null;
			foreach (ReservedItemSlotData unlockableReservedItemSlot in SyncManager.unlockableReservedItemSlots)
			{
				string text = unlockableReservedItemSlot.slotDisplayName.ToLower();
				if ((itemSlotNameInput == text || (itemSlotNameInput.Length >= 4 && text.StartsWith(itemSlotNameInput))) && (reservedItemSlotData == null || text.Length < reservedItemSlotData.slotDisplayName.Length) && !"the company".StartsWith(itemSlotNameInput) && !"company".StartsWith(itemSlotNameInput))
				{
					reservedItemSlotData = unlockableReservedItemSlot;
				}
			}
			return reservedItemSlotData;
		}
	}
}
namespace ReservedItemSlotCore.Networking
{
	internal static class NetworkHelper
	{
		private static int NONE_EXEC_STAGE = 0;

		private static int SERVER_EXEC_STAGE = 1;

		private static int CLIENT_EXEC_STAGE = 2;

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

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

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

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

		public static List<ReservedItemSlotData> unlockableReservedItemSlots = new List<ReservedItemSlotData>();

		public static Dictionary<string, ReservedItemSlotData> unlockableReservedItemSlotsDict = new Dictionary<string, ReservedItemSlotData>();

		public static List<ReservedItemData> reservedItems = new List<ReservedItemData>();

		public static Dictionary<string, ReservedItemData> reservedItemsDict = new Dictionary<string, ReservedItemData>();

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

		public static bool enablePurchasingItemSlots { get; internal set; } = false;


		internal static bool canUseModDisabledOnHost => ConfigSettings.forceEnableThisModIfNotEnabledOnHost.Value;

		public static bool isSynced { get; internal set; } = false;


		public static bool IsReservedItem(string itemName)
		{
			foreach (ReservedItemSlotData unlockableReservedItemSlot in unlockableReservedItemSlots)
			{
				if (unlockableReservedItemSlot.ContainsItem(itemName))
				{
					return true;
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		public static void ResetValues(StartOfRound __instance)
		{
			isSynced = false;
			requestedSyncHeldObjects = false;
			unlockableReservedItemSlots?.Clear();
			unlockableReservedItemSlotsDict?.Clear();
			enablePurchasingItemSlots = false;
			reservedItems?.Clear();
			reservedItemsDict?.Clear();
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void Init(PlayerControllerB __instance)
		{
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Expected O, but got Unknown
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Expected O, but got Unknown
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bb: Expected O, but got Unknown
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Expected O, but got Unknown
			//IL_00aa: 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_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Expected O, but got Unknown
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Expected O, but got Unknown
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Expected O, but got Unknown
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Expected O, but got Unknown
			if (NetworkManager.Singleton.IsServer)
			{
				enablePurchasingItemSlots = ConfigSettings.enablePurchasingItemSlots.Value;
				unlockableReservedItemSlots = new List<ReservedItemSlotData>();
				unlockableReservedItemSlotsDict = new Dictionary<string, ReservedItemSlotData>();
				foreach (ReservedItemSlotData value in ReservedItemSlotData.allReservedItemSlotData.Values)
				{
					ReservedItemSlotData reservedItemSlotData = new ReservedItemSlotData(value.slotName, value.slotPriority, (int)((float)value.purchasePrice * ConfigSettings.globalItemSlotPriceModifier.Value));
					foreach (ReservedItemData value2 in value.reservedItemData.Values)
					{
						reservedItemSlotData.AddItemToReservedItemSlot(new ReservedItemData(value2.itemName, value2.holsteredParentBone, value2.holsteredPositionOffset, value2.holsteredRotationOffset));
					}
					AddReservedItemSlotData(reservedItemSlotData);
					if (!enablePurchasingItemSlots)
					{
						SessionManager.UnlockReservedItemSlot(reservedItemSlotData);
					}
				}
				if (enablePurchasingItemSlots)
				{
					SessionManager.LoadGameValues();
				}
				if (enablePurchasingItemSlots)
				{
					foreach (ReservedItemSlotData unlockableReservedItemSlot in unlockableReservedItemSlots)
					{
						if (!unlockableReservedItemSlot.isUnlocked && unlockableReservedItemSlot.purchasePrice <= 0)
						{
							SessionManager.UnlockReservedItemSlot(unlockableReservedItemSlot);
						}
					}
				}
				isSynced = true;
				OnSyncedWithServer();
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlotCore.OnSwapHotbarServerRpc", new HandleNamedMessageDelegate(OnSwapHotbarServerRpc));
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlotCore.RequestSyncServerRpc", new HandleNamedMessageDelegate(RequestSyncServerRpc));
				NetworkManager.Singleton.CustomMe

plugins/FlipMods-ReservedWalkieSlot/ReservedWalkieSlot.dll

Decompiled 3 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.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using ReservedItemSlotCore;
using ReservedItemSlotCore.Config;
using ReservedItemSlotCore.Data;
using ReservedWalkieSlot.Config;
using ReservedWalkieSlot.Patches;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ReservedWalkieSlot")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReservedWalkieSlot")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("c15c320f-d8fc-4f1c-be3c-f2d2ffc41edd")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ReservedWalkieSlot
{
	[BepInPlugin("FlipMods.ReservedWalkieSlot", "ReservedWalkieSlot", "2.0.5")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		private static ManualLogSource logger;

		private Harmony _harmony;

		public static ReservedItemSlotData walkieSlotData;

		public static ReservedItemData walkieData;

		public static List<ReservedItemData> additionalItemData = new List<ReservedItemData>();

		private void Awake()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			instance = this;
			CreateCustomLogger();
			ConfigSettings.BindConfigSettings();
			CreateReservedItemSlots();
			CreateAdditionalReservedItemSlots();
			_harmony = new Harmony("ReservedWalkieSlot");
			PatchAll();
			Log("ReservedWalkieSlot loaded");
		}

		private void CreateReservedItemSlots()
		{
			//IL_003e: 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_0061: Expected O, but got Unknown
			walkieSlotData = ReservedItemSlotData.CreateReservedItemSlotData("walkie_talkie", ConfigSettings.overrideItemSlotPriority.Value, ConfigSettings.overridePurchasePrice.Value);
			walkieData = walkieSlotData.AddItemToReservedItemSlot(new ReservedItemData("Walkie-talkie", (PlayerBone)4, new Vector3(0.15f, -0.05f, 0.25f), new Vector3(0f, -90f, 100f)));
		}

		private void CreateAdditionalReservedItemSlots()
		{
			//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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			string[] array = ConfigSettings.ParseAdditionalItems();
			string[] array2 = array;
			foreach (string text in array2)
			{
				if (!walkieSlotData.ContainsItem(text))
				{
					LogWarning("Adding additional item to reserved item slot. Item: " + text);
					ReservedItemData val = new ReservedItemData(text, (PlayerBone)0, default(Vector3), default(Vector3));
					additionalItemData.Add(val);
					walkieSlotData.AddItemToReservedItemSlot(val);
				}
			}
		}

		private void PatchAll()
		{
			IEnumerable<Type> enumerable;
			try
			{
				enumerable = Assembly.GetExecutingAssembly().GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				enumerable = ex.Types.Where((Type t) => t != null);
			}
			foreach (Type item in enumerable)
			{
				_harmony.PatchAll(item);
			}
		}

		private void CreateCustomLogger()
		{
			try
			{
				logger = Logger.CreateLogSource($"{((BaseUnityPlugin)this).Info.Metadata.Name}-{((BaseUnityPlugin)this).Info.Metadata.Version}");
			}
			catch
			{
				logger = ((BaseUnityPlugin)this).Logger;
			}
		}

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

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

		public static void LogWarning(string message)
		{
			logger.LogWarning((object)message);
		}

		public static bool IsModLoaded(string guid)
		{
			return Chainloader.PluginInfos.ContainsKey(guid);
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FlipMods.ReservedWalkieSlot";

		public const string PLUGIN_NAME = "ReservedWalkieSlot";

		public const string PLUGIN_VERSION = "2.0.5";
	}
}
namespace ReservedWalkieSlot.Patches
{
	[HarmonyPatch(typeof(ShipBuildModeManager), "PlayerMeetsConditionsToBuild")]
	public class PlayerMeetsConditionsToBuildPatcher
	{
		private static bool activatingWalkie;

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

		public static void Prefix(ShipBuildModeManager __instance)
		{
			if (!((Object)(object)localPlayerController == (Object)null))
			{
				activatingWalkie = localPlayerController.activatingItem;
				WalkieTalkie mainWalkie = WalkiePatcher.GetMainWalkie(localPlayerController);
				if (!((Object)(object)mainWalkie == (Object)null) && !((Object)(object)((GrabbableObject)mainWalkie).playerHeldBy == (Object)null) && !((Object)(object)((GrabbableObject)mainWalkie).playerHeldBy != (Object)(object)localPlayerController) && localPlayerController.activatingItem && mainWalkie.speakingIntoWalkieTalkie)
				{
					localPlayerController.activatingItem = false;
				}
			}
		}

		public static void Postfix(ShipBuildModeManager __instance)
		{
			if (!((Object)(object)localPlayerController == (Object)null))
			{
				localPlayerController.activatingItem = activatingWalkie;
			}
		}
	}
	[HarmonyPatch]
	public static class WalkiePatcher
	{
		public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController;

		public static WalkieTalkie GetMainWalkie(PlayerControllerB playerController)
		{
			return GetCurrentlySelectedWalkie(playerController) ?? GetReservedWalkie(playerController);
		}

		public static WalkieTalkie GetReservedWalkie(PlayerControllerB playerController)
		{
			ReservedItemSlotData val = default(ReservedItemSlotData);
			ReservedPlayerData value;
			return (WalkieTalkie)((SessionManager.TryGetUnlockedItemSlotData(Plugin.walkieSlotData.slotName, ref val) && ReservedPlayerData.allPlayerData.TryGetValue(playerController, out value)) ? /*isinst with value type is only supported in some contexts*/: null);
		}

		public static WalkieTalkie GetCurrentlySelectedWalkie(PlayerControllerB playerController)
		{
			return (WalkieTalkie)((playerController.currentItemSlot >= 0 && playerController.currentItemSlot < playerController.ItemSlots.Length) ? /*isinst with value type is only supported in some contexts*/: null);
		}
	}
}
namespace ReservedWalkieSlot.Input
{
	internal class IngameKeybinds : LcInputActions
	{
		internal static IngameKeybinds Instance = new IngameKeybinds();

		[InputAction("<Keyboard>/x", Name = "[ReservedItemSlots]\nActivate walkie")]
		public InputAction ActivateWalkieHotkey { get; set; }

		internal static InputActionAsset GetAsset()
		{
			return ((LcInputActions)Instance).Asset;
		}
	}
	internal class InputUtilsCompat
	{
		internal static InputActionAsset Asset => IngameKeybinds.GetAsset();

		internal static bool Enabled => Plugin.IsModLoaded("com.rune580.LethalCompanyInputUtils");

		public static InputAction ActivateWalkieHotkey => IngameKeybinds.Instance.ActivateWalkieHotkey;
	}
	[HarmonyPatch]
	internal static class Keybinds
	{
		public static InputActionAsset Asset;

		public static InputActionMap ActionMap;

		private static InputAction ActivateWalkieAction;

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

		[HarmonyPatch(typeof(PreInitSceneScript), "Awake")]
		[HarmonyPrefix]
		public static void AddToKeybindMenu()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			Plugin.Log("Initializing hotkeys.");
			if (InputUtilsCompat.Enabled)
			{
				Asset = InputUtilsCompat.Asset;
				ActionMap = Asset.actionMaps[0];
				ActivateWalkieAction = InputUtilsCompat.ActivateWalkieHotkey;
			}
			else
			{
				Asset = ScriptableObject.CreateInstance<InputActionAsset>();
				ActionMap = new InputActionMap("ReservedItemSlots");
				InputActionSetupExtensions.AddActionMap(Asset, ActionMap);
				ActivateWalkieAction = InputActionSetupExtensions.AddAction(ActionMap, "ReservedItemSlots.ActivateWalkie", (InputActionType)0, "<keyboard>/x", (string)null, (string)null, (string)null, (string)null);
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "OnEnable")]
		[HarmonyPostfix]
		public static void OnEnable()
		{
			Asset.Enable();
			ActivateWalkieAction.performed += OnPressWalkieButtonPerformed;
			ActivateWalkieAction.canceled += OnReleaseWalkieButtonPerformed;
		}

		[HarmonyPatch(typeof(StartOfRound), "OnDisable")]
		[HarmonyPostfix]
		public static void OnDisable()
		{
			Asset.Disable();
			ActivateWalkieAction.performed -= OnPressWalkieButtonPerformed;
			ActivateWalkieAction.canceled -= OnReleaseWalkieButtonPerformed;
		}

		private static void OnPressWalkieButtonPerformed(CallbackContext context)
		{
			if ((Object)(object)localPlayerController == (Object)null || !localPlayerController.isPlayerControlled || (((NetworkBehaviour)localPlayerController).IsServer && !localPlayerController.isHostPlayerObject))
			{
				return;
			}
			WalkieTalkie mainWalkie = WalkiePatcher.GetMainWalkie(localPlayerController);
			if (((CallbackContext)(ref context)).performed && !((Object)(object)mainWalkie == (Object)null) && ((GrabbableObject)mainWalkie).isBeingUsed && !ShipBuildModeManager.Instance.InBuildMode && !localPlayerController.isTypingChat && !localPlayerController.quickMenuManager.isMenuOpen && !localPlayerController.isPlayerDead && !ReservedPlayerData.localPlayerData.isGrabbingReservedItem)
			{
				float num = (float)Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").GetValue();
				if (!(num < 0.075f))
				{
					((GrabbableObject)mainWalkie).UseItemOnClient(true);
					Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0);
				}
			}
		}

		private static void OnReleaseWalkieButtonPerformed(CallbackContext context)
		{
			if (!((Object)(object)localPlayerController == (Object)null) && localPlayerController.isPlayerControlled && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject))
			{
				WalkieTalkie mainWalkie = WalkiePatcher.GetMainWalkie(localPlayerController);
				if (((CallbackContext)(ref context)).canceled && !((Object)(object)mainWalkie == (Object)null))
				{
					((GrabbableObject)mainWalkie).UseItemOnClient(false);
				}
			}
		}
	}
}
namespace ReservedWalkieSlot.Config
{
	public static class ConfigSettings
	{
		public static ConfigEntry<int> overrideItemSlotPriority;

		public static ConfigEntry<int> overridePurchasePrice;

		public static ConfigEntry<string> additionalItemsInSlot;

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

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			overrideItemSlotPriority = AddConfigEntry<int>(((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server-side", "WalkieSlotPriorityOverride", 150, "[Host only] Manually set the priority for this item slot. Higher priority slots will come first in the reserved item slots, which will appear below the other slots. Negative priority items will appear on the left side of the screen, this is disabled in the core mod's config."));
			overridePurchasePrice = AddConfigEntry<int>(((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server-side", "WalkieSlotPriceOverride", 150, "[Host only] Manually set the price for this item in the store. Setting 0 will force this item to be unlocked immediately after the game starts."));
			additionalItemsInSlot = AddConfigEntry<string>(((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Server-side", "AdditionalItemsInSlot", "", "[Host only] Syntax: \"Item1,Item name2\" (without quotes). When adding items, use the item's name as it appears in game. Include spaces if there are spaces in the item name. Adding items that do not exist, or that are from a mod which is not enabled will not cause any problems.\nNOTE: IF YOU ARE USING A TRANSLATION MOD, YOU MAY NEED TO ADD THE TRANSLATED NAME OF ANY ITEM YOU WANT IN THIS SLOT."));
			additionalItemsInSlot.Value = additionalItemsInSlot.Value.Replace(", ", ",");
			TryRemoveOldConfigSettings();
		}

		public static ConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			currentConfigEntries.Add(((ConfigEntryBase)configEntry).Definition.Key, (ConfigEntryBase)(object)configEntry);
			return configEntry;
		}

		public static string[] ParseAdditionalItems()
		{
			return ConfigSettings.ParseItemNames(additionalItemsInSlot.Value);
		}

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

plugins/GameyStew-HutchersonWhistle/Hutcherson Whistle.dll

Decompiled 3 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using CustomEmotesAPI_Template_Mod;
using EmotesAPI;
using Hutcherson_Whistle;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Hutcherson Whistle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Hutcherson Whistle")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("a9e43460-d5a9-4333-a690-b426cb3bb807")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[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 Hutcherson_Whistle
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("com.gameystew6.hutchersonwhistle", "hutchersonwhistle", "1.0.0")]
	public class Whistle : BaseUnityPlugin
	{
		public const string PluginGUID = "com.gameystew6.hutchersonwhistle";

		public const string PluginName = "hutchersonwhistle";

		public const string PluginVersion = "1.0.0";

		public static Whistle instance;

		public static PluginInfo PInfo { get; private set; }

		public void Awake()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			//IL_00bd: 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_00f3: Expected O, but got Unknown
			instance = this;
			PInfo = ((BaseUnityPlugin)this).Info;
			Assets.LoadAssetBundlesFromFolder();
			AnimationClipParams val = new AnimationClipParams();
			val.animationClip = (AnimationClip[])(object)new AnimationClip[1] { Assets.Load<AnimationClip>("assets/whistle.anim") };
			val.secondaryAnimation = (AnimationClip[])(object)new AnimationClip[1] { Assets.Load<AnimationClip>("assets/whistle2.anim") };
			val.looping = true;
			val._primaryAudioClips = (AudioClip[])(object)new AudioClip[1] { Assets.Load<AudioClip>("assets/whistleaudio.mp3") };
			val._secondaryAudioClips = null;
			val._primaryDMCAFreeAudioClips = null;
			val._secondaryDMCAFreeAudioClips = null;
			val.visible = true;
			val.syncAnim = false;
			val.syncAudio = false;
			val.startPref = -1;
			val.joinPref = -1;
			val.joinSpots = null;
			val.customName = "Josh Hutcherson Whistle";
			val.lockType = (LockType)1;
			val.willGetClaimedByDMCA = true;
			val.audioLevel = 1f;
			val.stopWhenMove = true;
			CustomEmotesAPI.AddCustomAnimation(val);
			CustomEmotesAPI.animChanged += new AnimationChanged(CustomEmotesAPI_animChanged);
		}

		private void CustomEmotesAPI_animChanged(string newAnimation, BoneMapper mapper)
		{
			if (newAnimation == "whistle")
			{
				DebugClass.Log((object)"we whistled");
			}
		}
	}
}
namespace CustomEmotesAPI_Template_Mod
{
	public static class Assets
	{
		internal static readonly List<AssetBundle> AssetBundles = new List<AssetBundle>();

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

		public static void LoadAssetBundlesFromFolder()
		{
			string directoryName = Path.GetDirectoryName(Whistle.PInfo.Location);
			Console.WriteLine(directoryName);
			string[] files = Directory.GetFiles(directoryName);
			foreach (string text in files)
			{
				try
				{
					AssetBundle val = AssetBundle.LoadFromFile(text);
					int count = AssetBundles.Count;
					AssetBundles.Add(val);
					string[] allAssetNames = val.GetAllAssetNames();
					foreach (string text2 in allAssetNames)
					{
						string text3 = text2.ToLowerInvariant();
						if (text3.StartsWith("assets/"))
						{
							text3 = text3.Remove(0, "assets/".Length);
						}
						AssetIndices[text3] = count;
					}
					DebugClass.Log((object)("Loaded AssetBundle: " + Path.GetFileName(text)));
				}
				catch (Exception arg)
				{
					DebugClass.Log((object)$"AssetBundle Load Failed:  {arg}");
				}
			}
		}

		public static T Load<T>(string assetName) where T : Object
		{
			try
			{
				assetName = assetName.ToLowerInvariant();
				if (assetName.Contains(":"))
				{
					string[] array = assetName.Split(':');
					assetName = array[1].ToLowerInvariant();
				}
				if (assetName.StartsWith("assets/"))
				{
					assetName = assetName.Remove(0, "assets/".Length);
				}
				int index = AssetIndices[assetName];
				return AssetBundles[index].LoadAsset<T>("assets/" + assetName);
			}
			catch (Exception arg)
			{
				DebugClass.Log((object)$"Couldn't load asset [{assetName}] reason: {arg}");
				return default(T);
			}
		}
	}
}

plugins/Gemumoddo-LethalEmotesAPI/LethalEmotesAPI.dll

Decompiled 3 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.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using AdvancedCompany.Game;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BetterEmote.AssetScripts;
using BetterEmote.Patches;
using BetterEmote.Utils;
using EmotesAPI;
using GameNetcodeStuff;
using HarmonyLib;
using JetBrains.Annotations;
using LethalCompanyInputUtils.Api;
using LethalConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using LethalEmotesAPI;
using LethalEmotesAPI.Core;
using LethalEmotesAPI.Data;
using LethalEmotesAPI.ImportV2;
using LethalEmotesAPI.NetcodePatcher;
using LethalEmotesAPI.Patches;
using LethalEmotesAPI.Patches.ModCompat;
using LethalEmotesAPI.Utils;
using LethalEmotesApi.Ui;
using LethalEmotesApi.Ui.Data;
using LethalEmotesApi.Ui.Db;
using LethalEmotesApi.Ui.Dmca;
using LethalVRM;
using Microsoft.CodeAnalysis;
using ModelReplacement;
using MonoMod.RuntimeDetour;
using MoreCompany.Cosmetics;
using Newtonsoft.Json;
using TMPro;
using TooManyEmotes;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("BetterEmotes")]
[assembly: IgnoresAccessChecksTo("LethalVRM")]
[assembly: IgnoresAccessChecksTo("MToon")]
[assembly: IgnoresAccessChecksTo("UniGLTF")]
[assembly: IgnoresAccessChecksTo("UniGLTF.Utils")]
[assembly: IgnoresAccessChecksTo("UniHumanoid")]
[assembly: IgnoresAccessChecksTo("VRM10")]
[assembly: IgnoresAccessChecksTo("VrmLib")]
[assembly: IgnoresAccessChecksTo("VRMShaders.GLTF.IO.Runtime")]
[assembly: IgnoresAccessChecksTo("VRMShaders.VRM.IO.Runtime")]
[assembly: IgnoresAccessChecksTo("VRMShaders.VRM10.Format.Runtime")]
[assembly: IgnoresAccessChecksTo("VRMShaders.VRM10.MToon10.Runtime")]
[assembly: AssemblyCompany("LethalEmotesAPI")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+55a1e71f9c35eedd9ce7791eeb50354e32e3daff")]
[assembly: AssemblyProduct("LethalEmotesAPI")]
[assembly: AssemblyTitle("LethalEmotesAPI")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal static class AnimationReplacements
{
	internal static GameObject g;

	internal static bool setup;

	internal static void RunAll()
	{
		ChangeAnims();
	}

	internal static BoneMapper Import(GameObject prefab, string skeleton, int[] pos, bool hidemesh = true)
	{
		GameObject val = Object.Instantiate<GameObject>(Assets.Load<GameObject>("@CustomEmotesAPI_customemotespackage:assets/animationreplacements/commando.prefab"));
		GameObject val2 = Object.Instantiate<GameObject>(Assets.Load<GameObject>(skeleton));
		val2.GetComponent<Animator>().runtimeAnimatorController = val.GetComponent<Animator>().runtimeAnimatorController;
		BoneMapper result = ApplyAnimationStuff(prefab, val2, pos, hidemesh, jank: false, revertBonePositions: true);
		val.transform.SetParent(val2.transform);
		return result;
	}

	public static void DebugBones(GameObject fab)
	{
		SkinnedMeshRenderer[] componentsInChildren = fab.GetComponentsInChildren<SkinnedMeshRenderer>();
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append($"rendererererer: {componentsInChildren[0]}\n");
		stringBuilder.Append($"bone count: {componentsInChildren[0].bones.Length}\n");
		stringBuilder.Append($"mesh count: {componentsInChildren.Length}\n");
		stringBuilder.Append("root bone: " + ((Object)componentsInChildren[0].rootBone).name + "\n");
		stringBuilder.Append(((object)fab).ToString() + ":\n");
		SkinnedMeshRenderer[] array = componentsInChildren;
		foreach (SkinnedMeshRenderer val in array)
		{
			if (val.bones.Length == 0)
			{
				stringBuilder.Append("No bones");
			}
			else
			{
				stringBuilder.Append("[");
				Transform[] bones = val.bones;
				foreach (Transform val2 in bones)
				{
					stringBuilder.Append("'" + ((Object)val2).name + "', ");
				}
				stringBuilder.Remove(stringBuilder.Length - 2, 2);
				stringBuilder.Append("]");
			}
			stringBuilder.Append("\n\n");
			DebugClass.Log(stringBuilder.ToString());
		}
	}

	internal static void ChangeAnims()
	{
	}

	internal static void ApplyAnimationStuff(GameObject bodyPrefab, string resource, int[] pos)
	{
		GameObject animcontroller = Assets.Load<GameObject>(resource);
		ApplyAnimationStuff(bodyPrefab, animcontroller, pos);
	}

	internal static BoneMapper ApplyAnimationStuff(GameObject bodyPrefab, GameObject animcontroller, int[] pos, bool hidemeshes = true, bool jank = false, bool revertBonePositions = false)
	{
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		//IL_0118: Unknown result type (might be due to invalid IL or missing references)
		//IL_022a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0243: 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_026e: Unknown result type (might be due to invalid IL or missing references)
		//IL_027f: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (!animcontroller.GetComponentInChildren<Animator>().avatar.isHuman)
			{
				DebugClass.Log($"{animcontroller}'s avatar isn't humanoid, please fix it in unity!");
				return null;
			}
		}
		catch (Exception arg)
		{
			DebugClass.Log($"Had issue checking if avatar was humanoid: {arg}");
			throw;
		}
		try
		{
			if (hidemeshes)
			{
				SkinnedMeshRenderer[] componentsInChildren = animcontroller.GetComponentsInChildren<SkinnedMeshRenderer>();
				foreach (SkinnedMeshRenderer val in componentsInChildren)
				{
					val.sharedMesh = null;
				}
				MeshFilter[] componentsInChildren2 = animcontroller.GetComponentsInChildren<MeshFilter>();
				foreach (MeshFilter val2 in componentsInChildren2)
				{
					val2.sharedMesh = null;
				}
			}
		}
		catch (Exception arg2)
		{
			DebugClass.Log($"Had trouble while hiding meshes: {arg2}");
			throw;
		}
		Transform transform = ((Component)bodyPrefab.GetComponentInChildren<Animator>()).transform;
		try
		{
			animcontroller.transform.parent = transform;
			animcontroller.transform.localPosition = Vector3.zero;
			animcontroller.transform.eulerAngles = bodyPrefab.transform.eulerAngles;
			animcontroller.transform.localScale = Vector3.one;
		}
		catch (Exception arg3)
		{
			DebugClass.Log($"Had trouble setting emote skeletons parent: {arg3}");
			throw;
		}
		SkinnedMeshRenderer[] array = (SkinnedMeshRenderer[])(object)new SkinnedMeshRenderer[pos.Length];
		SkinnedMeshRenderer emoteSkeletonSMR;
		try
		{
			emoteSkeletonSMR = animcontroller.GetComponentsInChildren<SkinnedMeshRenderer>()[0];
		}
		catch (Exception arg4)
		{
			DebugClass.Log($"Had trouble setting emote skeletons SkinnedMeshRenderer: {arg4}");
			throw;
		}
		try
		{
			for (int k = 0; k < pos.Length; k++)
			{
				array[k] = bodyPrefab.GetComponentsInChildren<SkinnedMeshRenderer>()[pos[k]];
			}
		}
		catch (Exception arg5)
		{
			DebugClass.Log($"Had trouble setting the original skeleton's skinned mesh renderer: {arg5}");
			throw;
		}
		BoneMapper boneMapper = animcontroller.AddComponent<BoneMapper>();
		try
		{
			boneMapper.jank = jank;
			boneMapper.emoteSkeletonSMR = emoteSkeletonSMR;
			boneMapper.basePlayerModelSMR = array;
			boneMapper.bodyPrefab = bodyPrefab;
			boneMapper.basePlayerModelAnimator = ((Component)transform).GetComponentInChildren<Animator>();
			boneMapper.emoteSkeletonAnimator = animcontroller.GetComponentInChildren<Animator>();
		}
		catch (Exception arg6)
		{
			DebugClass.Log($"Had issue when setting up BoneMapper settings 1: {arg6}");
			throw;
		}
		try
		{
			GameObject val3 = Assets.Load<GameObject>("assets/customstuff/scavEmoteSkeleton.prefab");
			val3.transform.localScale = new Vector3(1.1216f, 1.1216f, 1.1216f);
			float num = Vector3.Distance(val3.GetComponentInChildren<Animator>().GetBoneTransform((HumanBodyBones)10).position, val3.GetComponentInChildren<Animator>().GetBoneTransform((HumanBodyBones)5).position);
			float num2 = Vector3.Distance(animcontroller.GetComponentInChildren<Animator>().GetBoneTransform((HumanBodyBones)10).position, animcontroller.GetComponentInChildren<Animator>().GetBoneTransform((HumanBodyBones)5).position);
			boneMapper.scale = num2 / num;
			boneMapper.model = ((Component)transform).gameObject;
		}
		catch (Exception arg7)
		{
			DebugClass.Log($"Had issue when setting up BoneMapper settings 2: {arg7}");
			throw;
		}
		boneMapper.revertTransform = revertBonePositions;
		return boneMapper;
	}
}
public struct WorldProp
{
	internal GameObject prop;

	internal JoinSpot[] joinSpots;

	public WorldProp(GameObject _prop, JoinSpot[] _joinSpots)
	{
		prop = _prop;
		joinSpots = _joinSpots;
	}
}
public enum TempThirdPerson
{
	none,
	on,
	off
}
public class BoneMapper : MonoBehaviour
{
	public static List<AudioClip[]> primaryAudioClips = new List<AudioClip[]>();

	public static List<AudioClip[]> secondaryAudioClips = new List<AudioClip[]>();

	public static List<AudioClip[]> primaryDMCAFreeAudioClips = new List<AudioClip[]>();

	public static List<AudioClip[]> secondaryDMCAFreeAudioClips = new List<AudioClip[]>();

	public GameObject audioObject;

	public SkinnedMeshRenderer emoteSkeletonSMR;

	public SkinnedMeshRenderer[] basePlayerModelSMR;

	public Animator basePlayerModelAnimator;

	public Animator emoteSkeletonAnimator;

	public int h;

	public List<BonePair> pairs = new List<BonePair>();

	public float timer = 0f;

	public GameObject model;

	private bool twopart = false;

	public static Dictionary<string, CustomAnimationClip> animClips = new Dictionary<string, CustomAnimationClip>();

	public CustomAnimationClip currentClip = null;

	public string currentClipName = "none";

	public string prevClipName = "none";

	public CustomAnimationClip prevClip = null;

	internal static float Current_MSX = 69f;

	internal static List<BoneMapper> allMappers = new List<BoneMapper>();

	internal static List<WorldProp> allWorldProps = new List<WorldProp>();

	public bool local = false;

	internal static bool moving = false;

	internal static bool attacking = false;

	public bool jank = false;

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

	public float scale = 1f;

	internal int desiredEvent = 0;

	public int currEvent = 0;

	public float autoWalkSpeed = 0f;

	public bool overrideMoveSpeed = false;

	public bool autoWalk = false;

	public GameObject currentEmoteSpot = null;

	public GameObject reservedEmoteSpot = null;

	public bool worldProp = false;

	public bool ragdolling = false;

	public GameObject bodyPrefab;

	public int uniqueSpot = -1;

	public bool preserveProps = false;

	public bool preserveParent = false;

	internal bool useSafePositionReset = false;

	public List<EmoteLocation> emoteLocations = new List<EmoteLocation>();

	private List<string> dontAnimateUs = new List<string>();

	public bool enableAnimatorOnDeath = true;

	public bool revertTransform = false;

	public bool oneFrameAnimatorLeeWay = false;

	public GameObject mapperBody;

	public PlayerControllerB playerController;

	public EnemyAI enemyController;

	public Transform mapperBodyTransform;

	public static bool firstMapperSpawn = true;

	public static List<List<AudioSource>> listOfCurrentEmoteAudio = new List<List<AudioSource>>();

	public List<EmoteConstraint> cameraConstraints = new List<EmoteConstraint>();

	public List<EmoteConstraint> itemHolderConstraints = new List<EmoteConstraint>();

	public Transform itemHolderPosition;

	public List<EmoteConstraint> additionalConstraints = new List<EmoteConstraint>();

	public EmoteConstraint thirdPersonConstraint;

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

	public Vector3 positionBeforeRootMotion = new Vector3(69f, 69f, 69f);

	public Quaternion rotationBeforeRootMotion = Quaternion.identity;

	public float currentAudioLevel = 0f;

	public TempThirdPerson temporarilyThirdPerson = TempThirdPerson.none;

	internal int originalCullingMask;

	internal bool needToTurnOffRenderingThing = false;

	public BoneMapper currentlyLockedBoneMapper;

	public static Dictionary<GameObject, BoneMapper> playersToMappers = new Dictionary<GameObject, BoneMapper>();

	public AudioSource personalAudioSource;

	public InteractTrigger personalTrigger;

	public string currentJoinButton;

	public bool isServer = false;

	public int networkId;

	public bool joined = false;

	public bool canThirdPerson = true;

	internal bool canEmote = false;

	public bool isValidPlayer = false;

	internal bool canStop = true;

	internal List<EmoteConstraint> cosmeticConstraints = new List<EmoteConstraint>();

	internal GameObject originalCosmeticPosition;

	public GameObject parentGameObject;

	public bool positionLock;

	public bool rotationLock;

	public bool scaleLock;

	private Vector3 ogScale = new Vector3(-69f, -69f, -69f);

	private Vector3 scaleDiff = Vector3.one;

	public GameObject rotationPoint;

	public GameObject desiredCameraPos;

	public GameObject realCameraPos;

	private bool ranSinceLastAnim = false;

	public Vector3 deltaPos = new Vector3(0f, 0f, 0f);

	public Quaternion deltaRot = Quaternion.identity;

	public Vector3 prevPosition = Vector3.zero;

	public Quaternion prevRotation = Quaternion.identity;

	public Vector3 prevMapperPos = new Vector3(69f, 69f, 69f);

	public Vector3 prevMapperRot = default(Vector3);

	public bool justSwitched = false;

	public bool isEnemy = false;

	public bool isInThirdPerson = false;

	public int originalLayer = -1;

	internal bool needToTurnOffShadows = true;

	internal bool needToTurnOffCosmetics = true;

	public static string GetRealAnimationName(string animationName)
	{
		if (customNamePairs.ContainsKey(animationName))
		{
			return customNamePairs[animationName];
		}
		return animationName;
	}

	private IEnumerator lockBonesAfterAFrame()
	{
		yield return (object)new WaitForEndOfFrame();
		LockBones();
	}

	public void PlayAnim(string s, int pos, int eventNum)
	{
		desiredEvent = eventNum;
		s = GetRealAnimationName(s);
		PlayAnim(s, pos);
	}

	public void PlayAnim(string s, int pos)
	{
		//IL_0593: Unknown result type (might be due to invalid IL or missing references)
		//IL_0599: Expected O, but got Unknown
		ranSinceLastAnim = false;
		s = GetRealAnimationName(s);
		prevClipName = currentClipName;
		if (s != "none")
		{
			if (!animClips.ContainsKey(s))
			{
				DebugClass.Log("No emote bound to the name [" + s + "]");
				return;
			}
			if (animClips[s] == null || !animClips[s].animates)
			{
				CustomEmotesAPI.Changed(s, this);
				return;
			}
		}
		((Behaviour)emoteSkeletonAnimator).enabled = true;
		dontAnimateUs.Clear();
		try
		{
			((object)currentClip.clip[0]).ToString();
			try
			{
				if (currentClip.syncronizeAnimation || currentClip.syncronizeAudio)
				{
					CustomAnimationClip.syncPlayerCount[currentClip.syncPos]--;
				}
				audioObject.GetComponent<AudioManager>().Stop();
			}
			catch (Exception arg)
			{
				DebugClass.Log($"had issue turning off audio before new audio played step 1: {arg}");
			}
			try
			{
				if ((Object)(object)primaryAudioClips[currentClip.syncPos][currEvent] != (Object)null && currentClip.syncronizeAudio)
				{
					try
					{
						listOfCurrentEmoteAudio[currentClip.syncPos].Remove(audioObject.GetComponent<AudioSource>());
					}
					catch (Exception arg2)
					{
						DebugClass.Log($"had issue turning off audio before new audio played step 2: {arg2}");
						try
						{
							DebugClass.Log($"{prevClip.syncPos}");
							DebugClass.Log($"{currentClip.syncPos}");
							DebugClass.Log(listOfCurrentEmoteAudio[currentClip.syncPos]);
						}
						catch (Exception)
						{
						}
						try
						{
							DebugClass.Log("going to try a brute force method to avoid audio desync issues");
							foreach (List<AudioSource> item in listOfCurrentEmoteAudio)
							{
								if (item.Contains(audioObject.GetComponent<AudioSource>()))
								{
									item.Remove(audioObject.GetComponent<AudioSource>());
								}
							}
						}
						catch (Exception arg3)
						{
							DebugClass.Log($"wow {arg3}");
						}
					}
				}
			}
			catch (Exception ex2)
			{
				DebugClass.Log($"had issue turning off audio before new audio played step 3: {primaryAudioClips[currentClip.syncPos]} {currentClip.syncPos} {currEvent} {ex2}");
			}
			try
			{
				if (uniqueSpot != -1 && CustomAnimationClip.uniqueAnimations[currentClip.syncPos][uniqueSpot])
				{
					CustomAnimationClip.uniqueAnimations[currentClip.syncPos][uniqueSpot] = false;
					uniqueSpot = -1;
				}
			}
			catch (Exception arg4)
			{
				DebugClass.Log($"had issue turning off audio before new audio played step 4: {arg4}");
			}
		}
		catch (Exception)
		{
		}
		currEvent = 0;
		currentClipName = s;
		if (s == "none")
		{
			emoteSkeletonAnimator.Play("none", -1, 0f);
			twopart = false;
			prevClip = currentClip;
			currentClip = null;
			NewAnimation(null);
			CustomEmotesAPI.Changed(s, this);
		}
		else
		{
			if (BlacklistSettings.emotesDisabled.Contains(s))
			{
				return;
			}
			if (s != "none")
			{
				prevClip = currentClip;
				currentClip = animClips[s];
				try
				{
					((object)currentClip.clip[0]).ToString();
				}
				catch (Exception)
				{
					return;
				}
				if (pos == -2)
				{
					pos = ((CustomAnimationClip.syncPlayerCount[animClips[s].syncPos] != 0) ? animClips[s].joinPref : animClips[s].startPref);
				}
				if (pos == -2)
				{
					for (int i = 0; i < CustomAnimationClip.uniqueAnimations[currentClip.syncPos].Count; i++)
					{
						if (!CustomAnimationClip.uniqueAnimations[currentClip.syncPos][i])
						{
							pos = i;
							uniqueSpot = pos;
							CustomAnimationClip.uniqueAnimations[currentClip.syncPos][uniqueSpot] = true;
							break;
						}
					}
					if (uniqueSpot == -1)
					{
						pos = -1;
					}
				}
				if (pos == -1)
				{
					pos = Random.Range(0, currentClip.clip.Length);
				}
				((MonoBehaviour)this).StartCoroutine(lockBonesAfterAFrame());
			}
			AnimatorOverrideController animController = new AnimatorOverrideController(emoteSkeletonAnimator.runtimeAnimatorController);
			if (currentClip.syncronizeAnimation || currentClip.syncronizeAudio)
			{
				CustomAnimationClip.syncPlayerCount[currentClip.syncPos]++;
				if (CustomAnimationClip.syncPlayerCount[currentClip.syncPos] == 1)
				{
					CustomAnimationClip.syncTimer[currentClip.syncPos] = 0f;
				}
			}
			if ((Object)(object)primaryAudioClips[currentClip.syncPos][currEvent] != (Object)null)
			{
				if (CustomAnimationClip.syncPlayerCount[currentClip.syncPos] == 1 && currentClip.syncronizeAudio)
				{
					if (desiredEvent != -1)
					{
						currEvent = desiredEvent;
					}
					else
					{
						currEvent = Random.Range(0, primaryAudioClips[currentClip.syncPos].Length);
					}
					foreach (BoneMapper allMapper in allMappers)
					{
						allMapper.currEvent = currEvent;
					}
					if (currentClip.customPostEventCodeSync != null)
					{
						currentClip.customPostEventCodeSync(this);
					}
				}
				else if (!currentClip.syncronizeAudio)
				{
					currEvent = Random.Range(0, primaryAudioClips[currentClip.syncPos].Length);
					if (currentClip.customPostEventCodeNoSync != null)
					{
						currentClip.customPostEventCodeNoSync(this);
					}
				}
				currentAudioLevel = currentClip.audioLevel;
				audioObject.GetComponent<AudioManager>().Play(currentClip.syncPos, currEvent, currentClip.looping, currentClip.syncronizeAudio, currentClip.willGetClaimed);
				if (currentClip.syncronizeAudio && (Object)(object)primaryAudioClips[currentClip.syncPos][currEvent] != (Object)null)
				{
					listOfCurrentEmoteAudio[currentClip.syncPos].Add(audioObject.GetComponent<AudioSource>());
				}
			}
			SetAnimationSpeed(1f);
			StartAnimations(animController, pos, emoteSkeletonAnimator);
			if (local && CustomEmotesAPI.hudObject != null)
			{
				if (currentClip.displayName != "")
				{
					((TMP_Text)CustomEmotesAPI.currentEmoteText).text = currentClip.displayName;
				}
				else if (currentClip.customInternalName != "")
				{
					((TMP_Text)CustomEmotesAPI.currentEmoteText).text = currentClip.customInternalName;
				}
				else if (!currentClip.visibility)
				{
					((TMP_Text)CustomEmotesAPI.currentEmoteText).text = "";
				}
				else
				{
					((TMP_Text)CustomEmotesAPI.currentEmoteText).text = currentClipName;
				}
			}
			twopart = false;
			NewAnimation(currentClip.joinSpots);
			if (currentClip.usesNewImportSystem)
			{
				CustomEmotesAPI.Changed(currentClip.customInternalName, this);
			}
			else
			{
				CustomEmotesAPI.Changed(s, this);
			}
		}
	}

	public void StartAnimations(AnimatorOverrideController animController, int pos, Animator animator)
	{
		if (currentClip.secondaryClip != null && currentClip.secondaryClip.Length != 0)
		{
			bool flag = true;
			if (CustomAnimationClip.syncTimer[currentClip.syncPos] > currentClip.clip[pos].length)
			{
				animController["Floss"] = currentClip.secondaryClip[pos];
				animator.runtimeAnimatorController = (RuntimeAnimatorController)(object)animController;
				animator.Play("Loop", -1, (CustomAnimationClip.syncTimer[currentClip.syncPos] - currentClip.clip[pos].length) % currentClip.secondaryClip[pos].length / currentClip.secondaryClip[pos].length);
			}
			else
			{
				animController["Dab"] = currentClip.clip[pos];
				animController["nobones"] = currentClip.secondaryClip[pos];
				animator.runtimeAnimatorController = (RuntimeAnimatorController)(object)animController;
				animator.Play("PoopToLoop", -1, CustomAnimationClip.syncTimer[currentClip.syncPos] % currentClip.clip[pos].length / currentClip.clip[pos].length);
			}
		}
		else if (((Motion)currentClip.clip[0]).isLooping)
		{
			animController["Floss"] = currentClip.clip[pos];
			animator.runtimeAnimatorController = (RuntimeAnimatorController)(object)animController;
			if (currentClip.clip[pos].length != 0f)
			{
				animator.Play("Loop", -1, CustomAnimationClip.syncTimer[currentClip.syncPos] % currentClip.clip[pos].length / currentClip.clip[pos].length);
			}
			else
			{
				animator.Play("Loop", -1, 0f);
			}
		}
		else
		{
			animController["Default Dance"] = currentClip.clip[pos];
			animator.runtimeAnimatorController = (RuntimeAnimatorController)(object)animController;
			animator.Play("Poop", -1, CustomAnimationClip.syncTimer[currentClip.syncPos] % currentClip.clip[pos].length / currentClip.clip[pos].length);
		}
	}

	public static void PreviewAnimations(Animator animator, string animation)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Expected O, but got Unknown
		AnimatorOverrideController val = new AnimatorOverrideController(animator.runtimeAnimatorController);
		animation = GetRealAnimationName(animation);
		if (!animClips.ContainsKey(animation))
		{
			return;
		}
		CustomAnimationClip customAnimationClip = animClips[animation];
		if (customAnimationClip != null && customAnimationClip.clip != null && customAnimationClip.clip[0] != null)
		{
			int num = 0;
			if (customAnimationClip.secondaryClip != null && customAnimationClip.secondaryClip.Length != 0)
			{
				val["Dab"] = customAnimationClip.clip[num];
				val["nobones"] = customAnimationClip.secondaryClip[num];
				animator.runtimeAnimatorController = (RuntimeAnimatorController)(object)val;
				animator.Play("PoopToLoop", -1, 0f);
			}
			else if (((Motion)customAnimationClip.clip[0]).isLooping)
			{
				val["Floss"] = customAnimationClip.clip[num];
				animator.runtimeAnimatorController = (RuntimeAnimatorController)(object)val;
				animator.Play("Loop", -1, 0f);
			}
			else
			{
				val["Default Dance"] = customAnimationClip.clip[num];
				animator.runtimeAnimatorController = (RuntimeAnimatorController)(object)val;
				animator.Play("Poop", -1, 0f);
			}
		}
	}

	public void SetAnimationSpeed(float speed)
	{
		emoteSkeletonAnimator.speed = speed;
	}

	internal void NewAnimation(JoinSpot[] locations)
	{
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_014b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			try
			{
				if (local)
				{
					((Component)itemHolderPosition).gameObject.GetComponent<EmoteConstraint>().DeactivateConstraints();
				}
			}
			catch (Exception)
			{
			}
			try
			{
				emoteLocations.Clear();
				autoWalkSpeed = 0f;
				autoWalk = false;
				overrideMoveSpeed = false;
				if (Object.op_Implicit((Object)(object)parentGameObject) && !preserveParent)
				{
					parentGameObject = null;
				}
			}
			catch (Exception)
			{
			}
			try
			{
				useSafePositionReset = currentClip.useSafePositionReset;
			}
			catch (Exception)
			{
				useSafePositionReset = true;
			}
			try
			{
				if (preserveParent)
				{
					preserveParent = false;
				}
				else
				{
					mapperBody.gameObject.transform.localEulerAngles = new Vector3(0f, mapperBody.gameObject.transform.localEulerAngles.y, 0f);
					if (ogScale != new Vector3(-69f, -69f, -69f))
					{
						mapperBody.transform.localScale = ogScale;
						ogScale = new Vector3(-69f, -69f, -69f);
					}
					Collider[] componentsInChildren = mapperBody.GetComponentsInChildren<Collider>();
					foreach (Collider val in componentsInChildren)
					{
						val.enabled = true;
					}
					if (Object.op_Implicit((Object)(object)mapperBody.GetComponent<CharacterController>()))
					{
						((Collider)mapperBody.GetComponent<CharacterController>()).enabled = true;
					}
				}
			}
			catch (Exception)
			{
			}
			if (preserveProps)
			{
				preserveProps = false;
			}
			else
			{
				foreach (GameObject prop in props)
				{
					if (Object.op_Implicit((Object)(object)prop))
					{
						Object.Destroy((Object)(object)prop);
					}
				}
				props.Clear();
			}
			if (locations != null)
			{
				for (int j = 0; j < locations.Length; j++)
				{
					SpawnJoinSpot(locations[j]);
				}
			}
		}
		catch (Exception arg)
		{
			DebugClass.Log($"error during new animation: {arg}");
		}
	}

	public void ScaleProps()
	{
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		foreach (GameObject prop in props)
		{
			if (Object.op_Implicit((Object)(object)prop))
			{
				Transform parent = prop.transform.parent;
				prop.transform.SetParent((Transform)null);
				prop.transform.localScale = new Vector3(scale * 1.15f, scale * 1.15f, scale * 1.15f);
				prop.transform.SetParent(parent);
			}
		}
	}

	public void UpdateHoverTip(string emoteName)
	{
		//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_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 (personalTrigger != null)
		{
			InputBinding val = EmotesInputSettings.Instance.JoinEmote.bindings[0];
			currentJoinButton = InputControlPath.ToHumanReadableString(((InputBinding)(ref val)).effectivePath, (HumanReadableStringOptions)2, (InputControl)null);
			personalTrigger.hoverTip = "Press [" + currentJoinButton + "] to join " + emoteName;
		}
	}

	internal IEnumerator preventEmotesInSpawnAnimation()
	{
		yield return (object)new WaitForSeconds(3f);
		foreach (EmoteConstraint item in cosmeticConstraints)
		{
			item.ActivateConstraints();
		}
		canEmote = true;
	}

	private void Start()
	{
		//IL_0219: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_04f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_04fa: Expected O, but got Unknown
		//IL_0529: Unknown result type (might be due to invalid IL or missing references)
		//IL_0540: Unknown result type (might be due to invalid IL or missing references)
		//IL_0563: Unknown result type (might be due to invalid IL or missing references)
		if (worldProp)
		{
			return;
		}
		if (Object.op_Implicit((Object)(object)((Component)((Component)this).transform).GetComponentInParent<PlayerControllerB>()))
		{
			mapperBody = ((Component)((Component)((Component)this).transform).GetComponentInParent<PlayerControllerB>()).gameObject;
			networkId = (int)((NetworkBehaviour)mapperBody.GetComponent<PlayerControllerB>()).NetworkObjectId;
		}
		else if (Object.op_Implicit((Object)(object)((Component)((Component)this).transform).GetComponentInParent<EnemyAI>()))
		{
			mapperBody = ((Component)((Component)((Component)this).transform).GetComponentInParent<EnemyAI>()).gameObject;
			networkId = -1;
			isEnemy = CustomEmotesAPI.localMapper.isServer;
		}
		else
		{
			networkId = -1;
			mapperBody = ((Component)this).gameObject;
		}
		playerController = mapperBody.GetComponent<PlayerControllerB>();
		if (playerController == null)
		{
			enemyController = mapperBody.GetComponent<EnemyAI>();
		}
		isValidPlayer = playerController != null;
		playersToMappers.Add(mapperBody, this);
		mapperBodyTransform = mapperBody.transform;
		allMappers.Add(this);
		if (!isEnemy)
		{
			GameObject gameObject = ((Component)mapperBody.gameObject.transform.Find("PlayerPhysicsBox")).gameObject;
			gameObject.tag = "InteractTrigger";
			personalTrigger = gameObject.AddComponent<InteractTrigger>();
			personalTrigger.interactable = false;
			personalTrigger.hoverIcon = Object.Instantiate<Sprite>(Assets.Load<Sprite>("assets/fineilldoitmyself/nothing.png"));
			personalTrigger.disabledHoverIcon = Object.Instantiate<Sprite>(Assets.Load<Sprite>("assets/fineilldoitmyself/nothing.png"));
			personalTrigger.disabledHoverTip = "";
			UpdateHoverTip("none");
		}
		GameObject val = Object.Instantiate<GameObject>(Assets.Load<GameObject>("assets/source1.prefab"));
		((Object)val).name = ((Object)this).name + "_AudioObject";
		val.transform.SetParent(mapperBody.transform);
		val.transform.localPosition = Vector3.zero;
		val.AddComponent<SphereCollider>().radius = 0.01f;
		val.layer = 6;
		personalAudioSource = val.GetComponent<AudioSource>();
		val.AddComponent<AudioManager>().Setup(personalAudioSource, this);
		personalAudioSource.playOnAwake = false;
		personalAudioSource.volume = Settings.EmotesVolume.Value / 100f;
		audioObject = val;
		int num = 0;
		if (true)
		{
			SkinnedMeshRenderer[] array = basePlayerModelSMR;
			foreach (SkinnedMeshRenderer val2 in array)
			{
				int num2 = 0;
				for (int j = 0; j < emoteSkeletonSMR.bones.Length; j++)
				{
					for (int k = num2; k < val2.bones.Length; k++)
					{
						if (((Object)emoteSkeletonSMR.bones[j]).name == ((Object)val2.bones[k]).name && !Object.op_Implicit((Object)(object)((Component)val2.bones[k]).gameObject.GetComponent<EmoteConstraint>()))
						{
							num2 = k;
							EmoteConstraint emoteConstraint = ((Component)val2.bones[k]).gameObject.AddComponent<EmoteConstraint>();
							emoteConstraint.AddSource(ref val2.bones[k], ref emoteSkeletonSMR.bones[j]);
							emoteConstraint.revertTransform = revertTransform;
							break;
						}
						if (k == num2 - 1)
						{
							break;
						}
						if (num2 > 0 && k == val2.bones.Length - 1)
						{
							k = -1;
						}
					}
				}
			}
		}
		if (jank)
		{
			SkinnedMeshRenderer[] array2 = basePlayerModelSMR;
			foreach (SkinnedMeshRenderer val3 in array2)
			{
				for (int m = 0; m < val3.bones.Length; m++)
				{
					try
					{
						if (Object.op_Implicit((Object)(object)((Component)val3.bones[m]).gameObject.GetComponent<EmoteConstraint>()))
						{
							((Component)val3.bones[m]).gameObject.GetComponent<EmoteConstraint>().ActivateConstraints();
						}
					}
					catch (Exception arg)
					{
						DebugClass.Log($"{arg}");
					}
				}
			}
		}
		((Component)this).transform.localPosition = Vector3.zero;
		CustomEmotesAPI.MapperCreated(this);
		if (playerController != null)
		{
			((MonoBehaviour)this).StartCoroutine(SetupHandConstraint());
		}
		((MonoBehaviour)this).StartCoroutine(preventEmotesInSpawnAnimation());
		((MonoBehaviour)this).StartCoroutine(GetLocal());
		GameObject val4 = new GameObject();
		((Object)val4).name = "BoneMapperHolder";
		val4.transform.SetParent(mapperBody.transform);
		val4.transform.localEulerAngles = ((Component)this).transform.localEulerAngles;
		val4.transform.position = ((Component)this).transform.position;
		((Component)this).transform.SetParent(val4.transform);
		val4.transform.localPosition = Vector3.zero;
	}

	public IEnumerator SetupHandConstraint()
	{
		while (!Object.op_Implicit((Object)(object)CustomEmotesAPI.localMapper))
		{
			yield return (object)new WaitForEndOfFrame();
		}
		itemHolderPosition = ((Component)this).GetComponentInChildren<Animator>().GetBoneTransform((HumanBodyBones)18).Find("ServerItemHolder");
		itemHolderConstraints.Add(EmoteConstraint.AddConstraint(((Component)playerController.serverItemHolder).gameObject, this, itemHolderPosition, needToFix: true));
		itemHolderConstraints.Add(EmoteConstraint.AddConstraint(((Component)playerController.localItemHolder).gameObject, this, itemHolderPosition, needToFix: true));
		((Component)itemHolderPosition).gameObject.AddComponent<EmoteConstraint>();
	}

	public void AssignParentGameObject(GameObject youAreTheFather, bool lockPosition, bool lockRotation, bool lockScale, bool scaleAsScavenger = true, bool disableCollider = true)
	{
		//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_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)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)parentGameObject))
		{
			NewAnimation(null);
		}
		ogScale = mapperBody.transform.localScale;
		if (scaleAsScavenger)
		{
			scaleDiff = ogScale / scale;
		}
		else
		{
			scaleDiff = ogScale;
		}
		parentGameObject = youAreTheFather;
		positionLock = lockPosition;
		rotationLock = lockRotation;
		scaleLock = lockScale;
		Collider[] componentsInChildren = mapperBody.GetComponentsInChildren<Collider>();
		foreach (Collider val in componentsInChildren)
		{
			val.enabled = !disableCollider;
		}
		if (Object.op_Implicit((Object)(object)mapperBody.GetComponent<CharacterController>()))
		{
			((Collider)mapperBody.GetComponent<CharacterController>()).enabled = !disableCollider;
		}
		if (disableCollider && Object.op_Implicit((Object)(object)currentEmoteSpot))
		{
			if (currentEmoteSpot.GetComponent<EmoteLocation>().validPlayers != 0)
			{
				currentEmoteSpot.GetComponent<EmoteLocation>().validPlayers--;
			}
			currentEmoteSpot.GetComponent<EmoteLocation>().SetColor();
			currentEmoteSpot = null;
		}
	}

	private void LocalFunctions()
	{
		if (!((Behaviour)emoteSkeletonAnimator).enabled)
		{
			return;
		}
		try
		{
			if (moving && currentClip.stopOnMove)
			{
				CustomEmotesAPI.PlayAnimation("none");
			}
		}
		catch (Exception)
		{
		}
	}

	private IEnumerator GetLocal()
	{
		yield return (object)new WaitForEndOfFrame();
		try
		{
			if (!Object.op_Implicit((Object)(object)CustomEmotesAPI.localMapper) && (Object)(object)playerController == (Object)(object)StartOfRound.Instance.localPlayerController)
			{
				CustomEmotesAPI.localMapper = this;
				local = true;
				originalCosmeticPosition = new GameObject();
				originalCosmeticPosition.transform.parent = playerController.headCostumeContainerLocal.parent;
				originalCosmeticPosition.transform.position = playerController.headCostumeContainerLocal.position;
				originalCosmeticPosition.transform.localEulerAngles = playerController.headCostumeContainerLocal.localEulerAngles;
				EmoteConstraint e2 = ((Component)playerController.headCostumeContainerLocal).gameObject.AddComponent<EmoteConstraint>();
				e2.AddSource(playerController.headCostumeContainerLocal, emoteSkeletonAnimator.GetBoneTransform((HumanBodyBones)10));
				cosmeticConstraints.Add(e2);
				((Component)this).gameObject.AddComponent<NearestEmoterChecker>().self = this;
				isServer = ((NetworkBehaviour)playerController).IsServer && ((NetworkBehaviour)playerController).IsOwner;
				HealthbarAnimator.Setup(this);
				FixLocalArms();
				Camera c = playerController.gameplayCamera;
				if (c != null)
				{
					rotationPoint = new GameObject();
					rotationPoint.transform.SetParent(((Component)c).transform.parent.parent.parent.parent);
					rotationPoint.transform.localPosition = new Vector3(0f, 0.8f, 0f);
					rotationPoint.transform.localEulerAngles = Vector3.zero;
					desiredCameraPos = new GameObject();
					desiredCameraPos.transform.SetParent(rotationPoint.transform);
					desiredCameraPos.transform.localPosition = new Vector3(0.3f, 1f, -3f);
					desiredCameraPos.transform.localEulerAngles = Vector3.zero;
					realCameraPos = new GameObject();
					realCameraPos.transform.SetParent(desiredCameraPos.transform);
					realCameraPos.transform.localPosition = Vector3.zero;
					realCameraPos.transform.localEulerAngles = Vector3.zero;
					thirdPersonConstraint = EmoteConstraint.AddConstraint(((Component)((Component)c).transform.parent).gameObject, this, realCameraPos.transform, needToFix: false);
					thirdPersonConstraint.debug = true;
					if (((Object)basePlayerModelSMR[0].bones[32]).name == "spine.004")
					{
						GameObject camHolder = new GameObject();
						((Object)camHolder).name = "EmotesAPICameraHolderThing";
						camHolder.transform.parent = basePlayerModelSMR[0].bones[32];
						camHolder.transform.localEulerAngles = Vector3.zero;
						camHolder.transform.position = ((Component)c).transform.parent.position;
						Transform transform = camHolder.transform;
						transform.localPosition += new Vector3(0f, 0.045f, 0f);
						cameraConstraints.Add(EmoteConstraint.AddConstraint(((Component)((Component)c).transform.parent).gameObject, this, camHolder.transform, needToFix: false));
					}
					else
					{
						cameraConstraints.Add(EmoteConstraint.AddConstraint(((Component)((Component)c).transform.parent).gameObject, this, emoteSkeletonAnimator.GetBoneTransform((HumanBodyBones)10), needToFix: false));
					}
					GameObject cameraRotationObjectLmao = new GameObject();
					cameraRotationObjectLmao.transform.SetParent(((Component)c).transform);
					cameraRotationObjectLmao.transform.localPosition = new Vector3(0.01f, -0.048f, -0.053f);
					cameraRotationObjectLmao.transform.localEulerAngles = new Vector3(270f, 0f, 0f);
					cameraConstraints.Add(EmoteConstraint.AddConstraint(((Component)StartOfRound.Instance.localPlayerController.localVisor).gameObject, this, cameraRotationObjectLmao.transform, needToFix: false));
				}
			}
		}
		catch (Exception e)
		{
			DebugClass.Log(e);
		}
		if (!Object.op_Implicit((Object)(object)CustomEmotesAPI.localMapper))
		{
			((MonoBehaviour)this).StartCoroutine(GetLocal());
		}
	}

	internal void FixLocalArms()
	{
		int i = 0;
		for (int j = 0; j < basePlayerModelSMR[1].bones.Length; j++)
		{
			EmoteConstraint component = ((Component)basePlayerModelSMR[1].bones[j]).GetComponent<EmoteConstraint>();
			if (component == null)
			{
				continue;
			}
			int num = i;
			for (; i < basePlayerModelSMR[0].bones.Length; i++)
			{
				if (((Object)basePlayerModelSMR[1].bones[j]).name == ((Object)basePlayerModelSMR[0].bones[i]).name)
				{
					component.AddSource(basePlayerModelSMR[1].bones[j], basePlayerModelSMR[0].bones[i]);
					component.forceGlobalTransforms = true;
					break;
				}
				if (i == num - 1)
				{
					break;
				}
				if (num > 0 && i == basePlayerModelSMR[0].bones.Length - 1)
				{
					i = -1;
				}
			}
		}
	}

	private void TwoPartThing()
	{
		//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 (ranSinceLastAnim)
		{
			return;
		}
		AnimatorStateInfo currentAnimatorStateInfo = emoteSkeletonAnimator.GetCurrentAnimatorStateInfo(0);
		if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("none"))
		{
			if (twopart)
			{
				ranSinceLastAnim = true;
				if (((Behaviour)emoteSkeletonAnimator).enabled && !jank)
				{
					UnlockBones();
				}
				if (!ragdolling)
				{
					((Behaviour)basePlayerModelAnimator).enabled = true;
					oneFrameAnimatorLeeWay = true;
				}
				((Behaviour)emoteSkeletonAnimator).enabled = false;
				try
				{
					currentClip.clip.ToString();
					CustomEmotesAPI.Changed("none", this);
					NewAnimation(null);
					if (currentClip.syncronizeAnimation || currentClip.syncronizeAudio)
					{
						CustomAnimationClip.syncPlayerCount[currentClip.syncPos]--;
					}
					if ((Object)(object)primaryAudioClips[currentClip.syncPos][currEvent] != (Object)null)
					{
						audioObject.GetComponent<AudioManager>().Stop();
						if ((Object)(object)primaryAudioClips[currentClip.syncPos][currEvent] != (Object)null && currentClip.syncronizeAudio)
						{
							listOfCurrentEmoteAudio[currentClip.syncPos].Remove(audioObject.GetComponent<AudioSource>());
						}
					}
					prevClip = currentClip;
					currentClip = null;
					return;
				}
				catch (Exception)
				{
					return;
				}
			}
			twopart = true;
		}
		else
		{
			twopart = false;
		}
	}

	private void Health()
	{
		if (!isValidPlayer || !playerController.isPlayerDead || !local || currentClip == null)
		{
			return;
		}
		UnlockBones();
		CustomEmotesAPI.PlayAnimation("none");
		foreach (GameObject prop in props)
		{
			if (Object.op_Implicit((Object)(object)prop))
			{
				Object.Destroy((Object)(object)prop);
			}
		}
		props.Clear();
	}

	private void WorldPropAndParent()
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)parentGameObject))
		{
			return;
		}
		if (positionLock)
		{
			mapperBody.gameObject.transform.position = parentGameObject.transform.position + new Vector3(0f, 1f, 0f);
			mapperBody.transform.position = parentGameObject.transform.position;
			PlayerControllerB obj = playerController;
			if (obj != null)
			{
				obj.ResetFallGravity();
			}
		}
		if (rotationLock)
		{
			mapperBody.transform.rotation = parentGameObject.transform.rotation;
		}
		if (scaleLock)
		{
			mapperBody.transform.localScale = new Vector3(parentGameObject.transform.localScale.x * scaleDiff.x, parentGameObject.transform.localScale.y * scaleDiff.y, parentGameObject.transform.localScale.z * scaleDiff.z);
		}
	}

	private void Update()
	{
		if (!worldProp)
		{
			WorldPropAndParent();
			if (local)
			{
				LocalFunctions();
			}
			TwoPartThing();
			Health();
			SetDeltaPosition();
			RootMotion();
			CameraControls();
		}
	}

	internal bool ThirdPersonCheck()
	{
		return !CustomEmotesAPI.LCThirdPersonPresent && currentClip != null && (((currentClip.thirdPerson || Settings.thirdPersonType.Value == ThirdPersonType.All) && Settings.thirdPersonType.Value != ThirdPersonType.None) || temporarilyThirdPerson == TempThirdPerson.on) && canThirdPerson && temporarilyThirdPerson != TempThirdPerson.off;
	}

	public void CameraControls()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: 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_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_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: 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_00d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0110: Unknown result type (might be due to invalid IL or missing references)
		if (local && isInThirdPerson)
		{
			Vector3 val = mapperBodyTransform.position + new Vector3(0f, 1.75f * scale, 0f);
			Ray val2 = default(Ray);
			((Ray)(ref val2))..ctor(val, desiredCameraPos.transform.position - val);
			RaycastHit val3 = default(RaycastHit);
			if (Physics.Raycast(val2, ref val3, 10f, 268437761, (QueryTriggerInteraction)1))
			{
				realCameraPos.transform.position = ((Ray)(ref val2)).GetPoint(((RaycastHit)(ref val3)).distance - 0.25f);
			}
			else
			{
				realCameraPos.transform.position = ((Ray)(ref val2)).GetPoint(10f);
			}
			if (Vector3.Distance(realCameraPos.transform.position, val) > Vector3.Distance(desiredCameraPos.transform.position, val))
			{
				realCameraPos.transform.position = desiredCameraPos.transform.position;
			}
		}
	}

	private void SetDeltaPosition()
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		deltaPos = ((Component)this).transform.position - prevPosition;
		deltaRot = ((Component)this).transform.rotation * Quaternion.Inverse(prevRotation);
		prevPosition = ((Component)this).transform.position;
		prevRotation = ((Component)this).transform.rotation;
	}

	public void RootMotion()
	{
		//IL_0292: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f1: 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_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_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_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_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)
		//IL_0203: Unknown result type (might be due to invalid IL or missing references)
		//IL_0208: Unknown result type (might be due to invalid IL or missing references)
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_0181: 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_0122: 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_014e: 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_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_023f: 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_01b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (!((Behaviour)emoteSkeletonAnimator).enabled)
			{
				return;
			}
			if (justSwitched)
			{
				justSwitched = false;
			}
			else
			{
				if (currentClip.lockType != AnimationClipParams.LockType.rootMotion)
				{
					return;
				}
				if (local || isEnemy)
				{
					if (Settings.rootMotionType.Value != RootMotionType.None || isEnemy)
					{
						Vector3 position = ((Component)this).transform.position;
						Quaternion rotation = ((Component)this).transform.rotation;
						mapperBody.transform.position = new Vector3(emoteSkeletonAnimator.GetBoneTransform((HumanBodyBones)7).position.x, mapperBody.transform.position.y, emoteSkeletonAnimator.GetBoneTransform((HumanBodyBones)7).position.z);
						if (isEnemy || !isInThirdPerson)
						{
							mapperBody.transform.eulerAngles = new Vector3(mapperBody.transform.eulerAngles.x, emoteSkeletonAnimator.GetBoneTransform((HumanBodyBones)10).eulerAngles.y, mapperBody.transform.eulerAngles.z);
						}
						((Component)this).transform.position = position;
						((Component)this).transform.rotation = rotation;
						if (positionBeforeRootMotion != new Vector3(69f, 69f, 69f))
						{
							mapperBody.transform.position = positionBeforeRootMotion;
							mapperBody.transform.rotation = rotationBeforeRootMotion;
							positionBeforeRootMotion = new Vector3(69f, 69f, 69f);
						}
					}
					if (deltaPos != Vector3.zero || deltaRot != Quaternion.identity)
					{
						if (isEnemy)
						{
							EmoteNetworker.instance.SyncBoneMapperPos(((NetworkBehaviour)enemyController).NetworkObjectId, ((Component)this).transform.position, ((Component)this).transform.eulerAngles);
						}
						else
						{
							EmoteNetworker.instance.SyncBoneMapperPos(((NetworkBehaviour)playerController).NetworkObjectId, ((Component)this).transform.position, ((Component)this).transform.eulerAngles);
						}
					}
				}
				else
				{
					((Component)this).transform.position = prevMapperPos;
					((Component)this).transform.eulerAngles = prevMapperRot;
				}
			}
		}
		catch (Exception)
		{
		}
	}

	public int SpawnJoinSpot(JoinSpot joinSpot)
	{
		props.Add(Object.Instantiate<GameObject>(Assets.Load<GameObject>("@CustomEmotesAPI_customemotespackage:assets/emotejoiner/JoinVisual.prefab")));
		props[props.Count - 1].transform.SetParent(((Component)this).transform);
		((Object)props[props.Count - 1]).name = joinSpot.name;
		EmoteLocation emoteLocation = props[props.Count - 1].AddComponent<EmoteLocation>();
		emoteLocation.joinSpot = joinSpot;
		emoteLocation.owner = this;
		emoteLocations.Add(emoteLocation);
		return props.Count - 1;
	}

	public void JoinEmoteSpot()
	{
		if (Object.op_Implicit((Object)(object)reservedEmoteSpot))
		{
			if (Object.op_Implicit((Object)(object)currentEmoteSpot))
			{
				if (currentEmoteSpot.GetComponent<EmoteLocation>().validPlayers != 0)
				{
					currentEmoteSpot.GetComponent<EmoteLocation>().validPlayers--;
				}
				currentEmoteSpot.GetComponent<EmoteLocation>().SetColor();
			}
			currentEmoteSpot = reservedEmoteSpot;
			reservedEmoteSpot = null;
		}
		int i;
		for (i = 0; i < ((Component)currentEmoteSpot.transform.parent).GetComponentsInChildren<EmoteLocation>().Length && !((Object)(object)((Component)currentEmoteSpot.transform.parent).GetComponentsInChildren<EmoteLocation>()[i] == (Object)(object)currentEmoteSpot.GetComponent<EmoteLocation>()); i++)
		{
		}
		EmoteNetworker.instance.SyncJoinSpot(mapperBody.GetComponent<NetworkObject>().NetworkObjectId, currentEmoteSpot.GetComponentInParent<NetworkObject>().NetworkObjectId, currentEmoteSpot.GetComponent<EmoteLocation>().owner.worldProp, i);
	}

	public void RemoveProp(int propPos)
	{
		Object.Destroy((Object)(object)props[propPos]);
	}

	public void SetAutoWalk(float speed, bool overrideBaseMovement, bool autoWalk)
	{
		autoWalkSpeed = speed;
		overrideMoveSpeed = overrideBaseMovement;
		this.autoWalk = autoWalk;
	}

	public void SetAutoWalk(float speed, bool overrideBaseMovement)
	{
		autoWalkSpeed = speed;
		overrideMoveSpeed = overrideBaseMovement;
		autoWalk = true;
	}

	internal IEnumerator waitForTwoFramesThenDisableA1()
	{
		yield return (object)new WaitForEndOfFrame();
	}

	private void OnDestroy()
	{
		if (playerController == null)
		{
			return;
		}
		playersToMappers.Remove(((Component)playerController).gameObject);
		if (worldProp)
		{
			return;
		}
		playersToMappers.Remove(mapperBody);
		try
		{
			((object)currentClip.clip[0]).ToString();
			NewAnimation(null);
			if ((currentClip.syncronizeAnimation || currentClip.syncronizeAudio) && CustomAnimationClip.syncPlayerCount[currentClip.syncPos] > 0)
			{
				CustomAnimationClip.syncPlayerCount[currentClip.syncPos]--;
			}
			if ((Object)(object)primaryAudioClips[currentClip.syncPos][currEvent] != (Object)null)
			{
				audioObject.GetComponent<AudioManager>().Stop();
				if (currentClip.syncronizeAudio)
				{
					listOfCurrentEmoteAudio[currentClip.syncPos].Remove(audioObject.GetComponent<AudioSource>());
				}
			}
			if (uniqueSpot != -1 && CustomAnimationClip.uniqueAnimations[currentClip.syncPos][uniqueSpot])
			{
				CustomAnimationClip.uniqueAnimations[currentClip.syncPos][uniqueSpot] = false;
				uniqueSpot = -1;
			}
			allMappers.Remove(this);
			prevClip = currentClip;
			currentClip = null;
		}
		catch (Exception)
		{
			allMappers.Remove(this);
		}
	}

	public void UnlockBones(bool animatorEnabled = true)
	{
		//IL_0007: 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)
		((Component)this).transform.localPosition = Vector3.zero;
		((Component)this).transform.eulerAngles = bodyPrefab.transform.eulerAngles;
		SkinnedMeshRenderer[] array = basePlayerModelSMR;
		foreach (SkinnedMeshRenderer val in array)
		{
			for (int j = 0; j < val.bones.Length; j++)
			{
				try
				{
					if (Object.op_Implicit((Object)(object)((Component)val.bones[j]).gameObject.GetComponent<EmoteConstraint>()))
					{
						((Component)val.bones[j]).gameObject.GetComponent<EmoteConstraint>().DeactivateConstraints();
					}
				}
				catch (Exception)
				{
					break;
				}
			}
		}
		foreach (EmoteConstraint cameraConstraint in cameraConstraints)
		{
			cameraConstraint.DeactivateConstraints();
		}
		foreach (EmoteConstraint itemHolderConstraint in itemHolderConstraints)
		{
			itemHolderConstraint.DeactivateConstraints();
		}
		foreach (EmoteConstraint additionalConstraint in additionalConstraints)
		{
			additionalConstraint.DeactivateConstraints();
		}
		if (thirdPersonConstraint != null)
		{
			thirdPersonConstraint.DeactivateConstraints();
		}
		DeThirdPerson();
	}

	public void LockBones()
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: 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_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: 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_00de: Unknown result type (might be due to invalid IL or missing references)
		UnlockBones();
		((Component)this).transform.localPosition = Vector3.zero;
		if (currentClip != null)
		{
			foreach (HumanBodyBones soloIgnoredBone in currentClip.soloIgnoredBones)
			{
				if (Object.op_Implicit((Object)(object)emoteSkeletonAnimator.GetBoneTransform(soloIgnoredBone)))
				{
					dontAnimateUs.Add(((Object)emoteSkeletonAnimator.GetBoneTransform(soloIgnoredBone)).name);
				}
			}
			foreach (HumanBodyBones rootIgnoredBone in currentClip.rootIgnoredBones)
			{
				if (Object.op_Implicit((Object)(object)emoteSkeletonAnimator.GetBoneTransform(rootIgnoredBone)))
				{
					dontAnimateUs.Add(((Object)emoteSkeletonAnimator.GetBoneTransform(rootIgnoredBone)).name);
				}
				Transform[] componentsInChildren = ((Component)emoteSkeletonAnimator.GetBoneTransform(rootIgnoredBone)).GetComponentsInChildren<Transform>();
				foreach (Transform val in componentsInChildren)
				{
					dontAnimateUs.Add(((Object)val).name);
				}
			}
		}
		if (!jank)
		{
			((Renderer)emoteSkeletonSMR).enabled = true;
			SkinnedMeshRenderer[] array = basePlayerModelSMR;
			foreach (SkinnedMeshRenderer val2 in array)
			{
				for (int k = 0; k < val2.bones.Length; k++)
				{
					try
					{
						if (Object.op_Implicit((Object)(object)((Component)val2.bones[k]).gameObject.GetComponent<EmoteConstraint>()) && !dontAnimateUs.Contains(((Object)val2.bones[k]).name))
						{
							EmoteConstraint component = ((Component)val2.bones[k]).gameObject.GetComponent<EmoteConstraint>();
							component.ActivateConstraints();
							if ((Object)(object)val2 == (Object)(object)basePlayerModelSMR.First() && currentClip != null)
							{
								component.SetLocalTransforms(currentClip.localTransforms);
							}
						}
						else if (dontAnimateUs.Contains(((Object)val2.bones[k]).name))
						{
							((Component)val2.bones[k]).gameObject.GetComponent<EmoteConstraint>().DeactivateConstraints();
						}
					}
					catch (Exception arg)
					{
						DebugClass.Log($"{arg}");
					}
				}
			}
			foreach (EmoteConstraint itemHolderConstraint in itemHolderConstraints)
			{
				itemHolderConstraint.ActivateConstraints();
			}
			foreach (EmoteConstraint additionalConstraint in additionalConstraints)
			{
				additionalConstraint.ActivateConstraints();
			}
			LockCameraStuff(local && ThirdPersonCheck());
		}
		else
		{
			((MonoBehaviour)this).StartCoroutine(waitForTwoFramesThenDisableA1());
		}
	}

	public void LockCameraStuff(bool thirdPersonLock)
	{
		if (thirdPersonLock)
		{
			TurnOnThirdPerson();
		}
		else
		{
			if (currentClip == null)
			{
				return;
			}
			if (Settings.rootMotionType.Value != RootMotionType.None && (currentClip.lockType == AnimationClipParams.LockType.rootMotion || Settings.rootMotionType.Value == RootMotionType.All || currentClip.lockType == AnimationClipParams.LockType.lockHead))
			{
				foreach (EmoteConstraint cameraConstraint in cameraConstraints)
				{
					cameraConstraint.ActivateConstraints();
				}
				return;
			}
			if (currentClip.lockType != AnimationClipParams.LockType.headBobbing || Settings.rootMotionType.Value == RootMotionType.None)
			{
				return;
			}
			foreach (EmoteConstraint cameraConstraint2 in cameraConstraints)
			{
				cameraConstraint2.ActivateConstraints();
				if ((Object)(object)cameraConstraint2 != (Object)(object)cameraConstraints[cameraConstraints.Count - 1])
				{
					cameraConstraint2.onlyY = true;
				}
			}
		}
	}

	public void UnlockCameraStuff()
	{
		foreach (EmoteConstraint cameraConstraint in cameraConstraints)
		{
			cameraConstraint.DeactivateConstraints();
		}
		thirdPersonConstraint.DeactivateConstraints();
		DeThirdPerson();
	}

	public void TurnOnThirdPerson()
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Invalid comparison between Unknown and I4
		((Component)playerController.localVisor).gameObject.SetActive(false);
		if ((int)((Renderer)playerController.thisPlayerModel).shadowCastingMode == 1)
		{
			needToTurnOffShadows = false;
		}
		((Renderer)playerController.thisPlayerModel).shadowCastingMode = (ShadowCastingMode)1;
		if (originalLayer == -1)
		{
			originalLayer = ((Component)playerController.thisPlayerModel).gameObject.layer;
			originalCullingMask = playerController.gameplayCamera.cullingMask;
		}
		((Component)playerController.thisPlayerModel).gameObject.layer = 1;
		playerController.grabDistance = 5.65f;
		playerController.gameplayCamera.cullingMask = StartOfRound.Instance.spectateCamera.cullingMask;
		thirdPersonConstraint.ActivateConstraints();
		isInThirdPerson = true;
		foreach (EmoteConstraint cosmeticConstraint in cosmeticConstraints)
		{
			cosmeticConstraint.emoteBone = playerController.playerGlobalHead;
		}
		if (CustomEmotesAPI.MoreCompanyPresent)
		{
			try
			{
				needToTurnOffCosmetics = true;
				MoreCompanyCompat.TurnOnCosmetics(this);
			}
			catch (Exception arg)
			{
				DebugClass.Log($"couldn't turn on cosmetics: {arg}");
			}
		}
		if (CustomEmotesAPI.BetterEmotesPresent)
		{
			Transform val = ((Component)playerController).transform.Find("ScavengerModel/LEGS");
			if (val != null)
			{
				((Component)val).gameObject.layer = 31;
			}
		}
	}

	public void DeThirdPerson()
	{
		if (!isInThirdPerson)
		{
			return;
		}
		playerController.gameplayCamera.cullingMask = originalCullingMask;
		if (needToTurnOffShadows)
		{
			((Renderer)playerController.thisPlayerModel).shadowCastingMode = (ShadowCastingMode)3;
		}
		needToTurnOffShadows = true;
		((Component)playerController.localVisor).gameObject.SetActive(true);
		((Component)playerController.thisPlayerModel).gameObject.layer = originalLayer;
		playerController.grabDistance = 3f;
		isInThirdPerson = false;
		foreach (EmoteConstraint cosmeticConstraint in cosmeticConstraints)
		{
			cosmeticConstraint.emoteBone = originalCosmeticPosition.transform;
		}
		if (CustomEmotesAPI.MoreCompanyPresent && needToTurnOffCosmetics)
		{
			try
			{
				MoreCompanyCompat.TurnOffCosmetics(this);
			}
			catch (Exception arg)
			{
				DebugClass.Log($"couldn't clear cosmetics: {arg}");
			}
		}
		if (CustomEmotesAPI.BetterEmotesPresent)
		{
			Transform val = ((Component)playerController).transform.Find("ScavengerModel/LEGS");
			if (val != null)
			{
				((Component)val).gameObject.layer = 0;
			}
		}
	}

	public void AttachItemHolderToTransform(Transform target)
	{
		((Component)itemHolderPosition).gameObject.GetComponent<EmoteConstraint>().AddSource(itemHolderPosition, target);
		((Component)itemHolderPosition).gameObject.GetComponent<EmoteConstraint>().ActivateConstraints();
	}
}
public class CustomAnimationClip : MonoBehaviour
{
	public AnimationClip[] clip;

	public AnimationClip[] secondaryClip;

	public bool looping;

	public string wwiseEvent;

	public bool syncronizeAudio;

	public List<HumanBodyBones> soloIgnoredBones;

	public List<HumanBodyBones> rootIgnoredBones;

	public bool dimAudioWhenClose;

	public bool stopOnAttack;

	public bool stopOnMove;

	public bool visibility;

	public int startPref;

	public int joinPref;

	public JoinSpot[] joinSpots;

	public bool useSafePositionReset;

	public string customInternalName;

	public Action<BoneMapper> customPostEventCodeSync;

	public Action<BoneMapper> customPostEventCodeNoSync;

	public bool syncronizeAnimation;

	public int syncPos;

	public static List<float> syncTimer = new List<float>();

	public static List<int> syncPlayerCount = new List<int>();

	public static List<List<bool>> uniqueAnimations = new List<List<bool>>();

	public bool vulnerableEmote = false;

	public AnimationClipParams.LockType lockType = AnimationClipParams.LockType.none;

	public bool willGetClaimed = false;

	public float audioLevel = 0.5f;

	public bool thirdPerson = false;

	public string displayName = "";

	public bool localTransforms = false;

	public BepInPlugin ownerPlugin;

	public bool usesNewImportSystem = false;

	public bool animates = true;

	public bool preventsMovement = false;

	public bool allowJoining = true;

	public string joinEmote = "";

	internal CustomAnimationClip(AnimationClip[] _clip, bool _loop, AudioClip[] primaryAudioClips = null, AudioClip[] secondaryAudioClips = null, HumanBodyBones[] rootBonesToIgnore = null, HumanBodyBones[] soloBonesToIgnore = null, AnimationClip[] _secondaryClip = null, bool dimWhenClose = false, bool stopWhenMove = false, bool stopWhenAttack = false, bool visible = true, bool syncAnim = false, bool syncAudio = false, int startPreference = -1, int joinPreference = -1, JoinSpot[] _joinSpots = null, bool safePositionReset = false, string customName = "", Action<BoneMapper> _customPostEventCodeSync = null, Action<BoneMapper> _customPostEventCodeNoSync = null, AnimationClipParams.LockType lockType = AnimationClipParams.LockType.none, AudioClip[] primaryDMCAFreeAudioClips = null, AudioClip[] secondaryDMCAFreeAudioClips = null, bool willGetClaimed = false, float audioLevel = 0.5f, bool thirdPerson = false, string displayName = "", BepInPlugin ownerPlugin = null, bool localTransforms = false, bool usesNewImportSystem = false, bool animates = true, bool preventsMovement = false, bool allowJoining = true, string joinEmote = "")
	{
		if (rootBonesToIgnore == null)
		{
			rootBonesToIgnore = (HumanBodyBones[])(object)new HumanBodyBones[0];
		}
		if (soloBonesToIgnore == null)
		{
			soloBonesToIgnore = (HumanBodyBones[])(object)new HumanBodyBones[0];
		}
		clip = _clip;
		secondaryClip = _secondaryClip;
		looping = _loop;
		dimAudioWhenClose = dimWhenClose;
		stopOnAttack = stopWhenAttack;
		stopOnMove = stopWhenMove;
		visibility = visible;
		joinPref = joinPreference;
		startPref = startPreference;
		customPostEventCodeSync = _customPostEventCodeSync;
		customPostEventCodeNoSync = _customPostEventCodeNoSync;
		if (primaryAudioClips == null)
		{
			BoneMapper.primaryAudioClips.Add((AudioClip[])(object)new AudioClip[1]);
		}
		else
		{
			BoneMapper.primaryAudioClips.Add(primaryAudioClips);
		}
		if (secondaryAudioClips == null)
		{
			BoneMapper.secondaryAudioClips.Add((AudioClip[])(object)new AudioClip[1]);
		}
		else
		{
			BoneMapper.secondaryAudioClips.Add(secondaryAudioClips);
		}
		if (primaryDMCAFreeAudioClips == null)
		{
			BoneMapper.primaryDMCAFreeAudioClips.Add((AudioClip[])(object)new AudioClip[1]);
		}
		else
		{
			BoneMapper.primaryDMCAFreeAudioClips.Add(primaryDMCAFreeAudioClips);
		}
		if (secondaryDMCAFreeAudioClips == null)
		{
			BoneMapper.secondaryDMCAFreeAudioClips.Add((AudioClip[])(object)new AudioClip[1]);
		}
		else
		{
			BoneMapper.secondaryDMCAFreeAudioClips.Add(secondaryDMCAFreeAudioClips);
		}
		if (soloBonesToIgnore.Length != 0)
		{
			soloIgnoredBones = new List<HumanBodyBones>(soloBonesToIgnore);
		}
		else
		{
			soloIgnoredBones = new List<HumanBodyBones>();
		}
		if (rootBonesToIgnore.Length != 0)
		{
			rootIgnoredBones = new List<HumanBodyBones>(rootBonesToIgnore);
		}
		else
		{
			rootIgnoredBones = new List<HumanBodyBones>();
		}
		syncronizeAnimation = syncAnim;
		syncronizeAudio = syncAudio;
		syncPos = syncTimer.Count;
		syncTimer.Add(0f);
		syncPlayerCount.Add(0);
		if (_clip != null)
		{
			List<bool> list = new List<bool>();
			for (int i = 0; i < _clip.Length; i++)
			{
				list.Add(item: false);
			}
			uniqueAnimations.Add(list);
		}
		if (_joinSpots == null)
		{
			_joinSpots = new JoinSpot[0];
		}
		joinSpots = _joinSpots;
		useSafePositionReset = safePositionReset;
		customInternalName = customName;
		this.usesNewImportSystem = usesNewImportSystem;
		if (!usesNewImportSystem && customName != "")
		{
			BoneMapper.customNamePairs.Add(customName, ((Object)_clip[0]).name);
		}
		BoneMapper.listOfCurrentEmoteAudio.Add(new List<AudioSource>());
		this.lockType = lockType;
		this.willGetClaimed = willGetClaimed;
		this.audioLevel = audioLevel;
		this.thirdPerson = thirdPerson;
		this.displayName = displayName;
		if (displayName == "")
		{
			DebugClass.Log("display name wasn't set, using " + customInternalName);
			this.displayName = customInternalName;
		}
		this.ownerPlugin = ownerPlugin;
		this.localTransforms = localTransforms;
		this.animates = animates;
		this.preventsMovement = preventsMovement;
		this.allowJoining = allowJoining;
		if (string.IsNullOrEmpty(customInternalName))
		{
			return;
		}
		Keybinds.DisableKeybinds();
		if (usesNewImportSystem)
		{
			InputActionReference orCreateInputRef = Keybinds.GetOrCreateInputRef(customInternalName);
			orCreateInputRef.action.Enable();
			orCreateInputRef.action.started += EmoteAction_started;
			if (Keybinds.keyBindOverrideStorage.TryGetValue(customInternalName, out var value))
			{
				InputActionRebindingExtensions.ApplyBindingOverride(orCreateInputRef.action, value, (string)null, (string)null);
			}
		}
		else
		{
			InputActionReference orCreateInputRef2 = Keybinds.GetOrCreateInputRef(((Object)clip[0]).name);
			orCreateInputRef2.action.Enable();
			orCreateInputRef2.action.started += EmoteAction_started;
			if (Keybinds.keyBindOverrideStorage.TryGetValue(((Object)clip[0]).name, out var value2))
			{
				InputActionRebindingExtensions.ApplyBindingOverride(orCreateInputRef2.action, value2, (string)null, (string)null);
			}
		}
		Keybinds.EnableKeybinds();
		if (joinEmote == "")
		{
			joinEmote = customInternalName;
		}
		this.joinEmote = joinEmote;
		if (EmoteDmcaVerificationStatusDb.IsNonDmcaCompliant(ownerPlugin.GUID))
		{
			this.willGetClaimed = true;
		}
	}

	private static void EmoteAction_started(CallbackContext obj)
	{
		if (EmoteUiManager.CanOpenEmoteWheels() && CustomEmotesAPI.localMapper != null)
		{
			CustomEmotesAPI.PlayAnimation(((CallbackContext)(ref obj)).action.name);
		}
	}
}
[DefaultExecutionOrder(-2)]
public class EmoteConstraint : MonoBehaviour
{
	public Transform originalBone;

	public Transform emoteBone;

	private Vector3 originalPosition;

	private Quaternion originalRotation;

	public bool constraintActive = false;

	public bool revertTransform;

	private bool firstTime = true;

	private bool firstTime2 = true;

	private bool hasEverActivatedConstraints = false;

	public bool onlyY = false;

	public bool debug = false;

	public bool forceGlobalTransforms = false;

	internal bool needToFix = true;

	public bool localTransforms { get; private set; } = false;


	public bool SetLocalTransforms(bool input)
	{
		localTransforms = !forceGlobalTransforms && input;
		return localTransforms;
	}

	private void LateUpdate()
	{
		ActUponConstraints();
	}

	public void ActUponConstraints()
	{
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: 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_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: 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_0034: 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_0054: 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)
		if (!constraintActive)
		{
			return;
		}
		if (localTransforms)
		{
			if (onlyY)
			{
				originalBone.localPosition = new Vector3(originalBone.localPosition.x, emoteBone.localPosition.y, originalBone.localPosition.z);
				return;
			}
			originalBone.localPosition = emoteBone.localPosition;
			originalBone.localRotation = emoteBone.localRotation;
		}
		else if (onlyY)
		{
			originalBone.position = new Vector3(originalBone.position.x, emoteBone.position.y, originalBone.position.z);
		}
		else
		{
			originalBone.position = emoteBone.position;
			originalBone.rotation = emoteBone.rotation;
		}
	}

	public void ActivateConstraints()
	{
		//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_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		if (!constraintActive && emoteBone != null)
		{
			if (firstTime2)
			{
				firstTime2 = false;
				((Component)this).gameObject.GetComponent<MonoBehaviour>().StartCoroutine(FirstTimeActiveFix(this));
				return;
			}
			originalPosition = originalBone.localPosition;
			originalRotation = originalBone.localRotation;
			hasEverActivatedConstraints = true;
			constraintActive = true;
			onlyY = false;
		}
	}

	internal IEnumerator FirstTimeActiveFix(EmoteConstraint e)
	{
		((Behaviour)e).enabled = false;
		yield return (object)new WaitForEndOfFrame();
		((Behaviour)e).enabled = true;
		if (e.onlyY)
		{
			e.ActivateConstraints();
			e.onlyY = true;
		}
		else
		{
			e.ActivateConstraints();
		}
	}

	public void DeactivateConstraints()
	{
		//IL_003b: 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)
		constraintActive = false;
		if (firstTime || !revertTransform || !hasEverActivatedConstraints)
		{
			firstTime = false;
			return;
		}
		originalBone.localPosition = originalPosition;
		originalBone.localRotation = originalRotation;
	}

	internal void AddSource(ref Transform originalBone, ref Transform emoteBone)
	{
		this.originalBone = originalBone;
		this.emoteBone = emoteBone;
		if (((Component)emoteBone).GetComponent<BoneRef>() != null)
		{
			((Component)emoteBone).GetComponent<BoneRef>().target = originalBone;
		}
		else
		{
			((Component)emoteBone).gameObject.AddComponent<BoneRef>().target = originalBone;
		}
	}

	internal void AddSource(Transform originalBone, Transform emoteBone)
	{
		this.originalBone = originalBone;
		this.emoteBone = emoteBone;
		if (((Component)emoteBone).GetComponent<BoneRef>() != null)
		{
			((Component)emoteBone).GetComponent<BoneRef>().target = originalBone;
		}
		else
		{
			((Component)emoteBone).gameObject.AddComponent<BoneRef>().target = originalBone;
		}
	}

	internal static EmoteConstraint AddConstraint(GameObject gameObject, BoneMapper mapper, Transform target, bool needToFix)
	{
		EmoteConstraint emoteConstraint = gameObject.AddComponent<EmoteConstraint>();
		emoteConstraint.AddSource(gameObject.transform, target);
		emoteConstraint.revertTransform = mapper.revertTransform;
		emoteConstraint.needToFix = needToFix;
		return emoteConstraint;
	}

	private void Start()
	{
		((MonoBehaviour)this).StartCoroutine(FixConstraints());
	}

	private IEnumerator FixConstraints()
	{
		yield return (object)new WaitForEndOfFrame();
		if (needToFix)
		{
			ActivateConstraints();
			yield return (object)new WaitForEndOfFrame();
			DeactivateConstraints();
		}
	}
}
public struct JoinSpot
{
	public string name;

	public Vector3 position;

	public Vector3 rotation;

	public Vector3 scale;

	public JoinSpot(string _name, Vector3 _position, Vector3 _rotation, Vector3 _scale)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_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)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		name = _name;
		position = _position;
		rotation = _rotation;
		scale = _scale;
	}

	public JoinSpot(string _name, Vector3 _position)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		name = _name;
		position = _position;
		rotation = Vector3.zero;
		scale = Vector3.one;
	}
}
public class EmoteLocation : MonoBehaviour
{
	public static List<EmoteLocation> emoteLocations = new List<EmoteLocation>();

	public static bool visibile = true;

	public int spot;

	public int validPlayers = 0;

	public BoneMapper owner;

	public BoneMapper emoter;

	public JoinSpot joinSpot;

	private InteractTrigger personalTrigger;

	public static void HideAllSpots()
	{
		visibile = false;
		foreach (EmoteLocation emoteLocation in emoteLocations)
		{
			try
			{
				Renderer[] componentsInChildren = ((Component)emoteLocation).GetComponentsInChildren<Renderer>();
				foreach (Renderer val in componentsInChildren)
				{
					val.enabled = false;
				}
				ParticleSystemRenderer[] componentsInChildren2 = ((Component)emoteLocation).GetComponentsInChildren<ParticleSystemRenderer>();
				foreach (ParticleSystemRenderer val2 in componentsInChildren2)
				{
					((Renderer)val2).enabled = false;
				}
			}
			catch (Exception)
			{
			}
		}
	}

	public static void ShowAllSpots()
	{
		visibile = true;
		foreach (EmoteLocation emoteLocation in emoteLocations)
		{
			try
			{
				Renderer[] componentsInChildren = ((Component)emoteLocation).GetComponentsInChildren<Renderer>();
				foreach (Renderer val in componentsInChildren)
				{
					val.enabled = true;
				}
				ParticleSystemRenderer[] componentsInChildren2 = ((Component)emoteLocation).GetComponentsInChildren<ParticleSystemRenderer>();
				foreach (ParticleSystemRenderer val2 in componentsInChildren2)
				{
					((Renderer)val2).enabled = true;
				}
			}
			catch (Exception)
			{
			}
		}
	}

	private void Start()
	{
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: Unknown result type (might be due to invalid IL or missing references)
		//IL_011f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		SetColor();
		emoteLocations.Add(this);
		((MonoBehaviour)this).StartCoroutine(setScale());
		if (!visibile)
		{
			Renderer[] componentsInChildren = ((Component)this).GetComponentsInChildren<Renderer>();
			foreach (Renderer val in componentsInChildren)
			{
				val.enabled = false;
			}
			ParticleSystemRenderer[] componentsInChildren2 = ((Component)this).GetComponentsInChildren<ParticleSystemRenderer>();
			foreach (ParticleSystemRenderer val2 in componentsInChildren2)
			{
				((Renderer)val2).enabled = false;
			}
		}
		personalTrigger = ((Component)this).gameObject.AddComponent<InteractTrigger>();
		((Component)this).gameObject.tag = "InteractTrigger";
		((Component)this).gameObject.layer = LayerMask.NameToLayer("InteractableObject");
		personalTrigger.interactable = true;
		personalTrigger.hoverIcon = Object.Instantiate<Sprite>(Assets.Load<Sprite>("assets/fineilldoitmyself/nothing.png"));
		personalTrigger.disabledHoverIcon = Object.Instantiate<Sprite>(Assets.Load<Sprite>("assets/fineilldoitmyself/nothing.png"));
		personalTrigger.disabledHoverTip = "";
		InputBinding val3 = EmotesInputSettings.Instance.JoinEmote.bindings[0];
		string text = InputControlPath.ToHumanReadableString(((InputBinding)(ref val3)).effectivePath, (HumanReadableStringOptions)2, (InputControl)null);
		personalTrigger.hoverTip = "Press [" + text + "] to join";
	}

	private void OnDestroy()
	{
		emoteLocations.Remove(this);
	}

	public void SetEmoterAndHideLocation(BoneMapper boneMapper)
	{
		if (!Object.op_Implicit((Object)(object)emoter))
		{
			emoter = boneMapper;
			SetVisible(visibility: false);
		}
	}

	public IEnumerator setScale()
	{
		yield return (object)new WaitForSeconds(0.1f);
		_ = Vector3.one;
		Vector3 scal = ((!Object.op_Implicit((Object)(object)owner.emoteSkeletonSMR)) ? ((Component)owner).transform.lossyScale : ((Component)owner).transform.parent.lossyScale);
		((Component)this).transform.localPosition = new Vector3(joinSpot.position.x / scal.x, joinSpot.position.y / scal.y, joinSpot.position.z / scal.z);
		((Component)this).transform.localEulerAngles = joinSpot.rotation;
		((Component)this).transform.localScale = new Vector3(joinSpot.scale.x / scal.x, joinSpot.scale.y / scal.y, joinSpot.scale.z / scal.z);
	}

	internal void SetVisible(bool visibility)
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: 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)
		if (visibility)
		{
			Transform transform = ((Component)this).gameObject.transform;
			transform.localPosition += new Vector3(5000f, 5000f, 5000f);
		}
		else
		{
			Transform transform2 = ((Component)this).gameObject.transform;
			transform2.localPosition -= new Vector3(5000f, 5000f, 5000f);
		}
	}

	private void OnTriggerEnter(Collider other)
	{
		if (!Object.op_Implicit((Object)(object)((Component)other).GetComponentInChildren<BoneMapper>()) || !((Object)(object)((Component)other).GetComponentInChildren<BoneMapper>() != (Object)(object)owner))
		{
			return;
		}
		BoneMapper componentInChildren = ((Component)other).GetComponentInChildren<BoneMapper>();
		if (Object.op_Implicit((Object)(object)componentInChildren))
		{
			validPlayers++;
			SetColor();
			if (componentInChildren.local)
			{
				personalTrigger.interactable = true;
			}
			componentInChildren.currentEmoteSpot = ((Component)this).gameObject;
			CustomEmotesAPI.JoinSpotEntered(componentInChildren, owner);
		}
	}

	private void OnTriggerExit(Collider other)
	{
		if (!Object.op_Implicit((Object)(object)((Component)other).GetComponentInChildren<BoneMapper>()) || !((Object)(object)((Component)other).GetComponentInChildren<BoneMapper>() != (Object)(object)owner))
		{
			return;
		}
		BoneMapper componentInChildren = ((Component)other).GetComponentInChildren<BoneMapper>();
		if (Object.op_Implicit((Object)(object)componentInChildren))
		{
			if (validPlayers != 0)
			{
				validPlayers--;
			}
			if (componentInChildren.local)
			{
				personalTrigger.interactable = false;
			}
			SetColor();
			if ((Object)(object)componentInChildren.currentEmoteSpot == (Object)(object)((Component)this).gameObject)
			{
				componentInChildren.currentEmoteSpot = null;
			}
		}
	}

	internal void SetColor()
	{
		//IL_010d: 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_0149: 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_0194: 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_01c6: 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_01de: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e3: 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_00c2: 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)
		if (validPlayers > 0)
		{
			((Component)this).GetComponentsInChildren<Renderer>()[((Component)this).GetComponentsInChildren<Renderer>().Length - 1].material.color = Color.green;
			Renderer[] componentsInChildren = ((Component)this).GetComponentsInChildren<Renderer>();
			foreach (Renderer val in componentsInChildren)
			{
				val.material.SetColor("_EmissionColor", Color.green);
			}
			ParticleSystemRenderer[] componentsInChildren2 = ((Component)this).GetComponentsInChildren<ParticleSystemRenderer>();
			foreach (ParticleSystemRenderer val2 in componentsInChildren2)
			{
				((Renderer)val2).material.SetColor("_EmissionColor", Color.green);
			}
			ParticleSystem[] componentsInChildren3 = ((Component)this).GetComponentsInChildren<ParticleSystem>();
			foreach (ParticleSystem val3 in componentsInChildren3)
			{
				TrailModule trails = val3.trails;
				((TrailModule)(ref trails)).colorOverTrail = MinMaxGradient.op_Implicit(Color.green);
			}
		}
		else
		{
			((Component)this).GetComponentsInChildren<Renderer>()[((Component)this).GetComponentsInChildren<Renderer>().Length - 1].material.color = new Color(0.003921569f, 52f / 85f, 38f / 51f);
			Renderer[] componentsInChildren4 = ((Component)this).GetComponentsInChildren<Renderer>();
			foreach (Renderer val4 in componentsInChildren4)
			{
				val4.material.SetColor("_EmissionColor", new Color(0.003921569f, 52f / 85f, 38f / 51f));
			}
			ParticleSystemRenderer[] componentsInChildren5 = ((Component)this).GetComponentsInChildren<ParticleSystemRenderer>();
			foreach (ParticleSystemRenderer val5 in componentsInChildren5)
			{
				((Renderer)val5).material.SetColor("_EmissionColor", new Color(0.003921569f, 52f / 85f, 38f / 51f));
			}
			ParticleSystem[] componentsInChildren6 = ((Component)this).GetComponentsInChildren<ParticleSystem>();
			foreach (ParticleSystem val6 in componentsInChildren6)
			{
				TrailModule trails2 = val6.trails;
				((TrailModule)(ref trails2)).colorOverTrail = MinMaxGradient.op_Implicit(new Color(0.003921569f, 52f / 85f, 38f / 51f));
			}
		}
	}
}
public class AudioContainer : MonoBehaviour
{
	internal List<GameObject> playingObjects = new List<GameObject>();
}
public class AudioObject : MonoBehaviour
{
	internal int spot;

	internal int playerCount;

	internal GameObject audioObject;

	internal int activeObjectsSpot;
}
public class BonePair
{
	public Transform original;

	public Transform newiginal;

	public BonePair(Transform n, Transform o)
	{
		newiginal = n;
		original = o;
	}

	public void test()
	{
	}
}
public static class DebugClass
{
	private static ManualLogSource Logger;

	public static void SetLogger(ManualLogSource logSource)
	{
		Logger = logSource;
	}

	public static void Log(object message)
	{
		Logger.Log((LogLevel)16, (object)$"{message}");
	}
}
public class EmoteNetworker : NetworkBehaviour
{
	public static EmoteNetworker instance;

	private void Awake()
	{
		((Object)this).name = "Bigma Lalls";
		instance = this;
	}

	public void SyncEmote(ulong playerId, string animation, int pos)
	{
		if (((NetworkBehaviour)this).IsOwner && ((NetworkBehaviour)this).IsServer)
		{
			SyncEmoteToClients(playerId, animation, pos);
		}
		else
		{
			SyncEmoteToServerRpc(playerId, animation, pos);
		}
	}

	public void SyncEmoteToClients(ulong playerId, string animation, int pos)
	{
		GameObject gameObject = ((Component)((NetworkBehaviour)this).GetNetworkObject(playerId)).gameObject;
		if (!Object.op_Implicit((Object)(object)gameObject))
		{
			DebugClass.Log("Body is null!!!");
		}
		int eventNum = -1;
		CustomAnimationClip customAnimationClip = BoneMapper.animClips[animation];
		try
		{
			((object)customAnimationClip.clip[0]).ToString();
			eventNum = Random.Range(0, BoneMapper.primaryAudioClips[customAnimationClip.syncPos].Length);
		}
		catch (Exception)
		{
		}
		SyncEmoteToClientRpc(playerId, animation, pos, eventNum);
	}

	[ClientRpc]
	public void SyncEmoteToClientRpc(ulong playerId, string animation, int pos, int eventNum)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: 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(1218916340u, val, (RpcDelivery)0);
			BytePacker.WriteValueBitPacked(val2, playerId);
			bool flag = animation != null;
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
			if (flag)
			{
				((FastBufferWriter)(ref val2)).WriteValueSafe(animation, false);
			}
			BytePacker.WriteValueBitPacked(val2, pos);
			BytePacker.WriteValueBitPacked(val2, eventNum);
			((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1218916340u, val, (RpcDelivery)0);
		}
		if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
		{
			return;
		}
		GameObject gameObject = ((Component)((NetworkBehaviour)this).GetNetworkObject(playerId)).gameObject;
		if (!Object.op_Implicit((Object)(object)gameObject))
		{
			DebugClass.Log("Body is null!!!");
		}
		BoneMapper componentInChildren = gameObject.GetComponentInChildren<BoneMapper>();
		if (componentInChildren.playerController != null && componentInChildren.playerController.performingEmote && !animation.Contains("BetterEmotes__") && !animation.Contains("TooManyEmotes__"))
		{
			componentInChildren.playerController.performingEmote = false;
			if (((NetworkBehaviour)componentInChildren.playerController).IsOwner)
			{
				componentInChildren.playerController.StopPerformingEmoteServerRpc();
			}
		}
		DebugClass.Log($"Recieved message to play {animation} on client. Playing on {gameObject}");
		componentInChildren.PlayAnim(animation, pos, eventNum);
	}

	[ServerRpc(RequireOwnership = false)]
	public void SyncEmoteToServerRpc(ulong playerId, string animation, int pos)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: 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)
		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(1304595851u, val, (RpcDelivery)0);
			BytePacker.WriteValueBitPacked(val2, playerId);
			bool flag = animation != null;
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
			if (flag)
			{
				((FastBufferWriter)(ref val2)).WriteValueSafe(animation, false);
			}
			BytePacker.WriteValueBitPacked(val2, pos);
			((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1304595851u, val, (RpcDelivery)0);
		}
		if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
		{
			SyncEmoteToClients(playerId, animation, pos);
		}
	}

	public void SyncJoinSpot(ulong playerId, ulong joinSpotId, bool worldProp, int posInArray)
	{
		if (((NetworkBehaviour)this).IsOwner && ((NetworkBehaviour)this).IsServer)
		{
			SyncJoinSpotToClientRpc(playerId, joinSpotId, worldProp, posInArray);
		}
		else
		{
			SyncJoinSpotToServerRpc(playerId, joinSpotId, worldProp, posInArray);
		}
	}

	[ClientRpc]
	public void SyncJoinSpotToClientRpc(ulong playerId, ulong joinSpotId, bool worldProp, int posInArray)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: 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_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_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)
		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(770217386u, val, (RpcDelivery)0);
			BytePacker.WriteValueBitPacked(val2, playerId);
			BytePacker.WriteValueBitPacked(val2, joinSpotId);
			((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref worldProp, default(ForPrimitives));
			BytePacker.WriteValueBitPacked(val2, posInArray);
			((NetworkBehaviour)this).__endSendClientRpc(ref val2, 770217386u, val, (RpcDelivery)0);
		}
		if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
		{
			GameObject gameObject = ((Component)((NetworkBehaviour)this).GetNetworkObject(playerId)).gameObject;
			GameObject gameObject2 = ((Component)((NetworkBehaviour)this).GetNetworkObject(joinSpotId)).gameObject;
			if (!Object.op_Implicit((Object)(object)gameObject))
			{
				DebugClass.Log("Body is null!!!");
			}
			if (!Object.op_Implicit((Object)(object)gameObject2))
			{
				DebugClass.Log("spotObject is null!!!");
			}
			BoneMapper componentInChildren = gameObject.GetComponentInChildren<BoneMapper>();
			componentInChildren.PlayAnim("none", 0, -1);
			componentInChildren.currentEmoteSpot = ((Component)gameObject2.GetComponentsInChildren<EmoteLocation>()[posInArray]).gameObject;
			if (worldProp)
			{
				CustomEmotesAPI.JoinedProp(componentInChildren.currentEmoteSpot, componentInChildren, componentInChildren.currentEmoteSpot.GetComponent<EmoteLocation>().owner);
			}
			else
			{
				CustomEmotesAPI.JoinedBody(componentInChildren.currentEmoteSpot, componentInChildren, componentInChildren.currentEmoteSpot.GetComponent<EmoteLocation>().owner);
			}
		}
	}

	[ServerRpc(RequireOwnership = false)]
	public void SyncJoinSpotToServerRpc(ulong playerId, ulong joinSpotId, bool worldProp, int posInArray)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: 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_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_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)
		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(711293682u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, playerId);
				BytePacker.WriteValueBitPacked(val2, joinSpotId);
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref worldProp, default(ForPrimitives));
				BytePacker.WriteValueBitPacked(val2, posInArray);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 711293682u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsSer

plugins/Gemumoddo-LethalEmotesAPI/LethalEmotesApi.Ui.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using LethalEmotesApi.Ui.Animation;
using LethalEmotesApi.Ui.Customize;
using LethalEmotesApi.Ui.Customize.DragDrop;
using LethalEmotesApi.Ui.Customize.Preview;
using LethalEmotesApi.Ui.Customize.RebindConflict;
using LethalEmotesApi.Ui.Customize.Wheel;
using LethalEmotesApi.Ui.Data;
using LethalEmotesApi.Ui.Db;
using LethalEmotesApi.Ui.Elements;
using LethalEmotesApi.Ui.Elements.Recycle;
using LethalEmotesApi.Ui.NetcodePatcher;
using LethalEmotesApi.Ui.Utils;
using LethalEmotesApi.Ui.Wheel;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.Rendering;
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("LethalEmotesApi.Ui")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+55a1e71f9c35eedd9ce7791eeb50354e32e3daff")]
[assembly: AssemblyProduct("LethalEmotesApi.Ui")]
[assembly: AssemblyTitle("LethalEmotesApi.Ui")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
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 LethalEmotesApi.Ui
{
	internal static class DebugUtils
	{
		public static string ToPrettyString<T>(this IEnumerable<T> enumerable)
		{
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			stringBuilder.AppendLine("{");
			num++;
			int num2 = 0;
			foreach (T item in enumerable)
			{
				if (item != null)
				{
					for (int i = 0; i < num; i++)
					{
						stringBuilder.Append("    ");
					}
					stringBuilder.AppendLine($"[{num2}]: {item.ToString()}");
					num2++;
				}
			}
			stringBuilder.AppendLine("}");
			return stringBuilder.ToString();
		}
	}
	public static class EmoteUiManager
	{
		private static IEmoteUiStateController? _stateController;

		internal static EmoteUiPanel? emoteUiInstance;

		private static bool _hasShownDmcaPrompt;

		private static EmoteWheelSetDisplayData? _emoteDisplayData;

		internal static IEmoteDb EmoteDb => _stateController.EmoteDb;

		internal static IReadOnlyCollection<string> EmoteKeys => _stateController.EmoteDb.EmoteKeys;

		internal static IReadOnlyCollection<string> RandomPoolBlacklist => _stateController.RandomPoolBlacklist;

		internal static IReadOnlyCollection<string> EmotePoolBlacklist => _stateController.EmotePoolBlacklist;

		public static float EmoteVolume
		{
			get
			{
				return _stateController.EmoteVolume;
			}
			set
			{
				_stateController.EmoteVolume = value;
			}
		}

		public static bool HideJoinSpots
		{
			get
			{
				return _stateController.HideJoinSpots;
			}
			set
			{
				_stateController.HideJoinSpots = value;
			}
		}

		public static int RootMotionType
		{
			get
			{
				return _stateController.RootMotionType;
			}
			set
			{
				_stateController.RootMotionType = value;
			}
		}

		public static bool EmotesAlertEnemies
		{
			get
			{
				return _stateController.EmotesAlertEnemies;
			}
			set
			{
				_stateController.EmotesAlertEnemies = value;
			}
		}

		public static int DmcaFree
		{
			get
			{
				return _stateController.DmcaFree;
			}
			set
			{
				_stateController.DmcaFree = value;
			}
		}

		public static int ThirdPerson
		{
			get
			{
				return _stateController.ThirdPerson;
			}
			set
			{
				_stateController.ThirdPerson = value;
			}
		}

		public static bool UseGlobalSettings
		{
			get
			{
				return _stateController.UseGlobalSettings;
			}
			set
			{
				_stateController.UseGlobalSettings = value;
			}
		}

		public static bool DontShowDmcaPrompt
		{
			get
			{
				return _stateController.DontShowDmcaPrompt;
			}
			set
			{
				_stateController.DontShowDmcaPrompt = value;
			}
		}

		public static void RegisterStateController(IEmoteUiStateController stateController)
		{
			_stateController = stateController;
		}

		public static IEmoteUiStateController? GetStateController()
		{
			return _stateController;
		}

		internal static void PlayEmote(string emoteKey)
		{
			try
			{
				_stateController?.PlayEmote(emoteKey);
			}
			catch
			{
				Debug.Log((object)"Emote selected might not exist");
			}
		}

		internal static void LockMouseInput()
		{
			_stateController?.LockMouseInput();
		}

		internal static void UnlockMouseInput()
		{
			_stateController?.UnlockMouseInput();
		}

		internal static void LockPlayerInput()
		{
			_stateController?.LockPlayerInput();
		}

		internal static void UnlockPlayerInput()
		{
			_stateController?.UnlockPlayerInput();
		}

		internal static void EnableKeybinds()
		{
			_stateController?.EnableKeybinds();
		}

		internal static void DisableKeybinds()
		{
			_stateController?.DisableKeybinds();
		}

		internal static void PlayAnimationOn(Animator animator, string emoteKey)
		{
			_stateController?.PlayAnimationOn(animator, emoteKey);
		}

		internal static string GetEmoteName(string emoteKey)
		{
			IEmoteDb emoteDb = _stateController.EmoteDb;
			if (emoteDb.EmoteExists(emoteKey))
			{
				return emoteDb.GetEmoteName(emoteKey);
			}
			if (_emoteDisplayData == null)
			{
				return emoteKey;
			}
			return _emoteDisplayData.EmoteKeyEmoteNameLut.GetValueOrDefault(emoteKey, emoteKey);
		}

		internal static string GetEmoteModName(string emoteKey)
		{
			IEmoteDb emoteDb = _stateController.EmoteDb;
			if (emoteDb.EmoteExists(emoteKey))
			{
				return emoteDb.GetModName(emoteKey);
			}
			if (_emoteDisplayData == null)
			{
				return "Unknown";
			}
			return _emoteDisplayData.EmoteKeyModNameLut.GetValueOrDefault(emoteKey, "Unknown");
		}

		internal static bool GetEmoteVisibility(string emoteKey)
		{
			return _stateController.EmoteDb.GetEmoteVisibility(emoteKey);
		}

		internal static void AddToRandomPoolBlacklist(string emoteKey)
		{
			_stateController?.AddToRandomPoolBlacklist(emoteKey);
		}

		internal static void RemoveFromRandomPoolBlacklist(string emoteKey)
		{
			_stateController?.RemoveFromRandomPoolBlacklist(emoteKey);
		}

		internal static void AddToEmoteBlacklist(string emoteKey)
		{
			_stateController?.AddToEmoteBlacklist(emoteKey);
		}

		internal static void RemoveFromEmoteBlacklist(string emoteKey)
		{
			_stateController?.RemoveFromEmoteBlacklist(emoteKey);
		}

		internal static void RefreshBothLists()
		{
			_stateController?.RefreshBothLists();
		}

		internal static InputActionReference? GetEmoteKeybind(string? emoteKey)
		{
			if (emoteKey == null)
			{
				return null;
			}
			return _stateController?.GetEmoteKeybind(emoteKey);
		}

		internal static string[] GetEmoteKeysForBindPath(string bindPath)
		{
			return _stateController.GetEmoteKeysForBindPath(bindPath);
		}

		internal static EmoteWheelSetData LoadEmoteWheelSetData()
		{
			_emoteDisplayData = _stateController.LoadEmoteWheelSetDisplayData();
			EmoteWheelSetData emoteWheelSetData = _stateController.LoadEmoteWheelSetData();
			_stateController.SaveEmoteWheelSetDisplayData(_emoteDisplayData.LoadFromWheelSetData(emoteWheelSetData));
			return emoteWheelSetData;
		}

		internal static void SaveEmoteWheelSetData(EmoteWheelSetData dataToSave)
		{
			_stateController.SaveEmoteWheelSetData(dataToSave);
			_emoteDisplayData = _emoteDisplayData.LoadFromWheelSetData(dataToSave);
			_stateController.SaveEmoteWheelSetDisplayData(_emoteDisplayData);
			if (emoteUiInstance != null)
			{
				emoteUiInstance.ReloadData();
			}
		}

		internal static void SaveKeybinds()
		{
			_stateController?.SaveKeybinds();
		}

		internal static void LoadKeybinds()
		{
			_stateController?.LoadKeybinds();
		}

		public static bool IsEmoteWheelsOpen()
		{
			EmoteUiPanel emoteUiPanel = emoteUiInstance;
			return emoteUiPanel != null && emoteUiPanel.IsOpen && emoteUiPanel.CurrentView == EmoteUiPanel.UiView.EmoteWheels;
		}

		public static bool IsCustomizePanelOpen()
		{
			EmoteUiPanel emoteUiPanel = emoteUiInstance;
			return emoteUiPanel != null && emoteUiPanel.IsOpen && emoteUiPanel.CurrentView == EmoteUiPanel.UiView.Customize;
		}

		public static bool IsEmoteUiOpen()
		{
			return emoteUiInstance?.IsOpen ?? false;
		}

		public static bool CanOpenEmoteWheels()
		{
			if (_stateController == null)
			{
				return false;
			}
			return _stateController.CanOpenEmoteUi() && !IsCustomizePanelOpen();
		}

		public static void OnLeftWheel()
		{
			if (emoteUiInstance != null && emoteUiInstance.emoteWheelsController != null && IsEmoteWheelsOpen())
			{
				emoteUiInstance.emoteWheelsController.PrevWheel();
			}
		}

		public static void OnRightWheel()
		{
			if (emoteUiInstance != null && emoteUiInstance.emoteWheelsController != null && IsEmoteWheelsOpen())
			{
				emoteUiInstance.emoteWheelsController.NextWheel();
			}
		}

		public static void OpenEmoteWheels()
		{
			if (emoteUiInstance != null && CanOpenEmoteWheels())
			{
				emoteUiInstance.Show();
				_stateController?.DisableKeybinds();
			}
		}

		public static void CloseEmoteWheels()
		{
			if (emoteUiInstance != null && IsEmoteWheelsOpen())
			{
				emoteUiInstance.Hide();
				_stateController?.EnableKeybinds();
			}
		}

		public static void CloseCustomizationPanel()
		{
			if (emoteUiInstance != null && IsCustomizePanelOpen())
			{
				emoteUiInstance.Hide();
				_stateController?.EnableKeybinds();
			}
		}

		public static void CloseUiGracefully()
		{
			if (emoteUiInstance != null)
			{
				emoteUiInstance.CloseGracefully();
				_stateController?.EnableKeybinds();
			}
		}

		public static void ShowDmcaPrompt()
		{
			if (_stateController == null || _hasShownDmcaPrompt)
			{
				return;
			}
			ThreadPool.QueueUserWorkItem(delegate
			{
				while (emoteUiInstance == null)
				{
					Thread.Sleep(250);
				}
				_hasShownDmcaPrompt = true;
				_stateController.EnqueueWorkOnUnityThread(emoteUiInstance.ShowDmcaPrompt);
			});
		}

		public static float GetUIScale()
		{
			if (emoteUiInstance == null)
			{
				Debug.LogWarning((object)"EmoteUiInstance is null!");
				return 0f;
			}
			return ((Component)((Component)emoteUiInstance).transform.parent).GetComponent<Canvas>().scaleFactor;
		}
	}
	public class EmoteUiPanel : MonoBehaviour
	{
		internal enum UiView
		{
			None,
			EmoteWheels,
			Customize,
			DmcaPrompt,
			DmcaVerificationPrompt
		}

		public EmoteWheelsController? emoteWheelsController;

		public CustomizePanel? customizePanel;

		public RectTransform? customizeButton;

		public GameObject? dmcaPromptPrefab;

		public GameObject? dmcaVerificationPromptPrefab;

		private TextMeshProUGUI? _customizeButtonLabel;

		private GameObject? _dmcaPromptInstance;

		private GameObject? _dmcaVerificationPromptInstance;

		private UiView _prevView;

		public bool IsOpen { get; private set; }

		internal UiView CurrentView { get; private set; } = UiView.EmoteWheels;


		private void Awake()
		{
			EmoteUiManager.emoteUiInstance = this;
			if (customizeButton != null && _customizeButtonLabel == null)
			{
				_customizeButtonLabel = ((Component)customizeButton).GetComponentInChildren<TextMeshProUGUI>();
			}
		}

		private void OnEnable()
		{
			if (customizeButton != null && _customizeButtonLabel == null)
			{
				_customizeButtonLabel = ((Component)customizeButton).GetComponentInChildren<TextMeshProUGUI>();
			}
		}

		public void ReloadData()
		{
			if (emoteWheelsController != null)
			{
				emoteWheelsController.ReloadWheels();
			}
		}

		public void Show()
		{
			CurrentView = UiView.EmoteWheels;
			_prevView = UiView.None;
			UpdateCustomizeButton();
			ShowCustomizeButton();
			ShowEmoteWheels();
			EmoteUiManager.LockMouseInput();
			IsOpen = true;
		}

		public void Hide()
		{
			HideCustomizePanel();
			HideCustomizeButton();
			HideEmoteWheels();
			CloseDmcaPrompt();
			CloseDmcaVerificationPrompt();
			CurrentView = UiView.EmoteWheels;
			_prevView = UiView.None;
			EmoteUiManager.UnlockMouseInput();
			EmoteUiManager.UnlockPlayerInput();
			EmoteUiManager.EnableKeybinds();
			IsOpen = false;
		}

		public void CloseGracefully()
		{
			HideCustomizePanel();
			HideCustomizeButton();
			CloseEmoteWheelsGracefully();
			CloseDmcaVerificationPrompt();
			if (_prevView == UiView.DmcaPrompt)
			{
				CurrentView = _prevView;
				_prevView = UiView.None;
				EmoteUiManager.LockMouseInput();
				EmoteUiManager.LockPlayerInput();
				EmoteUiManager.DisableKeybinds();
			}
			else
			{
				CloseDmcaPrompt();
				CurrentView = UiView.EmoteWheels;
				_prevView = UiView.None;
				IsOpen = false;
			}
		}

		public void ToggleCustomizePanel()
		{
			if (emoteWheelsController != null)
			{
				if (CurrentView == UiView.EmoteWheels)
				{
					EmoteUiManager.GetStateController()?.RefreshTME();
					CloseEmoteWheelsGracefully();
					ShowCustomizePanel();
					CurrentView = UiView.Customize;
					EmoteUiManager.LockPlayerInput();
				}
				else if (CurrentView == UiView.Customize)
				{
					Hide();
				}
				UpdateCustomizeButton();
			}
		}

		public void ShowEmoteWheels()
		{
			if (emoteWheelsController != null)
			{
				emoteWheelsController.Show();
				((Component)emoteWheelsController.wheelLabel).gameObject.SetActive(true);
			}
		}

		public void HideEmoteWheels()
		{
			if (emoteWheelsController != null)
			{
				emoteWheelsController.Hide();
				((Component)emoteWheelsController.wheelLabel).gameObject.SetActive(false);
			}
		}

		public void CloseEmoteWheelsGracefully()
		{
			if (emoteWheelsController != null)
			{
				emoteWheelsController.CloseGracefully();
				((Component)emoteWheelsController.wheelLabel).gameObject.SetActive(false);
			}
		}

		public void ShowCustomizePanel()
		{
			if (customizePanel != null)
			{
				((Component)customizePanel).gameObject.SetActive(true);
			}
		}

		public void HideCustomizePanel()
		{
			RebindConflictController.CancelExisting();
			if (customizePanel != null)
			{
				customizePanel.dragDropController.CancelDrag();
				((Component)customizePanel).gameObject.SetActive(false);
				EmoteUiManager.UnlockPlayerInput();
				EmoteUiManager.UnlockMouseInput();
			}
		}

		public void ShowCustomizeButton()
		{
			if (customizeButton != null)
			{
				((Component)customizeButton).gameObject.SetActive(true);
			}
		}

		public void HideCustomizeButton()
		{
			if (customizeButton != null)
			{
				((Component)customizeButton).gameObject.SetActive(false);
			}
		}

		private void UpdateCustomizeButton()
		{
			if (_customizeButtonLabel != null)
			{
				((TMP_Text)_customizeButtonLabel).SetText((CurrentView == UiView.EmoteWheels) ? "Customize" : "Close", true);
			}
		}

		public void ShowDmcaPrompt()
		{
			if (dmcaPromptPrefab != null)
			{
				CloseGracefully();
				if (_dmcaPromptInstance != null && Object.op_Implicit((Object)(object)_dmcaPromptInstance))
				{
					Object.DestroyImmediate((Object)(object)_dmcaPromptInstance);
					_dmcaPromptInstance = null;
				}
				CurrentView = UiView.DmcaPrompt;
				_dmcaPromptInstance = Object.Instantiate<GameObject>(dmcaPromptPrefab, ((Component)this).transform);
				EmoteUiManager.LockMouseInput();
				EmoteUiManager.LockPlayerInput();
				EmoteUiManager.DisableKeybinds();
				IsOpen = true;
			}
		}

		private void CloseDmcaPrompt()
		{
			if (_dmcaPromptInstance != null)
			{
				Object.DestroyImmediate((Object)(object)_dmcaPromptInstance);
				_dmcaPromptInstance = null;
			}
		}

		public void ShowDmcaVerificationPrompt()
		{
			if (dmcaVerificationPromptPrefab != null)
			{
				if (CurrentView == UiView.DmcaPrompt)
				{
					_prevView = UiView.DmcaPrompt;
				}
				else
				{
					CloseGracefully();
				}
				if (_dmcaVerificationPromptInstance != null && Object.op_Implicit((Object)(object)_dmcaVerificationPromptInstance))
				{
					Object.DestroyImmediate((Object)(object)_dmcaVerificationPromptInstance);
					_dmcaVerificationPromptInstance = null;
				}
				CurrentView = UiView.DmcaVerificationPrompt;
				_dmcaVerificationPromptInstance = Object.Instantiate<GameObject>(dmcaVerificationPromptPrefab, ((Component)this).transform);
				EmoteUiManager.LockMouseInput();
				EmoteUiManager.LockPlayerInput();
				EmoteUiManager.DisableKeybinds();
				IsOpen = true;
			}
		}

		private void CloseDmcaVerificationPrompt()
		{
			if (_dmcaVerificationPromptInstance != null)
			{
				Object.DestroyImmediate((Object)(object)_dmcaVerificationPromptInstance);
				_dmcaVerificationPromptInstance = null;
			}
		}

		private void OnDestroy()
		{
			EmoteUiManager.emoteUiInstance = null;
		}
	}
	[ExecuteAlways]
	public class WheelSegmentGen : MonoBehaviour
	{
		public Material segmentMat;

		public ColorBlock colorBlock;

		[Range(1f, 20f)]
		public int segments = 8;

		[Range(-90f, 90f)]
		public float offset;

		[Range(0f, 700f)]
		public float maxRadius = 300f;

		[Range(0f, 699f)]
		public float minRadius = 100f;

		private void OnDrawGizmos()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: 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_00b8: 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_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_0110: 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)
			if (minRadius >= maxRadius)
			{
				minRadius = maxRadius - 1f;
			}
			Vector3 position = ((Component)this).transform.position;
			float num = (float)(Math.PI * 2.0 / (double)segments);
			Vector3 val = default(Vector3);
			Vector3 val2 = default(Vector3);
			for (int i = 0; i < segments; i++)
			{
				float num2 = (float)i * num + MathF.PI / 180f * offset;
				float num3 = ((float)i * num + (float)(i + 1) * num) / 2f + MathF.PI / 180f * offset;
				float num4 = (float)((double)position.x + Math.Cos(num2) * (double)maxRadius);
				float num5 = (float)((double)position.y + Math.Sin(num2) * (double)maxRadius);
				float num6 = (float)((double)position.x + Math.Cos(num2) * (double)minRadius);
				float num7 = (float)((double)position.y + Math.Sin(num2) * (double)minRadius);
				((Vector3)(ref val))..ctor(num6, num7, position.z);
				((Vector3)(ref val2))..ctor(num4, num5, position.z);
				Gizmos.DrawLine(val, val2);
			}
		}
	}
}
namespace LethalEmotesApi.Ui.Wheel
{
	[RequireComponent(typeof(CanvasGroup))]
	public class EmoteWheel : MonoBehaviour, IPointerMoveHandler, IEventSystemHandler
	{
		private class EmoteSelectedCallback : UnityEvent<string>
		{
		}

		private readonly TweenRunner<AnimCurveTween<Vector3Tween>> _posTweenRunner = new TweenRunner<AnimCurveTween<Vector3Tween>>();

		private readonly TweenRunner<AnimCurveTween<FloatTween>> _alphaTweenRunner = new TweenRunner<AnimCurveTween<FloatTween>>();

		private readonly DelayedActionRunner<DelayedAction> _delayedActionRunner = new DelayedActionRunner<DelayedAction>();

		public CanvasGroup? canvasGroup;

		public WheelStopEmote? wheelStopEmote;

		public ColorBlock colors;

		[Range(1f, 2f)]
		public float scaleMultiplier;

		public int segmentCount = 8;

		public float segmentRotOffset = 22.5f;

		public float minRadius = 100f;

		public float maxRadius = 300f;

		public List<EmoteWheelSegment> wheelSegments = new List<EmoteWheelSegment>();

		public string[] emoteArray;

		private int _currentSegmentIndex = -1;

		private RectTransform? _rectTransform;

		private readonly EmoteSelectedCallback _emoteSelectedCallback = new EmoteSelectedCallback();

		private bool _focused;

		public bool Focused
		{
			get
			{
				return _focused;
			}
			set
			{
				_focused = value;
				foreach (EmoteWheelSegment wheelSegment in wheelSegments)
				{
					wheelSegment.focused = _focused;
				}
				if (!_focused)
				{
					((UnityEventBase)_emoteSelectedCallback).RemoveAllListeners();
				}
			}
		}

		protected EmoteWheel()
		{
			emoteArray = new string[segmentCount];
			_posTweenRunner.Init((MonoBehaviour)(object)this);
			_alphaTweenRunner.Init((MonoBehaviour)(object)this);
			_delayedActionRunner.Init((MonoBehaviour)(object)this);
		}

		private void Awake()
		{
			//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)
			_rectTransform = ((Component)this).GetComponent<RectTransform>();
			if (canvasGroup == null)
			{
				canvasGroup = ((Component)this).GetComponent<CanvasGroup>();
			}
			foreach (EmoteWheelSegment wheelSegment in wheelSegments)
			{
				wheelSegment.colors = colors;
				wheelSegment.scaleMultiplier = scaleMultiplier;
				wheelSegment.targetGraphic.segmentCount = segmentCount;
				wheelSegment.targetGraphic.segmentRotOffset = segmentRotOffset;
				wheelSegment.targetGraphic.minRadius = minRadius;
				wheelSegment.targetGraphic.maxRadius = maxRadius;
				wheelSegment.ResetState();
			}
		}

		private void OnEnable()
		{
			ResetState();
		}

		public void OnPointerMove(PointerEventData eventData)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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_009f: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
			if (!_focused)
			{
				return;
			}
			Vector2 val = default(Vector2);
			RectTransformUtility.ScreenPointToLocalPointInRectangle(_rectTransform, eventData.position, eventData.enterEventCamera, ref val);
			Rect rect = _rectTransform.rect;
			float num = Vector2.Distance(Vector2.zero, val);
			if (num < minRadius)
			{
				DeSelectAll();
				((UnityEvent<string>)(object)_emoteSelectedCallback).Invoke("none");
				wheelStopEmote.OnPointerEnter(eventData);
				return;
			}
			if (val.x > ((Rect)(ref rect)).xMax || val.x < ((Rect)(ref rect)).xMin || val.y > ((Rect)(ref rect)).yMax || val.y < ((Rect)(ref rect)).yMin)
			{
				DeSelectAll();
				((UnityEvent<string>)(object)_emoteSelectedCallback).Invoke("");
				return;
			}
			int closestSegmentIndex = GetClosestSegmentIndex(val);
			if (closestSegmentIndex != _currentSegmentIndex)
			{
				wheelStopEmote.OnPointerExit(eventData);
				if (_currentSegmentIndex > -1)
				{
					wheelSegments[_currentSegmentIndex].OnPointerExit(eventData);
				}
				_currentSegmentIndex = closestSegmentIndex;
				wheelSegments[closestSegmentIndex].OnPointerEnter(eventData);
				((UnityEvent<string>)(object)_emoteSelectedCallback).Invoke(emoteArray[_currentSegmentIndex]);
			}
		}

		public void DeSelectAll()
		{
			_currentSegmentIndex = -1;
			foreach (EmoteWheelSegment wheelSegment in wheelSegments)
			{
				wheelSegment.DeSelect();
			}
		}

		public void ResetState()
		{
			_currentSegmentIndex = -1;
			foreach (EmoteWheelSegment wheelSegment in wheelSegments)
			{
				wheelSegment.ResetState();
			}
			_posTweenRunner.StopTween();
			_alphaTweenRunner.StopTween();
			_delayedActionRunner.StopAction();
			canvasGroup.alpha = 1f;
		}

		public void LoadEmotes(string[] emotes)
		{
			emoteArray = emotes;
			for (int i = 0; i < emoteArray.Length; i++)
			{
				wheelSegments[i].targetLabel?.SetEmote(emoteArray[i]);
			}
		}

		private int GetClosestSegmentIndex(Vector2 mousePos)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: 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_003b: 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_003f: Unknown result type (might be due to invalid IL or missing references)
			int result = -1;
			float num = float.MaxValue;
			for (int i = 0; i < wheelSegments.Count; i++)
			{
				EmoteWheelSegment emoteWheelSegment = wheelSegments[i];
				Vector2 val = Vector2.op_Implicit(((Transform)emoteWheelSegment.segmentRectTransform).position - ((Transform)_rectTransform).position);
				float num2 = Vector2.Distance(val, mousePos);
				if (num2 < num)
				{
					num = num2;
					result = i;
				}
			}
			return result;
		}

		public void AddOnEmoteSelectedCallback(UnityAction<string> callback)
		{
			((UnityEvent<string>)(object)_emoteSelectedCallback).AddListener(callback);
		}

		public void TweenPos(Vector3 targetPos, AnimationCurve curve, float duration, bool ignoreTimeScale)
		{
			//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_004b: Unknown result type (might be due to invalid IL or missing references)
			if (((Component)this).transform.localPosition == targetPos)
			{
				_posTweenRunner.StopTween();
				return;
			}
			Vector3Tween vector3Tween = default(Vector3Tween);
			vector3Tween.Duration = duration;
			vector3Tween.StartValue = ((Component)this).transform.localPosition;
			vector3Tween.TargetValue = targetPos;
			vector3Tween.IgnoreTimeScale = ignoreTimeScale;
			Vector3Tween wrappedTweenValue = vector3Tween;
			wrappedTweenValue.AddOnChangedCallback(TweenPosChanged);
			AnimCurveTween<Vector3Tween> animCurveTween = default(AnimCurveTween<Vector3Tween>);
			animCurveTween.WrappedTweenValue = wrappedTweenValue;
			animCurveTween.Curve = curve;
			AnimCurveTween<Vector3Tween> tweenValue = animCurveTween;
			_posTweenRunner.StartTween(tweenValue);
		}

		private void TweenPosChanged(Vector3 pos)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			((Component)this).transform.localPosition = pos;
		}

		public void TweenAlpha(float targetAlpha, AnimationCurve curve, float duration, bool ignoreTimeScale)
		{
			if (canvasGroup != null)
			{
				if (canvasGroup.alpha == targetAlpha)
				{
					_alphaTweenRunner.StopTween();
					return;
				}
				FloatTween floatTween = default(FloatTween);
				floatTween.Duration = duration;
				floatTween.StartValue = canvasGroup.alpha;
				floatTween.TargetValue = targetAlpha;
				floatTween.IgnoreTimeScale = ignoreTimeScale;
				FloatTween wrappedTweenValue = floatTween;
				wrappedTweenValue.AddOnChangedCallback(TweenAlphaChanged);
				AnimCurveTween<FloatTween> animCurveTween = default(AnimCurveTween<FloatTween>);
				animCurveTween.WrappedTweenValue = wrappedTweenValue;
				animCurveTween.Curve = curve;
				AnimCurveTween<FloatTween> tweenValue = animCurveTween;
				_alphaTweenRunner.StartTween(tweenValue);
			}
		}

		private void TweenAlphaChanged(float alpha)
		{
			canvasGroup.alpha = alpha;
		}

		public void DisableAfterDuration(float duration, bool ignoreTimeScale)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			if (!((Component)this).gameObject.activeInHierarchy)
			{
				_delayedActionRunner.StopAction();
				return;
			}
			DelayedAction delayedAction = default(DelayedAction);
			delayedAction.Duration = duration;
			delayedAction.IgnoreTimeScale = ignoreTimeScale;
			delayedAction.Action = new UnityAction(DelayedDisable);
			DelayedAction delayedAction2 = delayedAction;
			_delayedActionRunner.StartAction(delayedAction2);
		}

		private void DelayedDisable()
		{
			((Component)this).gameObject.SetActive(false);
		}
	}
	public class EmoteWheelsController : MonoBehaviour
	{
		public GameObject? wheelPrefab;

		public RectTransform? wheelContainer;

		public TextMeshProUGUI? wheelLabel;

		public float fadeDist = 500f;

		public float fadeDuration = 0.5f;

		public AnimationCurve? fadeCurve;

		private EmoteWheel[] _wheels = Array.Empty<EmoteWheel>();

		private int _currentWheelIndex;

		private string _selectedEmote = "";

		private bool _wheelLock;

		private EmoteWheelSetData WheelSetData => EmoteUiManager.LoadEmoteWheelSetData();

		public void Start()
		{
			InitWheels();
		}

		private void OnEnable()
		{
			ReloadWheels();
		}

		public void ReloadWheels()
		{
			if (WheelSetData.EmoteWheels.Length != _wheels.Length)
			{
				EmoteWheel[] wheels = _wheels;
				foreach (EmoteWheel emoteWheel in wheels)
				{
					Object.DestroyImmediate((Object)(object)((Component)emoteWheel).gameObject);
				}
				InitWheels();
			}
			else
			{
				for (int j = 0; j < _wheels.Length; j++)
				{
					EmoteWheel emoteWheel2 = _wheels[j];
					EmoteWheelData emoteWheelData = WheelSetData.EmoteWheels[j];
					((Component)emoteWheel2).gameObject.SetActive(true);
					emoteWheel2.LoadEmotes(emoteWheelData.Emotes);
				}
			}
		}

		public void LockWheels()
		{
			_wheelLock = true;
			if (_currentWheelIndex >= 0)
			{
				_wheels[_currentWheelIndex].DeSelectAll();
			}
		}

		public void UnlockWheels()
		{
			_wheelLock = false;
		}

		private void InitWheels()
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			if (wheelPrefab == null || wheelContainer == null)
			{
				return;
			}
			int num = WheelSetData.EmoteWheels.Length;
			if (_wheels.Length != num)
			{
				_wheels = new EmoteWheel[num];
				for (int i = 0; i < _wheels.Length; i++)
				{
					GameObject val = Object.Instantiate<GameObject>(wheelPrefab, (Transform)(object)wheelContainer);
					val.transform.localPosition = Vector3.zero;
					EmoteWheel component = val.GetComponent<EmoteWheel>();
					EmoteWheelData emoteWheelData = WheelSetData.EmoteWheels[i];
					component.LoadEmotes(emoteWheelData.Emotes);
					component.Focused = false;
					((Component)component).gameObject.SetActive(false);
					_wheels[i] = component;
				}
				_currentWheelIndex = 0;
				int num2 = WheelSetData.IndexOfDefault();
				if (num2 >= 0)
				{
					_currentWheelIndex = num2;
				}
				UpdateWheelState();
			}
		}

		public void NextWheel()
		{
			if (!_wheelLock)
			{
				int currentWheelIndex = _currentWheelIndex;
				_currentWheelIndex++;
				if (_currentWheelIndex >= _wheels.Length)
				{
					_currentWheelIndex = 0;
				}
				EmoteWheel emoteWheel = _wheels[currentWheelIndex];
				emoteWheel.Focused = false;
				emoteWheel.DeSelectAll();
				FadeWheelLeft(currentWheelIndex);
				UpdateWheelState();
			}
		}

		public void PrevWheel()
		{
			if (!_wheelLock)
			{
				int currentWheelIndex = _currentWheelIndex;
				_currentWheelIndex--;
				if (_currentWheelIndex < 0)
				{
					_currentWheelIndex = _wheels.Length - 1;
				}
				EmoteWheel emoteWheel = _wheels[currentWheelIndex];
				emoteWheel.Focused = false;
				emoteWheel.DeSelectAll();
				FadeWheelRight(currentWheelIndex);
				UpdateWheelState();
			}
		}

		public void Show()
		{
			UnlockWheels();
			if (wheelContainer != null)
			{
				int num = WheelSetData.IndexOfDefault();
				if (num >= 0)
				{
					_currentWheelIndex = num;
				}
				EmoteWheel currentWheel = GetCurrentWheel();
				((Component)currentWheel).gameObject.SetActive(true);
				((Component)wheelContainer).gameObject.SetActive(true);
				if (wheelLabel != null)
				{
					((Component)wheelLabel).gameObject.SetActive(true);
					UpdateWheelState();
				}
			}
		}

		public void Hide()
		{
			UnlockWheels();
			if (wheelContainer == null)
			{
				return;
			}
			EmoteWheel[] wheels = _wheels;
			foreach (EmoteWheel emoteWheel in wheels)
			{
				((Component)emoteWheel).gameObject.SetActive(false);
			}
			((Component)wheelContainer).gameObject.SetActive(false);
			if (!string.IsNullOrEmpty(_selectedEmote))
			{
				EmoteUiManager.PlayEmote(_selectedEmote);
				_selectedEmote = "none";
				if (wheelLabel != null)
				{
					((Component)wheelLabel).gameObject.SetActive(false);
				}
			}
		}

		public void CloseGracefully()
		{
			if (wheelContainer != null)
			{
				EmoteWheel[] wheels = _wheels;
				foreach (EmoteWheel emoteWheel in wheels)
				{
					((Component)emoteWheel).gameObject.SetActive(false);
				}
				((Component)wheelContainer).gameObject.SetActive(false);
				_selectedEmote = "";
				if (wheelLabel != null)
				{
					((Component)wheelLabel).gameObject.SetActive(false);
				}
			}
		}

		private EmoteWheel GetCurrentWheel()
		{
			return _wheels[_currentWheelIndex];
		}

		private void UpdateWheelState()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			EmoteWheel currentWheel = GetCurrentWheel();
			((Component)currentWheel).gameObject.SetActive(true);
			Transform transform = ((Component)currentWheel).transform;
			transform.SetAsLastSibling();
			transform.localPosition = Vector3.zero;
			currentWheel.ResetState();
			currentWheel.Focused = true;
			currentWheel.AddOnEmoteSelectedCallback(UpdateSelectedEmote);
			EmoteWheelData emoteWheelData = WheelSetData.EmoteWheels[_currentWheelIndex];
			((TMP_Text)wheelLabel).SetText(emoteWheelData.Name, true);
		}

		private void UpdateSelectedEmote(string selectedEmote)
		{
			_selectedEmote = selectedEmote;
		}

		private void FadeWheelLeft(int wheelIndex, bool instant = false)
		{
			FadeWheel(wheelIndex, left: true, instant);
		}

		private void FadeWheelRight(int wheelIndex, bool instant = false)
		{
			FadeWheel(wheelIndex, left: false, instant);
		}

		private void FadeWheel(int wheelIndex, bool left, bool instant = false)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (fadeCurve != null)
			{
				EmoteWheel emoteWheel = _wheels[wheelIndex];
				Vector3 targetPos = default(Vector3);
				((Vector3)(ref targetPos))..ctor(left ? (0f - fadeDist) : fadeDist, 0f, 0f);
				emoteWheel.TweenPos(targetPos, fadeCurve, instant ? 0f : fadeDuration, ignoreTimeScale: true);
				emoteWheel.TweenAlpha(0f, fadeCurve, instant ? 0f : fadeDuration, ignoreTimeScale: true);
				emoteWheel.DisableAfterDuration(instant ? 0f : fadeDuration, ignoreTimeScale: true);
			}
		}
	}
	[DisallowMultipleComponent]
	[RequireComponent(typeof(RectTransform))]
	[ExecuteAlways]
	public class EmoteWheelSegment : UIBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public WheelSegmentGraphic? targetGraphic;

		public SegmentLabel? targetLabel;

		public RectTransform? segmentRectTransform;

		public ColorBlock colors;

		[Range(1f, 2f)]
		public float scaleMultiplier;

		public bool selected;

		public bool focused;

		private bool IsSelected()
		{
			return selected && focused;
		}

		protected override void Awake()
		{
			((UIBehaviour)this).Awake();
			if (targetGraphic == null)
			{
				targetGraphic = ((Component)this).GetComponentInChildren<WheelSegmentGraphic>();
			}
			if (targetLabel == null)
			{
				targetLabel = ((Component)this).GetComponentInChildren<SegmentLabel>();
			}
		}

		protected override void OnEnable()
		{
			((UIBehaviour)this).OnEnable();
			UpdateState(requireFocus: false, instant: true);
		}

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

		public void OnPointerExit(PointerEventData eventData)
		{
			selected = false;
			UpdateState();
		}

		public void DeSelect()
		{
			selected = false;
			UpdateState(requireFocus: false);
		}

		public void ResetState()
		{
			selected = false;
			UpdateState(requireFocus: false, instant: true);
		}

		private Color GetColor()
		{
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (IsSelected())
			{
				return ((ColorBlock)(ref colors)).selectedColor;
			}
			return ((ColorBlock)(ref colors)).normalColor;
		}

		private float GetScale()
		{
			if (IsSelected())
			{
				return scaleMultiplier;
			}
			return 1f;
		}

		private void UpdateState(bool requireFocus = true, bool instant = false)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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 (!(!focused && requireFocus))
			{
				Color color = GetColor();
				StartColorTween(color * ((ColorBlock)(ref colors)).colorMultiplier, instant);
				StartScaleTween(GetScale(), instant);
			}
		}

		private void StartColorTween(Color targetColor, bool instant)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (targetGraphic != null)
			{
				((Graphic)targetGraphic).CrossFadeColor(targetColor, instant ? 0f : ((ColorBlock)(ref colors)).fadeDuration, true, true);
			}
		}

		private void StartScaleTween(float targetScale, bool instant)
		{
			//IL_0024: 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 (targetGraphic != null && targetLabel != null)
			{
				targetGraphic.TweenScale(new Vector3(targetScale, targetScale, targetScale), instant ? 0f : ((ColorBlock)(ref colors)).fadeDuration, ignoreTimeScale: true);
				targetLabel.TweenScale(new Vector3(targetScale, targetScale, targetScale), instant ? 0f : ((ColorBlock)(ref colors)).fadeDuration, ignoreTimeScale: true);
			}
		}
	}
	[DisallowMultipleComponent]
	[RequireComponent(typeof(RectTransform))]
	[ExecuteAlways]
	public class SegmentLabel : UIBehaviour
	{
		private readonly TweenRunner<Vector3Tween> _scaleTweenRunner = new TweenRunner<Vector3Tween>();

		public RectTransform? targetLabel;

		public TextMeshProUGUI? targetText;

		public RectTransform? missingLabel;

		public TextMeshProUGUI? missingText;

		public RectTransform? lockedLabel;

		public TextMeshProUGUI? lockedText;

		private RectTransform? _rectTransform;

		private string? _emoteKey;

		protected DrivenRectTransformTracker tracker;

		public RectTransform RectTransform
		{
			get
			{
				if (_rectTransform == null)
				{
					_rectTransform = ((Component)this).GetComponent<RectTransform>();
				}
				return _rectTransform;
			}
		}

		protected SegmentLabel()
		{
			_scaleTweenRunner.Init((MonoBehaviour)(object)this);
		}

		protected override void OnEnable()
		{
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: 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)
			((UIBehaviour)this).OnEnable();
			if (targetLabel != null && missingLabel != null && lockedLabel != null)
			{
				((DrivenRectTransformTracker)(ref tracker)).Add((Object)(object)this, targetLabel, (DrivenTransformProperties)16);
				((DrivenRectTransformTracker)(ref tracker)).Add((Object)(object)this, missingLabel, (DrivenTransformProperties)16);
				((DrivenRectTransformTracker)(ref tracker)).Add((Object)(object)this, lockedLabel, (DrivenTransformProperties)16);
				Vector3 eulerAngles = ((Transform)RectTransform).eulerAngles;
				((Transform)targetLabel).localEulerAngles = -eulerAngles;
				((Transform)missingLabel).localEulerAngles = -eulerAngles;
				((Transform)lockedLabel).localEulerAngles = -eulerAngles;
				UpdateText();
			}
		}

		protected override void OnDisable()
		{
			((UIBehaviour)this).OnDisable();
			((DrivenRectTransformTracker)(ref tracker)).Clear();
		}

		public void SetEmote(string? emoteKey)
		{
			_emoteKey = emoteKey;
			UpdateText();
		}

		private void UpdateText()
		{
			if (targetText != null && missingLabel != null && missingText != null && _emoteKey != null)
			{
				string emoteName = EmoteUiManager.GetEmoteName(_emoteKey);
				((Component)lockedLabel).gameObject.SetActive(false);
				((Component)missingLabel).gameObject.SetActive(false);
				if (!EmoteUiManager.EmoteDb.EmoteExists(_emoteKey))
				{
					((TMP_Text)targetText).SetText("", true);
					string emoteModName = EmoteUiManager.GetEmoteModName(_emoteKey);
					((TMP_Text)missingText).SetText("<color=#FFFFFF>" + emoteName + "</color>\n<color=#eed202>Requires</color>\n<color=#FFFFFF>" + emoteModName + "</color>", true);
					((Component)missingLabel).gameObject.SetActive(true);
				}
				else if (!EmoteUiManager.GetEmoteVisibility(_emoteKey))
				{
					((TMP_Text)targetText).SetText("", true);
					((TMP_Text)lockedText).SetText("<color=#eed202>Unlock</color>\n" + emoteName + "\n<color=#eed202>With</color>\nTooManyEmotes", true);
					((Component)lockedLabel).gameObject.SetActive(true);
				}
				else
				{
					((TMP_Text)targetText).SetText(emoteName, true);
				}
			}
		}

		public void TweenScale(Vector3 targetScale, float duration, bool ignoreTimeScale)
		{
			//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_004b: Unknown result type (might be due to invalid IL or missing references)
			if (((Component)this).transform.localScale == targetScale)
			{
				_scaleTweenRunner.StopTween();
				return;
			}
			Vector3Tween vector3Tween = default(Vector3Tween);
			vector3Tween.Duration = duration;
			vector3Tween.StartValue = ((Component)this).transform.localScale;
			vector3Tween.TargetValue = targetScale;
			vector3Tween.IgnoreTimeScale = ignoreTimeScale;
			Vector3Tween tweenValue = vector3Tween;
			tweenValue.AddOnChangedCallback(TweenScaleChanged);
			_scaleTweenRunner.StartTween(tweenValue);
		}

		private void TweenScaleChanged(Vector3 scale)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			((Component)this).transform.localScale = scale;
		}
	}
	[DisallowMultipleComponent]
	[RequireComponent(typeof(CanvasRenderer))]
	[ExecuteAlways]
	public class WheelSegmentGraphic : Graphic
	{
		private readonly TweenRunner<Vector3Tween> _scaleTweenRunner = new TweenRunner<Vector3Tween>();

		public int segmentCount = 8;

		public float segmentRotOffset = 22.5f;

		public float minRadius = 100f;

		public float maxRadius = 300f;

		protected WheelSegmentGraphic()
		{
			_scaleTweenRunner.Init((MonoBehaviour)(object)this);
		}

		protected override void OnEnable()
		{
			((Graphic)this).OnEnable();
			((Graphic)this).raycastTarget = false;
		}

		protected override void OnPopulateMesh(VertexHelper vh)
		{
			//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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: 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_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_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: 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_013d: 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_0147: 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_0158: 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_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			vh.Clear();
			Color32 val = Color32.op_Implicit(((Graphic)this).color);
			float num = (float)(Math.PI * 2.0 / (double)segmentCount);
			float num2 = num + MathF.PI / 180f * segmentRotOffset;
			int num3 = 0;
			float num4 = MathF.PI / 180f;
			Vector3 val2 = CosSin(num2, minRadius);
			Vector3 val3 = CosSin(num2 + num, minRadius);
			Vector3 val4 = -Vector3.Lerp(val2, val3, 0.5f);
			float num5 = num + num4 / 2f - num4;
			for (float num6 = 0f; num6 < num5; num6 += num4)
			{
				float rad = num2 + num6;
				Vector3 val5 = CosSin(rad, minRadius) + val4;
				Vector3 val6 = CosSin(rad, maxRadius) + val4;
				rad = num2 + num6 + num4;
				Vector3 val7 = CosSin(rad, minRadius) + val4;
				Vector3 val8 = CosSin(rad, maxRadius) + val4;
				float num7 = num6 / num5;
				float num8 = (num6 + num4) / num5;
				vh.AddVert(val5, val, Vector4.op_Implicit(new Vector2(num7, 0f)));
				vh.AddVert(val6, val, Vector4.op_Implicit(new Vector2(num7, 1f)));
				vh.AddVert(val7, val, Vector4.op_Implicit(new Vector2(num8, 0f)));
				vh.AddVert(val8, val, Vector4.op_Implicit(new Vector2(num8, 1f)));
				vh.AddTriangle(num3 + 2, num3 + 1, num3);
				vh.AddTriangle(num3 + 3, num3 + 1, num3 + 2);
				num3 += 4;
			}
		}

		private static Vector3 CosSin(float rad, float dist)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			float num = (float)(Math.Cos(rad) * (double)dist);
			float num2 = (float)(Math.Sin(rad) * (double)dist);
			return new Vector3(num, num2, 0f);
		}

		public void TweenScale(Vector3 targetScale, float duration, bool ignoreTimeScale)
		{
			//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_004b: Unknown result type (might be due to invalid IL or missing references)
			if (((Component)this).transform.localScale == targetScale)
			{
				_scaleTweenRunner.StopTween();
				return;
			}
			Vector3Tween vector3Tween = default(Vector3Tween);
			vector3Tween.Duration = duration;
			vector3Tween.StartValue = ((Component)this).transform.localScale;
			vector3Tween.TargetValue = targetScale;
			vector3Tween.IgnoreTimeScale = ignoreTimeScale;
			Vector3Tween tweenValue = vector3Tween;
			tweenValue.AddOnChangedCallback(TweenScaleChanged);
			_scaleTweenRunner.StartTween(tweenValue);
		}

		private void TweenScaleChanged(Vector3 scale)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			((Component)this).transform.localScale = scale;
		}
	}
	[DisallowMultipleComponent]
	[RequireComponent(typeof(RectTransform))]
	[ExecuteAlways]
	public class WheelStopEmote : UIBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public WheelStopEmoteGraphic? backgroundGraphic;

		public Graphic? foregroundGraphic;

		public LeUiScaleTweener? scaleTweener;

		public ColorBlock colors;

		[Range(1f, 2f)]
		public float scaleMultiplier;

		public bool selected;

		protected override void OnEnable()
		{
			((UIBehaviour)this).OnEnable();
			UpdateState(instant: true);
		}

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

		public void OnPointerExit(PointerEventData eventData)
		{
			selected = false;
			UpdateState();
		}

		private Color GetBackgroundColor()
		{
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (selected)
			{
				return ((ColorBlock)(ref colors)).selectedColor;
			}
			return ((ColorBlock)(ref colors)).normalColor;
		}

		private Color GetForegroundColor()
		{
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (selected)
			{
				return ((ColorBlock)(ref colors)).highlightedColor;
			}
			return ((ColorBlock)(ref colors)).disabledColor;
		}

		private float GetScale()
		{
			if (selected)
			{
				return scaleMultiplier;
			}
			return 1f;
		}

		private void UpdateState(bool instant = false)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0010: 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_002d: Unknown result type (might be due to invalid IL or missing references)
			Color backgroundColor = GetBackgroundColor();
			Color foregroundColor = GetForegroundColor();
			StartColorTween(foregroundColor * ((ColorBlock)(ref colors)).colorMultiplier, backgroundColor * ((ColorBlock)(ref colors)).colorMultiplier, instant);
			float scale = GetScale();
			StartScaleTween(scale, instant);
		}

		private void StartColorTween(Color foregroundColor, Color backgroundColor, bool instant)
		{
			//IL_0007: 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)
			((Graphic)backgroundGraphic).CrossFadeColor(backgroundColor, instant ? 0f : ((ColorBlock)(ref colors)).fadeDuration, true, true);
			foregroundGraphic.CrossFadeColor(foregroundColor, instant ? 0f : ((ColorBlock)(ref colors)).fadeDuration, true, true);
		}

		private void StartScaleTween(float scale, bool instant)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			if (scaleTweener != null)
			{
				Vector3 targetScale = default(Vector3);
				((Vector3)(ref targetScale))..ctor(scale, scale, scale);
				scaleTweener.TweenScale(targetScale, instant ? 0f : ((ColorBlock)(ref colors)).fadeDuration, ignoreTimeScale: true);
			}
		}
	}
	[DisallowMultipleComponent]
	[RequireComponent(typeof(CanvasRenderer))]
	[ExecuteAlways]
	public class WheelStopEmoteGraphic : Graphic
	{
		public float radius = 95f;

		protected override void OnPopulateMesh(VertexHelper vh)
		{
			//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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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_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_0079: 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_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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			vh.Clear();
			Color32 val = Color32.op_Implicit(((Graphic)this).color);
			float num = MathF.PI * 2f;
			int num2 = 0;
			float num3 = MathF.PI / 180f;
			for (float num4 = 0f; num4 + num3 < num; num4 += num3)
			{
				float rad = num4;
				Vector3 val2 = CosSin(rad, radius);
				rad = num4 + num3;
				Vector3 val3 = CosSin(rad, radius);
				vh.AddVert(Vector3.zero, val, Vector4.op_Implicit(new Vector2(0f, 0f)));
				vh.AddVert(val2, val, Vector4.op_Implicit(new Vector2(0f, 1f)));
				vh.AddVert(Vector3.zero, val, Vector4.op_Implicit(new Vector2(1f, 0f)));
				vh.AddVert(val3, val, Vector4.op_Implicit(new Vector2(1f, 1f)));
				vh.AddTriangle(num2 + 2, num2 + 1, num2);
				vh.AddTriangle(num2 + 3, num2 + 1, num2 + 2);
				num2 += 4;
			}
		}

		private static Vector3 CosSin(float rad, float dist)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			float num = (float)(Math.Cos(rad) * (double)dist);
			float num2 = (float)(Math.Sin(rad) * (double)dist);
			return new Vector3(num, num2, 0f);
		}
	}
}
namespace LethalEmotesApi.Ui.Utils
{
	internal static class RectTransformUtils
	{
		private static Camera? _uiCamera;

		private static readonly Vector3[] Corners = (Vector3[])(object)new Vector3[4];

		private static Camera GetUiCamera()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (_uiCamera != null && Object.op_Implicit((Object)(object)_uiCamera))
			{
				return _uiCamera;
			}
			_uiCamera = null;
			Scene activeScene = SceneManager.GetActiveScene();
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref activeScene)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject go) => ((Object)go).name == "Systems"));
			if (val == null)
			{
				Debug.LogWarning((object)"Failed to find UICamera in active scene, falling back to Camera.current!");
				return Camera.current;
			}
			Transform val2 = val.transform.Find("UI/UICamera");
			if (val2 == null)
			{
				Debug.LogWarning((object)"Failed to find UICamera at MainMenu, falling back to Camera.current!");
				return Camera.current;
			}
			Camera component = ((Component)val2).GetComponent<Camera>();
			if (component == null)
			{
				Debug.LogWarning((object)"Failed to find Camera component on UICamera, falling back to Camera.current!");
				return Camera.current;
			}
			_uiCamera = component;
			return _uiCamera;
		}

		public static Rect GetRelativeRect(this RectTransform root, RectTransform worldRectTransform)
		{
			//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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00bc: 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_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: 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_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_00e0: 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_00ec: 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_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			Camera uiCamera = GetUiCamera();
			worldRectTransform.GetWorldCorners(Corners);
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			for (int i = 0; i < Corners.Length; i++)
			{
				array[i] = Vector2.op_Implicit(RectTransformUtility.WorldToScreenPoint(uiCamera, Corners[i]));
			}
			Vector2[] array2 = (Vector2[])(object)new Vector2[4];
			for (int j = 0; j < array.Length; j++)
			{
				RectTransformUtility.ScreenPointToLocalPointInRectangle(root, Vector2.op_Implicit(array[j]), uiCamera, ref array2[j]);
			}
			Vector2 val = Vector2.zero;
			Vector2 val2 = Vector2.zero;
			Vector2[] array3 = array2;
			foreach (Vector2 val3 in array3)
			{
				val = Vector2.Min(val, val3);
				val2 = Vector2.Max(val2, val3);
			}
			Vector2 val4 = val2 - val;
			return new Rect(val.x, val.y, val4.x, val4.y);
		}
	}
}
namespace LethalEmotesApi.Ui.Options
{
	public class DmcaFreeDropdown : LeUiDropdown
	{
		protected override int GetCurrentValue()
		{
			return EmoteUiManager.DmcaFree;
		}

		protected override void SetCurrentValue(int value)
		{
			EmoteUiManager.DmcaFree = value;
		}
	}
	public class DontShowDmcaPromptToggle : LeUiToggle
	{
		protected override bool GetCurrentValue()
		{
			return EmoteUiManager.DontShowDmcaPrompt;
		}

		protected override void SetCurrentValue(bool value)
		{
			EmoteUiManager.DontShowDmcaPrompt = value;
		}
	}
	public class EmotesAlertEnemies : LeUiToggle
	{
		protected override bool GetCurrentValue()
		{
			return EmoteUiManager.EmotesAlertEnemies;
		}

		protected override void SetCurrentValue(bool value)
		{
			EmoteUiManager.EmotesAlertEnemies = value;
		}
	}
	public class EmoteVolumeSlider : MonoBehaviour
	{
		public Slider? volumeSlider;

		private bool _hasListener;

		private void Awake()
		{
			UpdateSliderValue();
			EnsureListener();
		}

		private void Start()
		{
			UpdateSliderValue();
			EnsureListener();
		}

		private void OnEnable()
		{
			UpdateSliderValue();
			EnsureListener();
		}

		private void UpdateStateBroadcast()
		{
			UpdateSliderValue();
		}

		private void UpdateSliderValue()
		{
			if (volumeSlider != null)
			{
				volumeSlider.value = EmoteUiManager.EmoteVolume;
			}
		}

		private void EnsureListener()
		{
			if (volumeSlider != null && !_hasListener)
			{
				((UnityEvent<float>)(object)volumeSlider.onValueChanged).AddListener((UnityAction<float>)SliderChanged);
				_hasListener = true;
			}
		}

		private void SliderChanged(float value)
		{
			EmoteUiManager.EmoteVolume = value;
			SetValueWithoutNotify(value);
		}

		private void SetValueWithoutNotify(float value)
		{
			if (volumeSlider != null)
			{
				volumeSlider.SetValueWithoutNotify(value);
			}
		}
	}
	public class HideJoinSpots : LeUiToggle
	{
		protected override bool GetCurrentValue()
		{
			return EmoteUiManager.HideJoinSpots;
		}

		protected override void SetCurrentValue(bool value)
		{
			EmoteUiManager.HideJoinSpots = value;
		}
	}
	public abstract class LeUiDropdown : MonoBehaviour
	{
		public TMP_Dropdown? dropdown;

		private bool _hasListener;

		private void Awake()
		{
			UpdateDropdown();
			EnsureListener();
		}

		private void Start()
		{
			UpdateDropdown();
			EnsureListener();
		}

		private void OnEnable()
		{
			UpdateDropdown();
			EnsureListener();
		}

		private void UpdateDropdown()
		{
			if (dropdown != null)
			{
				dropdown.value = GetCurrentValue();
			}
		}

		private void EnsureListener()
		{
			if (dropdown != null && !_hasListener)
			{
				((UnityEvent<int>)(object)dropdown.onValueChanged).AddListener((UnityAction<int>)DropdownChanged);
				_hasListener = true;
			}
		}

		private void DropdownChanged(int value)
		{
			SetCurrentValue(value);
			SetValueWithoutNotify(value);
		}

		protected abstract int GetCurrentValue();

		protected abstract void SetCurrentValue(int value);

		private void SetValueWithoutNotify(int value)
		{
			if (dropdown != null)
			{
				dropdown.SetValueWithoutNotify(value);
			}
		}

		private void UpdateStateBroadcast()
		{
			UpdateDropdown();
		}
	}
	public abstract class LeUiToggle : MonoBehaviour
	{
		public Image? checkboxImage;

		private void Awake()
		{
			UpdateCheckbox();
		}

		private void Start()
		{
			UpdateCheckbox();
		}

		private void OnEnable()
		{
			UpdateCheckbox();
		}

		public void Toggle()
		{
			SetCurrentValue(!GetCurrentValue());
			UpdateCheckbox();
		}

		private void UpdateCheckbox()
		{
			if (checkboxImage != null)
			{
				((Behaviour)checkboxImage).enabled = GetCurrentValue();
			}
		}

		protected abstract bool GetCurrentValue();

		protected abstract void SetCurrentValue(bool value);

		private void UpdateStateBroadcast()
		{
			UpdateCheckbox();
		}
	}
	public class RootMotionTypeDropdown : LeUiDropdown
	{
		protected override int GetCurrentValue()
		{
			return EmoteUiManager.RootMotionType;
		}

		protected override void SetCurrentValue(int value)
		{
			EmoteUiManager.RootMotionType = value;
		}
	}
	public class ThirdPersonDropdown : LeUiDropdown
	{
		protected override int GetCurrentValue()
		{
			return EmoteUiManager.ThirdPerson;
		}

		protected override void SetCurrentValue(int value)
		{
			EmoteUiManager.ThirdPerson = value;
		}
	}
	public class UseGlobalSettings : LeUiToggle
	{
		protected override bool GetCurrentValue()
		{
			return EmoteUiManager.UseGlobalSettings;
		}

		protected override void SetCurrentValue(bool value)
		{
			EmoteUiManager.UseGlobalSettings = !value;
			EmoteUiManager.UseGlobalSettings = value;
			EmoteUiManager.RefreshBothLists();
			EmoteUiManager.emoteUiInstance.ReloadData();
			((Component)((Component)this).GetComponentInParent<CustomizePanel>()).gameObject.BroadcastMessage("UpdateStateBroadcast");
		}
	}
}
namespace LethalEmotesApi.Ui.Hud
{
	[DefaultExecutionOrder(-4)]
	public class HealthEmoteRenderer : MonoBehaviour
	{
		public SkinnedMeshRenderer? emoteSkinnedMeshRenderer;

		public Material? material;

		public RenderTexture? targetRenderTexture;

		private CommandBuffer? _cmdBuf;

		private readonly Matrix4x4 _projMat = Matrix4x4.Perspective(60f, 1f, 0.3f, 15f);

		private Matrix4x4 GetViewMatrix()
		{
			//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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: 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_0072: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: 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)
			Transform transform = ((Component)this).transform;
			Matrix4x4 val = Matrix4x4.Rotate(Quaternion.Inverse(transform.rotation)) * Matrix4x4.Translate(-transform.position);
			if (SystemInfo.usesReversedZBuffer)
			{
				val.m20 = 0f - val.m20;
				val.m21 = 0f - val.m21;
				val.m22 = 0f - val.m22;
				val.m23 = 0f - val.m23;
			}
			return val;
		}

		private void Start()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			_cmdBuf = new CommandBuffer();
		}

		private void LateUpdate()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			_cmdBuf.Clear();
			_cmdBuf.SetViewProjectionMatrices(GetViewMatrix(), _projMat);
			_cmdBuf.DrawRenderer((Renderer)(object)emoteSkinnedMeshRenderer, material);
			Graphics.SetRenderTarget(targetRenderTexture);
			GL.Clear(false, true, Color.green);
			Graphics.ExecuteCommandBuffer(_cmdBuf);
		}

		private void OnDestroy()
		{
			CommandBuffer? cmdBuf = _cmdBuf;
			if (cmdBuf != null)
			{
				cmdBuf.Dispose();
			}
		}
	}
}
namespace LethalEmotesApi.Ui.Elements
{
	[DisallowMultipleComponent]
	public class LeUiButton : UIBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler, IPointerDownHandler, IPointerUpHandler, IPointerClickHandler
	{
		public Graphic? targetGraphic;

		public LeUiScaleTweener? scaleTweener;

		public ColorBlock colors;

		[Range(0f, 2f)]
		public float scaleSelected;

		[Range(0f, 2f)]
		public float scalePressed;

		public UnityEvent onClick = new UnityEvent();

		public UnityEvent onEnter = new UnityEvent();

		public UnityEvent onExit = new UnityEvent();

		private bool _selected;

		private bool _pressed;

		protected override void OnEnable()
		{
			((UIBehaviour)this).OnEnable();
			UpdateState(instant: true);
		}

		public void OnPointerEnter(PointerEventData eventData)
		{
			_selected = true;
			onEnter.Invoke();
			UpdateState();
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			_selected = false;
			onExit.Invoke();
			UpdateState();
		}

		public void OnPointerDown(PointerEventData eventData)
		{
			_pressed = _selected;
			UpdateState();
		}

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

		public void OnPointerClick(PointerEventData eventData)
		{
			onClick.Invoke();
		}

		private Color GetColor()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if (_pressed)
			{
				return ((ColorBlock)(ref colors)).pressedColor;
			}
			if (_selected)
			{
				return ((ColorBlock)(ref colors)).selectedColor;
			}
			return ((ColorBlock)(ref colors)).normalColor;
		}

		private float GetScale()
		{
			if (_pressed)
			{
				return scalePressed;
			}
			if (_selected)
			{
				return scaleSelected;
			}
			return 1f;
		}

		private void UpdateState(bool instant = false)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: 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)
			Color color = GetColor();
			targetGraphic.CrossFadeColor(color, instant ? 0f : ((ColorBlock)(ref colors)).fadeDuration, true, true);
			float scale = GetScale();
			Vector3 targetScale = default(Vector3);
			((Vector3)(ref targetScale))..ctor(scale, scale, scale);
			scaleTweener.TweenScale(targetScale, instant ? 0f : ((ColorBlock)(ref colors)).fadeDuration, ignoreTimeScale: true);
		}
	}
	[DisallowMultipleComponent]
	[ExecuteAlways]
	public class LeUiScaleTweener : MonoBehaviour
	{
		private readonly TweenRunner<Vector3Tween> _scaleTweenRunner = new TweenRunner<Vector3Tween>();

		private Vector3 _internalScale = Vector3.one;

		public List<RectTransform> targets = new List<RectTransform>();

		protected LeUiScaleTweener()
		{
			//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)
			_scaleTweenRunner.Init((MonoBehaviour)(object)this);
		}

		public void TweenScale(Vector3 targetScale, float duration, bool ignoreTimeScale)
		{
			//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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if (_internalScale == targetScale)
			{
				_scaleTweenRunner.StopTween();
				return;
			}
			Vector3Tween vector3Tween = default(Vector3Tween);
			vector3Tween.Duration = duration;
			vector3Tween.IgnoreTimeScale = ignoreTimeScale;
			vector3Tween.StartValue = _internalScale;
			vector3Tween.TargetValue = targetScale;
			Vector3Tween tweenValue = vector3Tween;
			tweenValue.AddOnChangedCallback(TweenScaleChanged);
			_scaleTweenRunner.StartTween(tweenValue);
		}

		private void TweenScaleChanged(Vector3 scale)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			_internalScale = scale;
			foreach (RectTransform target in targets)
			{
				((Transform)target).localScale = scale;
			}
		}
	}
	public class LeUiSelectOutline : UIBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public Image? selectImage;

		public void OnPointerEnter(PointerEventData eventData)
		{
			if (selectImage != null)
			{
				((Behaviour)selectImage).enabled = true;
			}
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			if (selectImage != null)
			{
				((Behaviour)selectImage).enabled = false;
			}
		}
	}
}
namespace LethalEmotesApi.Ui.Elements.Recycle
{
	public interface IRecycleViewItem<in TData>
	{
		int ConstraintIndex { get; set; }

		RectTransform RectTransform { get; }

		void BindData(TData data);
	}
	[DisallowMultipleComponent]
	[RequireComponent(typeof(RectTransform))]
	public abstract class RecycleListView<TRecycleItem, TData> : UIBehaviour where TRecycleItem : Component, IRecycleViewItem<TData>
	{
		public enum Constraint
		{
			Columns,
			Rows
		}

		public ScrollRect? scrollRect;

		public GameObject? listItemPrefab;

		public RectOffset padding = new RectOffset();

		public float spacing;

		public Vector2 preferredItemSize;

		public Corner startCorner;

		public Constraint constraint;

		public int maxInConstraint;

		public int minPoolSize = 10;

		public float requiredCoverageMultiplier = 1.5f;

		public float recyclingThreshold = 0.2f;

		private RectTransform? _recycleViewTransform;

		private RectTransform? _viewport;

		private RectTransform? _content;

		private Bounds _viewBounds;

		private Vector2 _prevAnchoredPos;

		private bool _recycling;

		private bool _firstUpdate;

		private readonly RecyclePool<TRecycleItem, TData> _pool = new RecyclePool<TRecycleItem, TData>();

		private DrivenRectTransformTracker _tracker;

		private DrivenRectTransformTracker _poolTracker;

		protected abstract IList<TData> ListData { get; }

		protected override void Awake()
		{
			((UIBehaviour)this).Awake();
			_recycleViewTransform = ((Component)this).GetComponent<RectTransform>();
			if (scrollRect != null)
			{
				_viewport = scrollRect.viewport;
				_content = scrollRect.content;
				if (_viewport != null && _content != null)
				{
					((DrivenRectTransformTracker)(ref _tracker)).Add((Object)(object)this, _content, (DrivenTransformProperties)65286);
					((UnityEvent<Vector2>)(object)scrollRect.onValueChanged).AddListener((UnityAction<Vector2>)HandleScroll);
				}
			}
		}

		protected override void Start()
		{
			((UIBehaviour)this).Start();
			UpdateState();
		}

		protected override void OnEnable()
		{
			((UIBehaviour)this).OnEnable();
		}

		protected virtual void Update()
		{
			if (!_firstUpdate)
			{
				UpdateState();
				_firstUpdate = true;
			}
		}

		private void OnValidate()
		{
			UpdateState();
		}

		public void UpdateState()
		{
			UpdateContentSize();
			UpdateViewBounds();
			SetupPool();
		}

		private void UpdateContentSize()
		{
			//IL_00c9: 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_00b2: 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)
			if (_content != null)
			{
				int num = Mathf.CeilToInt((float)ListData.Count / (float)maxInConstraint);
				float num2 = ((constraint == Constraint.Columns) ? preferredItemSize.y : preferredItemSize.x);
				int num3 = ((constraint == Constraint.Columns) ? (padding.top + padding.bottom) : (padding.left + padding.right));
				float num4 = (float)num3 + (spacing * (float)(num - 1) + num2 * (float)num);
				_content.sizeDelta = ((constraint == Constraint.Columns) ? new Vector2(_content.sizeDelta.x, num4) : new Vector2(num4, _content.sizeDelta.y));
			}
		}

		private void UpdateViewBounds()
		{
			//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_0072: 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)
			if (_recycleViewTransform != null && _viewport != null)
			{
				Rect relativeRect = _recycleViewTransform.GetRelativeRect(_viewport);
				float num = ((Rect)(ref relativeRect)).width / 2f * recyclingThreshold;
				float num2 = ((Rect)(ref relativeRect)).height / 2f * recyclingThreshold;
				((Bounds)(ref _viewBounds)).min = new Vector3(((Rect)(ref relativeRect)).xMin - num, ((Rect)(ref relativeRect)).yMin - num2);
				((Bounds)(ref _viewBounds)).max = new Vector3(((Rect)(ref relativeRect)).xMax + num, ((Rect)(ref relativeRect)).yMax + num2);
			}
		}

		private void SetupPool()
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00a0: 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_00a9: Invalid comparison between Unknown and I4
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: 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_00e1: Invalid comparison between Unknown and I4
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: 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_01c8: Invalid comparison between Unknown and I4
			//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_01ee: 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_01f3: Invalid comparison between Unknown and I4
			//IL_029c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: 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)
			//IL_0308: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_030f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0311: Unknown result type (might be due to invalid IL or missing references)
			//IL_0313: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Expected I4, but got Unknown
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_0390: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_044c: 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_03ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_042d: Unknown result type (might be due to invalid IL or missing references)
			//IL_048a: Unknown result type (might be due to invalid IL or missing references)
			//IL_04de: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0500: Expected I4, but got Unknown
			//IL_0507: Unknown result type (might be due to invalid IL or missing references)
			//IL_0567: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0623: Unknown result type (might be due to invalid IL or missing references)
			//IL_0537: Unknown result type (might be due to invalid IL or missing references)
			//IL_0597: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f7: 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)
			if (listItemPrefab == null || _viewport == null || _content == null)
			{
				return;
			}
			((DrivenRectTransformTracker)(ref _poolTracker)).Clear();
			_pool.Clear();
			if (ListData.Count <= 0)
			{
				return;
			}
			Rect rect;
			float num;
			if (constraint != 0)
			{
				rect = _viewport.rect;
				num = ((Rect)(ref rect)).height;
			}
			else
			{
				rect = _viewport.rect;
				num = ((Rect)(ref rect)).width;
			}
			float num2 = num;
			float num3 = requiredCoverageMultiplier * num2;
			Corner val = startCorner;
			bool flag = (((int)val == 0 || (int)val == 2) ? true : false);
			float num4 = (flag ? padding.left : (-padding.right));
			val = startCorner;
			flag = val - 2 <= 1;
			float num5 = (flag ? (-padding.bottom) : (-padding.top));
			int num6 = ((constraint == Constraint.Columns) ? (padding.left + padding.right) : (padding.top + padding.bottom));
			float num7 = (num2 - (float)num6) / (float)maxInConstraint - spacing * (float)(maxInConstraint - 1);
			Vector2 sizeDelta = ((constraint == Constraint.Columns) ? new Vector2(Mathf.Min(preferredItemSize.x, num7), preferredItemSize.y) : new Vector2(preferredItemSize.x, Mathf.Min(preferredItemSize.y, num7)));
			val = startCorner;
			flag = (((int)val == 0 || (int)val == 2) ? true : false);
			float num8 = (flag ? 0f : 1f);
			val = startCorner;
			flag = val - 2 <= 1;
			float num9 = (flag ? 0f : 1f);
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(num8, num9);
			float num10 = 0f;
			int num11 = 0;
			while ((_pool.Size < minPoolSize || num10 < num3) && _pool.Size < ListData.Count)
			{
				TRecycleItem component = Object.Instantiate<GameObject>(listItemPrefab, (Transform)(object)_content).GetComponent<TRecycleItem>();
				((Object)((Component)component).gameObject).name = $"RecycleViewListItem {_pool.Size + 1}";
				OnInstantiateListItem(component);
				component.ConstraintIndex = num11;
				RectTransform rectTransform = component.RectTransform;
				rectTransform.anchoredPosition = new Vector2(num4, num5);
				rectTransform.anchorMin = val2;
				rectTransform.anchorMax = val2;
				rectTransform.pivot = val2;
				rectTransform.sizeDelta = sizeDelta;
				Rect rect2 = component.RectTransform.rect;
				num11++;
				switch (constraint)
				{
				case Constraint.Columns:
				{
					Corner val5 = startCorner;
					Corner val6 = val5;
					switch ((int)val6)
					{
					case 0:
						num4 = rectTransform.anchoredPosition.x + ((Rect)(ref rect2)).width + spacing;
						if (num11 >= maxInConstraint)
						{
							num4 = padding.left;
							num5 = rectTransform.anchoredPosition.y - (((Rect)(ref rect2)).height + spacing);
						}
						break;
					case 1:
						num4 = rectTransform.anchoredPosition.x - (((Rect)(ref rect2)).width + spacing);
						if (num11 >= maxInConstraint)
						{
							num4 = -padding.right;
							num5 = rectTransform.anchoredPosition.y - (((Rect)(ref rect2)).height + spacing);
						}
						break;
					case 2:
						num4 = rectTransform.anchoredPosition.x + ((Rect)(ref rect2)).width + spacing;
						if (num11 >= maxInConstraint)
						{
							num4 = padding.left;
							num5 = rectTransform.anchoredPosition.y + ((Rect)(ref rect2)).height + spacing;
						}
						break;
					case 3:
						num4 = rectTransform.anchoredPosition.x - (((Rect)(ref rect2)).width + spacing);
						if (num11 >= maxInConstraint)
						{
							num4 = -padding.right;
							num5 = rectTransform.anchoredPosition.y + ((Rect)(ref rect2)).height + spacing;
						}
						break;
					default:
						throw new ArgumentOutOfRangeException();
					}
					if (num11 >= maxInConstraint)
					{
						num11 = 0;
						num10 += ((Rect)(ref rect2)).height + spacing;
					}
					break;
				}
				case Constraint.Rows:
				{
					Corner val3 = startCorner;
					Corner val4 = val3;
					switch ((int)val4)
					{
					case 0:
						num5 = rectTransform.anchoredPosition.y - (((Rect)(ref rect2)).height + spacing);
						if (num11 >= maxInConstraint)
						{
							num4 = rectTransform.anchoredPosition.x + ((Rect)(ref rect2)).width + spacing;
							num5 = -padding.top;
						}
						break;
					case 1:
						num5 = rectTransform.anchoredPosition.y - (((Rect)(ref rect2)).height + spacing);
						if (num11 >= maxInConstraint)
						{
							num4 = rectTransform.anchoredPosition.x - (((Rect)(ref rect2)).width + spacing);
							num5 = -padding.top;
						}
						break;
					case 2:
						num5 = rectTransform.anchoredPosition.y + ((Rect)(ref rect2)).height + spacing;
						if (num11 >= maxInConstraint)
						{
							num4 = rectTransform.anchoredPosition.x + ((Rect)(ref rect2)).width + spacing;
							num5 = padding.bottom;
						}
						break;
					case 3:
						num5 = rectTransform.anchoredPosition.y + ((Rect)(ref rect2)).height + spacing;
						if (num11 >= maxInConstraint)
						{
							num4 = rectTransform.anchoredPosition.x - (((Rect)(ref rect2)).width + spacing);
							num5 = padding.bottom;
						}
						break;
					default:
						throw new ArgumentOutOfRangeException();
					}
					if (num11 >= maxInConstraint)
					{
						num11 = 0;
						num10 += ((Rect)(ref rect2)).width + spacing;
					}
					break;
				}
				default:
					throw new ArgumentOutOfRangeException();
				}
				((DrivenRectTransformTracker)(ref _poolTracker)).Add((Object)(object)this, rectTransform, (DrivenTransformProperties)65286);
				component.BindData(ListData[_pool.Size]);
				_pool.Add(component);
			}
		}

		protected abstract void OnInstantiateListItem(TRecycleItem instance);

		private void RefreshView()
		{
			int num = _pool.FirstIndex;
			foreach (TRecycleItem item in _pool)
			{
				item.BindData(ListData[num]);
				num++;
			}
		}

		private void HandleScroll(Vector2 _)
		{
			//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_0028: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			if (_content != null)
			{
				Vector2 dir = _content.anchoredPosition - _prevAnchoredPos;
				RecycleOnScroll(dir);
				_prevAnchoredPos = _content.anchoredPosition;
			}
		}

		private void RecycleOnScroll(Vector2 dir)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: 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_021c: 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_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)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Invalid comparison between Unknown and I4
			//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_010b: 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_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: 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_012e: Invalid comparison between Unknown and I4
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Invalid comparison between Unknown and I4
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_032f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Invalid comparison between Unknown and I4
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Invalid comparison between Unknown and I4
			//IL_02f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: Invalid comparison between Unknown and I4
			//IL_0346: 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_034d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0386: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Invalid comparison between Unknown and I4
			//IL_039d: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Invalid comparison between Unknown and I4
			//IL_0353: Unknown result type (might be due to invalid IL or missing references)
			//IL_0356: Invalid comparison between Unknown and I4
			//IL_03ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ae: Invalid comparison between Unknown and I4
			if (_recycling || _recycleViewTransform == null || ListData.Count <= 0)
			{
				return;
			}
			UpdateViewBounds();
			if (dir.y > 0f || dir.x > 0f)
			{
				TRecycleItem last = _pool.GetLast();
				Rect relativeRect = _recycleViewTransform.GetRelativeRect(last.RectTransform);
				switch (constraint)
				{
				case Constraint.Columns:
				{
					bool flag6 = ((Rect)(ref relativeRect)).yMax > ((Bounds)(ref _viewBounds)).min.y;
					bool flag7 = flag6;
					if (flag7)
					{
						Corner val = startCorner;
						bool flag3 = (int)val <= 1;
						flag7 = flag3;
					}
					if (flag7)
					{
						ScrollRecycleForwards();
						break;
					}
					bool flag8 = ((Rect)(ref relativeRect)).yMin < ((Bounds)(ref _viewBounds)).max.y;
					bool flag9 = flag8;
					if (flag9)
					{
						Corner val = startCorner;
						bool flag3 = val - 2 <= 1;
						flag9 = flag3;
					}
					if (flag9)
					{
						ScrollRecycleBackwards();
					}
					break;
				}
				case Constraint.Rows:
				{
					bool flag = ((Rect)(ref relativeRect)).xMax > ((Bounds)(ref _viewBounds)).min.x;
					bool flag2 = flag;
					if (flag2)
					{
						Corner val = startCorner;
						bool flag3 = (((int)val == 0 || (int)val == 2) ? true : false);
						flag2 = flag3;
					}
					if (flag2)
					{
						ScrollRecycleForwards();
						break;
					}
					bool flag4 = ((Rect)(ref relativeRect)).xMin < ((Bounds)(ref _viewBounds)).max.x;
					bool flag5 = flag4;
					if (flag5)
					{
						Corner val = startCorner;
						bool flag3 = (((int)val == 1 || (int)val == 3) ? true : false);
						flag5 = flag3;
					}
					if (flag5)
					{
						ScrollRecycleBackwards();
					}
					break;
				}
				default:
					throw new ArgumentOutOfRangeException();
				}
			}
			else
			{
				if (!(dir.y < 0f) && !(dir.x < 0f))
				{
					return;
				}
				TRecycleItem first = _pool.GetFirst();
				Rect relativeRect2 = _recycleViewTransform.GetRelativeRect(first.RectTransform);
				switch (constraint)
				{
				case Constraint.Columns:
				{
					bool flag14 = ((Rect)(ref relativeRect2)).yMin < ((Bounds)(ref _viewBounds)).max.y;
					bool flag15 = flag14;
					if (flag15)
					{
						Corner val = startCorner;
						bool flag3 = (int)val <= 1;
						flag15 = flag3;
					}
					if (flag15)
					{
						ScrollRecycleBackwards();
						break;
					}
					bool flag16 = ((Rect)(ref relativeRect2)).yMax > ((Bounds)(ref _viewBounds)).min.y;
					bool flag17 = flag16;
					if (flag17)
					{
						Corner val = startCorner;
						bool flag3 = val - 2 <= 1;
						flag17 = flag3;
					}
					if (flag17)
					{
						ScrollRecycleForwards();
					}
					break;
				}
				case Constraint.Rows:
				{
					bool flag10 = ((Rect)(ref relativeRect2)).xMin < ((Bounds)(ref _viewBounds)).max.x;
					bool flag11 = flag10;
					if (flag11)
					{
						Corner val = startCorner;
						bool flag3 = (((int)val == 0 || (int)val == 2) ? true : false);
						flag11 = flag3;
					}
					if (flag11)
					{
						ScrollRecycleBackwards();
						break;
					}
					bool flag12 = ((Rect)(ref relativeRect2)).xMax > ((Bounds)(ref _viewBounds)).min.x;
					bool flag13 = flag12;
					if (flag13)
					{
						Corner val = startCorner;
						bool flag3 = (((int)val == 1 || (int)val == 3) ? true : false);
						flag13 = flag3;
					}
					if (flag13)
					{
						ScrollRecycleForwards();
					}
					break;
				}
				default:
					throw new ArgumentOutOfRangeException();
				}
			}
		}

		private bool IsItemInsideViewBounds(TRecycleItem item)
		{
			//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_0039

plugins/no00ob-LCSoundTool/LC_SoundTool.dll

Decompiled 3 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LCSoundTool.Networking;
using LCSoundTool.Patches;
using LCSoundTool.Resources;
using LCSoundTool.Utilities;
using LCSoundToolMod.Properties;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LC_SoundTool")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Various audio related functions. Mainly logs all sounds that are playing and what type of playback they're into the BepInEx console.")]
[assembly: AssemblyFileVersion("1.5.1.0")]
[assembly: AssemblyInformationalVersion("1.5.1+88559329ca22fd77bccf008b2fc220541ba49b23")]
[assembly: AssemblyProduct("LC_SoundTool")]
[assembly: AssemblyTitle("LC_SoundTool")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/no00ob/LCSoundTool")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

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

		public const string PLUGIN_NAME = "LC_SoundTool";

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

		private static CultureInfo resourceCulture;

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

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

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

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

		public bool playOnAwake = false;

		public bool loop = false;

		private bool updateHasBeenLogged = false;

		private bool hasPlayed = false;

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

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

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

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

		public RandomAudioClip(AudioClip clip, float chance)
		{
			this.clip = clip;
			this.chance = chance;
		}
	}
	public class ReplacementAudioClip
	{
		public List<RandomAudioClip> clips;

		public string source = string.Empty;

		public bool canPlay = true;

		private bool initialized = false;

		public ReplacementAudioClip(AudioClip clip, float chance, string source)
		{
			if (!initialized)
			{
				Initialize();
			}
			RandomAudioClip randomAudioClip = new RandomAudioClip(clip, chance);
			if (!clips.ContainsThisRandomAudioClip(randomAudioClip))
			{
				clips.Add(randomAudioClip);
				this.source = source;
			}
			else if (SoundTool.infoDebugging)
			{
				SoundTool.Instance.logger.LogDebug((object)$"RandomAudioClip {randomAudioClip.clip.GetName()} ({Mathf.RoundToInt(chance * 100f)}%) already exists withing this AudioClipContainer!");
				SoundTool.Instance.logger.LogDebug((object)"- This AudioClipContainer contains the following clip(s):");
				for (int i = 0; i < clips.Count; i++)
				{
					SoundTool.Instance.logger.LogDebug((object)$"-- Clip {i + 1} - {clips[i].clip.GetName()} with a chance of {Mathf.RoundToInt(clips[i].chance * 100f)}%");
				}
			}
		}

		public ReplacementAudioClip(string source)
		{
			Initialize();
			this.source = source;
		}

		public ReplacementAudioClip()
		{
			Initialize();
			source = string.Empty;
		}

		public void AddClip(AudioClip clip, float chance)
		{
			if (!initialized)
			{
				Initialize();
			}
			RandomAudioClip randomAudioClip = new RandomAudioClip(clip, chance);
			if (!clips.ContainsThisRandomAudioClip(randomAudioClip))
			{
				clips.Add(randomAudioClip);
			}
			else if (SoundTool.infoDebugging)
			{
				SoundTool.Instance.logger.LogDebug((object)$"RandomAudioClip {randomAudioClip.clip.GetName()} ({Mathf.RoundToInt(chance * 100f)}%) already exists withing this AudioClipContainer!");
				SoundTool.Instance.logger.LogDebug((object)"- This AudioClipContainer contains the following clip(s):");
				for (int i = 0; i < clips.Count; i++)
				{
					SoundTool.Instance.logger.LogDebug((object)$"-- Clip {i + 1} - {clips[i].clip.GetName()} with a chance of {Mathf.RoundToInt(clips[i].chance * 100f)}%");
				}
			}
		}

		public bool Full()
		{
			if (!initialized)
			{
				Initialize();
			}
			float num = 0f;
			for (int i = 0; i < clips.Count; i++)
			{
				num += clips[i].chance;
			}
			return num >= 1f;
		}

		public bool ContainsClip(AudioClip clip, float chance)
		{
			if (!initialized)
			{
				Initialize();
			}
			RandomAudioClip thisClip = new RandomAudioClip(clip, chance);
			return clips.ContainsThisRandomAudioClip(thisClip);
		}

		public float TotalChance()
		{
			if (!initialized)
			{
				Initialize();
			}
			float num = 0f;
			for (int i = 0; i < clips.Count; i++)
			{
				num += clips[i].chance;
			}
			return num;
		}

		private void Initialize()
		{
			clips = new List<RandomAudioClip>();
			initialized = true;
		}
	}
	[BepInPlugin("LCSoundTool", "LC Sound Tool", "1.5.1")]
	public class SoundTool : BaseUnityPlugin
	{
		public enum AudioType
		{
			wav,
			ogg,
			mp3
		}

		private const string PLUGIN_GUID = "LCSoundTool";

		private const string PLUGIN_NAME = "LC Sound Tool";

		private ConfigEntry<bool> configUseNetworking;

		private ConfigEntry<bool> configSyncRandomSeed;

		private ConfigEntry<float> configPlayOnAwakePatchRepeatDelay;

		private ConfigEntry<bool> configPrintInfoByDefault;

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

		public static SoundTool Instance;

		internal ManualLogSource logger;

		public static bool debugAudioSources;

		public static bool indepthDebugging;

		public static bool infoDebugging;

		public static bool networkingInitialized { get; private set; }

		public static bool networkingAvailable { get; private set; }

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

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

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

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

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

		private void Awake()
		{
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			networkingAvailable = true;
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			configUseNetworking = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "EnableNetworking", false, "Whether or not to use the networking built into this plugin. If set to true everyone in the lobby needs LCSoundTool installed and networking enabled to join.");
			configSyncRandomSeed = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "SyncUnityRandomSeed", false, "Whether or not to sync the default Unity randomization seed with all clients. For this feature, networking has to be set to true. Will send the UnityEngine.Random.seed from the host to all clients automatically upon loading a networked scene.");
			configPlayOnAwakePatchRepeatDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Experimental", "NewPlayOnAwakePatchRepeatDelay", 90f, "How long to wait between checks for new playOnAwake AudioSources. Runs the same patching that is done when each scene is loaded with this delay between each run. DO NOT set too low or high. Anything below 10 or above 600 can cause issues. This time is in seconds. Set to 0 to disable rerunning the patch, but be warned that this might break runtime initialized playOnAwake AudioSources.");
			configPrintInfoByDefault = ((BaseUnityPlugin)this).Config.Bind<bool>("Logging", "PrintInfoByDefault", false, "Whether or not to print additional information logs created by this mod by default. If set to false, informational logs may be toggled on any time with LeftAlt + F5.");
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			logger = Logger.CreateLogSource("LCSoundTool");
			logger.LogInfo((object)"Plugin LCSoundTool is loaded!");
			InputHelper.Initialize();
			InputHelper.keybinds.Add("toggleAudioSourceDebugLog", new Keybind(new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[0]), ToggleDebug));
			InputHelper.keybinds.Add("toggleIndepthDebugLog", new Keybind(new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 }), ToggleIndepthDebug));
			InputHelper.keybinds.Add("toggleInformationalDebugLog", new Keybind(new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 }), ToggleInfoDebug));
			InputHelper.keybinds.Add("printAllSoundsDebugLog", new Keybind(new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), PrintAllReplacedSounds));
			InputHelper.keybinds.Add("printAllCurrentSoundsDebugLog", new Keybind(new KeyboardShortcut((KeyCode)287, (KeyCode[])(object)new KeyCode[0]), PrintAllCurrentSounds));
			debugAudioSources = false;
			indepthDebugging = false;
			if (configPrintInfoByDefault.Value)
			{
				infoDebugging = true;
			}
			else
			{
				infoDebugging = false;
			}
			replacedClips = new Dictionary<string, ReplacementAudioClip>();
		}

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

		private void Update()
		{
			if (configUseNetworking.Value)
			{
				if (!networkingInitialized)
				{
					if ((Object)(object)NetworkHandler.Instance != (Object)null)
					{
						networkingInitialized = true;
					}
				}
				else if ((Object)(object)NetworkHandler.Instance == (Object)null)
				{
					networkingInitialized = false;
				}
			}
			else
			{
				networkingInitialized = false;
			}
			if (!InputHelper.CheckInput("printAllCurrentSoundsDebugLog") && !InputHelper.CheckInput("printAllSoundsDebugLog") && !InputHelper.CheckInput("toggleInformationalDebugLog") && !InputHelper.CheckInput("toggleIndepthDebugLog") && !InputHelper.CheckInput("toggleAudioSourceDebugLog"))
			{
			}
		}

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

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)Instance == (Object)null))
			{
				PatchPlayOnAwakeAudio(scene);
				OnSceneLoadedNetworking();
				if (((Scene)(ref scene)).name.ToLower().Contains("level"))
				{
					((MonoBehaviour)this).StopAllCoroutines();
					((MonoBehaviour)this).StartCoroutine(PatchPlayOnAwakeDelayed(scene, 1f));
				}
			}
		}

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

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

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

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

		public static void ReplaceAudioClip(string originalName, AudioClip newClip)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified! This is not allowed");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without new clip specified! This is not allowed");
			}
			else
			{
				ReplaceAudioClipInternal(originalName, newClip, 1f, string.Empty);
			}
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip)
		{
			if ((Object)(object)originalClip == (Object)null || string.IsNullOrEmpty(originalClip.GetName()))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified or original clip's name is empty! This is not allowed.");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without new clip specified! This is not allowed.");
			}
			else
			{
				ReplaceAudioClipInternal(originalClip.GetName(), newClip, 1f, string.Empty);
			}
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip, float chance)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified! This is not allowed");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without new clip specified! This is not allowed");
			}
			else if (chance < 0f || chance > 1f)
			{
				Instance.logger.LogWarning((object)$"Trying to replace an audio clip with an invalid chance of {chance}! Chance has to be between 0 - 1.0");
			}
			else
			{
				ReplaceAudioClipInternal(originalName, newClip, chance, string.Empty);
			}
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, float chance)
		{
			if ((Object)(object)originalClip == (Object)null || string.IsNullOrEmpty(originalClip.GetName()))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified or original clip's name is empty! This is not allowed.");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without new clip specified! This is not allowed.");
			}
			else if (chance < 0f || chance > 1f)
			{
				Instance.logger.LogWarning((object)$"Trying to replace an audio clip with an invalid chance of {chance}! Chance has to be between 0 - 1.0");
			}
			else
			{
				ReplaceAudioClipInternal(originalClip.GetName(), newClip, chance, string.Empty);
			}
		}

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

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, string source)
		{
			if ((Object)(object)originalClip == (Object)null || string.IsNullOrEmpty(originalClip.GetName()))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified or original clip's name is empty! This is not allowed.");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
			}
			else
			{
				ReplaceAudioClipInternal(originalClip.GetName(), newClip, 1f, source);
			}
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip, string[] source)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified! This is not allowed");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			List<string> list = source.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (string.IsNullOrEmpty(list[i]))
				{
					list.RemoveAt(i);
					i--;
				}
			}
			ReplaceAudioClipInternal(originalName, newClip, 1f, string.Join(",", list));
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, string[] source)
		{
			if ((Object)(object)originalClip == (Object)null || string.IsNullOrEmpty(originalClip.GetName()))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified or original clip's name is empty! This is not allowed.");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			List<string> list = source.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (string.IsNullOrEmpty(list[i]))
				{
					list.RemoveAt(i);
					i--;
				}
			}
			ReplaceAudioClipInternal(originalClip.GetName(), newClip, 1f, string.Join(",", list));
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip, float chance, string source)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified! This is not allowed");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without new clip specified! This is not allowed");
			}
			else if (chance < 0f || chance > 1f)
			{
				Instance.logger.LogWarning((object)$"Trying to replace an audio clip with an invalid chance of {chance}! Chance has to be between 0 - 1.0");
			}
			else
			{
				ReplaceAudioClipInternal(originalName, newClip, chance, source);
			}
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, float chance, string source)
		{
			if ((Object)(object)originalClip == (Object)null || string.IsNullOrEmpty(originalClip.GetName()))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified or the specified original clip has no name! This is not allowed");
			}
			else if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without new clip specified! This is not allowed");
			}
			else if (chance < 0f || chance > 1f)
			{
				Instance.logger.LogWarning((object)$"Trying to replace an audio clip with an invalid chance of {chance}! Chance has to be between 0 - 1.0");
			}
			else
			{
				ReplaceAudioClipInternal(originalClip.GetName(), newClip, chance, source);
			}
		}

		public static void ReplaceAudioClip(string originalName, AudioClip newClip, float chance, string[] source)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified! This is not allowed");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			if (chance < 0f || chance > 1f)
			{
				Instance.logger.LogWarning((object)$"Trying to replace an audio clip with an invalid chance of {chance}! Chance has to be between 0 - 1.0");
				return;
			}
			List<string> list = source.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (string.IsNullOrEmpty(list[i]))
				{
					list.RemoveAt(i);
					i--;
				}
			}
			ReplaceAudioClipInternal(originalName, newClip, chance, string.Join(",", list));
		}

		public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, float chance, string[] source)
		{
			if ((Object)(object)originalClip == (Object)null || string.IsNullOrEmpty(originalClip.GetName()))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified or original clip's name is empty! This is not allowed.");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			if (chance < 0f || chance > 1f)
			{
				Instance.logger.LogWarning((object)$"Trying to replace an audio clip with an invalid chance of {chance}! Chance has to be between 0 - 1.0");
				return;
			}
			List<string> list = source.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (string.IsNullOrEmpty(list[i]))
				{
					list.RemoveAt(i);
					i--;
				}
			}
			ReplaceAudioClipInternal(originalClip.GetName(), newClip, chance, string.Join(",", list));
		}

		private static void ReplaceAudioClipInternal(string originalName, AudioClip newClip, float chance, string source)
		{
			string text = originalName;
			string name = newClip.GetName();
			if (!string.IsNullOrEmpty(source))
			{
				text = originalName + "#" + source;
			}
			if (replacedClips.ContainsKey(text))
			{
				replacedClips[text].AddClip(newClip, chance);
			}
			else
			{
				replacedClips.Add(text, new ReplacementAudioClip(newClip, chance, source));
			}
			float num = 0f;
			for (int i = 0; i < replacedClips[text].clips.Count(); i++)
			{
				num += replacedClips[text].clips[i].chance;
			}
			int num2 = Mathf.RoundToInt(num * 100f);
			if (infoDebugging)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[text].clips.Count()} random audio clips for audio clip {text} does not equal 100%. Currently {num2}% (at least yet?)");
			}
		}

		public static void RemoveRandomAudioClip(string name, float chance)
		{
			if (string.IsNullOrEmpty(name))
			{
				Instance.logger.LogWarning((object)"Trying to restore an audio clip without original clip specified! This is not allowed");
			}
			else if (!replacedClips.ContainsKey(name))
			{
				Instance.logger.LogWarning((object)"Trying to restore an audio clip that does not exist! This is not allowed");
			}
			else if (chance < 0f || chance > 1f)
			{
				Instance.logger.LogWarning((object)$"Trying to restore an audio clip with an invalid chance of {chance}! Chance has to be between 0 - 1.0");
			}
			else
			{
				RemoveRandomAudioClipInternal(name, chance, string.Empty);
			}
		}

		public static void RemoveRandomAudioClip(string name, float chance, string source)
		{
			if (string.IsNullOrEmpty(name))
			{
				Instance.logger.LogWarning((object)"Trying to restore an audio clip without original clip specified! This is not allowed");
			}
			else if (!replacedClips.ContainsKey(name))
			{
				Instance.logger.LogWarning((object)"Trying to restore an audio clip that does not exist! This is not allowed");
			}
			else
			{
				RemoveRandomAudioClipInternal(name, chance, source);
			}
		}

		public static void RemoveRandomAudioClip(string name, float chance, string[] source)
		{
			if (string.IsNullOrEmpty(name))
			{
				Instance.logger.LogWarning((object)"Trying to replace an audio clip without original clip specified! This is not allowed");
				return;
			}
			if (chance < 0f || chance > 1f)
			{
				Instance.logger.LogWarning((object)$"Trying to replace an audio clip with an invalid chance of {chance}! Chance has to be between 0 - 1.0");
				return;
			}
			List<string> list = source.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (string.IsNullOrEmpty(list[i]))
				{
					list.RemoveAt(i);
					i--;
				}
			}
			RemoveRandomAudioClipInternal(name, chance, string.Join(",", list));
		}

		private static void RemoveRandomAudioClipInternal(string name, float chance, string source)
		{
			if (!string.IsNullOrEmpty(source))
			{
				name = name + "#" + source;
			}
			if (!(chance > 0f))
			{
				return;
			}
			for (int i = 0; i < replacedClips[name].clips.Count(); i++)
			{
				if (replacedClips[name].clips[i].chance == chance)
				{
					replacedClips[name].clips.RemoveAt(i);
					if (replacedClips[name].clips.Count <= 0)
					{
						Instance.logger.LogDebug((object)("Removed replaced AudioClip " + name + " completely as all of it's random clips have been removed."));
						replacedClips.Remove(name);
					}
					break;
				}
			}
		}

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

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

		public static void RestoreAudioClip(string name, string[] source)
		{
			if (string.IsNullOrEmpty(name))
			{
				Instance.logger.LogWarning((object)"Trying to restore an audio clip without original clip specified! This is not allowed");
				return;
			}
			if (!replacedClips.ContainsKey(name))
			{
				Instance.logger.LogWarning((object)"Trying to restore an audio clip that does not exist! This is not allowed");
				return;
			}
			List<string> list = source.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (string.IsNullOrEmpty(list[i]))
				{
					list.RemoveAt(i);
					i--;
				}
			}
			RestoreAudioClipInternal(name, string.Join(",", list));
		}

		public static void RestoreAudioClip(AudioClip clip)
		{
			if ((Object)(object)clip == (Object)null || string.IsNullOrEmpty(clip.GetName()))
			{
				Instance.logger.LogWarning((object)"Trying to restore an audio clip without vanilla clip specified or specified clip's name is empty! This is not allowed");
			}
			else
			{
				RestoreAudioClipInternal(clip.GetName(), string.Empty);
			}
		}

		public static void RestoreAudioClip(AudioClip clip, string source)
		{
			if ((Object)(object)clip == (Object)null || string.IsNullOrEmpty(clip.GetName()))
			{
				Instance.logger.LogWarning((object)"Trying to restore an audio clip without vanilla clip specified or specified clip's name is empty! This is not allowed");
			}
			else
			{
				RestoreAudioClipInternal(clip.GetName(), source);
			}
		}

		public static void RestoreAudioClip(AudioClip clip, string[] source)
		{
			if ((Object)(object)clip == (Object)null || string.IsNullOrEmpty(clip.GetName()))
			{
				Instance.logger.LogWarning((object)"Trying to restore an audio clip without vanilla clip specified or specified clip's name is empty! This is not allowed");
				return;
			}
			List<string> list = source.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (string.IsNullOrEmpty(list[i]))
				{
					list.RemoveAt(i);
					i--;
				}
			}
			RestoreAudioClipInternal(clip.GetName(), string.Join(",", list));
		}

		private static void RestoreAudioClipInternal(string name, string source)
		{
			if (!string.IsNullOrEmpty(source))
			{
				name = name + "#" + source;
			}
			replacedClips.Remove(name);
		}

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

		public static AudioClip GetAudioClip(string modFolder, string subFolder, string soundName)
		{
			AudioType audioType = AudioType.wav;
			string[] array = soundName.Split('.');
			if (array[^1].ToLower().Contains("wav"))
			{
				audioType = AudioType.wav;
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)"File detected as a PCM WAVE file!");
				}
			}
			else if (array[^1].ToLower().Contains("ogg"))
			{
				audioType = AudioType.ogg;
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)"File detected as an Ogg Vorbis file!");
				}
			}
			else if (array[^1].ToLower().Contains("mp3"))
			{
				audioType = AudioType.mp3;
				if (infoDebugging)
				{
					Instance.logger.LogDebug((object)"File detected as a MPEG MP3 file!");
				}
			}
			else
			{
				audioType = AudioType.wav;
				Instance.logger.LogWarning((object)("Failed to detect file type of a sound file! This may cause issues with other mod functionality. Sound defaulted to WAV. Sound: " + soundName));
			}
			return GetAudioClip(modFolder, subFolder, soundName, audioType);
		}

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

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

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

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

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

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

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

		public void ToggleDebug()
		{
			debugAudioSources = !debugAudioSources;
			if (indepthDebugging && !debugAudioSources)
			{
				indepthDebugging = false;
			}
			Instance.logger.LogDebug((object)$"Toggling AudioSource debug logs {debugAudioSources}!");
		}

		public void ToggleIndepthDebug()
		{
			debugAudioSources = !debugAudioSources;
			indepthDebugging = debugAudioSources;
			infoDebugging = debugAudioSources;
			Instance.logger.LogDebug((object)$"Toggling in-depth AudioSource debug logs {debugAudioSources}!");
		}

		public void ToggleInfoDebug()
		{
			infoDebugging = !infoDebugging;
			Instance.logger.LogDebug((object)$"Toggling informational debug logs {infoDebugging}!");
		}

		public void PrintAllReplacedSounds()
		{
			Instance.logger.LogDebug((object)" ");
			Instance.logger.LogDebug((object)"Printing all currently replaced sounds...");
			Instance.logger.LogDebug((object)" ");
			string[] array = replacedClips.Keys.ToArray();
			for (int i = 0; i < replacedClips.Count; i++)
			{
				ReplacementAudioClip replacementAudioClip = replacedClips[array[i]];
				Instance.logger.LogDebug((object)$"Clip named {array[i]} with {replacementAudioClip.clips.Count} replacement clip(s)");
				Instance.logger.LogDebug((object)$"- Clip can play? {replacementAudioClip.canPlay}");
				Instance.logger.LogDebug((object)("- Clip audio source(s)? " + replacementAudioClip.source));
				Instance.logger.LogDebug((object)$"- All {replacementAudioClip.clips.Count} clip(s):");
				for (int j = 0; j < replacementAudioClip.clips.Count; j++)
				{
					Instance.logger.LogDebug((object)$"-- Clip {j + 1} - {replacementAudioClip.clips[j].clip.GetName()} with chance of {Mathf.RoundToInt(replacementAudioClip.clips[j].chance * 100f)}%");
				}
				Instance.logger.LogDebug((object)$"-- Total - All clips combined chance {Mathf.RoundToInt(replacementAudioClip.TotalChance() * 100f)}%");
			}
			Instance.logger.LogDebug((object)" ");
			Instance.logger.LogDebug((object)"Finished printing all currently replaced sounds!");
			Instance.logger.LogDebug((object)" ");
		}

		private void PrintAllCurrentSounds()
		{
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			Instance.logger.LogDebug((object)" ");
			Instance.logger.LogDebug((object)"Printing all sounds in currently loaded scenes...");
			Instance.logger.LogDebug((object)" ");
			AudioSource[] array = Object.FindObjectsOfType<AudioSource>(true);
			AudioSourceExtension audioSourceExtension = default(AudioSourceExtension);
			for (int i = 0; i < array.Length; i++)
			{
				Instance.logger.LogDebug((object)$"AudioSource {array[i]} with clip {array[i].clip}");
				Instance.logger.LogDebug((object)$"- Volume: {array[i].volume}");
				Instance.logger.LogDebug((object)$"- Priority: {array[i].priority}");
				Instance.logger.LogDebug((object)$"- Plays on awake? {array[i].playOnAwake}");
				Instance.logger.LogDebug((object)$"- Loops? {array[i].loop}");
				Instance.logger.LogDebug((object)$"- Needs custom LCSoundTool component? {array[i].playOnAwake}");
				Instance.logger.LogDebug((object)$"- Contains custom LCSoundTool component? {((Component)((Component)array[i]).transform).TryGetComponent<AudioSourceExtension>(ref audioSourceExtension)}");
				Instance.logger.LogDebug((object)$"- Used by PlayAudioAnimationEvent component? {array[i].UsedByAnimationEventScript()}");
				Instance.logger.LogDebug((object)$"- Located in Scene: {((Component)array[i]).gameObject.scene}");
				Instance.logger.LogDebug((object)"- Located on the following GameObject:");
				Transform val = ((Component)array[i]).transform;
				Instance.logger.LogDebug((object)$"-- (This) {val}");
				while ((Object)(object)val != (Object)(object)((Component)array[i]).transform.root)
				{
					val = val.parent;
					Instance.logger.LogDebug((object)$"-- {val}");
				}
			}
			Instance.logger.LogDebug((object)" ");
			Instance.logger.LogDebug((object)"Finished printing all sounds in currently loaded scenes!");
			Instance.logger.LogDebug((object)" ");
		}
	}
}
namespace LCSoundTool.Utilities
{
	public static class AudioUtility
	{
		public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples)
		{
			samples = new float[audioClip.samples * audioClip.channels];
			audioClip.GetData(samples, 0);
			byte[] array = new byte[samples.Length * 2];
			int num = 32767;
			for (int i = 0; i < samples.Length; i++)
			{
				short value = (short)(samples[i] * (float)num);
				BitConverter.GetBytes(value).CopyTo(array, i * 2);
			}
			return array;
		}

		public static AudioClip LoadFromMemory(byte[] fileData, string clipName)
		{
			int channels = BitConverter.ToInt16(fileData, 22);
			int frequency = BitConverter.ToInt32(fileData, 24);
			int num = BitConverter.ToInt16(fileData, 34);
			byte[] array = new byte[fileData.Length - 44];
			Array.Copy(fileData, 44, array, 0, array.Length);
			return ByteArrayToAudioClip(array, clipName, channels, frequency);
		}

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

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

		public static AudioClip LoadFromDiskToAudioClip(string path, AudioType type)
		{
			//IL_0004: 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: Invalid comparison between Unknown and I4
			AudioClip result = null;
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, type);
			try
			{
				audioClip.SendWebRequest();
				try
				{
					while (!audioClip.isDone)
					{
					}
					if ((int)audioClip.result != 1)
					{
						SoundTool.Instance.logger.LogError((object)("Failed to load WAV AudioClip from path: " + path + " Full error: " + audioClip.error));
					}
					else
					{
						result = DownloadHandlerAudioClip.GetContent(audioClip);
					}
				}
				catch (Exception ex)
				{
					SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace));
				}
			}
			finally
			{
				((IDisposable)audioClip)?.Dispose();
			}
			return result;
		}
	}
	public static class Extensions
	{
		public static bool ContainsThisRandomAudioClip(this List<RandomAudioClip> list, RandomAudioClip thisClip)
		{
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].chance == thisClip.chance && list[i].clip.GetName() == thisClip.clip.GetName())
				{
					return true;
				}
			}
			return false;
		}

		public static bool UsedByAnimationEventScript(this AudioSource source)
		{
			PlayAudioAnimationEvent componentInChildren = ((Component)((Component)source).transform.root).GetComponentInChildren<PlayAudioAnimationEvent>();
			if ((Object)(object)componentInChildren != (Object)null)
			{
				return (Object)(object)componentInChildren.audioToPlay == (Object)(object)source || (Object)(object)componentInChildren.audioToPlayB == (Object)(object)source;
			}
			return false;
		}
	}
	public static class InputHelper
	{
		public static Dictionary<string, Keybind> keybinds;

		public static void Initialize()
		{
			keybinds = new Dictionary<string, Keybind>();
		}

		public static bool CheckInput(string keybind)
		{
			if (keybinds.ContainsKey(keybind) && ((KeyboardShortcut)(ref keybinds[keybind].shortcut)).IsDown() && !keybinds[keybind].wasPressed)
			{
				keybinds[keybind].wasPressed = true;
			}
			return CheckInputResult(keybind);
		}

		private static bool CheckInputResult(string keybind)
		{
			if (keybinds.ContainsKey(keybind) && ((KeyboardShortcut)(ref keybinds[keybind].shortcut)).IsUp() && keybinds[keybind].wasPressed)
			{
				keybinds[keybind].wasPressed = false;
				keybinds[keybind].onPress();
				return true;
			}
			return false;
		}
	}
	[Serializable]
	public class Keybind
	{
		public KeyboardShortcut shortcut;

		public Action onPress;

		public bool wasPressed;

		public Keybind(KeyboardShortcut shortcut, Action onPress, bool wasPressed = false)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			this.shortcut = shortcut;
			this.onPress = onPress;
			this.wasPressed = wasPressed;
		}
	}
}
namespace LCSoundTool.Patches
{
	[HarmonyPatch(typeof(AudioSource))]
	internal class AudioSourcePatch
	{
		private static Dictionary<string, AudioClip> originalClips = new Dictionary<string, AudioClip>();

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

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

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

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

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

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

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

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

		private static void DebugPlayClipAtPointMethod(AudioSource audioSource, Vector3 position)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)audioSource == (Object)null)
			{
				return;
			}
			if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{audioSource} at {((Component)audioSource).transform.root} is playing {((Object)audioSource.clip).name} at point {position}");
			}
			else if (SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{audioSource} is playing {((Object)audioSource.clip).name} located at point {position} within ");
				Transform val = ((Component)audioSource).transform;
				while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)audioSource).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}");
					val = val.parent;
				}
				if ((Object)(object)val == (Object)(object)((Component)audioSource).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)audioSource).transform.root}");
				}
			}
		}

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

		private static void RunDynamicClipReplacement(AudioSource instance)
		{
			if (SoundTool.infoDebugging)
			{
				SoundTool.Instance.logger.LogDebug((object)$"instance {instance} instance.clip {instance.clip}");
			}
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.clip == (Object)null)
			{
				return;
			}
			string name = ((Object)((Component)instance).gameObject).name;
			bool flag = true;
			string name2 = instance.clip.GetName();
			if (SoundTool.infoDebugging)
			{
				SoundTool.Instance.logger.LogDebug((object)$"sourceName {((Object)((Component)instance).gameObject).name} clipName {name2} replaceClip {flag}");
			}
			string text = name2;
			if (SoundTool.replacedClips.Keys.Count > 0)
			{
				string[] array = SoundTool.replacedClips.Keys.ToArray();
				if (array.Length != 0)
				{
					for (int i = 0; i < array.Length; i++)
					{
						string[] array2 = array[i].Split("#");
						if (array2.Length == 2 && array2[0].Contains(name2) && array2[1].Contains(((Object)((Component)instance).gameObject).name))
						{
							text = name2 + "#" + array2[1];
						}
					}
				}
			}
			if (SoundTool.infoDebugging)
			{
				SoundTool.Instance.logger.LogDebug((object)("finalName after splitName operation " + text));
			}
			if (SoundTool.replacedClips.ContainsKey(text))
			{
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)"replacedClips contained finalName");
				}
				if (SoundTool.replacedClips[text].canPlay)
				{
					if (!originalClips.ContainsKey(name))
					{
						if (SoundTool.infoDebugging)
						{
							SoundTool.Instance.logger.LogDebug((object)("originalClips did not contain sourceName, adding sourceName " + name));
						}
						originalClips.Add(name, instance.clip);
					}
					if (!string.IsNullOrEmpty(SoundTool.replacedClips[text].source))
					{
						if (SoundTool.infoDebugging)
						{
							SoundTool.Instance.logger.LogDebug((object)("replacedClips[finalName].source " + SoundTool.replacedClips[text].source + " was not null or empty"));
						}
						flag = false;
						string[] array3 = SoundTool.replacedClips[text].source.Split(',');
						if (SoundTool.infoDebugging)
						{
							SoundTool.Instance.logger.LogDebug((object)$"sources array {array3.Length} {array3}");
						}
						if ((Object)(object)instance != (Object)null && ((Object)((Component)instance).gameObject).name != null)
						{
							if (array3.Length > 1)
							{
								for (int j = 0; j < array3.Length; j++)
								{
									if (array3[j] == ((Object)((Component)instance).gameObject).name)
									{
										if (SoundTool.infoDebugging)
										{
											SoundTool.Instance.logger.LogDebug((object)("sources[i] " + array3[j] + " matches instance.gameObject.name " + ((Object)((Component)instance).gameObject).name));
										}
										flag = true;
									}
									else if (SoundTool.infoDebugging)
									{
										SoundTool.Instance.logger.LogDebug((object)("sources[i] " + array3[j] + " does not match instance.gameObject.name " + ((Object)((Component)instance).gameObject).name));
									}
								}
							}
							else if (array3[0] == ((Object)((Component)instance).gameObject).name)
							{
								if (SoundTool.infoDebugging)
								{
									SoundTool.Instance.logger.LogDebug((object)("sources[0] " + array3[0] + " matches instance.gameObject.name " + ((Object)((Component)instance).gameObject).name));
								}
								flag = true;
							}
							else if (SoundTool.infoDebugging)
							{
								SoundTool.Instance.logger.LogDebug((object)("sources[0] " + array3[0] + " does not match instance.gameObject.name " + ((Object)((Component)instance).gameObject).name));
							}
						}
					}
					else if (SoundTool.infoDebugging)
					{
						SoundTool.Instance.logger.LogDebug((object)("replacedClips[finalName].source was empty or null '" + SoundTool.replacedClips[text].source + "'"));
					}
					if (SoundTool.infoDebugging)
					{
						SoundTool.Instance.logger.LogDebug((object)$"replaceClip {flag}");
					}
					List<RandomAudioClip> clips = SoundTool.replacedClips[text].clips;
					float num = 0f;
					foreach (RandomAudioClip item in clips)
					{
						num += item.chance;
					}
					if (SoundTool.infoDebugging)
					{
						SoundTool.Instance.logger.LogDebug((object)$"totalChance {num}");
					}
					float num2 = Random.Range(0f, num);
					{
						foreach (RandomAudioClip item2 in clips)
						{
							if (num2 <= item2.chance)
							{
								if (flag)
								{
									if (SoundTool.infoDebugging)
									{
										SoundTool.Instance.logger.LogDebug((object)$"clip replaced with {item2.clip}");
									}
									instance.clip = item2.clip;
									break;
								}
								if (SoundTool.infoDebugging)
								{
									SoundTool.Instance.logger.LogDebug((object)$"clip was not replaced with {item2.clip}");
								}
								if (originalClips.ContainsKey(name))
								{
									if (SoundTool.infoDebugging)
									{
										SoundTool.Instance.logger.LogDebug((object)$"originalClips.ContainsKey(sourceName), clip was restored to {originalClips[name]}");
									}
									instance.clip = originalClips[name];
									originalClips.Remove(name);
								}
								break;
							}
							num2 -= item2.chance;
						}
						return;
					}
				}
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)$"replacedClips[finalName].canPlay {SoundTool.replacedClips[text].canPlay}");
				}
			}
			else if (originalClips.ContainsKey(name))
			{
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)"replacedClips did not contain finalName but originalClips contained sourceName");
				}
				instance.clip = originalClips[name];
				originalClips.Remove(name);
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)$"clip was restored to {originalClips[name]}");
				}
			}
		}

		private static AudioClip ReplaceClipWithNew(AudioClip original, AudioSource source = null)
		{
			if (SoundTool.infoDebugging)
			{
				SoundTool.Instance.logger.LogDebug((object)$"original {original} source {source}");
			}
			if ((Object)(object)original == (Object)null)
			{
				return original;
			}
			string name = original.GetName();
			bool flag = true;
			string text = name;
			if (SoundTool.infoDebugging)
			{
				SoundTool.Instance.logger.LogDebug((object)$"sourceName {((Object)((Component)source).gameObject).name} clipName {name} replaceClip {flag}");
			}
			if ((Object)(object)source != (Object)null)
			{
				if (SoundTool.replacedClips.Keys.Count > 0)
				{
					string[] array = SoundTool.replacedClips.Keys.ToArray();
					if (array.Length != 0)
					{
						for (int i = 0; i < array.Length; i++)
						{
							string[] array2 = array[i].Split("#");
							if (array2.Length == 2 && array2[0].Contains(name) && array2[1].Contains(((Object)((Component)source).gameObject).name))
							{
								text = name + "#" + array2[1];
							}
						}
					}
				}
			}
			else if (SoundTool.infoDebugging)
			{
				SoundTool.Instance.logger.LogDebug((object)"source was null, this means we can't check for sourceName for this sound!");
			}
			if (SoundTool.infoDebugging)
			{
				SoundTool.Instance.logger.LogDebug((object)("finalName after splitName operation " + text));
			}
			if (SoundTool.replacedClips.ContainsKey(text))
			{
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)"replacedClips contained finalName");
				}
				if (!SoundTool.replacedClips[text].canPlay)
				{
					if (SoundTool.infoDebugging)
					{
						SoundTool.Instance.logger.LogDebug((object)$"replacedClips[finalName].canPlay {SoundTool.replacedClips[text].canPlay}");
					}
					return original;
				}
				if (!originalClips.ContainsKey(text))
				{
					if (SoundTool.infoDebugging)
					{
						SoundTool.Instance.logger.LogDebug((object)("originalClips did not contain finalName, adding finalName " + text));
					}
					originalClips.Add(text, original);
				}
				if (!string.IsNullOrEmpty(SoundTool.replacedClips[text].source))
				{
					if (SoundTool.infoDebugging)
					{
						SoundTool.Instance.logger.LogDebug((object)("replacedClips[finalName].source " + SoundTool.replacedClips[text].source + " was not null or empty"));
					}
					flag = false;
					string[] array3 = SoundTool.replacedClips[text].source.Split(',');
					if (SoundTool.infoDebugging)
					{
						SoundTool.Instance.logger.LogDebug((object)$"sources array {array3.Length} {array3}");
					}
					if ((Object)(object)source != (Object)null && ((Object)((Component)source).gameObject).name != null)
					{
						if (array3.Length > 1)
						{
							for (int j = 0; j < array3.Length; j++)
							{
								if (array3[j] == ((Object)((Component)source).gameObject).name)
								{
									if (SoundTool.infoDebugging)
									{
										SoundTool.Instance.logger.LogDebug((object)("sources[i] " + array3[j] + " matches instance.gameObject.name " + ((Object)((Component)source).gameObject).name));
									}
									flag = true;
								}
								else if (SoundTool.infoDebugging)
								{
									SoundTool.Instance.logger.LogDebug((object)("sources[i] " + array3[j] + " does not match instance.gameObject.name " + ((Object)((Component)source).gameObject).name));
								}
							}
						}
						else if (array3[0] == ((Object)((Component)source).gameObject).name)
						{
							if (SoundTool.infoDebugging)
							{
								SoundTool.Instance.logger.LogDebug((object)("sources[0] " + array3[0] + " matches instance.gameObject.name " + ((Object)((Component)source).gameObject).name));
							}
							flag = true;
						}
						else if (SoundTool.infoDebugging)
						{
							SoundTool.Instance.logger.LogDebug((object)("sources[0] " + array3[0] + " does not match instance.gameObject.name " + ((Object)((Component)source).gameObject).name));
						}
					}
				}
				else if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)("replacedClips[finalName].source was empty or null '" + SoundTool.replacedClips[text].source + "'"));
				}
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)$"replaceClip {flag}");
				}
				List<RandomAudioClip> clips = SoundTool.replacedClips[text].clips;
				float num = 0f;
				foreach (RandomAudioClip item in clips)
				{
					num += item.chance;
				}
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)$"totalChance {num}");
				}
				float num2 = Random.Range(0f, num);
				foreach (RandomAudioClip item2 in clips)
				{
					if (num2 <= item2.chance)
					{
						if (flag)
						{
							if (SoundTool.infoDebugging)
							{
								SoundTool.Instance.logger.LogDebug((object)$"clip replaced with {item2.clip}");
							}
							return item2.clip;
						}
						if (SoundTool.infoDebugging)
						{
							SoundTool.Instance.logger.LogDebug((object)$"clip was not replaced with {item2.clip}");
						}
						if (originalClips.ContainsKey(text))
						{
							if (SoundTool.infoDebugging)
							{
								SoundTool.Instance.logger.LogDebug((object)$"originalClips.ContainsKey(finalName), clip was restored to {originalClips[text]}");
							}
							AudioClip result = originalClips[text];
							originalClips.Remove(text);
							return result;
						}
						return original;
					}
					num2 -= item2.chance;
				}
			}
			else if (originalClips.ContainsKey(text))
			{
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)"replacedClips did not contain finalName but originalClips contained finalName");
				}
				AudioClip result2 = originalClips[text];
				originalClips.Remove(text);
				if (SoundTool.infoDebugging)
				{
					SoundTool.Instance.logger.LogDebug((object)$"clip was restored to {originalClips[text]}");
				}
				return result2;
			}
			return original;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		public static GameObject networkPrefab;

		public static GameObject networkHandlerHost;

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

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

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

		public static event Action ClientNetworkedAudioChanged;

		public static event Action HostNetworkedAudioChanged;

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

		[ClientRpc]
		public void ReceiveAudioClipClientRpc(string clipName, byte[] audioData, int channels, int frequency)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(292212293u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				bool flag2 = audioData != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioData, default(ForPrimitives));
				}
				BytePacker.WriteValueBitPacked(val2, channels);
				BytePacker.WriteValueBitPacked(val2, frequency);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 292212293u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (!networkedAudioClips.ContainsKey(clipName))
				{
					AudioClip val3 = null;
					val3 = AudioUtility.ByteArrayToAudioClip(audioData, clipName, channels, frequency);
					networkedAudioClips.Add(clipName, val3);
					NetworkHandler.ClientNetworkedAudioChanged?.Invoke();
				}
				else
				{
					SoundTool.Instance.logger.LogDebug((object)("Sound " + clipName + " already exists for this client! Skipping addition of this sound for this client."));
				}
			}
		}

		[ClientRpc]
		public void RemoveAudioClipClientRpc(string clipName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1355469546u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1355469546u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && networkedAudioClips.ContainsKey(clipName))
			{
				networkedAudioClips.Remove(clipName);
				NetworkHandler.ClientNetworkedAudioChanged?.Invoke();
			}
		}

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

		[ClientRpc]
		public void ReceiveSeedClientRpc(int seed)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1556253924u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, seed);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1556253924u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Random.InitState(seed);
					SoundTool.Instance.logger.LogDebug((object)$"Client received a new Unity Random seed of {seed}!");
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SendAudioClipServerRpc(string clipName, byte[] audioData, int channels, int frequency)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2399630547u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				bool flag2 = audioData != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioData, default(ForPrimitives));
				}
				BytePacker.WriteValueBitPacked(val2, channels);
				BytePacker.WriteValueBitPacked(val2, frequency);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2399630547u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ReceiveAudioClipClientRpc(clipName, audioData, channels, frequency);
				NetworkHandler.HostNetworkedAudioChanged?.Invoke();
			}
		}

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

		[ServerRpc(RequireOwnership = false)]
		public void SyncAudioClipsServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(178607916u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 178607916u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			string[] array = networkedAudioClips.Keys.ToArray();
			if (array.Length < 1)
			{
				SoundTool.Instance.logger.LogDebug((object)"No sounds found in networkedClips. Syncing process cancelled!");
				return;
			}
			for (int i = 0; i < array.Length; i++)
			{
				SyncAudioClipsClientRpc(array[i]);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SendExistingAudioClipServerRpc(string clipName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(4006259189u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 4006259189u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				if (networkedAudioClips.ContainsKey(clipName))
				{
					byte[] array = null;
					array = AudioUtility.AudioClipToByteArray(networkedAudioClips[clipName], out var _);
					ReceiveAudioClipClientRpc(clipName, array, networkedAudioClips[clipName].channels, networkedAudioClips[clipName].frequency);
				}
				else
				{
					SoundTool.Instance.logger.LogWarning((object)"Trying to obtain and sync a sound from the host that does not exist in the host's game!");
				}
			}
		}

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

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

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

		private static void __rpc_handler_292212293(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: 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_00c0: 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_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string clipName = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false);
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				byte[] audioData = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioData, default(ForPrimitives));
				}
				int channels = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref channels);
				int frequency = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref frequency);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).ReceiveAudioClipClientRpc(clipName, audioData, channels, frequency);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1355469546(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && net

plugins/notnotnotswipez-MoreCompany/MoreCompany.dll

Decompiled 3 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.Bootstrap;
using BepInEx.Configuration;
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(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;
			}
			return true;
		}
	}
	[HarmonyPatch]
	public static class ClientReceiveMessagePatch
	{
		internal enum __RpcExecStage
		{
			None,
			Server,
			Client
		}

		internal static MethodInfo AddTextMessageServerRpc = AccessTools.Method(typeof(HUDManager), "AddTextMessageServerRpc", (Type[])null, (Type[])null);

		internal static FieldInfo __rpc_exec_stage = AccessTools.Field(typeof(NetworkBehaviour), "__rpc_exec_stage");

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void ConnectClientToPlayerObject_Postfix(PlayerControllerB __instance)
		{
			MainClass.playerIdsAndCosmetics.Clear();
			string text = $"[morecompanycosmetics];{__instance.playerClientId};-1";
			foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics)
			{
				if (CosmeticRegistry.cosmeticInstances.ContainsKey(locallySelectedCosmetic))
				{
					text = text + ";" + locallySelectedCosmetic;
				}
			}
			AddTextMessageServerRpc?.Invoke(HUDManager.Instance, new object[1] { text });
		}

		[HarmonyPatch(typeof(HUDManager), "AddTextMessageServerRpc")]
		[HarmonyPostfix]
		public static void AddTextMessageServerRpc_Postfix(HUDManager __instance, string chatMessage)
		{
			if (!chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				return;
			}
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening || (__RpcExecStage)__rpc_exec_stage.GetValue(__instance) == __RpcExecStage.Server || !networkManager.IsHost)
			{
				return;
			}
			string[] array = chatMessage.Split(';');
			int num = int.Parse(array[1]);
			int num2 = int.Parse(array[2]);
			if (num2 != -1)
			{
				return;
			}
			foreach (KeyValuePair<int, List<string>> item in MainClass.playerIdsAndCosmetics.ToList())
			{
				if (item.Key == num)
				{
					continue;
				}
				string text = $"[morecompanycosmetics];{item.Key};{num}";
				foreach (string item2 in item.Value)
				{
					text = text + ";" + item2;
				}
				AddTextMessageServerRpc?.Invoke(__instance, new object[1] { text });
			}
		}

		[HarmonyPatch(typeof(HUDManager), "AddTextMessageClientRpc")]
		[HarmonyPrefix]
		public static void AddTextMessageClientRpc_Prefix(HUDManager __instance, string chatMessage)
		{
			if (chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
				if (!((Object)(object)networkManager == (Object)null) && networkManager.IsListening && (__RpcExecStage)__rpc_exec_stage.GetValue(__instance) == __RpcExecStage.Client && (networkManager.IsClient || networkManager.IsHost))
				{
					HandleDataMessage(chatMessage);
				}
			}
		}

		internal static void HandleDataMessage(string chatMessage)
		{
			//IL_0150: 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)
			string[] array = chatMessage.Split(';');
			int num = int.Parse(array[1]);
			int num2 = int.Parse(array[2]);
			array = array.Skip(3).ToArray();
			if (num2 != -1 && num2 != StartOfRound.Instance.thisClientPlayerId)
			{
				return;
			}
			CosmeticApplication cosmeticApplication = ((Component)((Component)StartOfRound.Instance.allPlayerScripts[num]).transform.Find("ScavengerModel").Find("metarig")).gameObject.GetComponent<CosmeticApplication>();
			if (!Object.op_Implicit((Object)(object)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 text in array2)
			{
				list.Add(text);
				if (MainClass.cosmeticsSyncOther.Value)
				{
					cosmeticApplication.ApplyCosmetic(text, startEnabled: true);
				}
			}
			if (num == StartOfRound.Instance.thisClientPlayerId)
			{
				cosmeticApplication.ClearCosmetics();
			}
			foreach (CosmeticInstance spawnedCosmetic in cosmeticApplication.spawnedCosmetics)
			{
				Transform transform = ((Component)spawnedCosmetic).transform;
				transform.localScale *= 0.38f;
			}
			if (MainClass.playerIdsAndCosmetics.ContainsKey(num))
			{
				MainClass.playerIdsAndCosmetics[num] = list;
			}
			else
			{
				MainClass.playerIdsAndCosmetics.Add(num, list);
			}
		}
	}
	[HarmonyPatch]
	public static class PreventOldVersionChatSpamPatch
	{
		[HarmonyPatch(typeof(HUDManager), "AddChatMessage")]
		[HarmonyPrefix]
		public static bool AddChatMessage_Prefix(string chatMessage, string nameOfUserWhoTyped = "")
		{
			if (chatMessage.StartsWith("[replacewithdata]") || chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageClientRpc")]
		[HarmonyPrefix]
		public static bool AddPlayerChatMessageClientRpc_Prefix(string chatMessage, int playerId)
		{
			if (chatMessage.StartsWith("[replacewithdata]") || chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				return false;
			}
			return true;
		}
	}
	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);
			}
			if (!flag2)
			{
				MainClass.StaticLogger.LogWarning((object)"SpringManAIUpdatePatch failed to replace newPlayerCount");
			}
			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);
			}
			if (!flag2)
			{
				MainClass.StaticLogger.LogWarning((object)"SpringManAIIntervalPatch failed to replace newPlayerCount");
			}
			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);
				}
			}
			if (!flag)
			{
				MainClass.StaticLogger.LogWarning((object)"GetClosestPlayerPatch failed to replace newPlayerCount");
			}
			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);
				}
			}
			if (!flag)
			{
				MainClass.StaticLogger.LogWarning((object)"GetAllPlayersInLineOfSightPatch failed to replace newPlayerCount");
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")]
	public static class DressGirlHauntPatch
	{
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			int num = 0;
			foreach (CodeInstruction instruction in instructions)
			{
				if (((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					num++;
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			if (num != 3)
			{
				MainClass.StaticLogger.LogWarning((object)$"DressGirlHauntPatch failed to replace newPlayerCount: {num}/3");
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(ButlerEnemyAI), "Start")]
	public static class ButlerEnemyAIPatch
	{
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			int num = 0;
			foreach (CodeInstruction instruction in instructions)
			{
				if (((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					num++;
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			if (num != 3)
			{
				MainClass.StaticLogger.LogWarning((object)$"ButlerEnemyAIPatch failed to replace newPlayerCount: {num}/3");
			}
			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.onSubmit).AddListener((UnityAction<string>)delegate(string s)
			{
				UpdateTextBox(inputField, s);
			});
			((UnityEvent<string>)(object)inputField.onDeselect).AddListener((UnityAction<string>)delegate(string s)
			{
				UpdateTextBox(inputField, s);
			});
		}

		public static void UpdateTextBox(TMP_InputField inputField, string s)
		{
			if (inputField.text == MainClass.newPlayerCount.ToString())
			{
				return;
			}
			if (int.TryParse(s, out var result))
			{
				int newPlayerCount = MainClass.newPlayerCount;
				MainClass.newPlayerCount = Mathf.Clamp(result, MainClass.minPlayerCount, MainClass.maxPlayerCount);
				foreach (TMP_InputField inputField2 in inputFields)
				{
					inputField2.text = MainClass.newPlayerCount.ToString();
				}
				MainClass.SaveSettingsToFile();
				if (MainClass.newPlayerCount != newPlayerCount)
				{
					MainClass.StaticLogger.LogInfo((object)$"Changed Crew Count: {MainClass.newPlayerCount}");
				}
			}
			else
			{
				if (s.Length == 0)
				{
					return;
				}
				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);
			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);
			}
			if (!flag2)
			{
				MainClass.StaticLogger.LogWarning((object)"KickPatch failed to replace newPlayerCount");
			}
			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);
				if (MainClass.newPlayerCount == crewSizeMismatch)
				{
					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.9.1";

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

		public static int minPlayerCount = 4;

		public static int maxPlayerCount = 50;

		public static int newPlayerCount = 32;

		public static ConfigFile StaticConfig;

		public static ConfigEntry<int> playerCount;

		public static ConfigEntry<bool> cosmeticsSyncOther;

		public static ConfigEntry<bool> defaultCosmetics;

		public static ConfigEntry<bool> cosmeticsPerProfile;

		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 dynamicCosmeticsPath;

		public static string cosmeticSavePath;

		private void Awake()
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			StaticLogger = ((BaseUnityPlugin)this).Logger;
			StaticConfig = ((BaseUnityPlugin)this).Config;
			playerCount = StaticConfig.Bind<int>("General", "Player Count", defaultPlayerCount, new ConfigDescription("How many players can be in your lobby?", (AcceptableValueBase)(object)new AcceptableValueRange<int>(minPlayerCount, maxPlayerCount), Array.Empty<object>()));
			cosmeticsSyncOther = StaticConfig.Bind<bool>("Cosmetics", "Show Cosmetics", true, "Should you be able to see cosmetics of other players?");
			defaultCosmetics = StaticConfig.Bind<bool>("Cosmetics", "Default Cosmetics", true, "Should the default cosmetics be enabled?");
			cosmeticsPerProfile = StaticConfig.Bind<bool>("Cosmetics", "Per Profile Cosmetics", false, "Should the cosmetics be saved per-profile?");
			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)"Loading SETTINGS...");
			ReadSettingsFromFile();
			dynamicCosmeticsPath = Paths.PluginPath + "/MoreCompanyCosmetics";
			if (cosmeticsPerProfile.Value)
			{
				cosmeticSavePath = Application.persistentDataPath + "/morecompanycosmetics-" + Directory.GetParent(Paths.BepInExRootPath).Name + ".txt";
			}
			else
			{
				cosmeticSavePath = Application.persistentDataPath + "/morecompanycosmetics.txt";
			}
			cosmeticsPerProfile.SettingChanged += delegate
			{
				if (cosmeticsPerProfile.Value)
				{
					cosmeticSavePath = Application.persistentDataPath + "/MCCosmeticsSave-" + Directory.GetParent(Paths.BepInExRootPath).Name + ".mcs";
				}
				else
				{
					cosmeticSavePath = Application.persistentDataPath + "/MCCosmeticsSave.mcs";
				}
			};
			StaticLogger.LogInfo((object)("Checking: " + dynamicCosmeticsPath));
			if (!Directory.Exists(dynamicCosmeticsPath))
			{
				StaticLogger.LogInfo((object)"Creating cosmetics directory");
				Directory.CreateDirectory(dynamicCosmeticsPath);
			}
			StaticLogger.LogInfo((object)"Loading COSMETICS...");
			ReadCosmeticsFromFile();
			if (defaultCosmetics.Value)
			{
				StaticLogger.LogInfo((object)"Loading DEFAULT COSMETICS...");
				AssetBundle val2 = BundleUtilities.LoadBundleFromInternalAssembly("morecompany.cosmetics", Assembly.GetExecutingAssembly());
				CosmeticRegistry.LoadCosmeticsFromBundle(val2);
				val2.Unload(false);
			}
			StaticLogger.LogInfo((object)"Loading USER COSMETICS...");
			RecursiveCosmeticLoad(Paths.PluginPath);
			AssetBundle bundle = BundleUtilities.LoadBundleFromInternalAssembly("morecompany.assets", Assembly.GetExecutingAssembly());
			LoadAssets(bundle);
			StaticLogger.LogInfo((object)"Loaded MoreCompany FULLY");
		}

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

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

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

		public static void SaveSettingsToFile()
		{
			playerCount.Value = newPlayerCount;
			StaticConfig.Save();
		}

		public static void ReadSettingsFromFile()
		{
			try
			{
				newPlayerCount = Mathf.Clamp(playerCount.Value, minPlayerCount, maxPlayerCount);
			}
			catch
			{
				newPlayerCount = defaultPlayerCount;
				playerCount.Value = newPlayerCount;
				StaticConfig.Save();
			}
		}

		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_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_025d: 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_029c: Expected O, but got Unknown
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e4: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			if (instance.allPlayerObjects.Length != newPlayerCount)
			{
				StaticLogger.LogInfo((object)$"ResizePlayerCache: {newPlayerCount}");
				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>();
						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];
						StartOfRound.Instance.mapScreen.radarTargets.Add(new TransformAndName(((Component)componentInChildren).transform, componentInChildren.playerUsername, false));
					}
				}
			}
			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);
			}
			if (!flag2)
			{
				MainClass.StaticLogger.LogWarning((object)"SendNewPlayerValuesServerRpcPatch failed to replace newPlayerCount");
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(HUDManager), "SyncAllPlayerLevelsServerRpc", new Type[] { })]
	public static class SyncAllPlayerLevelsPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			int num = 0;
			foreach (CodeInstruction instruction in instructions)
			{
				if (((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					num++;
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			if (num != 2)
			{
				MainClass.StaticLogger.LogWarning((object)$"SyncAllPlayerLevelsPatch failed to replace newPlayerCount: {num}/2");
			}
			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);
			}
			if (num != 2)
			{
				MainClass.StaticLogger.LogWarning((object)$"SyncShipUnlockablesServerRpc failed to replace newPlayerCount: {num}/2");
			}
			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);
			}
			if (!flag2)
			{
				MainClass.StaticLogger.LogWarning((object)"SyncShipUnlockablesClientRpc failed to replace newPlayerCount");
			}
			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);
			}
			if (!flag2)
			{
				MainClass.StaticLogger.LogWarning((object)"LobbyDataIsJoinable failed to replace maxPlayerCount");
			}
			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);
			}
			if (!flag2)
			{
				MainClass.StaticLogger.LogWarning((object)"ConnectionApproval failed to replace newPlayerCount");
			}
			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;
				}
			}
		}
	}
	[HarmonyPatch]
	public static class TogglePlayerObjectsPatch
	{
		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPrefix]
		private static void ConnectClientToPlayerObject()
		{
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if (val.isPlayerControlled || val.isPlayerDead)
				{
					((Component)val).gameObject.SetActive(true);
				}
				else
				{
					((Component)val).gameObject.SetActive(false);
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "OnPlayerConnectedClientRpc")]
		[HarmonyPrefix]
		private static void OnPlayerConnectedClientRpc(StartOfRound __instance, ulong clientId, int connectedPlayers, ulong[] connectedPlayerIdsOrdered, int assignedPlayerObjectId, int serverMoneyAmount, int levelID, int profitQuota, int timeUntilDeadline, int quotaFulfilled, int randomSeed, bool isChallenge)
		{
			((Component)__instance.allPlayerScripts[assignedPlayerObjectId]).gameObject.SetActive(true);
		}

		[HarmonyPatch(typeof(StartOfRound), "OnPlayerDC")]
		[HarmonyPostfix]
		private static void OnPlayerDC(StartOfRound __instance, int playerObjectNumber, ulong clientId)
		{
			((Component)__instance.allPlayerScripts[playerObjectNumber]).gameObject.SetActive(false);
		}
	}
	public class MimicPatches
	{
		[HarmonyPatch(typeof(MaskedPlayerEnemy), "SetEnemyOutside")]
		public class MaskedPlayerEnemyOnEnablePatch
		{
			public static void Postfix(ref MaskedPlayerEnemy __instance)
			{
				//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
				//IL_0107: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)__instance.mimickingPlayer != (Object)null) || !MainClass.cosmeticsSyncOther.Value || !MainClass.playerIdsAndCosmetics.ContainsKey((int)__instance.mimickingPlayer.playerClientId))
				{
					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;
				}
				((EnemyAI)__instance).skinnedMeshRenderers = ((Component)__instance).gameObject.GetComponentsInChildren<SkinnedMeshRenderer>();
				((EnemyAI)__instance).meshRenderers = ((Component)__instance).gameObject.GetComponentsInChildren<MeshRenderer>();
			}
		}
	}
	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_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			int num = 0;
			foreach (CodeInstruction instruction in instructions)
			{
				if (((object)instruction).ToString() == "ldc.i4.4 NULL")
				{
					num++;
					CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount"));
					list.Add(item);
				}
				else
				{
					list.Add(instruction);
				}
			}
			if (num != 2)
			{
				MainClass.StaticLogger.LogWarning((object)$"SpectateNextPlayer failed to replace newPlayerCount: {num}/2");
			}
			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.StartsWith("VoicePlayer")));
			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]))
				{
					AudioMixerGroup val2 = Object.Instantiate<AudioMixerGroup>(val);
					((Object)val2).name = $"VoicePlayer{i}";
					__instance.playerVoiceMixers[i] = val2;
				}
			}
		}
	}
	[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);
			}
			if (!flag2)
			{
				MainClass.StaticLogger.LogWarning((object)"OnClientConnect failed to replace newPlayerCount");
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnPlayerDC")]
	public static class OnPlayerDCPatch
	{
		public static void Postfix(int playerObjectNumber, ulong clientId)
		{
			if (MainClass.playerIdsAndCosmetics.ContainsKey(playerObjectNumber))
			{
				MainClass.playerIdsAndCosmetics.Remove(playerObjectNumber);
			}
		}
	}
	[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 (!Chainloader.PluginInfos.ContainsKey("LC_API"))
			{
				__instance.gameVersionNum = 9950 + originalVersion;
			}
		}
	}
	[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 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__9_0;

			public static UnityAction <>9__9_1;

			internal void <SpawnCosmeticGUI>b__9_0()
			{
				MainClass.cosmeticsSyncOther.Value = true;
				MainClass.StaticConfig.Save();
			}

			internal void <SpawnCosmeticGUI>b__9_1()
			{
				MainClass.cosmeticsSyncOther.Value = false;
				MainClass.StaticConfig.Save();
			}
		}

		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 UpdateVisibilityCheckbox(GameObject enableCosmeticsButton, GameObject disableCosmeticsButton)
		{
			if (MainClass.cosmeticsSyncOther.Value)
			{
				enableCosmeticsButton.SetActive(false);
				disableCosmeticsButton.SetActive(true);
			}
			else
			{
				enableCosmeticsButton.SetActive(true);
				disableCosmeticsButton.SetActive(false);
			}
		}

		public static void SpawnCosmeticGUI()
		{
			//IL_0042: 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_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: 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;
			GameObject gameObject2 = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen")
				.Find("DisableButton")).gameObject;
			ButtonClickedEvent onClick = gameObject.GetComponent<Button>().onClick;
			object obj = <>c.<>9__9_0;
			if (obj == null)
			{
				UnityAction val = delegate
				{
					MainClass.cosmeticsSyncOther.Value = true;
					MainClass.StaticConfig.Save();
				};
				<>c.<>9__9_0 = val;
				obj = (object)val;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
			ButtonClickedEvent onClick2 = gameObject2.GetComponent<Button>().onClick;
			object obj2 = <>c.<>9__9_1;
			if (obj2 == null)
			{
				UnityAction val2 = delegate
				{
					MainClass.cosmeticsSyncOther.Value = false;
					MainClass.StaticConfig.Save();
				};
				<>c.<>9__9_1 = val2;
				obj2 = (object)val2;
			}
			((UnityEvent)onClick2).AddListener((UnityAction)obj2);
			UpdateVisibilityCheckbox(gameObject, gameObject2);
			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/Ozone-Runtime_Netcode_Patcher/NicholaScott.BepInEx.RuntimeNetcodeRPCValidator.dll

Decompiled 3 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/Rattenbonkers-TVLoader/TVLoader.dll

Decompiled 3 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using TVLoader.Utils;
using UnityEngine;
using UnityEngine.Video;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("TVLoader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TVLoader")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("e59845a7-f2f7-4416-9a61-ca1939ce6e2d")]
[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 TVLoader
{
	[BepInPlugin("rattenbonkers.TVLoader", "TVLoader", "1.1.1")]
	public class TVLoaderPlugin : BaseUnityPlugin
	{
		private const string MyGUID = "rattenbonkers.TVLoader";

		private const string PluginName = "TVLoader";

		private const string VersionString = "1.1.1";

		private static readonly Harmony Harmony = new Harmony("rattenbonkers.TVLoader");

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

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			Harmony.PatchAll();
			VideoManager.Load();
			((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("PluginName: {0}, VersionString: {1} is loaded. Video Count: {2}", "TVLoader", "1.1.1", VideoManager.Videos.Count));
		}
	}
}
namespace TVLoader.Utils
{
	internal static class VideoManager
	{
		public static List<string> Videos = new List<string>();

		public static void Load()
		{
			string[] directories = Directory.GetDirectories(Paths.PluginPath);
			foreach (string text in directories)
			{
				string path = Path.Combine(Paths.PluginPath, text, "Television Videos");
				if (Directory.Exists(path))
				{
					string[] files = Directory.GetFiles(path, "*.mp4");
					Videos.AddRange(files);
					TVLoaderPlugin.Log.LogInfo((object)$"{text} has {files.Length} videos.");
				}
			}
			string path2 = Path.Combine(Paths.PluginPath, "Television Videos");
			if (!Directory.Exists(path2))
			{
				Directory.CreateDirectory(path2);
			}
			string[] files2 = Directory.GetFiles(path2, "*.mp4");
			Videos.AddRange(files2);
			TVLoaderPlugin.Log.LogInfo((object)$"Global has {files2.Length} videos.");
			TVLoaderPlugin.Log.LogInfo((object)$"Loaded {Videos.Count} total.");
		}
	}
}
namespace TVLoader.Patches
{
	[HarmonyPatch(typeof(TVScript))]
	internal class TVScriptPatches
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static EventHandler <>9__13_0;

			internal void <PrepareVideo>b__13_0(VideoPlayer source)
			{
				TVLoaderPlugin.Log.LogInfo((object)"Prepared next video!");
			}
		}

		private static FieldInfo currentClipProperty = typeof(TVScript).GetField("currentClip", BindingFlags.Instance | BindingFlags.NonPublic);

		private static FieldInfo currentTimeProperty = typeof(TVScript).GetField("currentClipTime", BindingFlags.Instance | BindingFlags.NonPublic);

		private static FieldInfo wasTvOnLastFrameProp = typeof(TVScript).GetField("wasTvOnLastFrame", BindingFlags.Instance | BindingFlags.NonPublic);

		private static FieldInfo timeSinceTurningOffTVProp = typeof(TVScript).GetField("timeSinceTurningOffTV", BindingFlags.Instance | BindingFlags.NonPublic);

		private static MethodInfo setMatMethod = typeof(TVScript).GetMethod("SetTVScreenMaterial", BindingFlags.Instance | BindingFlags.NonPublic);

		private static MethodInfo onEnableMethod = typeof(TVScript).GetMethod("OnEnable", BindingFlags.Instance | BindingFlags.NonPublic);

		private static bool tvHasPlayedBefore = false;

		private static RenderTexture renderTexture;

		private static VideoPlayer currentVideoPlayer;

		private static VideoPlayer nextVideoPlayer;

		[HarmonyPrefix]
		[HarmonyPatch("Update")]
		public static bool Update(TVScript __instance)
		{
			if ((Object)(object)currentVideoPlayer == (Object)null)
			{
				currentVideoPlayer = ((Component)__instance).GetComponent<VideoPlayer>();
				renderTexture = currentVideoPlayer.targetTexture;
				if (VideoManager.Videos.Count > 0)
				{
					PrepareVideo(__instance, 0);
				}
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch("TurnTVOnOff")]
		public static bool TurnTVOnOff(TVScript __instance, bool on)
		{
			TVLoaderPlugin.Log.LogInfo((object)$"TVOnOff: {on}");
			if (VideoManager.Videos.Count == 0)
			{
				return false;
			}
			int num = (int)currentClipProperty.GetValue(__instance);
			if (on && tvHasPlayedBefore)
			{
				num = (num + 1) % VideoManager.Videos.Count;
				currentClipProperty.SetValue(__instance, num);
			}
			__instance.tvOn = on;
			if (on)
			{
				PlayVideo(__instance);
				__instance.tvSFX.PlayOneShot(__instance.switchTVOn);
				WalkieTalkie.TransmitOneShotAudio(__instance.tvSFX, __instance.switchTVOn, 1f);
			}
			else
			{
				__instance.video.Stop();
				__instance.tvSFX.PlayOneShot(__instance.switchTVOff);
				WalkieTalkie.TransmitOneShotAudio(__instance.tvSFX, __instance.switchTVOff, 1f);
			}
			setMatMethod.Invoke(__instance, new object[1] { on });
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch("TVFinishedClip")]
		public static bool TVFinishedClip(TVScript __instance, VideoPlayer source)
		{
			if (!__instance.tvOn || GameNetworkManager.Instance.localPlayerController.isInsideFactory)
			{
				return false;
			}
			TVLoaderPlugin.Log.LogInfo((object)"TVFinishedClip");
			int num = (int)currentClipProperty.GetValue(__instance);
			if (VideoManager.Videos.Count > 0)
			{
				num = (num + 1) % VideoManager.Videos.Count;
			}
			currentTimeProperty.SetValue(__instance, 0f);
			currentClipProperty.SetValue(__instance, num);
			PlayVideo(__instance);
			return false;
		}

		private static void PrepareVideo(TVScript instance, int index = -1)
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Expected O, but got Unknown
			if (index == -1)
			{
				index = (int)currentClipProperty.GetValue(instance) + 1;
			}
			if ((Object)(object)nextVideoPlayer != (Object)null && ((Component)nextVideoPlayer).gameObject.activeInHierarchy)
			{
				Object.Destroy((Object)(object)nextVideoPlayer);
			}
			nextVideoPlayer = ((Component)instance).gameObject.AddComponent<VideoPlayer>();
			nextVideoPlayer.playOnAwake = false;
			nextVideoPlayer.isLooping = false;
			nextVideoPlayer.source = (VideoSource)1;
			nextVideoPlayer.controlledAudioTrackCount = 1;
			nextVideoPlayer.audioOutputMode = (VideoAudioOutputMode)1;
			nextVideoPlayer.SetTargetAudioSource((ushort)0, instance.tvSFX);
			nextVideoPlayer.url = "file://" + VideoManager.Videos[index % VideoManager.Videos.Count];
			nextVideoPlayer.Prepare();
			VideoPlayer obj = nextVideoPlayer;
			object obj2 = <>c.<>9__13_0;
			if (obj2 == null)
			{
				EventHandler val = delegate
				{
					TVLoaderPlugin.Log.LogInfo((object)"Prepared next video!");
				};
				<>c.<>9__13_0 = val;
				obj2 = (object)val;
			}
			obj.prepareCompleted += (EventHandler)obj2;
		}

		private static void PlayVideo(TVScript instance)
		{
			tvHasPlayedBefore = true;
			if (VideoManager.Videos.Count != 0)
			{
				if ((Object)(object)nextVideoPlayer != (Object)null)
				{
					VideoPlayer val = currentVideoPlayer;
					instance.video = (currentVideoPlayer = nextVideoPlayer);
					nextVideoPlayer = null;
					TVLoaderPlugin.Log.LogInfo((object)$"Destroy {val}");
					Object.Destroy((Object)(object)val);
					onEnableMethod.Invoke(instance, new object[0]);
				}
				currentTimeProperty.SetValue(instance, 0f);
				instance.video.targetTexture = renderTexture;
				instance.video.Play();
				PrepareVideo(instance);
			}
		}
	}
}

plugins/RickArg-Helmet_Cameras/HelmetCamera.dll

Decompiled 3 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/RugbugRedfern-Skinwalkers/SkinwalkerMod.dll

Decompiled 3 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[5]
		{
			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" }
			}
		};

		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", "5.0.0")]
	internal class PluginLoader : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("RugbugRedfern.SkinwalkerMod");

		private const string modGUID = "RugbugRedfern.SkinwalkerMod";

		private const string modVersion = "5.0.0";

		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 5.0.0");
			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)(object)sample != (Object)null)
					{
						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/Rune580-LethalCompany_InputUtils/LethalCompanyInputUtils/LethalCompanyInputUtils.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using LethalCompanyInputUtils.BindingPathEnums;
using LethalCompanyInputUtils.Components;
using LethalCompanyInputUtils.Components.Section;
using LethalCompanyInputUtils.Components.Switch;
using LethalCompanyInputUtils.Config;
using LethalCompanyInputUtils.Data;
using LethalCompanyInputUtils.Glyphs;
using LethalCompanyInputUtils.Localization;
using LethalCompanyInputUtils.Utils;
using LethalCompanyInputUtils.Utils.Anim;
using LethalCompanyInputUtils.Utils.Anim.TweenValues;
using LethalConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using LobbyCompatibility.Enums;
using LobbyCompatibility.Features;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

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

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalCompanyInputUtils
{
	public static class LcInputActionApi
	{
		private static readonly Dictionary<string, LcInputActions> InputActionsMap = new Dictionary<string, LcInputActions>();

		internal static bool PrefabLoaded;

		internal static RemapContainerController? ContainerInstance;

		internal static IReadOnlyCollection<LcInputActions> InputActions => InputActionsMap.Values;

		internal static void LoadIntoUI(KepRemapPanel panel)
		{
			//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_0104: Unknown result type (might be due to invalid IL or missing references)
			AdjustSizeAndPos(panel);
			LayoutElement val = EnsureLayoutElement(panel);
			panel.LoadKeybindsUI();
			float horizontalOffset = panel.horizontalOffset;
			Rect rect = ((Component)((Transform)panel.keyRemapContainer).parent).GetComponent<RectTransform>().rect;
			float num = Mathf.Floor(((Rect)(ref rect)).width / horizontalOffset);
			int count = panel.keySlots.Count;
			int num2 = NumberOfActualKeys(panel.keySlots);
			int num3 = count - num2;
			panel.maxVertical = (float)num2 / num + (float)num3;
			if (ContainerInstance != null && ContainerInstance.legacyButton != null)
			{
				((TMP_Text)((Component)ContainerInstance.legacyButton).GetComponentInChildren<TextMeshProUGUI>()).SetText($"> Show Legacy Controls ({num2} present)", true);
			}
			if (count == 0)
			{
				return;
			}
			val.minHeight = (panel.maxVertical + 1f) * panel.verticalOffset;
			int num4 = 0;
			int num5 = 0;
			foreach (GameObject keySlot in panel.keySlots)
			{
				if ((float)num5 > num)
				{
					num4++;
					num5 = 0;
				}
				keySlot.GetComponent<RectTransform>().anchoredPosition = new Vector2((float)num5 * panel.horizontalOffset, (float)num4 * (0f - panel.verticalOffset));
				if (keySlot.GetComponentInChildren<SettingsOption>() == null)
				{
					num5 = 0;
					num4++;
				}
				else
				{
					num5++;
				}
			}
		}

		public static bool RemapContainerVisible()
		{
			if (ContainerInstance == null)
			{
				return false;
			}
			return ContainerInstance.LayerShown > 0;
		}

		private static int NumberOfActualKeys(List<GameObject> keySlots)
		{
			int num = 0;
			foreach (GameObject keySlot in keySlots)
			{
				if (keySlot.GetComponentInChildren<SettingsOption>() != null)
				{
					num++;
				}
			}
			return num;
		}

		internal static void CloseContainerLayer()
		{
			if (ContainerInstance != null)
			{
				ContainerInstance.HideHighestLayer();
			}
		}

		private static void AdjustSizeAndPos(KepRemapPanel panel)
		{
			GameObject gameObject = ((Component)((Transform)panel.keyRemapContainer).parent).gameObject;
			if (gameObject.GetComponent<ContentSizeFitter>() == null)
			{
				panel.keyRemapContainer.SetPivotY(1f);
				panel.keyRemapContainer.SetAnchorMinY(1f);
				panel.keyRemapContainer.SetAnchorMaxY(1f);
				panel.keyRemapContainer.SetAnchoredPosY(0f);
				panel.keyRemapContainer.SetLocalPosY(0f);
				ContentSizeFitter obj = gameObject.AddComponent<ContentSizeFitter>();
				obj.horizontalFit = (FitMode)0;
				obj.verticalFit = (FitMode)1;
			}
		}

		private static LayoutElement EnsureLayoutElement(KepRemapPanel panel)
		{
			GameObject gameObject = ((Component)((Transform)panel.keyRemapContainer).parent).gameObject;
			LayoutElement component = gameObject.GetComponent<LayoutElement>();
			if (component != null)
			{
				return component;
			}
			return gameObject.AddComponent<LayoutElement>();
		}

		internal static void CalculateVerticalMaxForGamepad(KepRemapPanel panel)
		{
			//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)
			int num = panel.remappableKeys.Count((RemappableKey key) => key.gamepadOnly);
			float horizontalOffset = panel.horizontalOffset;
			Rect rect = ((Component)((Transform)panel.keyRemapContainer).parent).GetComponent<RectTransform>().rect;
			float num2 = Mathf.Floor(((Rect)(ref rect)).width / horizontalOffset);
			panel.maxVertical = (float)num / num2;
			LayoutElement obj = EnsureLayoutElement(panel);
			obj.minHeight += (panel.maxVertical + 3f) * panel.verticalOffset;
		}

		internal static void ResetLoadedInputActions()
		{
			PrefabLoaded = false;
			foreach (LcInputActions inputAction in InputActions)
			{
				inputAction.Loaded = false;
			}
		}

		internal static void RegisterInputActions(LcInputActions lcInputActions, InputActionMapBuilder builder)
		{
			if (!InputActionsMap.TryAdd(lcInputActions.Id, lcInputActions))
			{
				Logging.Warn("The mod [" + lcInputActions.Plugin.GUID + "] instantiated an Actions class [" + lcInputActions.GetType().Name + "] more than once!\n\t These classes should be treated as singletons!, do not instantiate more than once!");
			}
			else
			{
				lcInputActions.CreateInputActions(in builder);
				InputActionSetupExtensions.AddActionMap(lcInputActions.GetAsset(), builder.Build());
				lcInputActions.GetAsset().Enable();
				lcInputActions.OnAssetLoaded();
				lcInputActions.Load();
				lcInputActions.BuildActionRefs();
			}
		}

		internal static void DisableForRebind()
		{
			foreach (LcInputActions inputAction in InputActions)
			{
				if (inputAction.Enabled)
				{
					inputAction.Disable();
				}
			}
		}

		internal static void ReEnableFromRebind()
		{
			foreach (LcInputActions inputAction in InputActions)
			{
				if (inputAction.WasEnabled)
				{
					inputAction.Enable();
				}
			}
		}

		internal static void SaveOverrides()
		{
			if (ContainerInstance != null)
			{
				ContainerInstance.SaveOverrides();
			}
		}

		internal static void DiscardOverrides()
		{
			if (ContainerInstance != null)
			{
				ContainerInstance.DiscardOverrides();
			}
		}
	}
	[BepInPlugin("com.rune580.LethalCompanyInputUtils", "Lethal Company Input Utils", "0.7.4")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class LethalCompanyInputUtilsPlugin : BaseUnityPlugin
	{
		public const string ModId = "com.rune580.LethalCompanyInputUtils";

		public const string ModName = "Lethal Company Input Utils";

		public const string ModVersion = "0.7.4";

		private Harmony? _harmony;

		private void Awake()
		{
			Logging.SetLogSource(((BaseUnityPlugin)this).Logger);
			_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "com.rune580.LethalCompanyInputUtils");
			SceneManager.activeSceneChanged += OnSceneChanged;
			InputSystem.onDeviceChange += OnDeviceChanged;
			LoadAssetBundles();
			ControllerGlyph.LoadGlyphs();
			FsUtils.EnsureRequiredDirs();
			InputUtilsConfig.Init((BaseUnityPlugin)(object)this);
			LocaleManager.LoadLocaleData();
			RegisterExtendedMouseLayout();
			ModCompat.Init((BaseUnityPlugin)(object)this);
			Logging.Info("InputUtils 0.7.4 has finished loading!");
			LayoutExporter.TryExportLayouts();
		}

		private static void LoadAssetBundles()
		{
			Assets.AddBundle("ui-assets");
		}

		private static void OnSceneChanged(Scene current, Scene next)
		{
			LcInputActionApi.ResetLoadedInputActions();
			CameraUtils.ClearUiCameraReference();
			BindsListController.OffsetCompensation = ((((Scene)(ref next)).name != "MainMenu") ? 20 : 0);
		}

		private static void OnDeviceChanged(InputDevice device, InputDeviceChange state)
		{
			RebindButton.ReloadGlyphs();
		}

		private static void RegisterExtendedMouseLayout()
		{
			InputSystem.RegisterLayoutOverride("{\n   \"name\": \"InputUtilsExtendedMouse\",\n   \"extend\": \"Mouse\",\n   \"controls\": [\n       {\n           \"name\": \"scroll/up\",\n           \"layout\": \"Button\",\n           \"useStateFrom\": \"scroll/up\",\n           \"format\": \"BIT\",\n           \"synthetic\": true\n       },\n       {\n           \"name\": \"scroll/down\",\n           \"layout\": \"Button\",\n           \"useStateFrom\": \"scroll/down\",\n           \"format\": \"BIT\",\n           \"synthetic\": true\n       },\n       {\n           \"name\": \"scroll/left\",\n           \"layout\": \"Button\",\n           \"useStateFrom\": \"scroll/left\",\n           \"format\": \"BIT\",\n           \"synthetic\": true\n       },\n       {\n           \"name\": \"scroll/right\",\n           \"layout\": \"Button\",\n           \"useStateFrom\": \"scroll/right\",\n           \"format\": \"BIT\",\n           \"synthetic\": true\n       }\n   ]\n}", (string)null);
			Logging.Info("Registered InputUtilsExtendedMouse Layout Override!");
		}
	}
	internal static class ModCompat
	{
		public static void Init(BaseUnityPlugin plugin)
		{
			if (Chainloader.PluginInfos.ContainsKey("BMX.LobbyCompatibility"))
			{
				LoadLobbyCompatibilityCompat(plugin.Info.Metadata);
			}
		}

		private static void LoadLobbyCompatibilityCompat(BepInPlugin plugin)
		{
			PluginHelper.RegisterPlugin(plugin.GUID, plugin.Version, (CompatibilityLevel)0, (VersionStrictness)0);
		}
	}
}
namespace LethalCompanyInputUtils.BindingPathEnums
{
	public enum KeyboardControl
	{
		None = 0,
		Unbound = 0,
		AnyKey = 1,
		Escape = 2,
		Space = 3,
		Enter = 4,
		Tab = 5,
		Backquote = 6,
		Quote = 7,
		Semicolon = 8,
		Comma = 9,
		Period = 10,
		Slash = 11,
		Backslash = 12,
		LeftBracket = 13,
		RightBracket = 14,
		Minus = 15,
		Equals = 16,
		UpArrow = 17,
		DownArrow = 18,
		LeftArrow = 19,
		RightArrow = 20,
		A = 21,
		B = 22,
		C = 23,
		D = 24,
		E = 25,
		F = 26,
		G = 27,
		H = 28,
		I = 29,
		J = 30,
		K = 31,
		L = 32,
		M = 33,
		N = 34,
		O = 35,
		P = 36,
		Q = 37,
		R = 38,
		S = 39,
		T = 40,
		U = 41,
		V = 42,
		W = 43,
		X = 44,
		Y = 45,
		Z = 46,
		Num1 = 47,
		Num2 = 48,
		Num3 = 49,
		Num4 = 50,
		Num5 = 51,
		Num6 = 52,
		Num7 = 53,
		Num8 = 54,
		Num9 = 55,
		Num0 = 56,
		LeftShift = 57,
		RightShift = 58,
		Shift = 59,
		LeftAlt = 60,
		RightAlt = 61,
		Alt = 62,
		LeftCtrl = 63,
		RightCtrl = 64,
		Ctrl = 65,
		LeftMeta = 66,
		RightMeta = 67,
		ContextMenu = 68,
		Backspace = 69,
		PageDown = 70,
		PageUp = 71,
		Home = 72,
		End = 73,
		Insert = 74,
		Delete = 75,
		CapsLock = 76,
		NumLock = 77,
		PrintScreen = 78,
		ScrollLock = 79,
		Pause = 80,
		NumpadEnter = 81,
		NumpadDivide = 82,
		NumpadMultiply = 83,
		NumpadPlus = 84,
		NumpadMinus = 85,
		NumpadPeriod = 86,
		NumpadEquals = 87,
		Numpad1 = 88,
		Numpad2 = 89,
		Numpad3 = 90,
		Numpad4 = 91,
		Numpad5 = 92,
		Numpad6 = 93,
		Numpad7 = 94,
		Numpad8 = 95,
		Numpad9 = 96,
		Numpad0 = 97,
		F1 = 98,
		F2 = 99,
		F3 = 100,
		F4 = 101,
		F5 = 102,
		F6 = 103,
		F7 = 104,
		F8 = 105,
		F9 = 106,
		F10 = 107,
		F11 = 108,
		F12 = 109,
		OEM1 = 110,
		OEM2 = 111,
		OEM3 = 112,
		OEM4 = 113,
		OEM5 = 114,
		IMESelected = 115
	}
	public static class KeyboardControlExtensions
	{
		public static string ToPath(this KeyboardControl keyboardControl)
		{
			return keyboardControl switch
			{
				KeyboardControl.None => "", 
				KeyboardControl.AnyKey => "<Keyboard>/anyKey", 
				KeyboardControl.Escape => "<Keyboard>/escape", 
				KeyboardControl.Space => "<Keyboard>/space", 
				KeyboardControl.Enter => "<Keyboard>/enter", 
				KeyboardControl.Tab => "<Keyboard>/tab", 
				KeyboardControl.Backquote => "<Keyboard>/backquote", 
				KeyboardControl.Quote => "<Keyboard>/quote", 
				KeyboardControl.Semicolon => "<Keyboard>/semicolon", 
				KeyboardControl.Comma => "<Keyboard>/comma", 
				KeyboardControl.Period => "<Keyboard>/period", 
				KeyboardControl.Slash => "<Keyboard>/slash", 
				KeyboardControl.Backslash => "<Keyboard>/backslash", 
				KeyboardControl.LeftBracket => "<Keyboard>/leftBracket", 
				KeyboardControl.RightBracket => "<Keyboard>/rightBracket", 
				KeyboardControl.Minus => "<Keyboard>/minus", 
				KeyboardControl.Equals => "<Keyboard>/equals", 
				KeyboardControl.UpArrow => "<Keyboard>/upArrow", 
				KeyboardControl.DownArrow => "<Keyboard>/downArrow", 
				KeyboardControl.LeftArrow => "<Keyboard>/leftArrow", 
				KeyboardControl.RightArrow => "<Keyboard>/rightArrow", 
				KeyboardControl.A => "<Keyboard>/a", 
				KeyboardControl.B => "<Keyboard>/b", 
				KeyboardControl.C => "<Keyboard>/c", 
				KeyboardControl.D => "<Keyboard>/d", 
				KeyboardControl.E => "<Keyboard>/e", 
				KeyboardControl.F => "<Keyboard>/f", 
				KeyboardControl.G => "<Keyboard>/g", 
				KeyboardControl.H => "<Keyboard>/h", 
				KeyboardControl.I => "<Keyboard>/i", 
				KeyboardControl.J => "<Keyboard>/j", 
				KeyboardControl.K => "<Keyboard>/k", 
				KeyboardControl.L => "<Keyboard>/l", 
				KeyboardControl.M => "<Keyboard>/m", 
				KeyboardControl.N => "<Keyboard>/n", 
				KeyboardControl.O => "<Keyboard>/o", 
				KeyboardControl.P => "<Keyboard>/p", 
				KeyboardControl.Q => "<Keyboard>/q", 
				KeyboardControl.R => "<Keyboard>/r", 
				KeyboardControl.S => "<Keyboard>/s", 
				KeyboardControl.T => "<Keyboard>/t", 
				KeyboardControl.U => "<Keyboard>/u", 
				KeyboardControl.V => "<Keyboard>/v", 
				KeyboardControl.W => "<Keyboard>/w", 
				KeyboardControl.X => "<Keyboard>/x", 
				KeyboardControl.Y => "<Keyboard>/y", 
				KeyboardControl.Z => "<Keyboard>/z", 
				KeyboardControl.Num1 => "<Keyboard>/1", 
				KeyboardControl.Num2 => "<Keyboard>/2", 
				KeyboardControl.Num3 => "<Keyboard>/3", 
				KeyboardControl.Num4 => "<Keyboard>/4", 
				KeyboardControl.Num5 => "<Keyboard>/5", 
				KeyboardControl.Num6 => "<Keyboard>/6", 
				KeyboardControl.Num7 => "<Keyboard>/7", 
				KeyboardControl.Num8 => "<Keyboard>/8", 
				KeyboardControl.Num9 => "<Keyboard>/9", 
				KeyboardControl.Num0 => "<Keyboard>/0", 
				KeyboardControl.LeftShift => "<Keyboard>/leftShift", 
				KeyboardControl.RightShift => "<Keyboard>/rightShift", 
				KeyboardControl.Shift => "<Keyboard>/shift", 
				KeyboardControl.LeftAlt => "<Keyboard>/leftAlt", 
				KeyboardControl.RightAlt => "<Keyboard>/rightAlt", 
				KeyboardControl.Alt => "<Keyboard>/alt", 
				KeyboardControl.LeftCtrl => "<Keyboard>/leftCtrl", 
				KeyboardControl.RightCtrl => "<Keyboard>/rightCtrl", 
				KeyboardControl.Ctrl => "<Keyboard>/ctrl", 
				KeyboardControl.LeftMeta => "<Keyboard>/leftMeta", 
				KeyboardControl.RightMeta => "<Keyboard>/rightMeta", 
				KeyboardControl.ContextMenu => "<Keyboard>/contextMenu", 
				KeyboardControl.Backspace => "<Keyboard>/backspace", 
				KeyboardControl.PageDown => "<Keyboard>/pageDown", 
				KeyboardControl.PageUp => "<Keyboard>/pageUp", 
				KeyboardControl.Home => "<Keyboard>/home", 
				KeyboardControl.End => "<Keyboard>/end", 
				KeyboardControl.Insert => "<Keyboard>/insert", 
				KeyboardControl.Delete => "<Keyboard>/delete", 
				KeyboardControl.CapsLock => "<Keyboard>/capsLock", 
				KeyboardControl.NumLock => "<Keyboard>/numLock", 
				KeyboardControl.PrintScreen => "<Keyboard>/printScreen", 
				KeyboardControl.ScrollLock => "<Keyboard>/scrollLock", 
				KeyboardControl.Pause => "<Keyboard>/pause", 
				KeyboardControl.NumpadEnter => "<Keyboard>/numpadEnter", 
				KeyboardControl.NumpadDivide => "<Keyboard>/numpadDivide", 
				KeyboardControl.NumpadMultiply => "<Keyboard>/numpadMultiply", 
				KeyboardControl.NumpadPlus => "<Keyboard>/numpadPlus", 
				KeyboardControl.NumpadMinus => "<Keyboard>/numpadMinus", 
				KeyboardControl.NumpadPeriod => "<Keyboard>/numpadPeriod", 
				KeyboardControl.NumpadEquals => "<Keyboard>/numpadEquals", 
				KeyboardControl.Numpad1 => "<Keyboard>/numpad1", 
				KeyboardControl.Numpad2 => "<Keyboard>/numpad2", 
				KeyboardControl.Numpad3 => "<Keyboard>/numpad3", 
				KeyboardControl.Numpad4 => "<Keyboard>/numpad4", 
				KeyboardControl.Numpad5 => "<Keyboard>/numpad5", 
				KeyboardControl.Numpad6 => "<Keyboard>/numpad6", 
				KeyboardControl.Numpad7 => "<Keyboard>/numpad7", 
				KeyboardControl.Numpad8 => "<Keyboard>/numpad8", 
				KeyboardControl.Numpad9 => "<Keyboard>/numpad9", 
				KeyboardControl.Numpad0 => "<Keyboard>/numpad0", 
				KeyboardControl.F1 => "<Keyboard>/f1", 
				KeyboardControl.F2 => "<Keyboard>/f2", 
				KeyboardControl.F3 => "<Keyboard>/f3", 
				KeyboardControl.F4 => "<Keyboard>/f4", 
				KeyboardControl.F5 => "<Keyboard>/f5", 
				KeyboardControl.F6 => "<Keyboard>/f6", 
				KeyboardControl.F7 => "<Keyboard>/f7", 
				KeyboardControl.F8 => "<Keyboard>/f8", 
				KeyboardControl.F9 => "<Keyboard>/f9", 
				KeyboardControl.F10 => "<Keyboard>/f10", 
				KeyboardControl.F11 => "<Keyboard>/f11", 
				KeyboardControl.F12 => "<Keyboard>/f12", 
				KeyboardControl.OEM1 => "<Keyboard>/OEM1", 
				KeyboardControl.OEM2 => "<Keyboard>/OEM2", 
				KeyboardControl.OEM3 => "<Keyboard>/OEM3", 
				KeyboardControl.OEM4 => "<Keyboard>/OEM4", 
				KeyboardControl.OEM5 => "<Keyboard>/OEM5", 
				KeyboardControl.IMESelected => "<Keyboard>/IMESelected", 
				_ => throw new ArgumentOutOfRangeException("keyboardControl", keyboardControl, null), 
			};
		}
	}
	public enum MouseControl
	{
		None = 0,
		Unbound = 0,
		ScrollUp = 1,
		ScrollDown = 2,
		ScrollLeft = 3,
		ScrollRight = 4,
		Position = 5,
		Delta = 6,
		Scroll = 7,
		ScrollX = 8,
		ScrollY = 9,
		Press = 10,
		LeftButton = 11,
		RightButton = 12,
		MiddleButton = 13,
		ForwardButton = 14,
		BackButton = 15,
		Pressure = 16,
		Radius = 17,
		PointerId = 18,
		DisplayIndex = 19,
		ClickCount = 20
	}
	public static class MouseControlExtensions
	{
		public static string ToPath(this MouseControl mouseControl)
		{
			return mouseControl switch
			{
				MouseControl.None => "", 
				MouseControl.ScrollUp => "<Mouse>/scroll/up", 
				MouseControl.ScrollDown => "<Mouse>/scroll/down", 
				MouseControl.ScrollLeft => "<Mouse>/scroll/left", 
				MouseControl.ScrollRight => "<Mouse>/scroll/right", 
				MouseControl.Position => "<Mouse>/position", 
				MouseControl.Delta => "<Mouse>/delta", 
				MouseControl.Scroll => "<Mouse>/scroll", 
				MouseControl.ScrollX => "<Mouse>/scroll/x", 
				MouseControl.ScrollY => "<Mouse>/scroll/y", 
				MouseControl.Press => "<Mouse>/press", 
				MouseControl.LeftButton => "<Mouse>/leftButton", 
				MouseControl.RightButton => "<Mouse>/rightButton", 
				MouseControl.MiddleButton => "<Mouse>/middleButton", 
				MouseControl.ForwardButton => "<Mouse>/forwardButton", 
				MouseControl.BackButton => "<Mouse>/backButton", 
				MouseControl.Pressure => "<Mouse>/pressure", 
				MouseControl.Radius => "<Mouse>/radius", 
				MouseControl.PointerId => "<Mouse>/pointerId", 
				MouseControl.DisplayIndex => "<Mouse>/displayIndex", 
				MouseControl.ClickCount => "<Mouse>/clickCount", 
				_ => throw new ArgumentOutOfRangeException("mouseControl", mouseControl, null), 
			};
		}
	}
	public enum GamepadControl
	{
		None = 0,
		Unbound = 0,
		Dpad = 1,
		ButtonSouth = 2,
		ButtonWest = 3,
		ButtonNorth = 4,
		ButtonEast = 5,
		LeftStickPress = 6,
		RightStickPress = 7,
		LeftShoulder = 8,
		RightShoulder = 9,
		Start = 10,
		Select = 11,
		LeftStick = 12,
		RightStick = 13,
		LeftTrigger = 14,
		RightTrigger = 15
	}
	public static class GamepadControlExtensions
	{
		public static string ToPath(this GamepadControl gamepadControl)
		{
			return gamepadControl switch
			{
				GamepadControl.None => "", 
				GamepadControl.Dpad => "<Gamepad>/dpad", 
				GamepadControl.ButtonSouth => "<Gamepad>/buttonSouth", 
				GamepadControl.ButtonWest => "<Gamepad>/buttonWest", 
				GamepadControl.ButtonNorth => "<Gamepad>/buttonNorth", 
				GamepadControl.ButtonEast => "<Gamepad>/buttonEast", 
				GamepadControl.LeftStickPress => "<Gamepad>/leftStickPress", 
				GamepadControl.RightStickPress => "<Gamepad>/rightStickPress", 
				GamepadControl.LeftShoulder => "<Gamepad>/leftShoulder", 
				GamepadControl.RightShoulder => "<Gamepad>/rightShoulder", 
				GamepadControl.Start => "<Gamepad>/start", 
				GamepadControl.Select => "<Gamepad>/select", 
				GamepadControl.LeftStick => "<Gamepad>/leftStick", 
				GamepadControl.RightStick => "<Gamepad>/rightStick", 
				GamepadControl.LeftTrigger => "<Gamepad>/leftTrigger", 
				GamepadControl.RightTrigger => "<Gamepad>/rightTrigger", 
				_ => throw new ArgumentOutOfRangeException("gamepadControl", gamepadControl, null), 
			};
		}
	}
}
namespace LethalCompanyInputUtils.Utils
{
	internal static class AssemblyUtils
	{
		public static BepInPlugin? GetBepInPlugin(this Assembly assembly)
		{
			foreach (Type validType in assembly.GetValidTypes())
			{
				BepInPlugin customAttribute = ((MemberInfo)validType).GetCustomAttribute<BepInPlugin>();
				if (customAttribute != null)
				{
					return customAttribute;
				}
			}
			return null;
		}

		public static IEnumerable<Type> GetValidTypes(this Assembly assembly)
		{
			try
			{
				return assembly.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				return ex.Types.Where((Type type) => (object)type != null);
			}
		}
	}
	internal static class Assets
	{
		private static readonly List<AssetBundle> AssetBundles = new List<AssetBundle>();

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

		public static void AddBundle(string bundleName)
		{
			AssetBundle val = AssetBundle.LoadFromFile(Path.Combine(FsUtils.AssetBundlesDir, bundleName));
			int count = AssetBundles.Count;
			AssetBundles.Add(val);
			string[] allAssetNames = val.GetAllAssetNames();
			for (int i = 0; i < allAssetNames.Length; i++)
			{
				string text = allAssetNames[i].ToLowerInvariant();
				if (text.StartsWith("assets/"))
				{
					string text2 = text;
					int length = "assets/".Length;
					text = text2.Substring(length, text2.Length - length);
				}
				AssetIndices[text] = count;
			}
		}

		public static T? Load<T>(string assetName) where T : Object
		{
			try
			{
				assetName = assetName.ToLowerInvariant();
				if (assetName.StartsWith("assets/"))
				{
					string text = assetName;
					int length = "assets/".Length;
					assetName = text.Substring(length, text.Length - length);
				}
				int index = AssetIndices[assetName];
				return AssetBundles[index].LoadAsset<T>("assets/" + assetName);
			}
			catch (Exception arg)
			{
				Logging.Error($"Couldn't load asset [{assetName}] exception: {arg}");
				return default(T);
			}
		}
	}
	internal static class CameraUtils
	{
		private static Camera? _uiCamera;

		public static Camera GetBestUiCamera()
		{
			//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 (_uiCamera != null && Object.op_Implicit((Object)(object)_uiCamera))
			{
				return _uiCamera;
			}
			_uiCamera = null;
			Scene activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).name == "MainMenu")
			{
				GameObject val = ((IEnumerable<GameObject>)((Scene)(ref activeScene)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject go) => ((Object)go).name == "UICamera"));
				if (val == null)
				{
					Logging.Warn("Failed to find UICamera at MainMenu, falling back to Camera.current!");
					return Camera.current;
				}
				Camera component = val.GetComponent<Camera>();
				if (component == null)
				{
					Logging.Warn("Failed to find Camera component on UICamera, falling back to Camera.current!");
					return Camera.current;
				}
				_uiCamera = component;
			}
			else
			{
				GameObject val2 = ((IEnumerable<GameObject>)((Scene)(ref activeScene)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject go) => ((Object)go).name == "Systems"));
				if (val2 == null)
				{
					Logging.Warn("Failed to find UICamera in active scene, falling back to Camera.current!");
					return Camera.current;
				}
				Transform val3 = val2.transform.Find("UI/UICamera");
				if (val3 == null)
				{
					Logging.Warn("Failed to find UICamera at MainMenu, falling back to Camera.current!");
					return Camera.current;
				}
				Camera component2 = ((Component)val3).GetComponent<Camera>();
				if (component2 == null)
				{
					Logging.Warn("Failed to find Camera component on UICamera, falling back to Camera.current!");
					return Camera.current;
				}
				_uiCamera = component2;
			}
			return _uiCamera;
		}

		public static void ClearUiCameraReference()
		{
			_uiCamera = null;
		}
	}
	internal static class DebugUtils
	{
		public static string ToPrettyString<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("{");
			using (IEnumerator<KeyValuePair<TKey, TValue>> enumerator = dictionary.GetEnumerator())
			{
				string[] obj;
				object obj3;
				for (; enumerator.MoveNext(); obj[3] = (string)obj3, obj[4] = "\",", stringBuilder.AppendLine(string.Concat(obj)))
				{
					enumerator.Current.Deconstruct(out var key, out var value);
					TKey val = key;
					TValue val2 = value;
					obj = new string[5] { "\t\"", null, null, null, null };
					ref TKey reference = ref val;
					key = default(TKey);
					object obj2;
					if (key == null)
					{
						key = reference;
						reference = ref key;
						if (key == null)
						{
							obj2 = null;
							goto IL_007c;
						}
					}
					obj2 = reference.ToString();
					goto IL_007c;
					IL_007c:
					obj[1] = (string)obj2;
					obj[2] = "\": \"";
					ref TValue reference2 = ref val2;
					value = default(TValue);
					if (value == null)
					{
						value = reference2;
						reference2 = ref value;
						if (value == null)
						{
							obj3 = null;
							continue;
						}
					}
					obj3 = reference2.ToString();
				}
			}
			stringBuilder.Remove(stringBuilder.Length - 1, 1);
			stringBuilder.AppendLine("}");
			return stringBuilder.ToString();
		}

		public static void DrawGizmoUiRectWorld(this RectTransform rectTransform)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_0057: 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_0077: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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_00a2: 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_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			float z = ((Transform)rectTransform).position.z;
			Rect val = rectTransform.UiBoundsWorld();
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(((Rect)(ref val)).min.x, ((Rect)(ref val)).min.y, z);
			Vector3 val3 = default(Vector3);
			((Vector3)(ref val3))..ctor(((Rect)(ref val)).min.x, ((Rect)(ref val)).max.y, z);
			Vector3 val4 = default(Vector3);
			((Vector3)(ref val4))..ctor(((Rect)(ref val)).max.x, ((Rect)(ref val)).max.y, z);
			Vector3 val5 = default(Vector3);
			((Vector3)(ref val5))..ctor(((Rect)(ref val)).max.x, ((Rect)(ref val)).min.y, z);
			Gizmos.DrawLine(val2, val3);
			Gizmos.DrawLine(val3, val4);
			Gizmos.DrawLine(val4, val5);
			Gizmos.DrawLine(val5, val2);
		}

		public static void DrawGizmoUiRect(this RectTransform rectTransform, Vector3 position)
		{
			//IL_0000: 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_0013: 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_0033: 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_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: 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_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: 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_00a9: Unknown result type (might be due to invalid IL or missing references)
			float z = position.z;
			Rect val = rectTransform.UiBounds(position);
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(((Rect)(ref val)).min.x, ((Rect)(ref val)).min.y, z);
			Vector3 val3 = default(Vector3);
			((Vector3)(ref val3))..ctor(((Rect)(ref val)).min.x, ((Rect)(ref val)).max.y, z);
			Vector3 val4 = default(Vector3);
			((Vector3)(ref val4))..ctor(((Rect)(ref val)).max.x, ((Rect)(ref val)).max.y, z);
			Vector3 val5 = default(Vector3);
			((Vector3)(ref val5))..ctor(((Rect)(ref val)).max.x, ((Rect)(ref val)).min.y, z);
			Gizmos.DrawLine(val2, val3);
			Gizmos.DrawLine(val3, val4);
			Gizmos.DrawLine(val4, val5);
			Gizmos.DrawLine(val5, val2);
		}

		public static void DrawGizmoRect(this Rect rect, Vector3 position)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_0043: 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_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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: 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_009f: 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_00b2: 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_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			float z = position.z;
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(((Rect)(ref rect)).min.x + position.x, ((Rect)(ref rect)).min.y + position.y, z);
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(((Rect)(ref rect)).min.x + position.x, ((Rect)(ref rect)).max.y + position.y, z);
			Vector3 val3 = default(Vector3);
			((Vector3)(ref val3))..ctor(((Rect)(ref rect)).max.x + position.x, ((Rect)(ref rect)).max.y + position.y, z);
			Vector3 val4 = default(Vector3);
			((Vector3)(ref val4))..ctor(((Rect)(ref rect)).max.x + position.x, ((Rect)(ref rect)).min.y + position.y, z);
			Gizmos.DrawLine(val, val2);
			Gizmos.DrawLine(val2, val3);
			Gizmos.DrawLine(val3, val4);
			Gizmos.DrawLine(val4, val);
		}
	}
	internal static class DeconstructUtils
	{
		public static void Deconstruct(this Rect rect, out Vector2 min, out Vector2 max)
		{
			//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_0028: 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)
			min = new Vector2(((Rect)(ref rect)).xMin, ((Rect)(ref rect)).yMin);
			max = new Vector2(((Rect)(ref rect)).xMax, ((Rect)(ref rect)).yMax);
		}

		public static void Deconstruct(this Vector3 vector, out float x, out float y, out float z)
		{
			//IL_0001: 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_0011: Unknown result type (might be due to invalid IL or missing references)
			x = vector.x;
			y = vector.y;
			z = vector.z;
		}
	}
	public static class DeviceGroups
	{
		public const string KeyboardAndMouse = "KeyboardAndMouse";

		public const string Gamepad = "Gamepad";
	}
	internal static class FsUtils
	{
		private static string? _assetBundlesDir;

		private static string? _localeDir;

		public static string SaveDir { get; } = GetSaveDir();


		public static string PersistentDir { get; } = Path.Combine(SaveDir, "InputUtils");


		public static string PersistentConfigPath { get; } = Path.Combine(PersistentDir, "Settings.cfg");


		public static string Pre041ControlsDir { get; } = Path.Combine(Paths.BepInExRootPath, "controls");


		public static string ControlsDir { get; } = Path.Combine(Paths.ConfigPath, "controls");


		public static string PersistentControlsDir { get; } = Path.Combine(PersistentDir, "controls");


		public static string AssetBundlesDir
		{
			get
			{
				if (_assetBundlesDir == null)
				{
					_assetBundlesDir = GetAssetBundlesDir();
				}
				if (string.IsNullOrEmpty(_assetBundlesDir))
				{
					string text = Chainloader.PluginInfos.ToPrettyString();
					Logging.Warn("InputUtils is loading in an invalid state!\n\tOne of the following mods may be the culprit:\n" + text);
					return "";
				}
				return _assetBundlesDir;
			}
		}

		public static string LocaleDir
		{
			get
			{
				if (_localeDir == null)
				{
					_localeDir = GetLocaleDir();
				}
				if (string.IsNullOrEmpty(_localeDir))
				{
					string text = Chainloader.PluginInfos.ToPrettyString();
					Logging.Warn("InputUtils is loading in an invalid state!\n\tOne of the following mods may be the culprit:\n" + text);
					return "";
				}
				return _localeDir;
			}
		}

		private static string GetSaveDir()
		{
			string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
			return Path.Combine(folderPath, "AppData", "LocalLow", "ZeekerssRBLX", "Lethal Company");
		}

		private static string? GetAssetBundlesDir()
		{
			if (!Chainloader.PluginInfos.TryGetValue("com.rune580.LethalCompanyInputUtils", out var value))
			{
				return null;
			}
			string text = Path.Combine((Directory.GetParent(value.Location) ?? throw new NotSupportedException(BadInstallError())).FullName, "AssetBundles");
			if (!Directory.Exists(text))
			{
				throw new NotSupportedException(BadInstallError());
			}
			return text;
			static string BadInstallError()
			{
				Logging.Error("InputUtils can't find it's required AssetBundles! This will cause many issues!\nThis either means your mod manager incorrectly installed InputUtilsor if you've manually installed InputUtils, you've done so incorrectly. If you manually installed don't bother reporting the issue, I only provide support to people who use mod managers.");
				return "InputUtils can't find it's required AssetBundles! This will cause many issues!\nThis either means your mod manager incorrectly installed InputUtilsor if you've manually installed InputUtils, you've done so incorrectly. If you manually installed don't bother reporting the issue, I only provide support to people who use mod managers.";
			}
		}

		private static string? GetLocaleDir()
		{
			if (!Chainloader.PluginInfos.TryGetValue("com.rune580.LethalCompanyInputUtils", out var value))
			{
				return null;
			}
			string text = Path.Combine((Directory.GetParent(value.Location) ?? throw new NotSupportedException(BadInstallError())).FullName, "Locale");
			if (!Directory.Exists(text))
			{
				throw new NotSupportedException(BadInstallError());
			}
			return text;
			static string BadInstallError()
			{
				Logging.Error("InputUtils can't find it's required AssetBundles! This will cause many issues!\nThis either means your mod manager incorrectly installed InputUtilsor if you've manually installed InputUtils, you've done so incorrectly. If you manually installed don't bother reporting the issue, I only provide support to people who use mod managers.");
				return "InputUtils can't find it's required AssetBundles! This will cause many issues!\nThis either means your mod manager incorrectly installed InputUtilsor if you've manually installed InputUtils, you've done so incorrectly. If you manually installed don't bother reporting the issue, I only provide support to people who use mod managers.";
			}
		}

		public static void EnsureRequiredDirs()
		{
			if (!Directory.Exists(ControlsDir))
			{
				Directory.CreateDirectory(ControlsDir);
			}
			if (!Directory.Exists(SaveDir))
			{
				Logging.Warn("LethalCompany save directory doesn't exist!\n Persistent settings will fail!");
			}
			else if (!Directory.Exists(PersistentControlsDir))
			{
				Directory.CreateDirectory(PersistentControlsDir);
			}
		}
	}
	internal static class InputSystemUtils
	{
		public static bool IsGamepadOnly(this InputAction action)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return ((IEnumerable<InputBinding>)(object)action.bindings).All((InputBinding binding) => !binding.IsKbmBind());
		}

		public static bool IsKbmBind(this InputBinding binding)
		{
			return string.Equals(((InputBinding)(ref binding)).groups, "KeyboardAndMouse");
		}

		public static bool IsGamepadBind(this InputBinding binding)
		{
			return string.Equals(((InputBinding)(ref binding)).groups, "Gamepad");
		}

		public static RemappableKey? GetKbmKey(this InputActionReference actionRef)
		{
			//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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_0033: 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_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			ReadOnlyArray<InputBinding> bindings = actionRef.action.bindings;
			for (int i = 0; i < bindings.Count; i++)
			{
				InputBinding binding = bindings[i];
				if (binding.IsKbmBind())
				{
					return new RemappableKey
					{
						ControlName = ((InputBinding)(ref binding)).name,
						currentInput = actionRef,
						rebindingIndex = i,
						gamepadOnly = false
					};
				}
			}
			return null;
		}

		public static RemappableKey? GetGamepadKey(this InputActionReference actionRef)
		{
			//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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_0033: 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_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			ReadOnlyArray<InputBinding> bindings = actionRef.action.bindings;
			for (int i = 0; i < bindings.Count; i++)
			{
				InputBinding binding = bindings[i];
				if (binding.IsGamepadBind())
				{
					return new RemappableKey
					{
						ControlName = ((InputBinding)(ref binding)).name,
						currentInput = actionRef,
						rebindingIndex = i,
						gamepadOnly = true
					};
				}
			}
			return null;
		}
	}
	internal static class LayoutExporter
	{
		private static readonly InputControlLayout[] Layouts = (InputControlLayout[])(object)new InputControlLayout[3]
		{
			InputSystem.LoadLayout<Keyboard>(),
			InputSystem.LoadLayout<Mouse>(),
			InputSystem.LoadLayout<Gamepad>()
		};

		public static void TryExportLayouts()
		{
			string[] commandLineArgs = Environment.GetCommandLineArgs();
			string text = null;
			string[] array = commandLineArgs;
			foreach (string text2 in array)
			{
				if (text2.StartsWith("--inputUtilsExportLayoutsToDir="))
				{
					string[] array2 = text2.Split('=');
					if (array2.Length == 2)
					{
						text = array2[1];
					}
				}
			}
			if (text == null)
			{
				return;
			}
			try
			{
				ExportLayouts(Layouts, Path.Combine(text, "device_layouts.json"));
				Application.Quit();
			}
			catch (Exception data)
			{
				Logging.Error(data);
			}
		}

		public static void ExportLayouts(InputControlLayout[] layouts, string filePath)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("{");
			stringBuilder.AppendLine("\t\"layouts\": [");
			for (int i = 0; i < layouts.Length; i++)
			{
				string[] array = layouts[i].ToJson().Split("\n");
				foreach (string text in array)
				{
					stringBuilder.AppendLine("\t\t" + text);
				}
				stringBuilder.Remove(stringBuilder.Length - 2, 2);
				stringBuilder.AppendLine(",");
			}
			stringBuilder.Remove(stringBuilder.Length - 3, 1);
			stringBuilder.AppendLine("\t]");
			stringBuilder.AppendLine("}");
			File.WriteAllText(filePath, stringBuilder.ToString());
		}
	}
	internal static class Logging
	{
		private static ManualLogSource? _logSource;

		internal static void SetLogSource(ManualLogSource logSource)
		{
			_logSource = logSource;
		}

		public static void Error(object data)
		{
			Error(data.ToString());
		}

		public static void Warn(object data)
		{
			Warn(data.ToString());
		}

		public static void Info(object data)
		{
			Info(data.ToString());
		}

		public static void Error(string msg)
		{
			if (_logSource == null)
			{
				Debug.LogError((object)("[Lethal Company Input Utils] [Error] " + msg));
			}
			else
			{
				_logSource.LogError((object)msg);
			}
		}

		public static void Warn(string msg)
		{
			if (_logSource == null)
			{
				Debug.LogWarning((object)("[Lethal Company Input Utils] [Warning] " + msg));
			}
			else
			{
				_logSource.LogWarning((object)msg);
			}
		}

		public static void Info(string msg)
		{
			if (_logSource == null)
			{
				Debug.Log((object)("[Lethal Company Input Utils] [Info] " + msg));
			}
			else
			{
				_logSource.LogInfo((object)msg);
			}
		}
	}
	internal static class RectTransformExtensions
	{
		public static void SetLocalPosX(this RectTransform rectTransform, float x)
		{
			//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_0009: 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_0015: Unknown result type (might be due to invalid IL or missing references)
			Vector3 localPosition = ((Transform)rectTransform).localPosition;
			((Transform)rectTransform).localPosition = new Vector3(x, localPosition.y, localPosition.z);
		}

		public static void SetLocalPosY(this RectTransform rectTransform, float y)
		{
			//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_0008: 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_0015: Unknown result type (might be due to invalid IL or missing references)
			Vector3 localPosition = ((Transform)rectTransform).localPosition;
			((Transform)rectTransform).localPosition = new Vector3(localPosition.x, y, localPosition.z);
		}

		public static void SetPivotY(this RectTransform rectTransform, float y)
		{
			//IL_0002: 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)
			rectTransform.pivot = new Vector2(rectTransform.pivot.x, y);
		}

		public static void SetAnchorMinY(this RectTransform rectTransform, float y)
		{
			//IL_0002: 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)
			rectTransform.anchorMin = new Vector2(rectTransform.anchorMin.x, y);
		}

		public static void SetAnchorMaxY(this RectTransform rectTransform, float y)
		{
			//IL_0002: 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)
			rectTransform.anchorMax = new Vector2(rectTransform.anchorMax.x, y);
		}

		public static void SetAnchoredPosX(this RectTransform rectTransform, float x)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			rectTransform.anchoredPosition = new Vector2(x, rectTransform.anchoredPosition.y);
		}

		public static void SetAnchoredPosY(this RectTransform rectTransform, float y)
		{
			//IL_0002: 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)
			rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, y);
		}

		public static void SetSizeDeltaX(this RectTransform rectTransform, float x)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			rectTransform.sizeDelta = new Vector2(x, rectTransform.sizeDelta.y);
		}

		public static Rect UiBoundsWorld(this RectTransform rectTransform)
		{
			//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_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_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_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_0031: 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_0046: 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_005b: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Transform)rectTransform).position;
			Rect rect = rectTransform.rect;
			Vector3 lossyScale = ((Transform)rectTransform).lossyScale;
			return new Rect(((Rect)(ref rect)).x * lossyScale.x + position.x, ((Rect)(ref rect)).y * lossyScale.y + position.y, ((Rect)(ref rect)).width * lossyScale.x, ((Rect)(ref rect)).height * lossyScale.y);
		}

		[Obsolete("Use GetRelativeRect")]
		public static Rect UiBounds(this RectTransform rectTransform, Vector3 position)
		{
			//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_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			Rect rect = rectTransform.rect;
			Vector3 lossyScale = ((Transform)rectTransform).lossyScale;
			return new Rect(((Rect)(ref rect)).x * lossyScale.x + position.x, ((Rect)(ref rect)).y * lossyScale.y + position.y, ((Rect)(ref rect)).width * lossyScale.x, ((Rect)(ref rect)).height * lossyScale.y);
		}

		public static Rect GetRelativeRect(this RectTransform rectTransform, RectTransform worldRectTransform)
		{
			//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_0031: 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_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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0099: 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_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: 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_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: 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_00dd: 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)
			Camera bestUiCamera = CameraUtils.GetBestUiCamera();
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			worldRectTransform.GetWorldCorners(array);
			Vector2[] array2 = (Vector2[])(object)new Vector2[4];
			for (int i = 0; i < array.Length; i++)
			{
				array2[i] = RectTransformUtility.WorldToScreenPoint(bestUiCamera, array[i]);
			}
			Vector2[] array3 = (Vector2[])(object)new Vector2[4];
			for (int j = 0; j < array2.Length; j++)
			{
				RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, array2[j], bestUiCamera, ref array3[j]);
			}
			Vector2 val = array3[0];
			Vector2 val2 = array3[0];
			Vector2[] array4 = array3;
			foreach (Vector2 val3 in array4)
			{
				val = Vector2.Min(val, val3);
				val2 = Vector2.Max(val2, val3);
			}
			Vector2 val4 = val2 - val;
			return new Rect(val.x, val.y, val4.x, val4.y);
		}

		public static Vector2 WorldToLocalPoint(this RectTransform rectTransform, Vector3 worldPoint)
		{
			//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_000d: 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_0019: Unknown result type (might be due to invalid IL or missing references)
			Camera bestUiCamera = CameraUtils.GetBestUiCamera();
			Vector2 val = RectTransformUtility.WorldToScreenPoint(bestUiCamera, worldPoint);
			Vector2 result = default(Vector2);
			RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, val, bestUiCamera, ref result);
			return result;
		}

		public static Vector2 WorldToLocalPoint(this RectTransform rectTransform, RectTransform other)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return rectTransform.WorldToLocalPoint(((Transform)other).position);
		}

		public static float WorldMaxY(this RectTransform rectTransform)
		{
			//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_0009: Unknown result type (might be due to invalid IL or missing references)
			Rect val = rectTransform.UiBoundsWorld();
			return ((Rect)(ref val)).max.y;
		}

		public static float WorldMinY(this RectTransform rectTransform)
		{
			//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_0009: Unknown result type (might be due to invalid IL or missing references)
			Rect val = rectTransform.UiBoundsWorld();
			return ((Rect)(ref val)).min.y;
		}
	}
	internal static class RectUtils
	{
		public static Vector2 CenteredPos(this Rect rect)
		{
			//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)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			return ((Rect)(ref rect)).min + ((Rect)(ref rect)).size / 2f;
		}
	}
	internal static class RuntimeHelper
	{
		public static Vector3 LocalPositionRelativeTo(this Transform transform, Transform parent)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_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_0025: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = Vector3.zero;
			Transform val2 = transform;
			do
			{
				val += transform.localPosition;
				val2 = val2.parent;
			}
			while ((Object)(object)val2 != (Object)(object)parent);
			return val;
		}

		public static void DisableKeys(this IEnumerable<RemappableKey> keys)
		{
			foreach (RemappableKey key in keys)
			{
				key.currentInput.action.Disable();
			}
		}

		public static void EnableKeys(this IEnumerable<RemappableKey> keys)
		{
			foreach (RemappableKey key in keys)
			{
				key.currentInput.action.Enable();
			}
		}
	}
	internal static class VectorUtils
	{
		public static Vector3 Mul(this Vector3 left, Vector3 right)
		{
			//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_000d: 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_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_0027: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(left.x * right.x, left.y * right.y, left.z * right.z);
		}
	}
}
namespace LethalCompanyInputUtils.Utils.Anim
{
	public interface ITweenValue
	{
		bool IgnoreTimeScale { get; }

		float Duration { get; }

		void TweenValue(float percentage);

		bool ValidTarget();
	}
	public class TweenRunner<T> where T : struct, ITweenValue
	{
		protected MonoBehaviour? CoroutineContainer;

		protected IEnumerator? Tween;

		private static IEnumerator Start(T tweenValue)
		{
			if (tweenValue.ValidTarget())
			{
				float elapsedTime = 0f;
				while (elapsedTime < tweenValue.Duration)
				{
					elapsedTime += (tweenValue.IgnoreTimeScale ? Time.unscaledDeltaTime : Time.deltaTime);
					float percentage = Mathf.Clamp01(elapsedTime / tweenValue.Duration);
					tweenValue.TweenValue(percentage);
					yield return null;
				}
				tweenValue.TweenValue(1f);
			}
		}

		public void Init(MonoBehaviour coroutineContainer)
		{
			CoroutineContainer = coroutineContainer;
		}

		public void StartTween(T tweenValue)
		{
			if (CoroutineContainer != null)
			{
				if (Tween != null)
				{
					CoroutineContainer.StopCoroutine(Tween);
					Tween = null;
				}
				if (!((Component)CoroutineContainer).gameObject.activeInHierarchy)
				{
					tweenValue.TweenValue(1f);
					return;
				}
				Tween = Start(tweenValue);
				CoroutineContainer.StartCoroutine(Tween);
			}
		}

		public void StopTween()
		{
			if (Tween != null && CoroutineContainer != null)
			{
				CoroutineContainer.StopCoroutine(Tween);
				Tween = null;
			}
		}
	}
}
namespace LethalCompanyInputUtils.Utils.Anim.TweenValues
{
	public struct Vector2Tween : ITweenValue
	{
		private class Vector2TweenCallback : UnityEvent<Vector2>
		{
		}

		private Vector2TweenCallback? _target;

		public float Duration { get; set; }

		public Vector2 StartValue { get; set; }

		public Vector2 TargetValue { get; set; }

		public bool IgnoreTimeScale { get; set; }

		public void TweenValue(float percentage)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (ValidTarget())
			{
				Vector2 val = Vector2.Lerp(StartValue, TargetValue, percentage);
				((UnityEvent<Vector2>)_target).Invoke(val);
			}
		}

		public void AddOnChangedCallback(UnityAction<Vector2> callback)
		{
			if (_target == null)
			{
				_target = new Vector2TweenCallback();
			}
			((UnityEvent<Vector2>)_target).AddListener(callback);
		}

		public bool ValidTarget()
		{
			return _target != null;
		}
	}
	public struct Vector3Tween : ITweenValue
	{
		private class Vector3TweenCallback : UnityEvent<Vector3>
		{
		}

		private Vector3TweenCallback? _target;

		public float Duration { get; set; }

		public Vector3 StartValue { get; set; }

		public Vector3 TargetValue { get; set; }

		public bool IgnoreTimeScale { get; set; }

		public void TweenValue(float percentage)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (ValidTarget())
			{
				Vector3 val = Vector3.Lerp(StartValue, TargetValue, percentage);
				((UnityEvent<Vector3>)_target).Invoke(val);
			}
		}

		public void AddOnChangedCallback(UnityAction<Vector3> callback)
		{
			if (_target == null)
			{
				_target = new Vector3TweenCallback();
			}
			((UnityEvent<Vector3>)_target).AddListener(callback);
		}

		public bool ValidTarget()
		{
			return _target != null;
		}
	}
	public struct Vector4Tween : ITweenValue
	{
		private class Vector4TweenCallback : UnityEvent<Vector4>
		{
		}

		private Vector4TweenCallback? _target;

		public float Duration { get; set; }

		public Vector4 StartValue { get; set; }

		public Vector4 TargetValue { get; set; }

		public bool IgnoreTimeScale { get; set; }

		public void TweenValue(float percentage)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (ValidTarget())
			{
				Vector4 val = Vector4.Lerp(StartValue, TargetValue, percentage);
				((UnityEvent<Vector4>)_target).Invoke(val);
			}
		}

		public void AddOnChangedCallback(UnityAction<Vector4> callback)
		{
			if (_target == null)
			{
				_target = new Vector4TweenCallback();
			}
			((UnityEvent<Vector4>)_target).AddListener(callback);
		}

		public bool ValidTarget()
		{
			return _target != null;
		}
	}
}
namespace LethalCompanyInputUtils.Patches
{
	public static class InGamePlayerSettingsPatches
	{
		[HarmonyPatch(typeof(IngamePlayerSettings), "SaveChangedSettings")]
		public static class SaveChangedSettingsPatch
		{
			public static void Prefix()
			{
				LcInputActionApi.SaveOverrides();
			}
		}

		[HarmonyPatch(typeof(IngamePlayerSettings), "DiscardChangedSettings")]
		public static class DiscardChangedSettingsPatch
		{
			public static void Prefix()
			{
				LcInputActionApi.DiscardOverrides();
			}
		}
	}
	public static class InputControlPathPatches
	{
		[HarmonyPatch]
		public static class ToHumanReadableStringPatch
		{
			public static IEnumerable<MethodBase> TargetMethods()
			{
				return from method in AccessTools.GetDeclaredMethods(typeof(InputControlPath))
					where method.Name == "ToHumanReadableString" && method.ReturnType == typeof(string)
					select method;
			}

			public static void Postfix(ref string __result)
			{
				string text = __result;
				if ((text == "<InputUtils-Gamepad-Not-Bound>" || text == "<InputUtils-Kbm-Not-Bound>") ? true : false)
				{
					__result = "";
				}
			}
		}
	}
	public static class KeyRemapPanelPatches
	{
		[HarmonyPatch(typeof(KepRemapPanel), "OnEnable")]
		public static class LoadKeybindsUIPatch
		{
			[CompilerGenerated]
			private static class <>O
			{
				public static UnityAction <0>__CloseContainerLayer;
			}

			public static void Prefix(KepRemapPanel __instance)
			{
				//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d5: Expected O, but got Unknown
				//IL_011f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0129: Expected O, but got Unknown
				//IL_0130: 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_0182: Unknown result type (might be due to invalid IL or missing references)
				//IL_018c: Unknown result type (might be due to invalid IL or missing references)
				//IL_019f: 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_01f8: Unknown result type (might be due to invalid IL or missing references)
				//IL_0202: Expected O, but got Unknown
				//IL_023b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0245: Expected O, but got Unknown
				//IL_00ea: 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: Expected O, but got Unknown
				LcInputActionApi.DisableForRebind();
				if (LcInputActionApi.PrefabLoaded && LcInputActionApi.ContainerInstance != null)
				{
					LcInputActionApi.ContainerInstance.baseGameKeys.DisableKeys();
					return;
				}
				GameObject val = Object.Instantiate<GameObject>(Assets.Load<GameObject>("Prefabs/InputUtilsRemapContainer.prefab"), ((Component)__instance).transform);
				GameObject val2 = Object.Instantiate<GameObject>(Assets.Load<GameObject>("Prefabs/Legacy Holder.prefab"), ((Component)__instance).transform);
				if (val == null || val2 == null)
				{
					return;
				}
				Transform val3 = ((Component)__instance).transform.Find("Scroll View");
				if (val3 != null)
				{
					val3.SetParent(val2.transform);
					List<RemappableKey> remappableKeys = __instance.remappableKeys;
					__instance.remappableKeys = new List<RemappableKey>();
					val2.SetActive(false);
					GameObject gameObject = ((Component)((Component)__instance).transform.Find("Back")).gameObject;
					Button component = gameObject.GetComponent<Button>();
					GameObject obj = Object.Instantiate<GameObject>(gameObject, val2.transform, true);
					Object.DestroyImmediate((Object)(object)obj.GetComponentInChildren<SettingsOption>());
					Button component2 = obj.GetComponent<Button>();
					component2.onClick = new ButtonClickedEvent();
					ButtonClickedEvent onClick = component2.onClick;
					object obj2 = <>O.<0>__CloseContainerLayer;
					if (obj2 == null)
					{
						UnityAction val4 = LcInputActionApi.CloseContainerLayer;
						<>O.<0>__CloseContainerLayer = val4;
						obj2 = (object)val4;
					}
					((UnityEvent)onClick).AddListener((UnityAction)obj2);
					GameObject obj3 = Object.Instantiate<GameObject>(gameObject, gameObject.transform.parent);
					Object.DestroyImmediate((Object)(object)obj3.GetComponentInChildren<SettingsOption>());
					Button component3 = obj3.GetComponent<Button>();
					component3.onClick = new ButtonClickedEvent();
					RectTransform component4 = obj3.GetComponent<RectTransform>();
					component4.SetAnchoredPosY(component4.anchoredPosition.y + 25f);
					component4.SetSizeDeltaX(component4.sizeDelta.x + 180f);
					RectTransform component5 = ((Component)((Transform)component4).Find("SelectionHighlight")).GetComponent<RectTransform>();
					component5.SetSizeDeltaX(410f);
					component5.offsetMax = new Vector2(410f, component5.offsetMax.y);
					component5.offsetMin = new Vector2(0f, component5.offsetMin.y);
					RemapContainerController component6 = val.GetComponent<RemapContainerController>();
					component6.baseGameKeys = remappableKeys;
					component6.backButton = component;
					component6.legacyButton = component3;
					component6.legacyHolder = val2;
					component6.baseGameKeys.DisableKeys();
					((UnityEvent)component3.onClick).AddListener(new UnityAction(component6.ShowLegacyUi));
					component6.LoadUi();
					Button component7 = ((Component)((Component)__instance).transform.Find("SetDefault")).gameObject.GetComponent<Button>();
					((UnityEventBase)component7.onClick).RemoveAllListeners();
					((UnityEvent)component7.onClick).AddListener(new UnityAction(component6.OnSetToDefault));
					val2.transform.SetAsLastSibling();
					LcInputActionApi.PrefabLoaded = true;
				}
			}

			public static void Postfix(KepRemapPanel __instance)
			{
				LcInputActionApi.LoadIntoUI(__instance);
			}
		}

		[HarmonyPatch(typeof(KepRemapPanel), "OnDisable")]
		public static class UnloadKeybindsUIPatch
		{
			public static void Prefix()
			{
				if (LcInputActionApi.ContainerInstance != null)
				{
					LcInputActionApi.ContainerInstance.baseGameKeys.EnableKeys();
				}
			}
		}
	}
	public static class MenuManagerPatches
	{
		[HarmonyPatch(typeof(MenuManager), "Awake")]
		public static class AwakePatch
		{
			public static void Prefix(MenuManager __instance)
			{
				if (__instance.menuAnimator != null)
				{
					Transform transform = ((Component)__instance.menuAnimator).gameObject.transform;
					Object.Instantiate<GameObject>(Assets.Load<GameObject>("Prefabs/PopOver Layer.prefab"), transform);
				}
			}
		}
	}
	public static class QuickMenuManagerPatches
	{
		[HarmonyPatch(typeof(QuickMenuManager), "Start")]
		public static class StartPatch
		{
			public static void Prefix(QuickMenuManager __instance)
			{
				Object.Instantiate<GameObject>(Assets.Load<GameObject>("Prefabs/PopOver Layer.prefab"), __instance.menuContainer.transform);
			}
		}

		[HarmonyPatch(typeof(QuickMenuManager), "CloseQuickMenu")]
		public static class CloseQuickMenuPatch
		{
			public static bool Prefix(QuickMenuManager __instance)
			{
				if (LcInputActionApi.RemapContainerVisible() && __instance.isMenuOpen)
				{
					LcInputActionApi.CloseContainerLayer();
					return false;
				}
				return true;
			}
		}
	}
	public static class SettingsOptionPatches
	{
		[HarmonyPatch(typeof(SettingsOption), "SetBindingToCurrentSetting")]
		public static class SetBindingToCurrentSettingPatch
		{
			public static bool Prefix(SettingsOption __instance)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Invalid comparison between Unknown and I4
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				if ((int)__instance.optionType != 6)
				{
					return true;
				}
				Enumerator<InputBinding> enumerator = __instance.rebindableAction.action.bindings.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						InputBinding current = enumerator.Current;
						if (__instance.gamepadOnlyRebinding)
						{
							if (!string.Equals(((InputBinding)(ref current)).effectivePath, "<InputUtils-Gamepad-Not-Bound>"))
							{
								continue;
							}
						}
						else if (!string.Equals(((InputBinding)(ref current)).effectivePath, "<InputUtils-Kbm-Not-Bound>"))
						{
							continue;
						}
						((TMP_Text)__instance.currentlyUsedKeyText).SetText("", true);
						return false;
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				return true;
			}
		}
	}
}
namespace LethalCompanyInputUtils.Localization
{
	public static class LangTokens
	{
		public const string ResetToDefaultPopOver = "RebindButton.ResetToDefault.PopOver";

		public const string RemoveBindPopOver = "RebindButton.RemoveBind.PopOver";

		public const string UnsupportedDeviceBindPopOver = "RebindButton.NotSupportedDeviceBind.PopOver";

		public const string BindingOverrideContextSwitchInfoPopOver = "BindingOverrideContextSwitch.Info.PopOver";

		public const string BindingOverridePriorityDropdownInfoPopOver = "BindingOverridePriorityDropdown.Info.PopOver";
	}
	[Serializable]
	internal class Locale
	{
		public string? fallback;

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

		public static Locale LoadFrom(string jsonPath)
		{
			return JsonConvert.DeserializeObject<Locale>(File.ReadAllText(jsonPath)) ?? throw new NullReferenceException();
		}
	}
	internal static class LocaleManager
	{
		private static readonly Dictionary<string, string> LocaleEntries = new Dictionary<string, string>();

		internal static void LoadLocaleData()
		{
			Stack<Locale> stack = new Stack<Locale>();
			string text = InputUtilsConfig.localeKey.Value;
			string text2 = Path.Combine(FsUtils.LocaleDir, text + ".json");
			if (!File.Exists(text2))
			{
				Logging.Warn("Could not find Locale " + text + " at `" + text2 + "`!\nFalling back to `en_US`");
				text = "en_US";
				text2 = Path.Combine(FsUtils.LocaleDir, text + ".json");
			}
			while (File.Exists(text2))
			{
				Locale locale = Locale.LoadFrom(text2);
				stack.Push(locale);
				text = ((!(text != "en_US") || locale.fallback != null) ? locale.fallback : "en_US");
				text2 = Path.Combine(FsUtils.LocaleDir, text + ".json");
				if (text == null)
				{
					break;
				}
			}
			Locale result;
			while (stack.TryPop(out result))
			{
				foreach (var (key, value) in result.entries)
				{
					LocaleEntries[key] = value;
				}
			}
		}

		internal static string[] GetAllLocales()
		{
			return Directory.GetFiles(FsUtils.LocaleDir, "*.json").Select(Path.GetFileNameWithoutExtension).ToArray();
		}

		public static string GetString(string token)
		{
			return LocaleEntries[token];
		}
	}
}
namespace LethalCompanyInputUtils.Glyphs
{
	[CreateAssetMenu]
	public class ControllerGlyph : ScriptableObject
	{
		public List<string> validGamepadTypes = new List<string>();

		public List<GlyphDef> glyphSet = new List<GlyphDef>();

		private readonly Dictionary<string, Sprite?> _glyphLut = new Dictionary<string, Sprite>();

		private static readonly List<ControllerGlyph> Instances = new List<ControllerGlyph>();

		private static bool _loaded;

		public static ControllerGlyph? MouseGlyphs { get; private set; }

		public bool IsCurrent
		{
			get
			{
				Gamepad current = Gamepad.current;
				if (current == null)
				{
					return false;
				}
				return validGamepadTypes.Any((string gamepadTypeName) => string.Equals(gamepadTypeName, ((object)current).GetType().Name));
			}
		}

		public Sprite this[string controlPath]
		{
			get
			{
				if (_glyphLut.Count == 0)
				{
					UpdateLut();
				}
				return _glyphLut.GetValueOrDefault(controlPath, null);
			}
		}

		public static ControllerGlyph? GetBestMatching()
		{
			if (Instances.Count == 0)
			{
				return null;
			}
			foreach (ControllerGlyph instance in Instances)
			{
				if (instance.IsCurrent)
				{
					return instance;
				}
			}
			return Instances[0];
		}

		internal static void LoadGlyphs()
		{
			if (!_loaded)
			{
				Assets.Load<ControllerGlyph>("controller glyphs/xbox series x glyphs.asset");
				Assets.Load<ControllerGlyph>("controller glyphs/dualsense glyphs.asset");
				MouseGlyphs = Assets.Load<ControllerGlyph>("controller glyphs/mouse glyphs.asset");
				_loaded = true;
			}
		}

		private void Awake()
		{
			if (!Instances.Contains(this))
			{
				Instances.Add(this);
			}
		}

		private void UpdateLut()
		{
			foreach (GlyphDef item in glyphSet)
			{
				_glyphLut[item.controlPath] = item.glyphSprite;
			}
		}

		private void OnDestroy()
		{
			if (Instances.Contains(this))
			{
				Instances.Remove(this);
			}
		}
	}
	[CreateAssetMenu]
	public class GlyphDef : ScriptableObject
	{
		public string controlPath = "";

		public Sprite? glyphSprite;
	}
}
namespace LethalCompanyInputUtils.Data
{
	[Serializable]
	public struct BindingOverride
	{
		public string? action;

		public string? origPath;

		public string? path;

		public string? groups;
	}
	[Serializable]
	public class BindingOverrides
	{
		public List<BindingOverride> overrides;

		public BindingOverrides()
		{
			overrides = new List<BindingOverride>();
		}

		public BindingOverrides(IEnumerable<InputBinding> bindings)
		{
			//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)
			overrides = new List<BindingOverride>();
			foreach (InputBinding binding in bindings)
			{
				InputBinding current = binding;
				if (((InputBinding)(ref current)).hasOverrides)
				{
					BindingOverride item = new BindingOverride
					{
						action = ((InputBinding)(ref current)).action,
						origPath = ((InputBinding)(ref current)).path,
						path = ((InputBinding)(ref current)).overridePath,
						groups = ((InputBinding)(ref current)).groups
					};
					overrides.Add(item);
				}
			}
		}

		public void LoadInto(InputActionAsset asset)
		{
			foreach (BindingOverride @override in overrides)
			{
				InputAction obj = asset.FindAction(@override.action, false);
				if (obj != null)
				{
					InputActionRebindingExtensions.ApplyBindingOverride(obj, @override.path, @override.groups, (string)null);
				}
			}
		}

		public void LoadInto(IReadOnlyCollection<InputActionReference> actionRefs)
		{
			foreach (BindingOverride @override in overrides)
			{
				foreach (InputActionReference actionRef in actionRefs)
				{
					if (!(actionRef.action.name != @override.action))
					{
						InputActionRebindingExtensions.ApplyBindingOverride(actionRef.action, @override.path, @override.groups, (string)null);
						break;
					}
				}
			}
		}

		public string AsJson()
		{
			return JsonConvert.SerializeObject((object)this);
		}

		public static BindingOverrides FromJson(string json)
		{
			BindingOverrides bindingOverrides = new BindingOverrides();
			JToken value = JsonConvert.DeserializeObject<JObject>(json).GetValue("overrides");
			bindingOverrides.overrides = value.ToObject<List<BindingOverride>>();
			return bindingOverrides;
		}
	}
}
namespace LethalCompanyInputUtils.Config
{
	public enum BindingOverridePriority
	{
		GlobalThenLocal,
		LocalThenGlobal,
		GlobalOnly,
		LocalOnly
	}
	public enum BindingOverrideType
	{
		Global,
		Local
	}
	public static class BindingOverrideTypeExtensions
	{
		public static string GetJsonPath(this BindingOverrideType overrideType, string name)
		{
			return Path.Combine(overrideType switch
			{
				BindingOverrideType.Global => FsUtils.PersistentControlsDir, 
				BindingOverrideType.Local => FsUtils.ControlsDir, 
				_ => throw new ArgumentOutOfRangeException("overrideType", overrideType, null), 
			}, name + ".json");
		}
	}
	public static class InputUtilsConfig
	{
		public static ConfigEntry<BindingOverridePriority> bindingOverridePriority;

		public static ConfigEntry<string> localeKey;

		internal static void Init(BaseUnityPlugin plugin)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			bindingOverridePriority = new ConfigFile(FsUtils.PersistentConfigPath, true, plugin.Info.Metadata).Bind<BindingOverridePriority>("General", "Binding Overrides Priority", BindingOverridePriority.GlobalThenLocal, "Determines the priority when loading controls.\n\n\tGlobalThenLocal: Global defined controls take priority over Local/Profile/ModPack defined controls\n\tLocalThenGlobal: Local/Profile/ModPack defined controls take priority over Global defined controls\n\tGlobalOnly: Only loads Global defined controls\n\tLocalOnly: Only loads Local/Profile/ModPack defined controls\n");
			localeKey = plugin.Config.Bind<string>("General", "Locale", "en_US", "Valid Locales can be found in the 'Locale' folder where InputUtils is installed at.\nCan reload live in-game when using LethalConfig.");
			localeKey.SettingChanged += delegate
			{
				LocaleManager.LoadLocaleData();
			};
			if (Chainloader.PluginInfos.ContainsKey("ainavt.lc.lethalconfig"))
			{
				LethalConfigSetup();
			}
		}

		private static void LethalConfigSetup()
		{
			//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: Expected O, but got Unknown
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			TextDropDownOptions val = new TextDropDownOptions(LocaleManager.GetAllLocales())
			{
				RequiresRestart = false
			};
			LethalConfigManager.AddConfigItem((BaseConfigItem)new TextDropDownConfigItem(localeKey, val));
		}
	}
}
namespace LethalCompanyInputUtils.Components
{
	[RequireComponent(typeof(RectTransform))]
	public class BindsListController : MonoBehaviour
	{
		public GameObject? sectionHeaderPrefab;

		public GameObject? sectionAnchorPrefab;

		public GameObject? rebindItemPrefab;

		public GameObject? spacerPrefab;

		public ScrollRect? scrollRect;

		public RectTransform? headerContainer;

		public UnityEvent<int> OnSectionChanged = new UnityEvent<int>();

		public static float OffsetCompensation;

		private RectTransform? _rectTransform;

		private RectTransform? _scrollRectTransform;

		private RectTransform? _content;

		private VerticalLayoutGroup? _verticalLayoutGroup;

		private int _currentSection;

		private float _sectionHeight;

		private float _spacing;

		private readonly List<SectionHeaderAnchor> _anchors = new List<SectionHeaderAnchor>();

		private void Awake()
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			if (_rectTransform == null)
			{
				_rectTransform = ((Component)this).GetComponent<RectTransform>();
			}
			if (scrollRect == null)
			{
				scrollRect = ((Component)this).GetComponentInChildren<ScrollRect>();
			}
			if (_verticalLayoutGroup == null)
			{
				_verticalLayoutGroup = ((Component)scrollRect.content).GetComponent<VerticalLayoutGroup>();
			}
			_spacing = ((HorizontalOrVerticalLayoutGroup)_verticalLayoutGroup).spacing;
			if (sectionAnchorPrefab != null && rebindItemPrefab != null && spacerPrefab != null)
			{
				_sectionHeight = sectionAnchorPrefab.GetComponent<RectTransform>().sizeDelta.y;
				_scrollRectTransform = ((Component)scrollRect).GetComponent<RectTransform>();
				_content = scrollRect.content;
				if (headerContainer != null)
				{
					headerContainer.drivenByObject = (Object)(object)this;
					headerContainer.drivenProperties = (DrivenTransformProperties)3840;
					headerContainer.anchorMin = new Vector2(0f, 1f);
					headerContainer.anchorMax = Vector2.one;
					((UnityEvent<Vector2>)(object)scrollRect.onValueChanged).AddListener((UnityAction<Vector2>)OnScroll);
					OnScroll(Vector2.zero);
				}
			}
		}

		private void Start()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			OnScroll(Vector2.zero);
		}

		private void OnEnable()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			OnScroll(Vector2.zero);
		}

		public void JumpTo(int sectionIndex)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if (_content == null || scrollRect == null || _scrollRectTransform == null)
			{
				return;
			}
			int count = _anchors.Count;
			if (sectionIndex < count && sectionIndex >= 0)
			{
				Canvas.ForceUpdateCanvases();
				scrollRect.StopMovement();
				if (sectionIndex == 0)
				{
					scrollRect.verticalNormalizedPosition = 1f;
				}
				else
				{
					SectionHeaderAnchor sectionHeaderAnchor = _anchors[sectionIndex];
					float y = Vector2.op_Implicit(((Transform)_scrollRectTransform).InverseTransformPoint(((Transform)_content).position) - ((Transform)_scrollRectTransform).InverseTransformPoint(((Transform)sectionHeaderAnchor.RectTransform).position)).y + _sectionHeight / 2f - _spacing;
					_content.SetAnchoredPosY(y);
				}
				if (_currentSection != sectionIndex)
				{
					OnSectionChanged.Invoke(sectionIndex);
				}
				_currentSection = sectionIndex;
			}
		}

		public void AddSection(string sectionName)
		{
			//IL_0070: 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_008b: 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_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			if (((Behaviour)this).isActiveAndEnabled && sectionHeaderPrefab != null && sectionAnchorPrefab != null && scrollRect != null)
			{
				SectionHeaderAnchor component = Object.Instantiate<GameObject>(sectionAnchorPrefab, (Transform)(object)_content).GetComponent<SectionHeaderAnchor>();
				SectionHeader component2 = Object.Instantiate<GameObject>(sectionHeaderPrefab, (Transform)(object)headerContainer).GetComponent<SectionHeader>();
				RectTransform rectTransform = component2.RectTransform;
				rectTransform.drivenByObject = (Object)(object)this;
				rectTransform.drivenProperties = (DrivenTransformProperties)1286;
				rectTransform.anchorMin = new Vector2(0f, rectTransform.anchorMin.y);
				rectTransform.anchorMax = new Vector2(1f, rectTransform.anchorMax.y);
				component2.anchor = component;
				component.sectionHeader = component2;
				component2.SetText(sectionName);
				OnScroll(Vector2.zero);
				if (_anchors.Count == 0)
				{
					component.RectTransform.sizeDelta = default(Vector2);
				}
				_currentSection = _anchors.Count;
				_anchors.Add(component);
			}
		}

		public void AddBinds(RemappableKey? kbmKey, RemappableKey? gamepadKey, bool isBaseGame = false, string controlName = "")
		{
			if (((Behaviour)this).isActiveAndEnabled && rebindItemPrefab != null && scrollRect != null)
			{
				if (kbmKey != null && string.IsNullOrEmpty(controlName))
				{
					controlName = kbmKey.ControlName;
				}
				else if (gamepadKey != null && string.IsNullOrEmpty(controlName))
				{
					controlName = gamepadKey.ControlName;
				}
				Object.Instantiate<GameObject>(rebindItemPrefab, (Transform)(object)_content).GetComponent<RebindItem>().SetBind(controlName, kbmKey, gamepadKey, isBaseGame);
			}
		}

		public void AddFooter()
		{
			if (((Behaviour)this).isActiveAndEnabled && spacerPrefab != null)
			{
				Object.Instantiate<GameObject>(spacerPrefab, (Transform)(object)_content);
			}
		}

		private void OnScroll(Vector2 delta)
		{
			//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)
			if (_scrollRectTransform == null || headerContainer == null || _rectTransform == null)
			{
				return;
			}
			float maxY = GetMaxY(headerContainer);
			int num = -1;
			for (int i = 0; i < _anchors.Count; i++)
			{
				SectionHeaderAnchor sectionHeaderAnchor = _anchors[i];
				SectionHeader sectionHeader = sectionHeaderAnchor.sectionHeader;
				if (i == 0)
				{
					sectionHeader.RectTransform.SetLocalPosY(maxY - (_sectionHeight / 2f - _spacing));
					num = i;
					continue;
				}
				SectionHeader sectionHeader2 = _anchors[i - 1].sectionHeader;
				float num2 = CalculateHeaderRawYPos(sectionHeaderAnchor);
				sectionHeader.RectTransform.SetLocalPosY(num2);
				float num3 = GetMaxY(sectionHeader.RectTransform) + ((Transform)sectionHeader.RectTransform).localPosition.y;
				float num4 = GetMinY(sectionHeader2.RectTransform) + ((Transform)sectionHeader2.RectTransform).localPosition.y;
				if (num3 + _sectionHeight / 2f + _spacing >= num4)
				{
					sectionHeader2.RectTransform.SetLocalPosY(num2 + _sectionHeight);
				}
				if (num3 + _spacing / 2f >= maxY - _sectionHeight / 2f)
				{
					num = i;
					sectionHeader.RectTransform.SetLocalPosY(maxY - (_sectionHeight / 2f - _spacing));
				}
			}
			if (_currentSection != num)
			{
				OnSectionChanged.Invoke(num);
			}
			_currentSection = num;
		}

		private float CalculateHeaderRawYPos(SectionHeaderAnchor anchor)
		{
			//IL_0055: 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 (_content == null || headerContainer == null || _scrollRectTransform == null)
			{
				return 0f;
			}
			float num = GetMaxY(headerContainer) - GetMaxY(_scrollRectTransform);
			num += _sectionHeight / 2f;
			num -= OffsetCompensation;
			return ((Transform)anchor.RectTransform).localPosition.y - (num + 50f) + ((Transform)_content).localPosition.y;
		}

		private void OnDrawGizmos()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			if (_rectTransform != null && headerContainer != null)
			{
				Color color = Gizmos.color;
				_rectTransform.DrawGizmoUiRectWorld();
				Gizmos.color = color;
			}
		}

		private float GetMaxY(RectTransform element)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (_rectTransform == null)
			{
				_rectTransform = ((Component)this).GetComponent<RectTransform>();
			}
			Rect val = element.UiBounds(Vector3.zero);
			return ((Rect)(ref val)).max.y;
		}

		private float GetMinY(RectTransform element)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (_rectTransform == null)
			{
				_rectTransform = ((Component)this).GetComponent<RectTransform>();
			}
			Rect val = element.UiBounds(Vector3.zero);
			return ((Rect)(ref val)).min.y;
		}
	}
	public class RebindButton : MonoBehaviour
	{
		public Selectable? button;

		public TextMeshProUGUI? bindLabel;

		public Image? glyphLabel;

		public Image? notSupportedImage;

		public RebindIndicator? rebindIndicator;

		public Button? resetButton;

		public Button? removeButton;

		public float timeout = 5f;

		private RemappableKey? _key;

		private bool _isBaseGame;

		private RebindingOperation? _rebindingOperation;

		private bool _rebinding;

		private float _timeoutTimer;

		private static MethodInfo? _setChangesNotAppliedMethodInfo;

		private static readonly List<RebindButton> Instances = new List<RebindButton>();

		public void SetKey(RemappableKey? key, bool isBaseGame)
		{
			_key = key;
			_isBaseGame = isBaseGame;
			UpdateState();
		}

		public void UpdateState()
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			if (bindLabel == null || glyphLabel == null || button == null || notSupportedImage == null || resetButton == null || removeButton == null)
			{
				return;
			}
			if (_key == null)
			{
				SetAsUnsupported();
				return;
			}
			int rebindingIndex = GetRebindingIndex();
			InputAction action = _key.currentInput.action;
			if (rebindingIndex >= action.bindings.Count)
			{
				SetAsUnsupported();
				return;
			}
			GameObject gameObject = ((Component)resetButton).gameObject;
			InputBinding val = action.bindings[rebindingIndex];
			gameObject.SetActive(((InputBinding)(ref val)).hasOverrides);
			val = action.bindings[rebindingIndex];
			string effectivePath = ((InputBinding)(ref val)).effectivePath;
			string bindPath = InputControlPath.ToHumanReadableString(effectivePath, (HumanReadableStringOptions)2, (InputControl)null);
			if (_key.gamepadOnly)
			{
				((TMP_Text)bindLabel).SetText("", true);
				if (effectivePath == "<InputUtils-Gamepad-Not-Bound>")
				{
					((Component)removeButton).gameObject.SetActive(false);
					((Behaviour)glyphLabel).enabled = false;
					return;
				}
				((Component)removeButton).gameObject.SetActive(true);
				ControllerGlyph bestMatching = ControllerGlyph.GetBestMatching();
				if (bestMatching == null)
				{
					((TMP_Text)bindLabel).SetText(effectivePath, true);
					((Behaviour)glyphLabel).enabled = false;
					return;
				}
				Sprite val2 = bestMatching[effectivePath];
				if (val2 == null)
				{
					((TMP_Text)bindLabel).SetText(effectivePath, true);
					((Behaviour)glyphLabel).enabled = false;
				}
				else
				{
					glyphLabel.sprite = val2;
					((Behaviour)glyphLabel).enabled = true;
				}
			}
			else
			{
				((Component)removeButton).gameObject.SetActive(!string.Equals(effectivePath, "<InputUtils-Kbm-Not-Bound>"));
				HandleKbmGlyphOrLabel(effectivePath, bindPath);
			}
		}

		private void HandleKbmGlyphOrLabel(string effectivePath, string bindPath)
		{
			if (bindLabel == null || glyphLabel == null)
			{
				return;
			}
			if (ControllerGlyph.MouseGlyphs != null)
			{
				Sprite val = ControllerGlyph.MouseGlyphs[effectivePath];
				if (val != null)
				{
					((TMP_Text)bindLabel).SetText("", true);
					glyphLabel.sprite = val;
					((Behaviour)glyphLabel).enabled = true;
					return;
				}
			}
			((Behaviour)glyphLabel).enabled = false;
			((TMP_Text)bindLabel).SetText(bindPath, true);
		}

		private void SetAsUnsupported()
		{
			if (button != null && bindLabel != null && glyphLabel != null && notSupportedImage != null && resetButton != null && removeButton != null)
			{
				button.interactable = false;
				button.targetGraphic.raycastTarget = false;
				((Behaviour)button.targetGraphic).enabled = false;
				((TMP_Text)bindLabel).SetText("", true);
				((Behaviour)glyphLabel).enabled = false;
				((Component)notSupportedImage).gameObject.SetActive(true);
				((Component)resetButton).gameObject.SetActive(false);
				((Component)removeButton).gameObject.SetActive(false);
			}
		}

		private int GetRebindingIndex()
		{
			//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_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_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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (_key == null)
			{
				return -1;
			}
			InputAction action = _key.currentInput.action;
			if (action.controls.Count == 0)
			{
				if (action.bindings.Count == 0)
				{
					return -1;
				}
				if (_key.gamepadOnly && action.bindings.Count > 1)
			

plugins/Sligili-More_Emotes/MoreEmotes1.3.3.dll

Decompiled 3 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/Steven-Custom_Boombox_Music/CustomBoomboxTracks.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CustomBoomboxTracks.Configuration;
using CustomBoomboxTracks.Managers;
using CustomBoomboxTracks.Utilities;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Networking;

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

		private const string NAME = "Custom Boombox Music";

		private const string VERSION = "1.4.0";

		private static BoomboxPlugin Instance;

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

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

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

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

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

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

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

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

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

		private static bool firstRun = true;

		private static bool finishedLoading = false;

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

		public static bool FinishedLoading => finishedLoading;

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

		public static event Action OnAllSongsLoaded;

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

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

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

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

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

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

		private static ConfigFile _config;

		private static ConfigEntry<bool> _useDefaultSongs;

		private static ConfigEntry<bool> _streamAudioFromDisk;

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

		public static bool StreamFromDisk => _streamAudioFromDisk.Value;

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

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

plugins/sunnobunno-YippeeMod/YippeeMod.dll

Decompiled 3 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.4")]
	public class YippeeModBase : BaseUnityPlugin
	{
		private const string modGUID = "sunnobunno.YippeeMod";

		private const string modName = "Yippee tbh mod";

		private const string modVersion = "1.2.4";

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

plugins/Suskitech-AlwaysHearActiveWalkies/AlwaysHearWalkie.dll

Decompiled 3 months ago
using System;
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.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LCAlwaysHearWalkieMod.Patches;
using Microsoft.CodeAnalysis;
using UnityEngine;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BepInEx5.PluginTemplate
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "AlwaysHearWalkie";

		public const string PLUGIN_NAME = "Always Hear Active Walkies";

		public const string PLUGIN_VERSION = "1.4.5";
	}
}
namespace LCAlwaysHearWalkieMod
{
	public static class PluginInfo
	{
		public const string modGUID = "suskitech.LCAlwaysHearActiveWalkie";

		public const string modName = "LC Always Hear Active Walkies";

		public const string modVersion = "1.4.4";
	}
	[BepInPlugin("suskitech.LCAlwaysHearActiveWalkie", "LC Always Hear Active Walkies", "1.4.4")]
	public class Plugin : BaseUnityPlugin
	{
		private ConfigEntry<float> configAudibleDistance;

		public static float AudibleDistance;

		private ConfigEntry<float> configWalkieRecordingRange;

		public static float WalkieRecordingRange;

		private ConfigEntry<float> configPlayerToPlayerSpatialHearingRange;

		public static float PlayerToPlayerSpatialHearingRange;

		public static ManualLogSource Log;

		private static Plugin Instance;

		public void Awake()
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			configAudibleDistance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "AudibleDistance", 12f, "");
			AudibleDistance = configAudibleDistance.Value;
			configWalkieRecordingRange = ((BaseUnityPlugin)this).Config.Bind<float>("General", "WalkieRecordingRange", 20f, "");
			WalkieRecordingRange = configWalkieRecordingRange.Value;
			configPlayerToPlayerSpatialHearingRange = ((BaseUnityPlugin)this).Config.Bind<float>("General", "PlayerToPlayerSpatialHearingRange", 20f, "");
			PlayerToPlayerSpatialHearingRange = configPlayerToPlayerSpatialHearingRange.Value;
			Log = Logger.CreateLogSource("suskitech.LCAlwaysHearActiveWalkie");
			Harmony val = new Harmony("suskitech.LCAlwaysHearActiveWalkie");
			val.PatchAll(typeof(Plugin));
			val.PatchAll(typeof(PlayerControllerBPatch));
			val.PatchAll(typeof(WalkieTalkiePatch));
			Log.LogInfo((object)"\\ /");
			Log.LogInfo((object)"/|\\");
			Log.LogInfo((object)" |----|");
			Log.LogInfo((object)" |[__]| Always Hear Active Walkies");
			Log.LogInfo((object)" |.  .| Version 1.4.4 Loaded");
			Log.LogInfo((object)" |____|");
			Log.LogInfo((object)"");
			Log.LogInfo((object)("AudibleDistance: " + AudibleDistance));
			Log.LogInfo((object)("WalkieRecordingRange: " + WalkieRecordingRange));
			Log.LogInfo((object)("PlayerToPlayerSpatialHearingRange: " + PlayerToPlayerSpatialHearingRange));
		}
	}
}
namespace LCAlwaysHearWalkieMod.Patches
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		private static readonly float throttleInterval = 0.35f;

		private static float throttle = 0f;

		private static readonly float AverageDistanceToHeldWalkie = 2f;

		private static readonly float AudibleDistance = Plugin.AudibleDistance;

		private static readonly float WalkieRecordingRange = Plugin.WalkieRecordingRange;

		private static readonly float PlayerToPlayerSpatialHearingRange = Plugin.PlayerToPlayerSpatialHearingRange;

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void alwaysHearWalkieTalkiesPatch(ref bool ___holdingWalkieTalkie, ref PlayerControllerB __instance)
		{
			//IL_00d5: 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_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f2: 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_035c: 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)
			throttle += Time.deltaTime;
			if (throttle < throttleInterval)
			{
				return;
			}
			throttle = 0f;
			if ((Object)(object)__instance == (Object)null || (Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)__instance != (Object)(object)GameNetworkManager.Instance.localPlayerController || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null)
			{
				return;
			}
			if (!GameNetworkManager.Instance.localPlayerController.isPlayerDead)
			{
				List<WalkieTalkie> list = new List<WalkieTalkie>();
				List<WalkieTalkie> list2 = new List<WalkieTalkie>();
				for (int i = 0; i < WalkieTalkie.allWalkieTalkies.Count; i++)
				{
					float num = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[i]).transform.position, ((Component)__instance).transform.position);
					if (num <= AudibleDistance)
					{
						if (((GrabbableObject)WalkieTalkie.allWalkieTalkies[i]).isBeingUsed)
						{
							list.Add(WalkieTalkie.allWalkieTalkies[i]);
						}
					}
					else
					{
						list2.Add(WalkieTalkie.allWalkieTalkies[i]);
					}
				}
				bool flag = list.Count > 0;
				if (flag != __instance.holdingWalkieTalkie)
				{
					___holdingWalkieTalkie = flag;
					for (int j = 0; j < list2.Count; j++)
					{
						if (j < list.Count)
						{
							list2[j].thisAudio.Stop();
						}
					}
				}
				if (!flag)
				{
					return;
				}
			}
			PlayerControllerB val = ((!GameNetworkManager.Instance.localPlayerController.isPlayerDead || !((Object)(object)GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript != (Object)null)) ? GameNetworkManager.Instance.localPlayerController : GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript);
			for (int k = 0; k < StartOfRound.Instance.allPlayerScripts.Length; k++)
			{
				PlayerControllerB val2 = StartOfRound.Instance.allPlayerScripts[k];
				if ((!val2.isPlayerControlled && !val2.isPlayerDead) || (Object)(object)val2 == (Object)(object)GameNetworkManager.Instance.localPlayerController || val2.isPlayerDead || !val2.holdingWalkieTalkie)
				{
					continue;
				}
				float num2 = Vector3.Distance(((Component)val).transform.position, ((Component)val2).transform.position);
				float num3 = float.MaxValue;
				float num4 = float.MaxValue;
				for (int l = 0; l < WalkieTalkie.allWalkieTalkies.Count; l++)
				{
					WalkieTalkie val3 = WalkieTalkie.allWalkieTalkies[l];
					if (!((GrabbableObject)val3).isBeingUsed)
					{
						continue;
					}
					float num5 = Vector3.Distance(((Component)val3.target).transform.position, ((Component)val).transform.position);
					if (num5 < num3)
					{
						num3 = num5;
					}
					if (Object.op_Implicit((Object)(object)((GrabbableObject)val3).playerHeldBy) && (!Object.op_Implicit((Object)(object)((GrabbableObject)val3).playerHeldBy) || ((GrabbableObject)val3).playerHeldBy.speakingToWalkieTalkie))
					{
						float num6 = Vector3.Distance(((Component)val3).transform.position, ((Component)val2).transform.position);
						if (num6 < num4)
						{
							num4 = num6;
						}
					}
				}
				float num7 = 1f - Mathf.InverseLerp(AverageDistanceToHeldWalkie, WalkieRecordingRange, num4);
				float num8 = 1f - Mathf.InverseLerp(AverageDistanceToHeldWalkie, WalkieRecordingRange, num3);
				float num9 = Mathf.Clamp01(1f + (num7 - num8));
				float num10 = 1f - Mathf.InverseLerp(1f, PlayerToPlayerSpatialHearingRange, num2);
				val2.voicePlayerState.Volume = Mathf.Max(num9, num10);
				if (num9 > num10)
				{
					makePlayerSoundWalkieTalkie(val2);
				}
				else
				{
					makePlayerSoundSpatial(val2);
				}
			}
			static void makePlayerSoundSpatial(PlayerControllerB playerController)
			{
				AudioSource currentVoiceChatAudioSource = playerController.currentVoiceChatAudioSource;
				AudioLowPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>();
				AudioHighPassFilter component2 = ((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>();
				OccludeAudio component3 = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>();
				((Behaviour)component2).enabled = false;
				((Behaviour)component).enabled = true;
				component3.overridingLowPass = playerController.voiceMuffledByEnemy;
				currentVoiceChatAudioSource.spatialBlend = 1f;
				playerController.currentVoiceChatIngameSettings.set2D = false;
				currentVoiceChatAudioSource.bypassListenerEffects = false;
				currentVoiceChatAudioSource.bypassEffects = false;
				currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[playerController.playerClientId];
				component.lowpassResonanceQ = 1f;
			}
			static void makePlayerSoundWalkieTalkie(PlayerControllerB playerController)
			{
				AudioSource currentVoiceChatAudioSource2 = playerController.currentVoiceChatAudioSource;
				AudioLowPassFilter component4 = ((Component)currentVoiceChatAudioSource2).GetComponent<AudioLowPassFilter>();
				AudioHighPassFilter component5 = ((Component)currentVoiceChatAudioSource2).GetComponent<AudioHighPassFilter>();
				OccludeAudio component6 = ((Component)currentVoiceChatAudioSource2).GetComponent<OccludeAudio>();
				((Behaviour)component5).enabled = true;
				((Behaviour)component4).enabled = true;
				component6.overridingLowPass = true;
				currentVoiceChatAudioSource2.spatialBlend = 0f;
				playerController.currentVoiceChatIngameSettings.set2D = true;
				currentVoiceChatAudioSource2.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[playerController.playerClientId];
				currentVoiceChatAudioSource2.bypassListenerEffects = false;
				currentVoiceChatAudioSource2.bypassEffects = false;
				currentVoiceChatAudioSource2.panStereo = (GameNetworkManager.Instance.localPlayerController.isPlayerDead ? 0f : 0.4f);
				component6.lowPassOverride = 4000f;
				component4.lowpassResonanceQ = 3f;
			}
		}
	}
	[HarmonyPatch(typeof(WalkieTalkie))]
	internal class WalkieTalkiePatch
	{
		[HarmonyPatch("EnableWalkieTalkieListening")]
		[HarmonyPrefix]
		private static bool alwaysHearWalkieTalkiesEnableWalkieTalkieListeningPatch(bool enable)
		{
			if (!enable)
			{
				return false;
			}
			return true;
		}
	}
}

plugins/x753-More_Suits/MoreSuits.dll

Decompiled 3 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.3.0")]
[assembly: AssemblyInformationalVersion("1.4.3")]
[assembly: AssemblyProduct("MoreSuits")]
[assembly: AssemblyTitle("MoreSuits")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.3.0")]
[module: UnverifiableCode]
namespace MoreSuits;

[BepInPlugin("x753.More_Suits", "More Suits", "1.4.3")]
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_0695: 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_06a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0402: Unknown result type (might be due to invalid IL or missing references)
			//IL_0409: 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_05b1: 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);
						val6.Apply(true, true);
						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);
										val7.Apply(true, true);
										val5.SetTexture(text, (Texture)(object)val7);
										continue;
									}
									if (text == "PRICE" && int.TryParse(text2, out var result))
									{
										try
										{
											if (!UnlockAll)
											{
												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.3";

	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 bool UnlockAll;

	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;
		UnlockAll = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Unlock All Suits", false, "If true, unlocks all custom suits that would normally be sold in the shop.").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;
	}
}