plugins/DacreDOLOLO-WeaponStatShower/WeaponStatShower.dll

Decompiled 7 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Json;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CellMenu;
using GameData;
using Gear;
using HarmonyLib;
using Localization;
using Microsoft.CodeAnalysis;
using Player;
using UnityEngine;
using WeaponStatShower.Patches;
using WeaponStatShower.Utils;
using WeaponStatShower.Utils.Language;
using WeaponStatShower.Utils.Language.Models;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("WeaponStatShower")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WeaponStatShower")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("052b6857-9abd-4300-b5bd-ceb4b0c295db")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[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 WeaponStatShower
{
	public static class BIEExtensions
	{
		public static ConfigEntry<T> GetConfigEntry<T>(this ConfigFile configFile, ConfigDefinition definition)
		{
			ConfigEntry<T> result = default(ConfigEntry<T>);
			if (!configFile.TryGetEntry<T>(definition, ref result))
			{
				throw new InvalidOperationException("Config entry has not been added yet.");
			}
			return result;
		}
	}
	[BepInPlugin("WeaponStatShower", "Weapon Stat Shower", "1.4.0")]
	[BepInProcess("GTFO.exe")]
	public class WeaponStatShowerPlugin : BasePlugin
	{
		internal const string ModName = "Weapon Stat Shower";

		internal const string GUID = "WeaponStatShower";

		private const string SectionMain = "Config";

		private static readonly ConfigDefinition configDefinition = new ConfigDefinition("Config", "Version");

		private static readonly ConfigDefinition ConfigGameVersion = new ConfigDefinition("Config", "GameVersion");

		private static Harmony HarmonyInstance;

		private static readonly Dictionary<Type, Patch> RegisteredPatches = new Dictionary<Type, Patch>();

		public static WeaponStatShowerPlugin Instance { get; private set; }

		public WeaponStatShowerPlugin()
		{
			((BasePlugin)this).Config.SaveOnConfigSet = false;
		}

		public override void Load()
		{
			Instance = this;
			((BasePlugin)this).Config.SaveOnConfigSet = true;
			LogInfo("STARTED");
			RegisterPatch<ShowStat>();
			((BasePlugin)this).Config.Save();
		}

		public static void RegisterPatch<T>() where T : Patch, new()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			if (HarmonyInstance == null)
			{
				HarmonyInstance = new Harmony("WeaponStatShower");
			}
			if (RegisteredPatches.ContainsKey(typeof(T)))
			{
				LogDebug("Ignoring duplicate patch: " + typeof(T).Name);
				return;
			}
			T val = new T
			{
				Harmony = HarmonyInstance
			};
			val.Initialize();
			if (val.Enabled)
			{
				LogInfo("Applying patch: " + val.Name);
				val.Execute();
			}
			RegisteredPatches[typeof(T)] = val;
		}

		public static void LogDebug(object data)
		{
			((BasePlugin)Instance).Log.LogDebug(data);
		}

		public static void LogError(object data)
		{
			((BasePlugin)Instance).Log.LogError(data);
		}

		public static void LogFatal(object data)
		{
			((BasePlugin)Instance).Log.LogFatal(data);
		}

		public static void LogInfo(object data)
		{
			((BasePlugin)Instance).Log.LogInfo(data);
		}

		public static void LogMessage(object data)
		{
			((BasePlugin)Instance).Log.LogMessage(data);
		}

		public static void LogWarning(object data)
		{
			((BasePlugin)Instance).Log.LogWarning(data);
		}
	}
}
namespace WeaponStatShower.Utils
{
	internal class SleepersDatas
	{
		private readonly Dictionary<string, float[]> EnemyDatas = new Dictionary<string, float[]>();

		private SleepersLanguageModel sleepersLanguageDatas;

		public SleepersDatas(string[] activatedSleepers, SleepersLanguageModel sleepersLanguageDatas)
		{
			this.sleepersLanguageDatas = sleepersLanguageDatas;
			foreach (string text in activatedSleepers)
			{
				switch (text.Trim())
				{
				case "NONE":
					EnemyDatas.Clear();
					return;
				case "ALL":
					EnemyDatas.TryAdd(sleepersLanguageDatas.striker, new float[4] { 20f, 3f, 2f, 0f });
					EnemyDatas.TryAdd(sleepersLanguageDatas.shooter, new float[4] { 30f, 5f, 2f, 0f });
					EnemyDatas.TryAdd(sleepersLanguageDatas.scout, new float[4] { 42f, 3f, 2f, 0f });
					EnemyDatas.TryAdd(sleepersLanguageDatas.bigStriker, new float[4] { 120f, 1.5f, 2f, 0f });
					EnemyDatas.TryAdd(sleepersLanguageDatas.bigShooter, new float[4] { 150f, 2f, 2f, 0f });
					EnemyDatas.TryAdd(sleepersLanguageDatas.charger, new float[4] { 30f, 1f, 2f, 1f });
					EnemyDatas.TryAdd(sleepersLanguageDatas.chargerScout, new float[4] { 60f, 1f, 2f, 1f });
					return;
				case "STRIKER":
					EnemyDatas.TryAdd(sleepersLanguageDatas.striker, new float[4] { 20f, 3f, 2f, 0f });
					break;
				case "SHOOTER":
					EnemyDatas.TryAdd(sleepersLanguageDatas.shooter, new float[4] { 30f, 5f, 2f, 0f });
					break;
				case "SCOUT":
					EnemyDatas.TryAdd(sleepersLanguageDatas.scout, new float[4] { 42f, 3f, 2f, 0f });
					break;
				case "BIG_STRIKER":
					EnemyDatas.TryAdd(sleepersLanguageDatas.bigStriker, new float[4] { 120f, 1.5f, 2f, 0f });
					break;
				case "BIG_SHOOTER":
					EnemyDatas.TryAdd(sleepersLanguageDatas.bigShooter, new float[4] { 150f, 2f, 2f, 0f });
					break;
				case "CHARGER":
					EnemyDatas.TryAdd(sleepersLanguageDatas.charger, new float[4] { 30f, 1f, 2f, 1f });
					break;
				case "CHARGER_SCOUT":
					EnemyDatas.TryAdd(sleepersLanguageDatas.chargerScout, new float[4] { 60f, 1f, 2f, 1f });
					break;
				default:
					WeaponStatShowerPlugin.LogWarning("You inserted an incorrect value in the config: " + text.Trim());
					break;
				}
			}
		}

		public string VerboseKill(ArchetypeDataBlock archetypeDataBlock)
		{
			StringBuilder stringBuilder = new StringBuilder();
			float damage = archetypeDataBlock.Damage * (float)((archetypeDataBlock.ShotgunBulletCount <= 0) ? 1 : archetypeDataBlock.ShotgunBulletCount);
			float precisionDamageMulti = archetypeDataBlock.PrecisionDamageMulti;
			int num = 0;
			for (int i = 0; i < EnemyDatas.Count; i++)
			{
				string text = EnemyDatas.Keys.ElementAt(i);
				List<string> list = new List<string>();
				float[] currEnemyDatas = EnemyDatas[text];
				if (canKillOnOccipit(damage, precisionDamageMulti, currEnemyDatas))
				{
					list.Add(sleepersLanguageDatas.occipit);
				}
				if (canKillOnHead(damage, precisionDamageMulti, currEnemyDatas))
				{
					list.Add(sleepersLanguageDatas.head);
				}
				if (canKillOnBack(damage, currEnemyDatas))
				{
					list.Add(sleepersLanguageDatas.back);
				}
				if (canKillOnChest(damage, currEnemyDatas))
				{
					list.Add(sleepersLanguageDatas.chest);
				}
				if (list.Count > 0)
				{
					if (num % 2 == 1)
					{
						stringBuilder.Append(" | ");
					}
					list.Reverse();
					stringBuilder.Append(text + ": [" + string.Join(",", list.ToArray()) + "]");
					if (num++ % 2 == 1 && i != EnemyDatas.Count - 1)
					{
						stringBuilder.Append('\n');
					}
				}
			}
			return stringBuilder.ToString();
		}

		internal string? VerboseKill(MeleeArchetypeDataBlock archeTypeDataBlock)
		{
			StringBuilder stringBuilder = new StringBuilder();
			float num = archeTypeDataBlock.ChargedAttackDamage * archeTypeDataBlock.ChargedSleeperMulti;
			float chargedPrecisionMulti = archeTypeDataBlock.ChargedPrecisionMulti;
			int num2 = 0;
			for (int i = 0; i < EnemyDatas.Count; i++)
			{
				string text = EnemyDatas.Keys.ElementAt(i);
				if (text.Contains("SCOUT") || text.Contains("哨兵") || text.Contains("黑触"))
				{
					num /= archeTypeDataBlock.ChargedSleeperMulti;
				}
				List<string> list = new List<string>();
				float[] currEnemyDatas = EnemyDatas[text];
				if (canKillOnOccipit(num, chargedPrecisionMulti, currEnemyDatas))
				{
					list.Add(sleepersLanguageDatas.occipit);
				}
				if (canKillOnHead(num, chargedPrecisionMulti, currEnemyDatas))
				{
					list.Add(sleepersLanguageDatas.head);
				}
				if (canKillOnBack(num, currEnemyDatas))
				{
					list.Add(sleepersLanguageDatas.back);
				}
				if (canKillOnChest(num, currEnemyDatas))
				{
					list.Add(sleepersLanguageDatas.chest);
				}
				if (list.Count > 0)
				{
					if (num2 % 2 == 1)
					{
						stringBuilder.Append(" | ");
					}
					list.Reverse();
					stringBuilder.Append(text + ": [" + string.Join(",", list.ToArray()) + "]");
					if (num2++ % 2 == 1 && i != EnemyDatas.Count - 1)
					{
						stringBuilder.Append('\n');
					}
				}
			}
			return stringBuilder.ToString();
		}

		private bool canKillOnChest(float damage, float[] currEnemyDatas)
		{
			return damage >= currEnemyDatas[0];
		}

		private bool canKillOnBack(float damage, float[] currEnemyDatas)
		{
			return damage * currEnemyDatas[2] >= currEnemyDatas[0];
		}

		private bool canKillOnHead(float damage, float prcsnMultiplier, float[] currEnemyDatas)
		{
			if (isArmored(currEnemyDatas))
			{
				return damage * currEnemyDatas[1] >= currEnemyDatas[0];
			}
			return damage * prcsnMultiplier * currEnemyDatas[1] >= currEnemyDatas[0];
		}

		private bool canKillOnOccipit(float damage, float prcsnMultiplier, float[] currEnemyDatas)
		{
			if (isArmored(currEnemyDatas))
			{
				return damage * currEnemyDatas[2] * currEnemyDatas[1] >= currEnemyDatas[0];
			}
			return damage * prcsnMultiplier * currEnemyDatas[2] * currEnemyDatas[1] >= currEnemyDatas[0];
		}

		private bool isArmored(float[] currEnemyDatas)
		{
			return currEnemyDatas[3] == 1f;
		}
	}
	internal class WeaponDescriptionBuilder
	{
		private SleepersDatas sleepersDatas;

		private PlayerDataBlock _playerDataBlock;

		private GearIDRange idRange;

		private uint categoryID;

		private GearCategoryDataBlock gearCatBlock;

		private ItemDataBlock itemDataBlock;

		private LanguageDatas languageDatas;

		private const string DIVIDER = " | ";

		private const string CLOSE_COLOR_TAG = "</color>";

		internal void Inizialize(GearIDRange idRange, PlayerDataBlock playerDataBlock, LanguageEnum language)
		{
			this.idRange = idRange;
			_playerDataBlock = playerDataBlock;
			categoryID = idRange.GetCompID((eGearComponent)2);
			gearCatBlock = GameDataBlockBase<GearCategoryDataBlock>.GetBlock(categoryID);
			itemDataBlock = GameDataBlockBase<ItemDataBlock>.GetBlock(gearCatBlock.BaseItem);
			languageDatas = desirializeLanguageJson(language);
		}

		public void UpdateSleepersDatas(string[] activatedSleepers, LanguageEnum language)
		{
			if (activatedSleepers[0].Trim().Length == 0)
			{
				WeaponStatShowerPlugin.LogWarning("Empty String in the config file, applying Default values");
				activatedSleepers = new string[1] { "ALL" };
			}
			sleepersDatas = new SleepersDatas(activatedSleepers, desirializeLanguageJson(language).sleepers);
		}

		private LanguageDatas desirializeLanguageJson(LanguageEnum language)
		{
			LanguageDatasClass languageDatasClass = JsonSerializer.Deserialize<LanguageDatasClass>(LocalizedString.JsonString);
			return language.Equals(LanguageEnum.English) ? languageDatasClass.english : languageDatasClass.chinese;
		}

		public string DescriptionFormatter(string GearDescription)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			//IL_0057: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			if ((int)itemDataBlock.inventorySlot == 10)
			{
				MeleeArchetypeDataBlock block = GameDataBlockBase<MeleeArchetypeDataBlock>.GetBlock(GearBuilder.GetMeleeArchetypeID(gearCatBlock));
				GearDescription = VerboseDescriptionFormatter(block);
				return GearDescription + "\n\n" + GetFormatedWeaponStats(block, itemDataBlock);
			}
			eWeaponFireMode val = (eWeaponFireMode)idRange.GetCompID((eGearComponent)1);
			bool flag = categoryID == 12;
			ArchetypeDataBlock val2 = (flag ? SentryGunInstance_Firing_Bullets.GetArchetypeDataForFireMode(val) : GameDataBlockBase<ArchetypeDataBlock>.GetBlock(GearBuilder.GetArchetypeID(gearCatBlock, val)));
			if (val2 == null)
			{
				return GearDescription;
			}
			GearDescription = VerboseDescriptionFormatter(val2, flag);
			return GearDescription + GetFormatedWeaponStats(val2, flag);
		}

		internal string FireRateFormatter(string gearPublicName)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			//IL_003d: 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_0054: Unknown result type (might be due to invalid IL or missing references)
			if ((int)itemDataBlock.inventorySlot == 10)
			{
				MeleeArchetypeDataBlock block = GameDataBlockBase<MeleeArchetypeDataBlock>.GetBlock(GearBuilder.GetMeleeArchetypeID(gearCatBlock));
				return VerbosePublicNameMelee(block);
			}
			eWeaponFireMode val = (eWeaponFireMode)idRange.GetCompID((eGearComponent)1);
			ArchetypeDataBlock val2 = ((categoryID == 12) ? SentryGunInstance_Firing_Bullets.GetArchetypeDataForFireMode(val) : GameDataBlockBase<ArchetypeDataBlock>.GetBlock(GearBuilder.GetArchetypeID(gearCatBlock, val)));
			if (val2 == null)
			{
				return gearPublicName;
			}
			return VerbosePublicNameFireMode(val2);
		}

		private string VerbosePublicNameMelee(MeleeArchetypeDataBlock meleeArchetypeDataBlock)
		{
			MeleeLanguageModel melee = languageDatas.melee;
			return ((GameDataBlockBase<MeleeArchetypeDataBlock>)(object)meleeArchetypeDataBlock).persistentID switch
			{
				1u => melee.hammer, 
				2u => melee.knife, 
				4u => melee.bat, 
				3u => melee.spear, 
				_ => "", 
			};
		}

		private string VerbosePublicNameFireMode(ArchetypeDataBlock archetypeDataBlock)
		{
			//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_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected I4, but got Unknown
			//IL_0110: 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_0326: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			FiremodeLanguageModel firemode = languageDatas.firemode;
			eWeaponFireMode fireMode = archetypeDataBlock.FireMode;
			StringBuilder stringBuilder = new StringBuilder();
			eWeaponFireMode val = fireMode;
			eWeaponFireMode val2 = val;
			switch ((int)val2)
			{
			case 2:
			case 11:
				stringBuilder.Append(firemode.fullA + " (");
				stringBuilder.Append("<#12FF50>");
				stringBuilder.Append(languageDatas.rateOfFire + " ");
				stringBuilder.Append(GetRateOfFire(archetypeDataBlock, fireMode));
				stringBuilder.Append("</color>");
				stringBuilder.Append(")");
				break;
			case 0:
			case 10:
				stringBuilder.Append(firemode.semiA + " (");
				stringBuilder.Append("<#12FF50>");
				stringBuilder.Append(languageDatas.rateOfFire + " ");
				stringBuilder.Append(GetRateOfFire(archetypeDataBlock, fireMode));
				stringBuilder.Append("</color>");
				stringBuilder.Append(")");
				break;
			case 1:
			case 12:
				if (archetypeDataBlock.BurstShotCount != 1)
				{
					stringBuilder.Append(firemode.burst + " (");
					stringBuilder.Append("<#704dfa>");
					stringBuilder.Append("#" + archetypeDataBlock.BurstShotCount);
					stringBuilder.Append("</color>");
					stringBuilder.Append(" | ");
					stringBuilder.Append("<#12FF50>");
					stringBuilder.Append(languageDatas.rateOfFire + " ");
					stringBuilder.Append(GetRateOfFire(archetypeDataBlock, fireMode));
					stringBuilder.Append("</color>");
					stringBuilder.Append(")");
				}
				else
				{
					stringBuilder.Append(firemode.semiA + " (");
					stringBuilder.Append("<#12FF50>");
					stringBuilder.Append(languageDatas.rateOfFire + " ");
					stringBuilder.Append(GetRateOfFire(archetypeDataBlock, (eWeaponFireMode)0));
					stringBuilder.Append("</color>");
					stringBuilder.Append(")");
				}
				break;
			case 3:
				stringBuilder.Append("S-Burst (");
				stringBuilder.Append("<#12FF50>");
				stringBuilder.Append("#" + archetypeDataBlock.BurstShotCount);
				stringBuilder.Append(" every " + archetypeDataBlock.SpecialSemiBurstCountTimeout + "'");
				stringBuilder.Append("</color>");
				stringBuilder.Append(")");
				break;
			case 13:
				stringBuilder.Append(firemode.shotgunSentry + " (");
				stringBuilder.Append("<#12FF50>");
				stringBuilder.Append(languageDatas.rateOfFire + " ");
				stringBuilder.Append(GetRateOfFire(archetypeDataBlock, fireMode));
				stringBuilder.Append("</color>");
				stringBuilder.Append(")");
				break;
			default:
				WeaponStatShowerPlugin.LogError("FireMode not found");
				break;
			}
			return stringBuilder.ToString();
		}

		private string VerboseDescriptionFormatter(MeleeArchetypeDataBlock meleeArchetypeDataBlock)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine(((double)meleeArchetypeDataBlock.CameraDamageRayLength < 1.76) ? languageDatas.melee.shortRange : (((double)meleeArchetypeDataBlock.CameraDamageRayLength < 2.5) ? languageDatas.melee.mediumRange : languageDatas.melee.longRange));
			stringBuilder.Append(meleeArchetypeDataBlock.CanHitMultipleEnemies ? (languageDatas.melee.canPierce + "\n") : "");
			return "".Equals(stringBuilder.ToString()) ? "" : (stringBuilder.ToString() + "\n");
		}

		private string VerboseDescriptionFormatter(ArchetypeDataBlock archetypeDataBlock, bool isSentryGun)
		{
			StringBuilder stringBuilder = new StringBuilder();
			SpreadLanguageModel spread = languageDatas.spread;
			if (isSentryGun)
			{
				stringBuilder.AppendLine(languageDatas.deployable);
			}
			switch (archetypeDataBlock.ShotgunBulletSpread + archetypeDataBlock.ShotgunConeSize)
			{
			case 1:
				stringBuilder.AppendLine(spread.chocked);
				break;
			case 4:
				stringBuilder.AppendLine(spread.small);
				break;
			case 5:
				stringBuilder.AppendLine(spread.medium);
				break;
			case 7:
				stringBuilder.AppendLine(spread.medium);
				break;
			case 9:
				stringBuilder.AppendLine(spread.huge);
				break;
			default:
				WeaponStatShowerPlugin.LogError(LocalizedText.op_Implicit(archetypeDataBlock.PublicName) + ": spread not considered{" + archetypeDataBlock.ShotgunBulletSpread + "/" + archetypeDataBlock.ShotgunConeSize + "}");
				break;
			case 0:
				break;
			}
			if (archetypeDataBlock.SpecialChargetupTime > 0f)
			{
				stringBuilder.AppendLine(((double)archetypeDataBlock.SpecialChargetupTime > 0.4) ? $"{languageDatas.longChargeUp} ({FormatFloat(archetypeDataBlock.SpecialChargetupTime, 2)})" : $"{languageDatas.shortChargeUp} ({FormatFloat(archetypeDataBlock.SpecialChargetupTime, 2)})");
			}
			return "".Equals(stringBuilder.ToString()) ? "" : (stringBuilder.ToString() + "\n");
		}

		private string GetFormatedWeaponStats(ArchetypeDataBlock archeTypeDataBlock, bool isSentryGun = false)
		{
			//IL_0322: Unknown result type (might be due to invalid IL or missing references)
			if (archeTypeDataBlock == null)
			{
				return string.Empty;
			}
			bool isChinese = !languageDatas.damage.Equals("Dmg");
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			stringBuilder.Append("<#9D2929>");
			StringBuilder stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder3 = stringBuilder2;
			StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(1, 1, stringBuilder2);
			handler.AppendFormatted(languageDatas.damage);
			handler.AppendLiteral(" ");
			stringBuilder3.Append(ref handler);
			stringBuilder.Append(FormatFloat(archeTypeDataBlock.Damage, 2));
			stringBuilder.Append((archeTypeDataBlock.ShotgunBulletCount > 0) ? ("(x" + archeTypeDataBlock.ShotgunBulletCount + ")") : "");
			stringBuilder.Append("</color>");
			num++;
			if (!isSentryGun)
			{
				stringBuilder.Append(" | ");
				stringBuilder.Append("<color=orange>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder4 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(1, 1, stringBuilder2);
				handler.AppendFormatted(languageDatas.clip);
				handler.AppendLiteral(" ");
				stringBuilder4.Append(ref handler);
				stringBuilder.Append(archeTypeDataBlock.DefaultClipSize);
				stringBuilder.Append("</color>");
				num++;
			}
			stringBuilder.Append(" | ");
			stringBuilder.Append("<#FFD306>");
			stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder5 = stringBuilder2;
			handler = new StringBuilder.AppendInterpolatedStringHandler(1, 1, stringBuilder2);
			handler.AppendFormatted(languageDatas.maxAmmo);
			handler.AppendLiteral(" ");
			stringBuilder5.Append(ref handler);
			stringBuilder.Append(GetTotalAmmo(archeTypeDataBlock, itemDataBlock, isSentryGun));
			stringBuilder.Append("</color>");
			num++;
			if (!isSentryGun)
			{
				Divider(ref num, stringBuilder);
				stringBuilder.Append("<#C0FF00>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder6 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(1, 1, stringBuilder2);
				handler.AppendFormatted(languageDatas.reload);
				handler.AppendLiteral(" ");
				stringBuilder6.Append(ref handler);
				stringBuilder.Append(FormatFloat(archeTypeDataBlock.DefaultReloadTime, 2));
				stringBuilder.Append("</color>");
				num++;
			}
			if (archeTypeDataBlock.PrecisionDamageMulti != 1f)
			{
				Divider(ref num, stringBuilder);
				stringBuilder.Append("<#18A4A9>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder7 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(1, 1, stringBuilder2);
				handler.AppendFormatted(languageDatas.precision);
				handler.AppendLiteral(" ");
				stringBuilder7.Append(ref handler);
				stringBuilder.Append(FormatFloat(archeTypeDataBlock.PrecisionDamageMulti, 2));
				stringBuilder.Append("</color>");
				num++;
			}
			Divider(ref num, stringBuilder);
			stringBuilder.Append("<#6764de>");
			stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder8 = stringBuilder2;
			handler = new StringBuilder.AppendInterpolatedStringHandler(1, 1, stringBuilder2);
			handler.AppendFormatted(languageDatas.falloff);
			handler.AppendLiteral(" ");
			stringBuilder8.Append(ref handler);
			stringBuilder.Append((int)archeTypeDataBlock.DamageFalloff.x + "m");
			stringBuilder.Append("</color>");
			num++;
			if (archeTypeDataBlock.StaggerDamageMulti != 1f)
			{
				Divider(ref num, stringBuilder);
				stringBuilder.Append("<color=green>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder9 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(1, 1, stringBuilder2);
				handler.AppendFormatted(languageDatas.stagger);
				handler.AppendLiteral(" ");
				stringBuilder9.Append(ref handler);
				stringBuilder.Append(FormatFloat(archeTypeDataBlock.StaggerDamageMulti, 2));
				stringBuilder.Append("</color>");
				num++;
			}
			if (archeTypeDataBlock.HipFireSpread != 0f && archeTypeDataBlock.ShotgunBulletCount == 0)
			{
				Divider(ref num, stringBuilder);
				stringBuilder.Append("<#cc9347>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder10 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(1, 1, stringBuilder2);
				handler.AppendFormatted(languageDatas.hipSpread);
				handler.AppendLiteral(" ");
				stringBuilder10.Append(ref handler);
				stringBuilder.Append(FormatFloat(archeTypeDataBlock.HipFireSpread, 2));
				stringBuilder.Append("</color>");
				num++;
			}
			if (archeTypeDataBlock.AimSpread != 0f && archeTypeDataBlock.ShotgunBulletCount == 0)
			{
				Divider(ref num, stringBuilder);
				stringBuilder.Append("<#e6583c>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder11 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(1, 1, stringBuilder2);
				handler.AppendFormatted(languageDatas.aimDSpread);
				handler.AppendLiteral(" ");
				stringBuilder11.Append(ref handler);
				stringBuilder.Append(FormatFloat(archeTypeDataBlock.AimSpread, 2));
				stringBuilder.Append("</color>");
				num++;
			}
			if (archeTypeDataBlock.PiercingBullets)
			{
				Divider(ref num, stringBuilder);
				stringBuilder.Append("<#097345>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder12 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(1, 1, stringBuilder2);
				handler.AppendFormatted(languageDatas.pierceCount);
				handler.AppendLiteral(" ");
				stringBuilder12.Append(ref handler);
				stringBuilder.Append(archeTypeDataBlock.PiercingDamageCountLimit);
				stringBuilder.Append("</color>");
				num++;
			}
			stringBuilder.AppendLine("\n");
			stringBuilder.Append(sleepersDatas.VerboseKill(archeTypeDataBlock));
			return stringBuilder.ToString();
			void Divider(ref int count, StringBuilder builder)
			{
				if (count >= 4 || (isChinese && count >= 3))
				{
					builder.Append("\n");
					count = 0;
				}
				else if (count > 0)
				{
					builder.Append(" | ");
				}
			}
		}

		private string GetFormatedWeaponStats(MeleeArchetypeDataBlock archeTypeDataBlock, ItemDataBlock itemDataBlock)
		{
			MeleeLanguageModel melee = languageDatas.melee;
			if (archeTypeDataBlock == null)
			{
				return string.Empty;
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("<#9D2929>");
			StringBuilder stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder3 = stringBuilder2;
			StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder2);
			handler.AppendFormatted(languageDatas.damage);
			handler.AppendLiteral(".");
			handler.AppendFormatted(melee.light);
			handler.AppendLiteral(" ");
			stringBuilder3.Append(ref handler);
			stringBuilder.Append(archeTypeDataBlock.LightAttackDamage);
			stringBuilder.Append("</color>");
			stringBuilder.Append(" | ");
			stringBuilder.Append("<color=orange>");
			stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder4 = stringBuilder2;
			handler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder2);
			handler.AppendFormatted(languageDatas.damage);
			handler.AppendLiteral(".");
			handler.AppendFormatted(melee.heavy);
			handler.AppendLiteral(" ");
			stringBuilder4.Append(ref handler);
			stringBuilder.Append(archeTypeDataBlock.ChargedAttackDamage);
			stringBuilder.Append("</color>");
			int count2 = 2;
			if (!archeTypeDataBlock.AllowRunningWhenCharging)
			{
				Divider(ref count2, stringBuilder);
				stringBuilder.Append("<#FFD306>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder5 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(0, 1, stringBuilder2);
				handler.AppendFormatted(melee.canRunWhileCharging);
				stringBuilder5.Append(ref handler);
				stringBuilder.Append("</color>");
				count2++;
			}
			if (archeTypeDataBlock.LightStaggerMulti != 1f)
			{
				Divider(ref count2, stringBuilder);
				stringBuilder.Append("<#C0FF00>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder6 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder2);
				handler.AppendFormatted(languageDatas.stagger);
				handler.AppendLiteral(".");
				handler.AppendFormatted(melee.light);
				handler.AppendLiteral(" ");
				stringBuilder6.Append(ref handler);
				stringBuilder.Append(archeTypeDataBlock.LightStaggerMulti);
				stringBuilder.Append("</color>");
				count2++;
			}
			if (archeTypeDataBlock.ChargedStaggerMulti != 1f)
			{
				Divider(ref count2, stringBuilder);
				stringBuilder.Append("<color=green>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder7 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder2);
				handler.AppendFormatted(languageDatas.stagger);
				handler.AppendLiteral(".");
				handler.AppendFormatted(melee.heavy);
				handler.AppendLiteral(" ");
				stringBuilder7.Append(ref handler);
				stringBuilder.Append(archeTypeDataBlock.ChargedStaggerMulti);
				stringBuilder.Append("</color>");
				count2++;
			}
			if (archeTypeDataBlock.LightPrecisionMulti != 1f)
			{
				Divider(ref count2, stringBuilder);
				stringBuilder.Append("<#004E2C>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder8 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder2);
				handler.AppendFormatted(languageDatas.precision);
				handler.AppendLiteral(".");
				handler.AppendFormatted(melee.light);
				handler.AppendLiteral(" ");
				stringBuilder8.Append(ref handler);
				stringBuilder.Append(archeTypeDataBlock.LightPrecisionMulti);
				stringBuilder.Append("</color>");
				count2++;
			}
			if (archeTypeDataBlock.ChargedPrecisionMulti != 1f)
			{
				Divider(ref count2, stringBuilder);
				stringBuilder.Append("<#55022B>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder9 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder2);
				handler.AppendFormatted(languageDatas.precision);
				handler.AppendLiteral(".");
				handler.AppendFormatted(melee.heavy);
				handler.AppendLiteral(" ");
				stringBuilder9.Append(ref handler);
				stringBuilder.Append(archeTypeDataBlock.ChargedPrecisionMulti);
				stringBuilder.Append("</color>");
				count2++;
			}
			if (archeTypeDataBlock.LightSleeperMulti != 1f)
			{
				Divider(ref count2, stringBuilder);
				stringBuilder.Append("<#A918A7>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder10 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder2);
				handler.AppendFormatted(melee.sleepingEnemiesMultiplier);
				handler.AppendLiteral(".");
				handler.AppendFormatted(melee.light);
				handler.AppendLiteral(" ");
				stringBuilder10.Append(ref handler);
				stringBuilder.Append(archeTypeDataBlock.LightSleeperMulti);
				stringBuilder.Append("</color>");
				count2++;
			}
			if (archeTypeDataBlock.ChargedSleeperMulti != 1f)
			{
				Divider(ref count2, stringBuilder);
				stringBuilder.Append("<#025531>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder11 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder2);
				handler.AppendFormatted(melee.sleepingEnemiesMultiplier);
				handler.AppendLiteral(".");
				handler.AppendFormatted(melee.heavy);
				handler.AppendLiteral(" ");
				stringBuilder11.Append(ref handler);
				stringBuilder.Append(archeTypeDataBlock.ChargedSleeperMulti);
				stringBuilder.Append("</color>");
				count2++;
			}
			if (archeTypeDataBlock.LightEnvironmentMulti != 1f)
			{
				Divider(ref count2, stringBuilder);
				stringBuilder.Append("<#18A4A9>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder12 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder2);
				handler.AppendFormatted(melee.environmentMultiplier);
				handler.AppendLiteral(".");
				handler.AppendFormatted(melee.light);
				handler.AppendLiteral(" ");
				stringBuilder12.Append(ref handler);
				stringBuilder.Append(archeTypeDataBlock.LightEnvironmentMulti);
				stringBuilder.Append("</color>");
				count2++;
			}
			if (archeTypeDataBlock.ChargedEnvironmentMulti != 1f)
			{
				Divider(ref count2, stringBuilder);
				stringBuilder.Append("<#75A2AA>");
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder13 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(2, 2, stringBuilder2);
				handler.AppendFormatted(melee.environmentMultiplier);
				handler.AppendLiteral(".");
				handler.AppendFormatted(melee.heavy);
				handler.AppendLiteral(" ");
				stringBuilder13.Append(ref handler);
				stringBuilder.Append(archeTypeDataBlock.ChargedEnvironmentMulti);
				stringBuilder.Append("</color>");
				count2++;
			}
			stringBuilder.AppendLine("\n");
			stringBuilder.Append(sleepersDatas.VerboseKill(archeTypeDataBlock));
			return stringBuilder.ToString();
			static void Divider(ref int count, StringBuilder builder)
			{
				if (count >= 3)
				{
					builder.Append("\n");
					count = 0;
				}
				else if (count > 0)
				{
					builder.Append(" | ");
				}
			}
		}

		private static float FormatFloat(float value, int v)
		{
			return (float)Math.Round((decimal)value, v);
		}

		private int GetAmmoMax(ItemDataBlock itemDataBlock)
		{
			//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_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected I4, but got Unknown
			AmmoType ammoTypeFromSlot = PlayerAmmoStorage.GetAmmoTypeFromSlot(itemDataBlock.inventorySlot);
			AmmoType val = ammoTypeFromSlot;
			AmmoType val2 = val;
			return (int)val2 switch
			{
				0 => _playerDataBlock.AmmoStandardMaxCap, 
				1 => _playerDataBlock.AmmoSpecialMaxCap, 
				2 => _playerDataBlock.AmmoClassMaxCap, 
				5 => itemDataBlock.ConsumableAmmoMax, 
				_ => -1, 
			};
		}

		private int GetTotalAmmo(ArchetypeDataBlock archetypeDataBlock, ItemDataBlock itemDataBlock, bool isSentryGun = false)
		{
			int ammoMax = GetAmmoMax(itemDataBlock);
			float num = archetypeDataBlock.CostOfBullet;
			if (isSentryGun)
			{
				num *= itemDataBlock.ClassAmmoCostFactor;
				if ((float)archetypeDataBlock.ShotgunBulletCount > 0f)
				{
					num *= (float)archetypeDataBlock.ShotgunBulletCount;
				}
			}
			int num2 = (int)((float)ammoMax / num);
			if (isSentryGun)
			{
				return num2;
			}
			return num2 + archetypeDataBlock.DefaultClipSize;
		}

		private string GetRateOfFire(ArchetypeDataBlock archetypeDataBlock, eWeaponFireMode fireMode)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected I4, but got Unknown
			//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)
			//IL_0034: Expected I4, but got Unknown
			float value = -1f;
			float num;
			switch ((int)fireMode)
			{
			default:
				switch (fireMode - 11)
				{
				case 0:
					break;
				case 2:
					goto IL_0045;
				case 1:
					goto IL_005b;
				default:
					goto end_IL_000c;
				}
				goto case 2;
			case 2:
				value = 1f / archetypeDataBlock.ShotDelay;
				break;
			case 0:
				goto IL_0045;
			case 1:
				goto IL_005b;
				IL_005b:
				num = 1f / (archetypeDataBlock.BurstDelay + archetypeDataBlock.SpecialChargetupTime + archetypeDataBlock.ShotDelay * (float)(archetypeDataBlock.BurstShotCount - 1));
				value = num * (float)archetypeDataBlock.BurstShotCount;
				break;
				IL_0045:
				value = 1f / (archetypeDataBlock.ShotDelay + archetypeDataBlock.SpecialChargetupTime);
				break;
				end_IL_000c:
				break;
			}
			return FormatFloat(value, 1).ToString();
		}
	}
}
namespace WeaponStatShower.Utils.Language
{
	public class LanguageDatas
	{
		public FiremodeLanguageModel firemode { get; set; }

		public MeleeLanguageModel melee { get; set; }

		public SpreadLanguageModel spread { get; set; }

		public SleepersLanguageModel sleepers { get; set; }

		public string damage { get; set; }

		public string clip { get; set; }

		public string maxAmmo { get; set; }

		public string falloff { get; set; }

		public string reload { get; set; }

		public string stagger { get; set; }

		public string precision { get; set; }

		public string pierceCount { get; set; }

		public string rateOfFire { get; set; }

		public string aimDSpread { get; set; }

		public string hipSpread { get; set; }

		public string deployable { get; set; }

		public string longChargeUp { get; set; }

		public string shortChargeUp { get; set; }
	}
	internal class LanguageDatasClass
	{
		public LanguageDatas english { get; set; }

		public LanguageDatas chinese { get; set; }
	}
	internal enum LanguageEnum
	{
		English,
		Chinese
	}
	internal class LocalizedString
	{
		public static readonly string JsonString = "{\r\n\t\t\t\"english\": {\r\n\t\t\t\t\"firemode\": {\r\n\t\t\t\t\t\"fullA\": \"Full-A\",\r\n\t\t\t\t\t\"semiA\": \"Semi-A\",\r\n\t\t\t\t\t\"burst\": \"Burst\",\r\n\t\t\t\t\t\"shotgunSentry\": \"Shotgun-S\"\r\n\t\t\t\t},\r\n\t\t\t\t\"melee\": {\r\n\t\t\t\t\t\"light\": \"Lgt\",\r\n\t\t\t\t\t\"heavy\": \"Hvy\",\r\n\t\t\t\t\t\"canRunWhileCharging\": \"Can't run\",\r\n\t\t\t\t\t\"sleepingEnemiesMultiplier\": \"Slp\",\r\n\t\t\t\t\t\"environmentMultiplier\": \"Env\",\r\n\t\t\t\t\t\"canPierce\": \"Piercing\",\r\n\t\t\t\t\t\"shortRange\": \"Short Range\",\r\n\t\t\t\t\t\"mediumRange\": \"Medium Range\",\r\n\t\t\t\t\t\"longRange\": \"Long Range\",\r\n\t\t\t\t\t\"hammer\": \"Hammer - Balanced\",\r\n\t\t\t\t\t\"knife\": \"Knife - Fast\",\r\n\t\t\t\t\t\"bat\": \"Bat - Fast\",\r\n\t\t\t\t\t\"spear\": \"Spear - Slow\"\r\n\t\t\t\t},\r\n\t\t\t\t\"spread\": {\r\n\t\t\t\t\t\"chocked\": \"Chocked Spread\",\r\n\t\t\t\t\t\"small\": \"Small Spread\",\r\n\t\t\t\t\t\"medium\": \"Medium Spread\",\r\n\t\t\t\t\t\"large\": \"Large Spread\",\r\n\t\t\t\t\t\"huge\": \"Huge Spread\"\r\n\t\t\t\t},\r\n\t\t\t\t\"sleepers\": {\r\n\t\t\t\t\t\"striker\": \"STRK\",\r\n\t\t\t\t\t\"shooter\": \"SHTR\",\r\n\t\t\t\t\t\"scout\": \"SCOUT\",\r\n\t\t\t\t\t\"bigStriker\": \"B-STRK\",\r\n\t\t\t\t\t\"bigShooter\": \"B-SHTR\",\r\n\t\t\t\t\t\"charger\": \"CHRG\",\r\n\t\t\t\t\t\"chargerScout\": \"C-SCOUT\",\r\n\t\t\t\t\t\"occipit\": \"o\",\r\n\t\t\t\t\t\"head\": \"h\",\r\n\t\t\t\t\t\"back\": \"b\",\r\n\t\t\t\t\t\"chest\": \"c\"\r\n\t\t\t\t},\r\n\t\t\t\t\"damage\": \"Dmg\",\r\n\t\t\t\t\"clip\": \"Clp\",\r\n\t\t\t\t\"maxAmmo\": \"Max\",\r\n\t\t\t\t\"falloff\": \"Dist\",\r\n\t\t\t\t\"reload\": \"Rld\",\r\n\t\t\t\t\"stagger\": \"Stgr\",\r\n\t\t\t\t\"precision\": \"Prcn\",\r\n\t\t\t\t\"pierceCount\": \"Pierc\",\r\n\t\t\t\t\"rateOfFire\": \"RoF\",\r\n\t\t\t\t\"aimDSpread\": \"ADS\",\r\n\t\t\t\t\"hipSpread\": \"HIP\",\r\n\t\t\t\t\"deployable\": \"Deployable\",\r\n\t\t\t\t\"longChargeUp\": \"Long Charge-up\",\r\n\t\t\t\t\"shortChargeUp\": \"short Charge-up\"\r\n\t\t\t},\r\n\r\n\t\t\t\"chinese\": {\r\n\t\t\t\t\"firemode\": {\r\n\t\t\t\t\t\"fullA\": \"全自动\",\r\n\t\t\t\t\t\"semiA\": \"半自动\",\r\n\t\t\t\t\t\"burst\": \"连发\",\r\n\t\t\t\t\t\"shotgunSentry\": \"半自动霰弹射击\"\r\n\t\t\t\t},\r\n\t\t\t\t\"melee\": {\r\n\t\t\t\t\t\"light\": \"轻击\",\r\n\t\t\t\t\t\"heavy\": \"重击\",\r\n\t\t\t\t\t\"canRunWhileCharging\": \"不能冲刺\",\r\n\t\t\t\t\t\"sleepingEnemiesMultiplier\": \"沉睡倍率\",\r\n\t\t\t\t\t\"environmentMultiplier\": \"环境倍率\",\r\n\t\t\t\t\t\"canPierce\": \"穿刺\",\r\n\t\t\t\t\t\"shortRange\": \"短距离\",\r\n\t\t\t\t\t\"mediumRange\": \"中距离\",\r\n\t\t\t\t\t\"longRange\": \"长距离\",\r\n\t\t\t\t\t\"hammer\": \"大锤 - 均衡\",\r\n\t\t\t\t\t\"knife\": \"刀 - 快速\",\r\n\t\t\t\t\t\"bat\": \"棍棒 - 快速\",\r\n\t\t\t\t\t\"spear\": \"矛 - 慢速\"\r\n\t\t\t\t},\r\n\t\t\t\t\"spread\": {\r\n\t\t\t\t\t\"chocked\": \"收束扩散\",\r\n\t\t\t\t\t\"small\": \"扩散小\",\r\n\t\t\t\t\t\"medium\": \"中度扩散\",\r\n\t\t\t\t\t\"large\": \"扩散大\",\r\n\t\t\t\t\t\"huge\": \"超大扩散\"\r\n\t\t\t\t},\r\n\t\t\t\t\"sleepers\": {\r\n\t\t\t\t\t\"striker\": \"前锋\",\r\n\t\t\t\t\t\"shooter\": \"射手\",\r\n\t\t\t\t\t\"scout\": \"哨兵\",\r\n\t\t\t\t\t\"bigStriker\": \"大壮\",\r\n\t\t\t\t\t\"bigShooter\": \"大姐\",\r\n\t\t\t\t\t\"charger\": \"黑刺\",\r\n\t\t\t\t\t\"chargerScout\": \"黑触\",\r\n\t\t\t\t\t\"occipit\": \"后脑\",\r\n\t\t\t\t\t\"head\": \"头\",\r\n\t\t\t\t\t\"back\": \"背\",\r\n\t\t\t\t\t\"chest\": \"胸\"\r\n\t\t\t\t},\r\n\r\n\t\t\t\t\"damage\": \"伤害\",\r\n\t\t\t\t\"clip\": \"弹容量\",\r\n\t\t\t\t\"maxAmmo\": \"总弹量\",\r\n\t\t\t\t\"falloff\": \"衰减距离\",\r\n\t\t\t\t\"reload\": \"换弹时间\",\r\n\t\t\t\t\"stagger\": \"硬直倍率\",\r\n\t\t\t\t\"precision\": \"精准倍率\",\r\n\t\t\t\t\"pierceCount\": \"穿透\",\r\n\t\t\t\t\"rateOfFire\": \"射速\",\r\n\t\t\t\t\"aimDSpread\": \"倍镜\",\r\n\t\t\t\t\"hipSpread\": \"后坐力\",\r\n\t\t\t\t\"deployable\": \"可部署\",\r\n\t\t\t\t\"longChargeUp\": \"长蓄力\",\r\n\t\t\t\t\"shortChargeUp\": \"短蓄力\"\r\n\t\t\t}\r\n\t\t}";
	}
}
namespace WeaponStatShower.Utils.Language.Models
{
	public class FiremodeLanguageModel
	{
		public string fullA { get; set; }

		public string semiA { get; set; }

		public string burst { get; set; }

		public string shotgunSentry { get; set; }
	}
	public class MeleeLanguageModel
	{
		public string light { get; set; }

		public string heavy { get; set; }

		public string canRunWhileCharging { get; set; }

		public string sleepingEnemiesMultiplier { get; set; }

		public string environmentMultiplier { get; set; }

		public string canPierce { get; set; }

		public string shortRange { get; set; }

		public string mediumRange { get; set; }

		public string longRange { get; set; }

		public string hammer { get; set; }

		public string knife { get; set; }

		public string bat { get; set; }

		public string spear { get; set; }
	}
	public class SleepersLanguageModel
	{
		public string striker { get; set; }

		public string shooter { get; set; }

		public string scout { get; set; }

		public string bigStriker { get; set; }

		public string bigShooter { get; set; }

		public string charger { get; set; }

		public string chargerScout { get; set; }

		public string occipit { get; set; }

		public string head { get; set; }

		public string back { get; set; }

		public string chest { get; set; }
	}
	public class SpreadLanguageModel
	{
		public string chocked { get; set; }

		public string small { get; set; }

		public string medium { get; set; }

		public string large { get; set; }

		public string huge { get; set; }
	}
}
namespace WeaponStatShower.Patches
{
	public abstract class Patch
	{
		protected internal Harmony? Harmony { get; set; }

		public virtual string Name { get; }

		public virtual bool Enabled => true;

		public virtual void Initialize()
		{
		}

		public abstract void Execute();

		public void PatchConstructor<TClass>(PatchType patchType, string? prefixMethodName = null, string? postfixMethodName = null) where TClass : class
		{
			PatchConstructor<TClass>(null, patchType, prefixMethodName, postfixMethodName);
		}

		public void PatchConstructor<TClass>(Type[]? parameters, PatchType patchType, string? prefixMethodName = null, string? postfixMethodName = null) where TClass : class
		{
			ConstructorInfo methodBase = AccessTools.Constructor(typeof(TClass), parameters, false);
			PatchMethod<TClass>(methodBase, patchType, prefixMethodName, postfixMethodName);
		}

		public void PatchMethod<TClass>(string methodName, PatchType patchType, Type[] generics = null, string prefixMethodName = null, string postfixMethodName = null) where TClass : class
		{
			PatchMethod<TClass>(methodName, null, patchType, generics, prefixMethodName, postfixMethodName);
		}

		public void PatchMethod<TClass>(string methodName, Type[] parameters, PatchType patchType, Type[] generics = null, string prefixMethodName = null, string postfixMethodName = null) where TClass : class
		{
			MethodInfo methodBase = AccessTools.Method(typeof(TClass), methodName, parameters, generics);
			PatchMethod<TClass>(methodBase, patchType, prefixMethodName, postfixMethodName);
		}

		public void PatchMethod<TClass>(MethodBase methodBase, PatchType patchType, string prefixMethodName = null, string postfixMethodName = null) where TClass : class
		{
			PatchMethod(typeof(TClass), methodBase, patchType, prefixMethodName, postfixMethodName);
		}

		public void PatchMethod(Type classType, string methodName, PatchType patchType, Type[] generics = null, string prefixMethodName = null, string postfixMethodName = null)
		{
			PatchMethod(classType, methodName, null, patchType, generics, prefixMethodName, postfixMethodName);
		}

		public void PatchMethod(Type classType, string methodName, Type[] parameters, PatchType patchType, Type[] generics = null, string prefixMethodName = null, string postfixMethodName = null)
		{
			MethodInfo methodBase = AccessTools.Method(classType, methodName, parameters, generics);
			PatchMethod(classType, methodBase, patchType, prefixMethodName, postfixMethodName);
		}

		public void PatchMethod(Type classType, MethodBase methodBase, PatchType patchType, string? prefixMethodName = null, string? postfixMethodName = null)
		{
			//IL_0164: 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_0177: Expected O, but got Unknown
			//IL_0177: Expected O, but got Unknown
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Expected O, but got Unknown
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Expected O, but got Unknown
			string text = classType.Name.Replace("`", "__");
			string value = methodBase.ToString();
			string text2 = (methodBase.IsConstructor ? "ctor" : methodBase.Name);
			MethodInfo methodInfo = null;
			MethodInfo methodInfo2 = null;
			if ((patchType & PatchType.Prefix) != 0)
			{
				try
				{
					methodInfo2 = AccessTools.Method(GetType(), prefixMethodName ?? (text + "__" + text2 + "__Prefix"), (Type[])null, (Type[])null);
				}
				catch (Exception value2)
				{
					LogFatal($"Failed to obtain the prefix patch method for {value}): {value2}");
				}
			}
			if ((patchType & PatchType.Postfix) != 0)
			{
				try
				{
					methodInfo = AccessTools.Method(GetType(), postfixMethodName ?? (text + "__" + text2 + "__Postfix"), (Type[])null, (Type[])null);
				}
				catch (Exception value3)
				{
					LogFatal($"Failed to obtain the postfix patch method for {value}): {value3}");
				}
			}
			try
			{
				if (methodInfo2 != null && methodInfo != null)
				{
					Harmony.Patch(methodBase, new HarmonyMethod(methodInfo2), new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else if (methodInfo2 != null)
				{
					Harmony.Patch(methodBase, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else if (methodInfo != null)
				{
					Harmony.Patch(methodBase, (HarmonyMethod)null, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception value4)
			{
				LogError($"Failed to patch method {value}: {value4}");
			}
		}

		public void Log(LogLevel level, object data)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: 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_0011: 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_001a: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			ManualLogSource log = ((BasePlugin)WeaponStatShowerPlugin.Instance).Log;
			bool flag = default(bool);
			BepInExLogInterpolatedStringHandler val = new BepInExLogInterpolatedStringHandler(3, 2, level, ref flag);
			if (flag)
			{
				val.AppendLiteral("<");
				val.AppendFormatted<string>(Name);
				val.AppendLiteral("> ");
				val.AppendFormatted<object>(data);
			}
			log.Log(level, val);
		}

		public void LogDebug(object data)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			ManualLogSource log = ((BasePlugin)WeaponStatShowerPlugin.Instance).Log;
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(3, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("<");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("> ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<object>(data);
			}
			log.LogDebug(val);
		}

		public void LogError(object data)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			ManualLogSource log = ((BasePlugin)WeaponStatShowerPlugin.Instance).Log;
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(3, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("<");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("> ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<object>(data);
			}
			log.LogError(val);
		}

		public void LogFatal(object data)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			ManualLogSource log = ((BasePlugin)WeaponStatShowerPlugin.Instance).Log;
			bool flag = default(bool);
			BepInExFatalLogInterpolatedStringHandler val = new BepInExFatalLogInterpolatedStringHandler(3, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("<");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("> ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<object>(data);
			}
			log.LogFatal(val);
		}

		public void LogInfo(object data)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			ManualLogSource log = ((BasePlugin)WeaponStatShowerPlugin.Instance).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(3, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("<");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("> ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<object>(data);
			}
			log.LogInfo(val);
		}

		public void LogMessage(object data)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			ManualLogSource log = ((BasePlugin)WeaponStatShowerPlugin.Instance).Log;
			bool flag = default(bool);
			BepInExMessageLogInterpolatedStringHandler val = new BepInExMessageLogInterpolatedStringHandler(3, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("<");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("> ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<object>(data);
			}
			log.LogMessage(val);
		}

		public void LogWarning(object data)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			ManualLogSource log = ((BasePlugin)WeaponStatShowerPlugin.Instance).Log;
			bool flag = default(bool);
			BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(3, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("<");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("> ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<object>(data);
			}
			log.LogWarning(val);
		}
	}
	[Flags]
	public enum PatchType : byte
	{
		Prefix = 1,
		Postfix = 2,
		Both = 3
	}
	internal class ShowStat : Patch
	{
		private const string PatchName = "ShowStat";

		private const PatchType patchType = PatchType.Postfix;

		private static readonly ConfigDefinition ConfigEnabled = new ConfigDefinition("ShowStat", "Enabled");

		private static readonly ConfigDefinition Language = new ConfigDefinition("ShowStat", "Language");

		private static readonly ConfigDefinition ConfigSleepers = new ConfigDefinition("ShowStat", "SleepersShown");

		private static LanguageEnum PrevLanguageEnum = LanguageEnum.English;

		private static string PrevShownSleepers = "PLACEHOLDER";

		private static WeaponDescriptionBuilder? _weaponDescriptionBuilder;

		public static Patch Instance { get; private set; }

		public override string Name { get; } = "ShowStat";


		public override void Initialize()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			Instance = this;
			((BasePlugin)WeaponStatShowerPlugin.Instance).Config.Bind<bool>(ConfigEnabled, true, new ConfigDescription("Show the stats of a weapon.", (AcceptableValueBase)null, Array.Empty<object>()));
			((BasePlugin)WeaponStatShowerPlugin.Instance).Config.Bind<LanguageEnum>(Language, LanguageEnum.English, new ConfigDescription("Select the mod language.", (AcceptableValueBase)null, Array.Empty<object>()));
			((BasePlugin)WeaponStatShowerPlugin.Instance).Config.Bind<string>(ConfigSleepers, "ALL", new ConfigDescription("Select which Sleepers are shown, separeted by a comma.\nAcceptable values: ALL, NONE, STRIKER, SHOOTER, SCOUT, BIG_STRIKER, BIG_SHOOTER, CHARGER, CHARGER_SCOUT", (AcceptableValueBase)null, Array.Empty<object>()));
			_weaponDescriptionBuilder = new WeaponDescriptionBuilder();
		}

		public override void Execute()
		{
			PatchMethod<CM_InventorySlotItem>("LoadData", PatchType.Postfix);
		}

		public static void CM_InventorySlotItem__LoadData__Postfix(CM_InventorySlotItem __instance, GearIDRange idRange, bool clickable, bool detailedInfo)
		{
			if ((Object)(object)__instance == (Object)null || !detailedInfo)
			{
				return;
			}
			if (_weaponDescriptionBuilder == null)
			{
				WeaponStatShowerPlugin.LogError("Something went wrong with the DescriptionBuilder");
				return;
			}
			((BasePlugin)WeaponStatShowerPlugin.Instance).Config.Reload();
			string text = ((BasePlugin)WeaponStatShowerPlugin.Instance).Config.GetConfigEntry<string>(ConfigSleepers).Value.Trim().ToUpper();
			LanguageEnum value = ((BasePlugin)WeaponStatShowerPlugin.Instance).Config.GetConfigEntry<LanguageEnum>(Language).Value;
			if (!PrevShownSleepers.Equals(text) || !value.Equals(PrevLanguageEnum))
			{
				_weaponDescriptionBuilder.UpdateSleepersDatas(text.Split(','), value);
				PrevShownSleepers = text;
				PrevLanguageEnum = value;
			}
			_weaponDescriptionBuilder.Inizialize(idRange, GameDataBlockBase<PlayerDataBlock>.GetBlock(1u), value);
			__instance.GearDescription = _weaponDescriptionBuilder.DescriptionFormatter(__instance.GearDescription);
			__instance.GearPublicName = _weaponDescriptionBuilder.FireRateFormatter(__instance.GearPublicName);
		}
	}
}

plugins/dakkhuza-MTFO/MTFO.dll

Decompiled 7 hours ago
using System;
using System.CodeDom.Compiler;
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 System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using AK;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using CellMenu;
using ChainedPuzzles;
using GTFO.API;
using GameData;
using GameEvent;
using Gear;
using Globals;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.InteropTypes.Fields;
using Il2CppInterop.Runtime.Runtime;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.Class;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MTFO.API;
using MTFO.Custom;
using MTFO.Custom.CCP.Components;
using MTFO.CustomCP;
using MTFO.HotReload;
using MTFO.Managers;
using MTFO.NativeDetours;
using MTFO.Utilities;
using Player;
using SNetwork;
using Steamworks;
using TMPro;
using UnityEngine;
using UnityEngine.Analytics;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("MTFO")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© dakkhuza 2021")]
[assembly: AssemblyFileVersion("4.6.2")]
[assembly: AssemblyInformationalVersion("4.6.2+git44e73d7-dirty-main")]
[assembly: AssemblyProduct("MTFO")]
[assembly: AssemblyTitle("MTFO")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.6.2.0")]
[module: UnverifiableCode]
namespace MTFO
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class ConfigStrings
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

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

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

		internal static string SECTION_DEBUG => ResourceManager.GetString("SECTION_DEBUG", resourceCulture);

		internal static string SECTION_DEV => ResourceManager.GetString("SECTION_DEV", resourceCulture);

		internal static string SECTION_GENERAL => ResourceManager.GetString("SECTION_GENERAL", resourceCulture);

		internal static string SETTING_DISABLE_ACHIEVEMENTS => ResourceManager.GetString("SETTING_DISABLE_ACHIEVEMENTS", resourceCulture);

		internal static string SETTING_DISABLE_ACHIEVEMENTS_DESC => ResourceManager.GetString("SETTING_DISABLE_ACHIEVEMENTS_DESC", resourceCulture);

		internal static string SETTING_DUMPDATA => ResourceManager.GetString("SETTING_DUMPDATA", resourceCulture);

		internal static string SETTING_DUMPDATA_DESC => ResourceManager.GetString("SETTING_DUMPDATA_DESC", resourceCulture);

		internal static string SETTING_DUMPDATA_MODE => ResourceManager.GetString("SETTING_DUMPDATA_MODE", resourceCulture);

		internal static string SETTING_DUMPDATA_MODE_DESC => ResourceManager.GetString("SETTING_DUMPDATA_MODE_DESC", resourceCulture);

		internal static string SETTING_HOTRELOAD => ResourceManager.GetString("SETTING_HOTRELOAD", resourceCulture);

		internal static string SETTING_HOTRELOAD_DESC => ResourceManager.GetString("SETTING_HOTRELOAD_DESC", resourceCulture);

		internal static string SETTING_RUNDOWNPACKAGE => ResourceManager.GetString("SETTING_RUNDOWNPACKAGE", resourceCulture);

		internal static string SETTING_RUNDOWNPACKAGE_DESC => ResourceManager.GetString("SETTING_RUNDOWNPACKAGE_DESC", resourceCulture);

		internal static string SETTING_USE_LEGACY_PATH => ResourceManager.GetString("SETTING_USE_LEGACY_PATH", resourceCulture);

		internal static string SETTING_USE_LEGACY_PATH_DESC => ResourceManager.GetString("SETTING_USE_LEGACY_PATH_DESC", resourceCulture);

		internal static string SETTING_VERBOSE => ResourceManager.GetString("SETTING_VERBOSE", resourceCulture);

		internal static string SETTING_VERBOSE_DESC => ResourceManager.GetString("SETTING_VERBOSE_DESC", resourceCulture);

		internal ConfigStrings()
		{
		}
	}
	[BepInPlugin("com.dak.MTFO", "MTFO", "4.6.2+git44e73d7-dirty-main")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class MTFO : BasePlugin
	{
		public const string MODNAME = "MTFO";

		public const string AUTHOR = "dak";

		public const string GUID = "com.dak.MTFO";

		public const string VERSION = "4.6.2+git44e73d7-dirty-main";

		public override void Load()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			Analytics.enabled = false;
			Harmony harmony = new Harmony("com.dak.MTFO");
			AssetAPI.OnImplReady += delegate
			{
				if (ConfigManager.IsHotReloadEnabled)
				{
					ClassInjector.RegisterTypeInIl2Cpp<HotReloader>();
					harmony.PatchAll(typeof(HotReloadInjector));
				}
			};
			harmony.PatchAll();
			Detour_DataBlockBase.Patch();
		}
	}
	public static class DataDumperExtensions
	{
		public static int GetStableHashCode(this string str)
		{
			int num = 5381;
			int num2 = num;
			for (int i = 0; i < str.Length && str[i] != 0; i += 2)
			{
				num = ((num << 5) + num) ^ str[i];
				if (i == str.Length - 1 || str[i + 1] == '\0')
				{
					break;
				}
				num2 = ((num2 << 5) + num2) ^ str[i + 1];
			}
			return num + num2 * 1566083941;
		}
	}
	public static class JsonNodeExtension
	{
		private static JsonDocumentOptions _JsonDocumentOptions = new JsonDocumentOptions
		{
			AllowTrailingCommas = true,
			CommentHandling = JsonCommentHandling.Skip
		};

		private static readonly JsonSerializerOptions _JsonSerializerOptions = new JsonSerializerOptions
		{
			AllowTrailingCommas = true,
			ReadCommentHandling = JsonCommentHandling.Skip,
			WriteIndented = true,
			Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
		};

		public static string ToJsonStringIndented(this JsonNode jsonNode)
		{
			return jsonNode.ToJsonString(_JsonSerializerOptions);
		}

		public static bool TryParseToJsonNode(this string json, out JsonNode jsonNode)
		{
			try
			{
				jsonNode = json.ToJsonNode();
				return jsonNode != null;
			}
			catch
			{
				jsonNode = null;
				return false;
			}
		}

		public static bool TryParseJsonNode(this Stream stream, bool dispose, out JsonNode jsonNode)
		{
			try
			{
				jsonNode = stream.ToJsonNode();
				return jsonNode != null;
			}
			catch
			{
				jsonNode = null;
				return false;
			}
			finally
			{
				if (dispose)
				{
					stream.Close();
				}
			}
		}

		public static JsonNode ToJsonNode(this string json)
		{
			return JsonNode.Parse(json, null, _JsonDocumentOptions);
		}

		public static JsonNode ToJsonNode(this Stream jsonStream)
		{
			return JsonNode.Parse(jsonStream, null, _JsonDocumentOptions);
		}

		public static bool TryAddJsonItem(this JsonArray jsonArray, string json)
		{
			try
			{
				if (jsonArray == null)
				{
					throw new Exception();
				}
				if (string.IsNullOrWhiteSpace(json))
				{
					throw new Exception();
				}
				if (!json.TryParseToJsonNode(out var jsonNode))
				{
					throw new Exception();
				}
				jsonArray.Add(jsonNode);
				return true;
			}
			catch
			{
				return false;
			}
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "MTFO";

		public const string Version = "4.6.2";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "git44e73d7-dirty-main";

		public const string SemVer = "4.6.2+git44e73d7-dirty-main";

		public const string GitRevShort = "44e73d7-dirty";

		public const string GitRevLong = "44e73d7509b98440c382e03ed0d3eef361127d4f-dirty";

		public const string GitBranch = "main";

		public const string GitTag = "v4.3.0";

		public const bool GitIsDirty = true;
	}
}
namespace MTFO.Utilities
{
	public class JsonSerializer
	{
		public JsonSerializerOptions Options;

		public JsonSerializer()
		{
			Options = new JsonSerializerOptions
			{
				AllowTrailingCommas = true,
				IncludeFields = true,
				PropertyNameCaseInsensitive = true,
				ReadCommentHandling = JsonCommentHandling.Skip,
				WriteIndented = true
			};
			Options.Converters.Add(new JsonStringEnumConverter());
		}

		public JsonSerializer(bool allowTrailingCommas = true, bool includeFields = true, bool propertyNameCaseInsensitive = true, bool writeIndented = true)
		{
			Options = new JsonSerializerOptions
			{
				AllowTrailingCommas = allowTrailingCommas,
				IncludeFields = includeFields,
				PropertyNameCaseInsensitive = propertyNameCaseInsensitive,
				ReadCommentHandling = JsonCommentHandling.Skip,
				WriteIndented = writeIndented
			};
			Options.Converters.Add(new JsonStringEnumConverter());
		}

		public void TryRead<T>(string path, out T output) where T : new()
		{
			if (File.Exists(path))
			{
				string json = File.ReadAllText(path);
				output = Deserialize<T>(json);
			}
			else
			{
				output = new T();
				string json = Serialize(output);
				File.WriteAllText(path, json);
			}
		}

		public string Serialize(object value)
		{
			return System.Text.Json.JsonSerializer.Serialize(value, Options);
		}

		public T Deserialize<T>(string json)
		{
			return System.Text.Json.JsonSerializer.Deserialize<T>(json, Options);
		}
	}
	public static class Log
	{
		private static readonly ManualLogSource logger;

		static Log()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			logger = new ManualLogSource("MTFO");
			Logger.Sources.Add((ILogSource)(object)logger);
		}

		public static void Verbose(object msg)
		{
			if (ConfigManager.IsVerbose)
			{
				logger.LogInfo(msg);
			}
		}

		public static void Debug(object msg)
		{
			logger.LogDebug(msg);
		}

		public static void Message(object msg)
		{
			logger.LogMessage(msg);
		}

		public static void Error(object msg)
		{
			logger.LogError(msg);
		}

		public static void Warn(object msg)
		{
			logger.LogWarning(msg);
		}
	}
	public enum BaseDirectory
	{
		BepInEx,
		Plugins,
		GameData
	}
	public static class PathUtil
	{
		public static string Prepare(BaseDirectory baseDir, params string[] subDirs)
		{
			string text = baseDir switch
			{
				BaseDirectory.BepInEx => Paths.BepInExRootPath, 
				BaseDirectory.Plugins => Paths.PluginPath, 
				BaseDirectory.GameData => Path.Combine(Paths.BepInExRootPath, "GameData"), 
				_ => throw new ArgumentOutOfRangeException("baseDir", string.Format("{0} is not a valid value for Argument: {1}", baseDir, "baseDir")), 
			};
			string obj = ((subDirs == null || subDirs.Length == 0) ? text : Path.Combine(text, Path.Combine(subDirs)));
			Directory.CreateDirectory(obj);
			return obj;
		}

		public static bool CheckCustomFile(string file, out string CombinedPath)
		{
			CombinedPath = Path.Combine(ConfigManager.CustomPath, file);
			if (File.Exists(CombinedPath))
			{
				return true;
			}
			return false;
		}

		public static bool CheckFile(string pathToFile)
		{
			if (File.Exists(pathToFile))
			{
				return true;
			}
			return false;
		}

		[Obsolete]
		public static string MakeRelativeDirectory(string path, bool createPath = true)
		{
			string text = Path.Combine(Path.Combine(Paths.ConfigPath, "Rundowns"), path);
			if (createPath && !Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
			return text;
		}

		public static string MakeRelativeDirectory(string path, string folder)
		{
			string text = Path.Combine(path, folder);
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
			return text;
		}

		public static void PrepareEmptyDirectory(string path)
		{
			if (Directory.Exists(path))
			{
				Directory.Delete(path, recursive: true);
			}
			Directory.CreateDirectory(path);
		}

		public static Stream OpenUtf8Stream(string filePath)
		{
			return new StreamReader(filePath, Encoding.UTF8).BaseStream;
		}
	}
}
namespace MTFO.Patches
{
	[HarmonyPatch(typeof(SteamUserStats), "SetAchievement")]
	internal static class Patch_SteamAPI_Achievement
	{
		private static bool Prefix(string pchName)
		{
			if (!ConfigManager.DisableAchievements)
			{
				return true;
			}
			Log.Error("Achievement Completion Blocked: " + pchName);
			return false;
		}
	}
	[HarmonyPatch(typeof(AnalyticsManager), "OnGameEvent", new Type[] { typeof(GameEventData) })]
	internal static class Patch_Analytics
	{
		public static bool Prefix(GameEventData data)
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(SNet_Core_STEAM), "SetFriendsData", new Type[]
	{
		typeof(FriendsDataType),
		typeof(string)
	})]
	internal static class Patch_RichPresence2
	{
		public static void Prefix(FriendsDataType type, ref string data, SNet_Core_STEAM __instance)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if ((int)type != 1)
			{
				if ((int)type == 9)
				{
					data = "0";
				}
				else
				{
					Log.Verbose($"Lobby data\nType: {type} Data: {data}");
				}
			}
			else
			{
				data = "MODDED - " + data;
			}
		}
	}
	[HarmonyPatch(typeof(DiscordManager), "UpdateDiscordDetails")]
	internal static class Patch_DiscordManager
	{
		[HarmonyPostfix]
		private static void Post_UpdateDiscordDetails(eDiscordDetailsDisplay details)
		{
		}
	}
	[HarmonyPatch(typeof(GlowstickInstance), "Update")]
	internal static class Patch_Glowstick
	{
		public static void Postfix(GlowstickInstance __instance)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Invalid comparison between Unknown and I4
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Invalid comparison between Unknown and I4
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			if (ConfigManager.HasCustomContent && ConfigManager.CustomContent.GlowstickHolder != null && !((Object)(object)__instance == (Object)null) && (int)__instance.m_state != 3 && (int)__instance.m_state != 4 && ConfigManager.CustomContent.GlowstickHolder.GlowstickLookup.TryGetValue(((Item)__instance).PublicName, out var value) && (Object)(object)__instance.m_light != (Object)null)
			{
				((LightBase)__instance.m_light).Range = value.Range;
				((LightBase)__instance.m_light).Color = value.Color * __instance.m_progression;
				((LightBase)__instance.m_light).UpdateVisibility(true);
			}
		}
	}
	[HarmonyPatch(typeof(CP_Holopath_Spline), "Reveal")]
	internal static class Patch_InstantRevealPuzzlePath
	{
		public static bool Prefix(CP_Holopath_Spline __instance)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.m_revealSpeed < 0f)
			{
				if (!__instance.m_isSetup)
				{
					return false;
				}
				__instance.SetSplineProgress(1f);
				__instance.SetVisible(true);
				__instance.m_sound.UpdatePosition(__instance.TipPos);
				if (!__instance.m_didSetColor)
				{
					__instance.m_didSetColor = __instance.TrySetColor();
				}
				__instance.m_sound.Post(EVENTS.BIOSCAN_TUBE_EMITTER_STOP, true);
				Action onRevealDone = __instance.OnRevealDone;
				if (onRevealDone != null)
				{
					onRevealDone.Invoke();
				}
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(CM_PageLoadout), "UpdatePageData")]
	internal static class Patch_PageLoadoutUpdatePageData
	{
		public static void Prefix(CM_PageLoadout __instance)
		{
			((TMP_Text)((Component)((Transform)((CM_PageBase)__instance).m_movingContentHolder).Find("ShareServerId/ShareText")).gameObject.GetComponent<TextMeshPro>()).SetText("<color=red><b>Do not play modded content on the official GTFO server or online matchmake lobbies.</b></color>\n\nFeel free to join the unofficial discord server linked below and ask people to play.", true);
			__instance.m_discordButton.SetText("Mod Server");
			__instance.m_discordButton.OnBtnPressCallback = Action<int>.op_Implicit((Action<int>)delegate
			{
				Application.OpenURL("https://discord.com/invite/rRMPtv4FAh");
			});
		}
	}
	[HarmonyPatch(typeof(CM_PageLoadout), "UpdatePlayerBars")]
	internal static class Patch_PageLoadoutUpdatePlayerBars
	{
		public static void Prefix(CM_PageLoadout __instance)
		{
			foreach (CM_PlayerLobbyBar item in (Il2CppArrayBase<CM_PlayerLobbyBar>)(object)__instance.m_playerLobbyBars)
			{
				item.m_matchmakeButton.SetOnBtnPressCallback((Action<int>)null);
				item.m_matchmakeButton.SetText("DISABLED");
			}
		}
	}
	[HarmonyPatch(typeof(CM_PageRundown_New), "Intro_RevealRundown")]
	internal static class Patch_PageRundownNew
	{
		public static void Postfix(CM_PageRundown_New __instance)
		{
			__instance.m_discordButton.SetText("MOD SERVER");
			__instance.m_discordButton.OnBtnPressCallback = Action<int>.op_Implicit((Action<int>)delegate
			{
				Application.OpenURL("https://discord.com/invite/rRMPtv4FAh");
			});
			((RectTransformComp)__instance.m_matchmakeAllButton).SetVisible(false);
			__instance.m_matchmakeAllButton.SetText("MATCHMAKE DISABLED");
			__instance.m_matchmakeAllButton.OnBtnPressCallback = null;
			__instance.m_aboutTheRundownButton.SetText("THUNDERSTORE");
			__instance.m_aboutTheRundownButton.OnBtnPressCallback = Action<int>.op_Implicit((Action<int>)delegate
			{
				Application.OpenURL("https://gtfo.thunderstore.io/");
			});
		}
	}
	[HarmonyPatch(typeof(CM_PageRundown_New), "PlaceRundown")]
	internal static class Patch_RundownTierMarker
	{
		public static void Postfix(CM_PageRundown_New __instance)
		{
			ContentManager customContent = ConfigManager.CustomContent;
			if (customContent != null)
			{
				__instance.m_tierMarker1.m_name = customContent.TierNames.Tier1;
				__instance.m_tierMarker2.m_name = customContent.TierNames.Tier2;
				__instance.m_tierMarker3.m_name = customContent.TierNames.Tier3;
				__instance.m_tierMarker4.m_name = customContent.TierNames.Tier4;
				__instance.m_tierMarker5.m_name = customContent.TierNames.Tier5;
				__instance.m_tierMarker1.UpdateHeader();
				__instance.m_tierMarker2.UpdateHeader();
				__instance.m_tierMarker3.UpdateHeader();
				__instance.m_tierMarker4.UpdateHeader();
				__instance.m_tierMarker5.UpdateHeader();
			}
		}
	}
	[HarmonyPatch(typeof(PUI_Watermark), "UpdateWatermark")]
	internal static class Patch_WatermarkUpdateWatermark
	{
		public static void Postfix(PUI_Watermark __instance)
		{
			((TMP_Text)__instance.m_watermarkText).SetText("<color=red>MODDED</color> <color=orange>4.6.2</color>", true);
		}
	}
}
namespace MTFO.NativeDetours
{
	internal class DataBlockBaseWrapper
	{
		private static readonly HashSet<string> _PreferPartialDumpBlocks = new HashSet<string>
		{
			"RundownDataBlock".ToLower(),
			"LightSettingsDataBlock".ToLower(),
			"FogSettingsDataBlock".ToLower(),
			"LevelLayoutDataBlock".ToLower(),
			"WardenObjectiveDataBlock".ToLower(),
			"DimensionDataBlock".ToLower(),
			"EnemyDataBlock".ToLower(),
			"EnemySFXDataBlock".ToLower(),
			"EnemyBehaviorDataBlock".ToLower(),
			"EnemyBalancingDataBlock".ToLower(),
			"EnemyMovementDataBlock".ToLower(),
			"ArchetypeDataBlock".ToLower(),
			"PlayerOfflineGearDataBlock".ToLower(),
			"ComplexResourceSetDataBlock".ToLower(),
			"TextDataBlock".ToLower()
		};

		private IntPtr Ptr__m_fileNameNoExt;

		public IntPtr ClassPointer { get; private set; }

		public string FileName { get; private set; }

		public string BinaryFileName { get; private set; }

		public bool PreferPartialBlockOnDump { get; private set; }

		public unsafe DataBlockBaseWrapper(Il2CppMethodInfo* methodInfo)
		{
			INativeClassStruct val = UnityVersionHandler.Wrap(UnityVersionHandler.Wrap(methodInfo).Class);
			ClassPointer = ((INativeStruct)val).Pointer;
			Ptr__m_fileNameNoExt = IL2CPP.GetIl2CppField(((INativeStruct)val).Pointer, "m_fileNameNoExt");
			IntPtr zero = IntPtr.Zero;
			IL2CPP.il2cpp_field_static_get_value(Ptr__m_fileNameNoExt, (void*)(&zero));
			FileName = IL2CPP.Il2CppStringToManaged(zero).Replace('.', '_');
			BinaryFileName = FileName + "_bin";
			if (_PreferPartialDumpBlocks.Contains(FileName.ToLower().Replace("gamedata_", "")))
			{
				PreferPartialBlockOnDump = true;
			}
		}
	}
	internal static class Detour_DataBlockBase
	{
		private unsafe delegate IntPtr GetFileContentsDel(Il2CppMethodInfo* methodInfo);

		private static string _BasePathToDump;

		private static INativeDetour _Detour;

		private static GetFileContentsDel _Original;

		public unsafe static void Patch()
		{
			_BasePathToDump = Path.Combine(Paths.BepInExRootPath, "GameData-Dump", CellBuildData.GetRevision().ToString());
			if (ConfigManager.DumpGameData)
			{
				PathUtil.PrepareEmptyDirectory(_BasePathToDump);
			}
			_Detour = INativeDetour.CreateAndApply<GetFileContentsDel>((IntPtr)(nint)Il2CppAPI.GetIl2CppMethod<GameDataBlockBase<EnemyDataBlock>>("GetFileContents", typeof(string).FullName, false, Array.Empty<string>()), (GetFileContentsDel)Dtor_GetFileContents, ref _Original);
		}

		private unsafe static IntPtr Dtor_GetFileContents(Il2CppMethodInfo* methodInfo)
		{
			IntPtr intPtr = _Original(methodInfo);
			try
			{
				DataBlockBaseWrapper dataBlockBaseWrapper = new DataBlockBaseWrapper(methodInfo);
				string binaryFileName = dataBlockBaseWrapper.BinaryFileName;
				_ = binaryFileName + ".json";
				if (ConfigManager.DumpGameData)
				{
					DumpContent(dataBlockBaseWrapper, IL2CPP.Il2CppStringToManaged(intPtr));
				}
				Log.Verbose("GetFileContents Call of " + binaryFileName);
				Stream contentStream = GetContentStream(dataBlockBaseWrapper, intPtr);
				JsonNode jsonNode = contentStream.ToJsonNode();
				JsonArray jsonArray = jsonNode["Blocks"].AsArray();
				string path = Path.Combine(ConfigManager.GameDataPath, dataBlockBaseWrapper.FileName);
				if (Directory.Exists(path))
				{
					int num = 0;
					string[] files = Directory.GetFiles(path, "*.json");
					foreach (string text in files)
					{
						Log.Verbose(" - Trying to add PartialData [" + text + "]");
						if (File.Exists(text) && PathUtil.OpenUtf8Stream(text).TryParseJsonNode(dispose: true, out var jsonNode2))
						{
							jsonArray.Add(jsonNode2);
							num++;
						}
					}
					Log.Verbose($" - Added {num} partial data of {binaryFileName}");
				}
				List<string> jsonItemsToInject = new List<string>();
				MTFOGameDataAPI.Invoke_OnGameDataContentLoad(dataBlockBaseWrapper.FileName, contentStream, in jsonItemsToInject);
				foreach (string item2 in jsonItemsToInject)
				{
					try
					{
						JsonNode item = item2.ToJsonNode();
						jsonArray.Add(item);
					}
					catch (Exception ex)
					{
						Log.Error("Exception were found while reading Injected Json Data!");
						Log.Error(ex.ToString());
						Log.Error("Full Json:\n" + item2);
					}
				}
				uint num2 = 0u;
				foreach (JsonNode item3 in jsonNode["Blocks"].AsArray())
				{
					uint num3 = (uint)(JsonNode)item3["persistentID"].AsValue();
					if (num3 > num2)
					{
						num2 = num3;
					}
				}
				jsonNode["LastPersistentID"] = num2;
				string text2 = jsonNode.ToJsonStringIndented();
				IntPtr result = IL2CPP.ManagedStringToIl2Cpp(text2);
				MTFOGameDataAPI.Invoke_OnGameDataContentLoaded(dataBlockBaseWrapper.FileName, text2);
				return result;
			}
			catch (Exception ex2)
			{
				Log.Error("Exception were found while handling Detour;Falling back to original content!");
				Log.Error(ex2.ToString());
				return intPtr;
			}
		}

		private static Stream GetContentStream(DataBlockBaseWrapper datablock, IntPtr originalContentPtr)
		{
			string binaryFileName = datablock.BinaryFileName;
			string path = binaryFileName + ".json";
			string s = IL2CPP.Il2CppStringToManaged(originalContentPtr);
			string text = Path.Combine(ConfigManager.GameDataPath, path);
			if (File.Exists(text))
			{
				Log.Verbose("Opening filestream of [" + binaryFileName + "] from disk...");
				Log.Verbose(text);
				return PathUtil.OpenUtf8Stream(text);
			}
			Log.Verbose("No file found at [" + binaryFileName + "]");
			return new MemoryStream(Encoding.UTF8.GetBytes(s));
		}

		private static void DumpContent(DataBlockBaseWrapper datablock, string json)
		{
			if (!json.TryParseToJsonNode(out var jsonNode))
			{
				Log.Verbose("Unable to dump " + datablock.FileName + ", Invalid Json Content!");
				return;
			}
			bool flag = false;
			switch (ConfigManager.DumpMode)
			{
			case DumpGameDataMode.Single:
				flag = false;
				break;
			case DumpGameDataMode.PartialData:
				flag = datablock.PreferPartialBlockOnDump;
				break;
			case DumpGameDataMode.FullPartialData:
				flag = true;
				break;
			}
			if (flag)
			{
				JsonArray jsonArray = jsonNode["Blocks"].AsArray();
				string text = Path.Combine(path2: datablock.FileName, path1: _BasePathToDump);
				PathUtil.PrepareEmptyDirectory(text);
				foreach (JsonNode item in jsonArray)
				{
					string path = string.Format("{0}__{1}.json", item["persistentID"], item["name"]);
					string text2 = Path.Combine(text, path);
					File.WriteAllText(text2, item.ToJsonStringIndented());
					Log.Verbose(" - Save... " + text2);
				}
				jsonNode["Blocks"] = new JsonArray();
			}
			string path2 = datablock.BinaryFileName + ".json";
			File.WriteAllText(Path.Combine(_BasePathToDump, path2), jsonNode.ToJsonStringIndented());
			Log.Verbose(datablock.FileName + " has dumped to '" + _BasePathToDump + "'");
		}
	}
}
namespace MTFO.Managers
{
	public enum DumpGameDataMode
	{
		Single,
		PartialData,
		FullPartialData
	}
	public static class ConfigManager
	{
		private const string CUSTOM_FOLDER = "Custom";

		private static readonly ConfigEntry<bool> _enableHotReload;

		private static readonly ConfigEntry<bool> _dumpGameData;

		private static readonly ConfigEntry<bool> _isVerbose;

		private static readonly ConfigEntry<DumpGameDataMode> _dumpGameDataMode;

		private static readonly ConfigEntry<bool> _disableAchievements;

		public static int GAME_VERSION;

		public static ContentManager CustomContent;

		public static readonly string GameDataPath;

		public static readonly string CustomPath;

		public static bool HasGameDataPath;

		public static bool HasCustomContent;

		public static bool IsModded;

		public static bool IsPluginGameDataPath;

		public static bool IsVerbose => _isVerbose.Value;

		public static bool DisableAchievements => _disableAchievements.Value;

		public static bool IsHotReloadEnabled => _enableHotReload.Value;

		public static bool DumpGameData => _dumpGameData.Value;

		public static DumpGameDataMode DumpMode => _dumpGameDataMode.Value;

		private static string ResolveGameDataPath(string rootPath)
		{
			foreach (string item in Directory.GetFiles(rootPath, "GameData_*.json", SearchOption.AllDirectories).OrderBy(Path.GetDirectoryName))
			{
				if (Path.GetDirectoryName(item) != GameDataPath)
				{
					HasGameDataPath = true;
					return Path.GetDirectoryName(item);
				}
			}
			return null;
		}

		static ConfigManager()
		{
			//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_0030: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			ConfigFile val = new ConfigFile(Path.Combine(Paths.ConfigPath, "MTFO.cfg"), true);
			_enableHotReload = val.Bind<bool>(ConfigStrings.SECTION_DEV, ConfigStrings.SETTING_HOTRELOAD, false, ConfigStrings.SETTING_HOTRELOAD_DESC);
			_dumpGameData = val.Bind<bool>(ConfigStrings.SECTION_DEV, ConfigStrings.SETTING_DUMPDATA, false, ConfigStrings.SETTING_DUMPDATA_DESC);
			_dumpGameDataMode = val.Bind<DumpGameDataMode>(ConfigStrings.SECTION_DEV, ConfigStrings.SETTING_DUMPDATA_MODE, DumpGameDataMode.Single, ConfigStrings.SETTING_DUMPDATA_MODE_DESC);
			_isVerbose = val.Bind<bool>(ConfigStrings.SECTION_DEBUG, ConfigStrings.SETTING_VERBOSE, false, ConfigStrings.SETTING_VERBOSE_DESC);
			_disableAchievements = val.Bind<bool>(ConfigStrings.SECTION_GENERAL, ConfigStrings.SETTING_DISABLE_ACHIEVEMENTS, true, ConfigStrings.SETTING_DISABLE_ACHIEVEMENTS_DESC);
			GAME_VERSION = GetGameVersion();
			GameDataPath = ResolveGameDataPath(PathUtil.Prepare(BaseDirectory.GameData));
			IsPluginGameDataPath = string.IsNullOrEmpty(GameDataPath);
			if (IsPluginGameDataPath)
			{
				GameDataPath = ResolveGameDataPath(Paths.PluginPath);
				Log.Warn("Plugin paths for gamedata are under legacy support and will be removed in the future. Considering migrating to the '\\BepInEx\\GameData' folder.");
			}
			if (HasGameDataPath)
			{
				CustomPath = Path.Combine(GameDataPath, "Custom");
				HasCustomContent = Directory.Exists(CustomPath);
			}
			else
			{
				GameDataPath = string.Empty;
				CustomPath = string.Empty;
				HasCustomContent = false;
				IsPluginGameDataPath = false;
			}
			try
			{
				CustomContent = new ContentManager();
			}
			catch (Exception arg)
			{
				HasCustomContent = false;
				Log.Error($"Failed to init custom content!\nIs your JSON valid?\n---- ERROR MESSAGE ---- {arg} ---- END ERROR MESSAGE ----");
			}
			Log.Debug("---- DEBUG INFO ----");
			Log.Debug($"Time: {DateTime.Now}");
			Log.Debug($"Game Version: {GAME_VERSION}");
			Log.Debug("---- PATHS ----");
			Log.Debug("Path to rundown: " + GameDataPath);
			Log.Debug("Path to custom content: " + CustomPath);
			Log.Debug("---- FLAGS ----");
			Log.Debug($"Has GameData Path? {HasGameDataPath}");
			Log.Debug($"Using plugin GameData path? {IsPluginGameDataPath}");
			Log.Debug($"Has Custom Content? {HasCustomContent}");
			Log.Debug($"Hot Reload Enabled? {IsHotReloadEnabled}");
			Log.Debug($"Verbose Logging? {IsVerbose}");
			Log.Debug($"Dump Game Data? {DumpGameData}");
			Log.Debug($"Are Achievements Disabled? {DisableAchievements}");
			Log.Debug("---- DEBUG END ----");
		}

		private static int GetGameVersion()
		{
			return CellBuildData.GetRevision();
		}
	}
	public class ContentManager
	{
		private readonly global::MTFO.Utilities.JsonSerializer json = new global::MTFO.Utilities.JsonSerializer();

		private readonly Dictionary<string, Action<string>> Handlers;

		public ScanHolder ScanHolder;

		public GlowstickHolder GlowstickHolder;

		public TierNames TierNames;

		public ContentManager()
		{
			Handlers = new Dictionary<string, Action<string>>
			{
				{ "puzzletypes.json", SetupChainedPuzzles },
				{ "glowsticks.json", SetupGlowsticks },
				{ "tiernames.json", SetupTierNames }
			};
			Init();
		}

		private void Init()
		{
			if (!ConfigManager.HasCustomContent)
			{
				return;
			}
			foreach (string key in Handlers.Keys)
			{
				if (PathUtil.CheckCustomFile(key, out var CombinedPath))
				{
					Handlers.TryGetValue(key, out var value);
					try
					{
						value?.Invoke(CombinedPath);
					}
					catch (Exception msg)
					{
						Log.Error(msg);
					}
					Log.Debug(CombinedPath);
				}
			}
		}

		public void SetupChainedPuzzles(string path)
		{
			Log.Debug("Custom puzzles found");
			ScanHolder = json.Deserialize<ScanHolder>(File.ReadAllText(path));
		}

		public void SetupGlowsticks(string path)
		{
			Log.Debug("Custom glowsticks found");
			GlowstickHolder = json.Deserialize<GlowstickHolder>(File.ReadAllText(path));
			GlowstickHolder.Setup();
		}

		public void SetupTierNames(string path)
		{
			TierNames = json.Deserialize<TierNames>(File.ReadAllText(path));
		}
	}
}
namespace MTFO.HotReload
{
	internal class HotGameDataManager : IHotManager
	{
		public void OnHotReload(int id)
		{
			GameDataInit.ReInitialize();
			Log.Verbose("Reinitialized GameData");
		}
	}
	internal class HotGearManager : IHotManager
	{
		private readonly int gearSlotsTotal = 3;

		public void OnHotReload(int id)
		{
			GearManager.Current.m_offlineSetupDone = false;
			CleanGearIcons();
			CleanGearSlots();
			GearManager.Current.SetupGearContainers();
			LoadOfflineGearDatas();
			GearManager.GenerateAllGearIcons();
			GearManager.Current.m_offlineSetupDone = true;
			Log.Verbose("Reloaded Gear");
		}

		private void CleanGearIcons()
		{
			GearManager.m_allGearWithPostedIconJobs.Clear();
			foreach (Dictionary<uint, RenderTexture> item in (Il2CppArrayBase<Dictionary<uint, RenderTexture>>)(object)GearManager.Current.m_allGearIconTexturesPerInstanceKey)
			{
				item.Clear();
			}
		}

		[Obsolete]
		private void CleanGearLobbySlots()
		{
			if (!((Object)(object)CM_PageLoadout.Current != (Object)null))
			{
				return;
			}
			foreach (CM_InventorySlotItem componentsInChild in ((Component)CM_PageLoadout.Current.m_popupAlign).gameObject.GetComponentsInChildren<CM_InventorySlotItem>(true))
			{
				Object.Destroy((Object)(object)((Component)componentsInChild).gameObject);
			}
		}

		private void CleanGearSlots()
		{
			for (int i = 0; i < gearSlotsTotal; i++)
			{
				((Il2CppArrayBase<List<GearIDRange>>)(object)GearManager.Current.m_gearPerSlot)[i].Clear();
			}
		}

		private void LoadOfflineGearDatas()
		{
			Il2CppArrayBase<PlayerOfflineGearDataBlock> allBlocks = GameDataBlockBase<PlayerOfflineGearDataBlock>.GetAllBlocks();
			if (allBlocks == null)
			{
				Log.Warn("Unable to get Player Offline Gear blocks");
				return;
			}
			Log.Verbose($"Loading {allBlocks.Length} gear");
			foreach (PlayerOfflineGearDataBlock item in allBlocks)
			{
				OfflineGear.Load(item);
			}
		}
	}
	public class HotReloader : MonoBehaviour
	{
		public static HotReloader Current;

		private CM_Item button;

		private readonly string buttonLabel = "Reload Game Data";

		private readonly Vector3 buttonPosition = new Vector3(0f, 77f, 0f);

		private readonly List<IHotManager> managers = new List<IHotManager>();

		public HotReloader(IntPtr intPtr)
			: base(intPtr)
		{
		}//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)


		private void Awake()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			((Component)this).gameObject.transform.localPosition = buttonPosition;
			button = ((Component)this).gameObject.GetComponent<CM_Item>();
			button.SetText(buttonLabel);
			AddOnReloadListener(new HotGameDataManager());
			AddOnReloadListener(new HotRundownManager());
			AddOnReloadListener(new HotGearManager());
			button.OnBtnPressCallback += Action<int>.op_Implicit((Action<int>)delegate
			{
				MTFOHotReloadAPI.HotReloaded();
			});
		}

		public void AddOnReloadListener(IHotManager manager)
		{
			if (!managers.Contains(manager))
			{
				button.OnBtnPressCallback += Action<int>.op_Implicit((Action<int>)manager.OnHotReload);
				managers.Add(manager);
			}
		}

		public void RemoveOnReloadListener(IHotManager manager)
		{
			if (managers.Contains(manager))
			{
				button.OnBtnPressCallback -= Action<int>.op_Implicit((Action<int>)manager.OnHotReload);
				managers.Remove(manager);
			}
		}

		public static void Setup()
		{
			if (!((Object)(object)Current != (Object)null) && !((Object)(object)MainMenuGuiLayer.Current.PageRundownNew == (Object)null))
			{
				GameObject obj = Object.Instantiate<GameObject>(((Component)MainMenuGuiLayer.Current.PageRundownNew.m_discordButton).gameObject, ((Component)MainMenuGuiLayer.Current.PageRundownNew.m_discordButton).transform.parent, false);
				((Object)obj).name = "Button HotReload";
				Current = obj.AddComponent<HotReloader>();
				obj.SetActive(true);
				Log.Verbose("Created hot reload button");
			}
		}
	}
	public class HotReloadInjector
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_PageRundown_New), "OnEnable")]
		public static void OnEnable()
		{
			HotReloader.Setup();
		}
	}
	internal class HotRundownManager : IHotManager
	{
		private CM_PageRundown_New rundownPage;

		private bool hasValidRundown => GameDataBlockBase<RundownDataBlock>.s_blockByID.ContainsKey(Global.RundownIdToLoad);

		private RundownDataBlock rundownDataCurrent => GameDataBlockBase<RundownDataBlock>.GetBlock(Global.RundownIdToLoad);

		public HotRundownManager()
		{
			rundownPage = MainMenuGuiLayer.Current.PageRundownNew;
		}

		public void OnHotReload(int id)
		{
			if (hasValidRundown)
			{
				rundownPage.m_dataIsSetup = false;
				CleanIconsOfTier();
				TryPlaceRundown();
			}
			else
			{
				Log.Warn($"Failed to place the rundown due to missing Rundown id {Global.RundownIdToLoad}");
			}
			Log.Verbose("Reloaded Rundown");
		}

		private void CleanIconsOfTier()
		{
			CleanIconsOfTier(rundownPage.m_expIconsTier1);
			CleanIconsOfTier(rundownPage.m_expIconsTier2);
			CleanIconsOfTier(rundownPage.m_expIconsTier3);
			CleanIconsOfTier(rundownPage.m_expIconsTier4);
			CleanIconsOfTier(rundownPage.m_expIconsTier5);
		}

		private void CleanIconsOfTier(List<CM_ExpeditionIcon_New> tier)
		{
			Enumerator<CM_ExpeditionIcon_New> enumerator = tier.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Object.Destroy((Object)(object)((Component)enumerator.Current).gameObject);
			}
		}

		private void TryPlaceRundown()
		{
			rundownPage.m_currentRundownData = rundownDataCurrent;
			if (rundownPage.m_currentRundownData != null)
			{
				rundownPage.PlaceRundown(rundownPage.m_currentRundownData);
				rundownPage.m_dataIsSetup = true;
			}
			else
			{
				Log.Warn("Unable to place rundown due to null data during reload");
			}
		}
	}
	public interface IHotManager
	{
		void OnHotReload(int id);
	}
	public class OfflineGear
	{
		private GearIDRange gearIDRange;

		private ItemDataBlock itemData;

		private int inventorySlot;

		private uint persistentID;

		private OfflineGear(PlayerOfflineGearDataBlock block)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (TryParseGearJson(block.GearJSON, out gearIDRange))
			{
				gearIDRange.PlayfabItemId = ((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).name;
				gearIDRange.PlayfabItemInstanceId = $"OfflineGear_ID_{((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).persistentID}";
				gearIDRange.OfflineGearType = block.Type;
			}
			if (TryParseGearID(gearIDRange, out itemData, out inventorySlot))
			{
				persistentID = ((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).persistentID;
			}
			else
			{
				Log.Warn($"Unable to construct Offline Gear [{((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).persistentID}] {((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).name}");
			}
		}

		public static void Load(PlayerOfflineGearDataBlock block)
		{
			if (TryParse(block, out var result) && TryStash(result))
			{
				Log.Verbose($"Loaded offline gear [{((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).persistentID}] {((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).name}");
			}
		}

		private static bool TryParse(PlayerOfflineGearDataBlock block, out OfflineGear result)
		{
			//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_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_000b: Invalid comparison between Unknown and I4
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			eOfflineGearType type = block.Type;
			if (type - 1 <= 1)
			{
				result = new OfflineGear(block);
				return true;
			}
			result = null;
			Log.Warn($"Unimplemented Offline Gear Type [{((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).persistentID}] {block.Type}");
			return false;
		}

		private bool TryParseGearID(GearIDRange gearIDRange, out ItemDataBlock itemData, out int inventorySlot)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected I4, but got Unknown
			inventorySlot = 0;
			itemData = null;
			if (gearIDRange == null)
			{
				Log.Warn("Unable to parse GearIDRange due to it being null");
				return false;
			}
			uint compID = gearIDRange.GetCompID((eGearComponent)3);
			itemData = ((compID != 0) ? GameDataBlockBase<ItemDataBlock>.GetBlock(compID) : null);
			if (itemData == null)
			{
				Log.Warn($"Invalid ItemDataBlock for component in offlinear gear [c:{compID}]");
				return false;
			}
			inventorySlot = (int)itemData.inventorySlot;
			return true;
		}

		private bool TryParseGearJson(string gearJson, out GearIDRange gearIDRange)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			if (string.IsNullOrEmpty(gearJson))
			{
				gearIDRange = null;
				Log.Warn("Unable to assign GearIDRange due to null or empty GearJson");
				return false;
			}
			gearIDRange = new GearIDRange(gearJson);
			if (gearIDRange == null)
			{
				return false;
			}
			return true;
		}

		private static bool TryStash(OfflineGear gear)
		{
			if (gear == null)
			{
				Log.Warn("Unable to stash due to null offline gear");
				return false;
			}
			if (gear.gearIDRange == null)
			{
				Log.Warn($"Unable to stash offline gear due to null GearIDRange [{gear.persistentID}]");
				return false;
			}
			if (gear.itemData == null)
			{
				Log.Warn($"Unable to stash offline gear due to null ItemDataBlock [{gear.persistentID}]");
				return false;
			}
			((Il2CppArrayBase<List<GearIDRange>>)(object)GearManager.Current.m_gearPerSlot)[gear.inventorySlot].Add(gear.gearIDRange);
			return true;
		}
	}
}
namespace MTFO.CustomCP
{
	public static class CustomPuzzleManager
	{
		private static readonly Dictionary<uint, CustomBioScan> s_scanMap = new Dictionary<uint, CustomBioScan>();

		private static readonly Dictionary<uint, CustomClusterScan> s_clusterMap = new Dictionary<uint, CustomClusterScan>();

		private static bool s_initialized = false;

		public static bool TryGetScanByID(uint id, out CustomBioScan scan)
		{
			return s_scanMap.TryGetValue(id, out scan);
		}

		public static bool TryGetClusterByID(uint id, out CustomClusterScan cluster)
		{
			return s_clusterMap.TryGetValue(id, out cluster);
		}

		internal static void Initialize(ChainedPuzzleManager manager)
		{
			if (!s_initialized)
			{
				s_initialized = true;
				ClassInjector.RegisterTypeInIl2Cpp<CorePuzzleData>();
				ClassInjector.RegisterTypeInIl2Cpp<ClusterPuzzleData>();
				if (ConfigManager.CustomContent.ScanHolder != null)
				{
					InitScans(manager);
					InitClusters(manager);
				}
			}
		}

		private static void InitScans(ChainedPuzzleManager manager)
		{
			//IL_00fd: 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 ((Object)(object)manager == (Object)null)
			{
				Log.Error("Attempted to initialize custom bioscans with a null ChainedPuzzleManager. This should not happen!");
				throw new NullReferenceException("ChainedPuzzleManager was null");
			}
			foreach (CustomBioScan scan in ConfigManager.CustomContent.ScanHolder.Scans)
			{
				Log.Debug($"Adding scan with ID of [{scan.PersistentID}]");
				if (!manager.m_puzzleComponentPrefabs.ContainsKey(scan.BaseScan))
				{
					Log.Error($"Custom scan with persistent ID {scan.PersistentID} references a non-existing base scan of persistent ID {scan.BaseScan}");
					continue;
				}
				GameObject val = manager.m_puzzleComponentPrefabs[scan.BaseScan];
				if ((Object)(object)val.GetComponent<CP_Bioscan_Core>() == (Object)null)
				{
					Log.Error(string.Format("BaseScan id: {0} does not have {1} component!", scan.PersistentID, "CP_Bioscan_Core"));
					continue;
				}
				GameObject val2 = Object.Instantiate<GameObject>(val);
				val2.transform.position = new Vector3(10000f, 10000f, 10000f);
				CP_PlayerScanner component = val2.GetComponent<CP_PlayerScanner>();
				if ((Object)(object)component != (Object)null)
				{
					component.m_reduceSpeed = scan.ReduceSpeed;
					component.m_reduceWhenNoPlayer = scan.ReduceWhenNoPlayer;
					component.m_scanRadius = scan.ScanRadius;
					component.m_scanSpeeds = Il2CppStructArray<float>.op_Implicit(scan.PlayersInScanMulti);
					component.m_playerRequirement = scan.PlayerRequirement;
				}
				else
				{
					Log.Warn(string.Format("BaseScan id: {0} does not have {1} component! This will make following setting won't work!", scan.BaseScan, "CP_PlayerScanner"));
					Log.Warn(" - ReduceSpeed");
					Log.Warn(" - ReduceWhenNoPlayer");
					Log.Warn(" - ScanRadius");
					Log.Warn(" - PlayersInScanMulti");
					Log.Warn(" - PlayerRequirement");
				}
				CP_Bioscan_Graphics component2 = val2.GetComponent<CP_Bioscan_Graphics>();
				if ((Object)(object)component2 != (Object)null)
				{
					component2.m_radius = scan.BioScanGraphics.Radius;
					component2.m_colors = Il2CppReferenceArray<ColorModeColor>.op_Implicit(ConvertToColorMode(scan.BioScanGraphics.ColorModeColor));
					component2.SetText(scan.BioScanGraphics.ScanText);
				}
				else
				{
					Log.Warn(string.Format("BaseScan id: {0} does not have {1} component! This will make {2} setting won't work!", scan.BaseScan, "CP_Bioscan_Graphics", "BioScanGraphics"));
				}
				val2.GetComponent<CP_Bioscan_Core>().m_playerAgents = new List<PlayerAgent>();
				val2.AddComponent<CorePuzzleData>().PersistentID.Set(scan.PersistentID);
				s_scanMap.Add(scan.PersistentID, scan);
				manager.m_puzzleComponentPrefabs.Add(scan.PersistentID, val2);
			}
		}

		private static void InitClusters(ChainedPuzzleManager manager)
		{
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)manager == (Object)null)
			{
				Log.Error("Attempted to initialize custom clusters with a null ChainedPuzzleManager. This should not happen!");
				throw new NullReferenceException("ChainedPuzzleManager was null");
			}
			foreach (CustomClusterScan cluster in ConfigManager.CustomContent.ScanHolder.Clusters)
			{
				Log.Debug($"Adding cluster with ID of [{cluster.PersistentID}]");
				if (!manager.m_puzzleComponentPrefabs.ContainsKey(cluster.BaseCluster))
				{
					Log.Error($"Custom cluster scan with persistent ID {cluster.PersistentID} references a non-existing base cluster of persistent ID {cluster.BaseCluster}");
					continue;
				}
				if (!manager.m_puzzleComponentPrefabs.ContainsKey(cluster.BioscanID))
				{
					Log.Error($"Custom cluster scan with persistent ID {cluster.PersistentID} references a non-existing bioscan of persistent ID {cluster.BioscanID}");
					continue;
				}
				GameObject val = manager.m_puzzleComponentPrefabs[cluster.BaseCluster];
				if ((Object)(object)val.GetComponent<CP_Cluster_Core>() == (Object)null)
				{
					Log.Error(string.Format("BaseScan id: {0} does not have {1} component!", cluster.PersistentID, "CP_Cluster_Core"));
					continue;
				}
				GameObject val2 = Object.Instantiate<GameObject>(val);
				val2.transform.position = new Vector3(1000f, 1000f, 1000f);
				CP_Cluster_Core component = val2.GetComponent<CP_Cluster_Core>();
				GameObject childPuzzlePrefab = manager.m_puzzleComponentPrefabs[cluster.BioscanID];
				component.m_amountOfPuzzles = cluster.ClusterCount;
				component.m_childPuzzlePrefab = childPuzzlePrefab;
				component.m_distanceBetween = cluster.DistanceBetweenScans;
				component.m_revealWithHoloPath = cluster.RevealWithHoloPath;
				val2.AddComponent<ClusterPuzzleData>().PersistentID.Set(cluster.PersistentID);
				s_clusterMap.Add(cluster.PersistentID, cluster);
				manager.m_puzzleComponentPrefabs.Add(cluster.PersistentID, val2);
			}
		}

		private static ColorModeColor[] ConvertToColorMode(CustomBioScan.BioScanColorByMode[] bioScanColorByModes)
		{
			//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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			ColorModeColor[] array = (ColorModeColor[])(object)new ColorModeColor[bioScanColorByModes.Length];
			for (int i = 0; i < bioScanColorByModes.Length; i++)
			{
				CustomBioScan.BioScanColorByMode bioScanColorByMode = bioScanColorByModes[i];
				array[i] = new ColorModeColor
				{
					col = new Color(bioScanColorByMode.R, bioScanColorByMode.G, bioScanColorByMode.B, bioScanColorByMode.A),
					mode = bioScanColorByMode.Mode
				};
			}
			return array;
		}
	}
}
namespace MTFO.CustomCP.Patches
{
	[HarmonyPatch(typeof(ChainedPuzzleManager), "OnAssetsLoaded")]
	internal static class Patch_PuzzleManager
	{
		internal static void Postfix(ChainedPuzzleManager __instance)
		{
			CustomPuzzleManager.Initialize(__instance);
		}
	}
	[HarmonyPatch(typeof(CP_Bioscan_Core), "Update")]
	internal static class FixNullRefSpam
	{
		internal static bool Prefix(CP_Bioscan_Core __instance)
		{
			//IL_000b: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			if (((Component)__instance).gameObject.transform.position.x > 9000f && ((Component)__instance).gameObject.transform.position.y > 9000f && ((Component)__instance).gameObject.transform.position.z > 9000f)
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class Patch_SetupPuzzleCores
	{
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(CP_Bioscan_Core), "Setup")]
		public static void SetupSpline(CP_Bioscan_Core __instance)
		{
			CorePuzzleData component = ((Component)__instance).GetComponent<CorePuzzleData>();
			if (!((Object)(object)component == (Object)null) && CustomPuzzleManager.TryGetScanByID(component.PersistentID.Value, out var scan))
			{
				CP_Holopath_Spline val = ((Il2CppObjectBase)__instance.m_spline).TryCast<CP_Holopath_Spline>();
				if ((Object)(object)val != (Object)null)
				{
					scan.ApplySplineRevealSpeed(val);
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(CP_Cluster_Core), "Setup")]
		public static void SetupSpline(CP_Cluster_Core __instance)
		{
			ClusterPuzzleData component = ((Component)__instance).GetComponent<ClusterPuzzleData>();
			if (!((Object)(object)component == (Object)null) && CustomPuzzleManager.TryGetClusterByID(component.PersistentID.Value, out var cluster))
			{
				CP_Holopath_Spline val = ((Il2CppObjectBase)__instance.m_spline).TryCast<CP_Holopath_Spline>();
				if ((Object)(object)val != (Object)null)
				{
					cluster.ApplySplineRevealSpeed(val);
				}
			}
		}
	}
}
namespace MTFO.Custom
{
	public class GlowstickHolder
	{
		[JsonIgnore]
		public Dictionary<string, CustomGlowstick> GlowstickLookup;

		public List<GlowstickConfig> Glowsticks { get; set; }

		public void Setup()
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			GlowstickLookup = new Dictionary<string, CustomGlowstick>();
			foreach (GlowstickConfig glowstick in Glowsticks)
			{
				Log.Verbose(glowstick);
				if (GlowstickLookup.TryGetValue(glowstick.Name, out var value))
				{
					Log.Warn("Custom glowstick with name " + glowstick.Name + " already exists in the lookup! Skipping...");
					continue;
				}
				value = default(CustomGlowstick);
				value.Color = new Color(glowstick.r, glowstick.g, glowstick.b, (glowstick.a == 0f) ? 1f : glowstick.a);
				value.Range = ((glowstick.Range == 0f) ? 15f : glowstick.Range);
				CustomGlowstick value2 = value;
				GlowstickLookup.Add(glowstick.Name, value2);
			}
		}
	}
	public struct CustomGlowstick
	{
		public Color Color { get; set; }

		public float Range { get; set; }
	}
	public struct GlowstickConfig
	{
		public string Name { get; set; }

		public float Range { get; set; }

		public float r { get; set; }

		public float g { get; set; }

		public float b { get; set; }

		public float a { get; set; }

		public override string ToString()
		{
			return $"{Name},{Range},{r},{g},{b},{a}";
		}
	}
	public class ScanHolder
	{
		public List<CustomBioScan> Scans { get; set; }

		public List<CustomClusterScan> Clusters { get; set; }
	}
	public enum RevealMode
	{
		ScaleByDistance,
		ConstantTime,
		Instant
	}
	public struct CustomBioScan : IRevealableScanConfig
	{
		public struct BioScanGx
		{
			public bool HideScanText { get; set; }

			public string ScanText { get; set; }

			public float Radius { get; set; }

			public BioScanColorByMode[] ColorModeColor { get; set; }
		}

		public class BioScanColorByMode
		{
			public eChainedPuzzleGraphicsColorMode Mode { get; set; }

			public float R { get; set; }

			public float G { get; set; }

			public float B { get; set; }

			public float A { get; set; }
		}

		public uint BaseScan { get; set; }

		public uint PersistentID { get; set; }

		public PlayerRequirement PlayerRequirement { get; set; }

		public float ScanRadius { get; set; }

		public float[] PlayersInScanMulti { get; set; }

		public float ReduceSpeed { get; set; }

		public bool ReduceWhenNoPlayer { get; set; }

		public float RevealTime { get; set; }

		public RevealMode RevealMode { get; set; }

		public BioScanGx BioScanGraphics { get; set; }
	}
	public struct CustomClusterScan : IRevealableScanConfig
	{
		public uint BaseCluster { get; set; }

		public uint PersistentID { get; set; }

		public int ClusterCount { get; set; }

		public uint BioscanID { get; set; }

		public float DistanceBetweenScans { get; set; }

		public float RevealTime { get; set; }

		public RevealMode RevealMode { get; set; }

		public bool RevealWithHoloPath { get; set; }
	}
	internal interface IRevealableScanConfig
	{
		uint PersistentID { get; }

		float RevealTime { get; }

		RevealMode RevealMode { get; }
	}
	internal static class IRevealibleScanConfigExtensions
	{
		public static void ApplySplineRevealSpeed(this IRevealableScanConfig scan, CP_Holopath_Spline spline)
		{
			float revealTime = scan.RevealTime;
			switch (scan.RevealMode)
			{
			case RevealMode.ConstantTime:
				if (revealTime <= 0f)
				{
					Log.Warn($"Attempted to set a custom scan with persistent id '{scan.PersistentID}' to reveal in less than or equal to 0 seconds. This is not supported. Instead, use RevealMode \"{RevealMode.Instant}\" or integer value {2}");
					break;
				}
				spline.m_splineLength = 1f;
				spline.m_revealSpeed = revealTime;
				break;
			case RevealMode.ScaleByDistance:
				if (revealTime < 0f)
				{
					Log.Warn($"Attempted to set a custom scan with persistent id '{scan.PersistentID}' to reveal in less than 0 seconds. This is not supported.");
				}
				else if (revealTime != 0f)
				{
					spline.m_revealSpeed = revealTime;
				}
				break;
			case RevealMode.Instant:
				spline.m_revealSpeed = -1f;
				break;
			}
		}
	}
	public struct TierNames
	{
		public string Tier1 { get; set; }

		public string Tier2 { get; set; }

		public string Tier3 { get; set; }

		public string Tier4 { get; set; }

		public string Tier5 { get; set; }
	}
}
namespace MTFO.Custom.CCP.Patches
{
	[HarmonyPatch(typeof(CP_Bioscan_Hud))]
	internal static class Patch_Bioscan_Hud
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		internal static void Post_Setup(CP_Bioscan_Hud __instance)
		{
			UpdateText(__instance);
		}

		[HarmonyPatch("SetVisible")]
		[HarmonyPostfix]
		internal static void Post_SetVisible(CP_Bioscan_Hud __instance)
		{
			UpdateText(__instance);
		}

		[HarmonyPatch("UpdateText")]
		[HarmonyPostfix]
		internal static void Post_UpdateText(CP_Bioscan_Hud __instance)
		{
			UpdateText(__instance);
		}

		private static void UpdateText(CP_Bioscan_Hud hud)
		{
			CorePuzzleData component = ((Component)hud).gameObject.GetComponent<CorePuzzleData>();
			if ((Object)(object)component != (Object)null)
			{
				if (!CustomPuzzleManager.TryGetScanByID(component.PersistentID.Value, out var scan))
				{
					Log.Error($"scanData missing... {component.PersistentID.Value}");
				}
				else if (scan.BioScanGraphics.HideScanText)
				{
					((TMP_Text)hud.m_bioscanWorldText).SetText(string.Empty, true);
				}
				else if (!string.IsNullOrWhiteSpace(scan.BioScanGraphics.ScanText))
				{
					((TMP_Text)hud.m_bioscanWorldText).SetText(scan.BioScanGraphics.ScanText, true);
				}
			}
		}
	}
}
namespace MTFO.Custom.CCP.Components
{
	internal sealed class ClusterPuzzleData : MonoBehaviour
	{
		public Il2CppValueField<uint> PersistentID;

		public CP_Bioscan_Hud[] ChildHuds = Array.Empty<CP_Bioscan_Hud>();
	}
	internal sealed class CorePuzzleData : MonoBehaviour
	{
		public Il2CppValueField<uint> PersistentID;
	}
}
namespace MTFO.API
{
	public delegate void GameDataContentLoadEvent(string datablockName, string jsonContent, in List<string> jsonItemsToInject);
	public delegate void GameDataContentLoadedDelegate(string datablockName, string jsonContent);
	public static class MTFOGameDataAPI
	{
		public static event GameDataContentLoadEvent OnGameDataContentLoad;

		public static event GameDataContentLoadedDelegate OnGameDataContentLoaded;

		internal static void Invoke_OnGameDataContentLoad(string datablockName, Stream jsonContentStream, in List<string> jsonItemsToInject)
		{
			if (MTFOGameDataAPI.OnGameDataContentLoad != null)
			{
				MTFOGameDataAPI.OnGameDataContentLoad(datablockName, new StreamReader(jsonContentStream).ReadToEnd(), in jsonItemsToInject);
			}
		}

		internal static void Invoke_OnGameDataContentLoaded(string datablockName, string jsonContent)
		{
			MTFOGameDataAPI.OnGameDataContentLoaded?.Invoke(datablockName, jsonContent);
		}
	}
	public static class MTFOHotReloadAPI
	{
		public static bool HotReloadEnabled => ConfigManager.IsHotReloadEnabled;

		public static event Action OnHotReload;

		internal static void HotReloaded()
		{
			MTFOHotReloadAPI.OnHotReload?.Invoke();
		}
	}
	public static class MTFOPathAPI
	{
		public static string RundownPath => ConfigManager.GameDataPath;

		public static bool HasRundownPath => ConfigManager.HasGameDataPath;

		public static string CustomPath => ConfigManager.CustomPath;

		public static bool HasCustomPath => ConfigManager.HasCustomContent;
	}
}

plugins/Dakstar-VideoReplacerReupload/VideoReplacerReupload.dll

Decompiled 7 hours ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CellMenu;
using Globals;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine.Video;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("VideoReplacerReupload")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("VideoReplacerReupload")]
[assembly: AssemblyTitle("VideoReplacerReupload")]
[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;
		}
	}
}
public class VideoFile
{
	public static string RootPath = Path.Combine(Paths.BepInExRootPath, "Assets", "Video");

	public string TargetPath;

	public bool IsAvailable;

	public VideoFile(string path)
	{
		TargetPath = Path.Combine(RootPath, path);
		IsAvailable = File.Exists(TargetPath);
	}
}
public static class VideoPlayerExtension
{
	public static void Replace(this VideoPlayer videoPlayer, VideoFile videoFile)
	{
		if (videoFile.IsAvailable)
		{
			videoPlayer.url = videoFile.TargetPath;
		}
	}
}
namespace VideoReplacerReupload
{
	internal static class Patch
	{
		[HarmonyPatch(typeof(Global), "OnGlobalSceneManagerLinksLoaded")]
		[HarmonyPostfix]
		public static void Patch2(GlobalSceneManagerLinks links)
		{
			MainMenuGuiLayer.Current.PageIntro.m_bgScare1.Replace(new VideoFile("Intro1.mp4"));
			MainMenuGuiLayer.Current.PageIntro.m_bgScare2.Replace(new VideoFile("Intro2.mp4"));
			MainMenuGuiLayer.Current.PageIntro.m_bgScare3.Replace(new VideoFile("Intro3.mp4"));
			MainMenuGuiLayer.Current.PageCredits.video.Replace(new VideoFile("Credits.mp4"));
		}
	}
	internal static class Patch_CM_PageCredits
	{
		[HarmonyPatch(typeof(CM_PageCredits), "Update")]
		[HarmonyPostfix]
		public static void Patch(CM_PageCredits __instance)
		{
			__instance.video.Play();
		}
	}
	[BepInPlugin("VideoReplacerReupload", "VideoReplacerReupload", "1.0.0")]
	public class VideoReplacerReupload : BasePlugin
	{
		public override void Load()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(17, 0, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin is loaded!");
			}
			log.LogInfo(val);
			Harmony.CreateAndPatchAll(typeof(Patch), "VideoReplacerReupload");
		}
	}
}

plugins/Dinorush-EnemyAnimationFix/EnemyAnimationFix.dll

Decompiled 7 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using AIGraph;
using Agents;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using Enemies;
using EnemyAnimationFix.API;
using EnemyAnimationFix.NativePatches;
using EnemyAnimationFix.Networking.Notify;
using EnemyAnimationFix.Patches;
using GTFO.API;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.Class;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.MethodInfo;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using SNetwork;
using StateMachines;
using UnityEngine;

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

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace EnemyAnimationFix
{
	[BepInPlugin("Dinorush.EnemyAnimationFix", "EnemyAnimationFix", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal sealed class EntryPoint : BasePlugin
	{
		public const string MODNAME = "EnemyAnimationFix";

		public override void Load()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			((BasePlugin)this).Log.LogMessage((object)"Loading EnemyAnimationFix");
			new Harmony("EnemyAnimationFix").PatchAll();
			ChangeStatePatches.ApplyNativePatch();
			AssetAPI.OnStartupAssetsLoaded += AssetAPI_OnStartupAssetsLoaded;
			LevelAPI.OnLevelCleanup += LevelAPI_OnLevelCleanup;
			((BasePlugin)this).Log.LogMessage((object)"Loaded EnemyAnimationFix");
		}

		private void AssetAPI_OnStartupAssetsLoaded()
		{
			NotifyManager.Init();
		}

		private void LevelAPI_OnLevelCleanup()
		{
			EB_InCombat.s_globalScreamTimer = 0f;
		}
	}
}
namespace EnemyAnimationFix.Utils
{
	internal static class DinoLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("EnemyAnimationFix");

		public static void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		public static void Log(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)8, (object)str);
			}
		}

		public static void Warning(string format, params object[] args)
		{
			Warning(string.Format(format, args));
		}

		public static void Warning(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)4, (object)str);
			}
		}

		public static void Error(string format, params object[] args)
		{
			Error(string.Format(format, args));
		}

		public static void Error(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)2, (object)str);
			}
		}

		public static void Debug(string format, params object[] args)
		{
			Debug(string.Format(format, args));
		}

		public static void Debug(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)32, (object)str);
			}
		}
	}
}
namespace EnemyAnimationFix.Patches
{
	[HarmonyPatch]
	internal static class EnemyAttackPatches
	{
		[HarmonyPatch(typeof(ES_StrikerAttack), "OnAttackPerform")]
		[HarmonyPostfix]
		private static void Post_StrikerAttackPerform(ES_StrikerAttack __instance)
		{
			__instance.m_tentacleAbility.m_tentacle.m_inAttackMove = true;
		}

		[HarmonyPatch(typeof(ES_ShooterAttack), "OnAttackPerform")]
		[HarmonyPostfix]
		private static void Post_ShooterAttackPerform(ES_ShooterAttack __instance)
		{
			if (!(((ES_EnemyAttackBase)__instance).m_attackDoneTimer >= Clock.Time))
			{
				EAB_ProjectileShooter projectileAbility = __instance.m_projectileAbility;
				((ES_EnemyAttackBase)__instance).m_attackDoneTimer = Clock.Time + (projectileAbility.m_shotDelayMin + projectileAbility.m_shotDelayMax) / 2f * (float)projectileAbility.m_burstCount * 0.7f + __instance.m_burstCoolDownBeforeExit;
			}
		}

		[HarmonyPatch(typeof(ES_StrikerAttack), "CommonExit")]
		[HarmonyPostfix]
		private static void Post_StrikerAttackExit(ES_StrikerAttack __instance)
		{
			if (NotifyManager.MasterHasFix && !(Clock.Time <= ((ES_EnemyAttackBase)__instance).m_performAttackTimer))
			{
				MovingEnemyTentacleBase tentacle = __instance.m_tentacleAbility.m_tentacle;
				if (tentacle.m_currentRoutine != null)
				{
					tentacle.SwitchCoroutine(tentacle.AttackIn(tentacle.m_attackInDuration));
				}
			}
		}

		[HarmonyPatch(typeof(ES_PathMove), "Exit")]
		[HarmonyPostfix]
		private static void Post_TankPathMoveExit(ES_PathMove __instance)
		{
			if (NotifyManager.MasterHasFix)
			{
				EnemyAbilities abilities = ((ES_Base)__instance).m_enemyAgent.Abilities;
				if (!ResetTankTongues(abilities, (AgentAbility)2))
				{
					ResetTankTongues(abilities, (AgentAbility)1);
				}
			}
		}

		private static bool ResetTankTongues(EnemyAbilities abilities, AgentAbility abilityType)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			EnemyAbility ability = abilities.GetAbility(abilityType, 0);
			if ((Object)(object)ability == (Object)null)
			{
				return false;
			}
			EAB_MovingEnemyTentacleMultiple val = ((Il2CppObjectBase)ability).TryCast<EAB_MovingEnemyTentacleMultiple>();
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			foreach (MovingEnemyTentacleBase item in (Il2CppArrayBase<MovingEnemyTentacleBase>)(object)val.m_tentacles)
			{
				if (item.m_currentRoutine != null)
				{
					item.SwitchCoroutine(item.AttackIn(item.m_attackInDuration));
				}
			}
			return true;
		}

		[HarmonyPatch(typeof(ES_ShooterAttack), "CommonExit")]
		[HarmonyPostfix]
		private static void Post_ShooterAttackExit(ES_ShooterAttack __instance)
		{
			if (NotifyManager.MasterHasFix && !(Clock.Time <= ((ES_EnemyAttackBase)__instance).m_performAttackTimer))
			{
				__instance.m_projectileAbility.FireEnd();
			}
		}
	}
	[HarmonyPatch]
	internal static class EnemyMovementPatches
	{
		private const float MinBufferTime = 0.1f;

		private static float _exitTime;

		private static bool _hasExited;

		internal static bool Pre_ChangeState(StateMachine<ES_Base> _, ES_Base newState)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Invalid comparison between Unknown and I4
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			bool hasExited = _hasExited;
			_hasExited = false;
			if (SNet.IsMaster || (int)newState.m_stateEnum != 2 || Clock.Time - _exitTime > 0.1f)
			{
				return true;
			}
			ES_PathMove val = ((Il2CppObjectBase)newState).Cast<ES_PathMove>();
			if (val.m_positionBuffer.Count == 0)
			{
				return true;
			}
			if (!hasExited)
			{
				return true;
			}
			EnemyAgent enemyAgent = ((ES_Base)val).m_enemyAgent;
			PositionSnapshotBuffer<pES_PathMoveData> positionBuffer = val.m_positionBuffer;
			ForcePosition(enemyAgent, val, positionBuffer[positionBuffer.Count - 1]);
			return false;
		}

		[HarmonyPatch(typeof(ES_PathMove), "Exit")]
		[HarmonyPrefix]
		private static void Pre_Exit(ES_PathMove __instance)
		{
			//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)
			//IL_0042: 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_0066: 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_00dc: 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_00e4: 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)
			_hasExited = true;
			_exitTime = Clock.Time;
			EnemyAgent enemyAgent = ((ES_Base)__instance).m_enemyAgent;
			pES_PathMoveData val;
			if (SNet.IsMaster)
			{
				val = __instance.m_pathMoveData;
				((pCourseNode)(ref val.CourseNode)).Set(((Agent)enemyAgent).CourseNode);
				val.Position = enemyAgent.Position;
				((LowResVector3_NoY)(ref val.Movement)).Set(__instance.m_moveDir, 1f);
				((LowResVector3_NoY_Normalized)(ref val.TargetLookDir)).Value = ((Agent)enemyAgent).TargetLookDir;
				val.Tick++;
				__instance.m_pathMoveData = val;
				{
					foreach (SNet_Player fixedClient in NotifyManager.FixedClients)
					{
						__instance.m_pathMovePacket.Send(val, (SNet_ChannelType)4, fixedClient);
					}
					return;
				}
			}
			if (__instance.m_positionBuffer.Count != 0)
			{
				PositionSnapshotBuffer<pES_PathMoveData> positionBuffer = __instance.m_positionBuffer;
				val = positionBuffer[positionBuffer.Count - 1];
				ForcePosition(enemyAgent, __instance, val);
			}
		}

		private static void ForcePosition(EnemyAgent enemy, ES_PathMove pathMove, pES_PathMoveData data)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			((Component)enemy).transform.position = enemy.Position;
			enemy.MovingCuller.UpdatePosition(((Agent)enemy).DimensionIndex, enemy.Position);
			enemy.Position = data.Position;
			((ES_PathMoveBase)pathMove).m_lastPos = data.Position;
			enemy.Locomotion.ForceNode(data.CourseNode);
			pathMove.m_targetPosition = data.Position;
			pathMove.m_moveDir = ((LowResVector3_NoY)(ref data.Movement)).Get(1f);
			((Agent)enemy).TargetLookDir = ((LowResVector3_NoY_Normalized)(ref data.TargetLookDir)).Value;
			((ES_PathMoveBase)pathMove).UpdateRotation();
			((ES_PathMoveBase)pathMove).UpdateLocalAnimator();
			pathMove.UpdateAnimationBlend(((ES_PathMoveBase)pathMove).m_animFwd, ((ES_PathMoveBase)pathMove).m_animRight, false);
		}
	}
	[HarmonyPatch]
	internal static class EnemyScreamPatches
	{
		[HarmonyPatch(typeof(ES_Scream), "Enter")]
		[HarmonyPostfix]
		private static void FixScreamReset(ES_Scream __instance)
		{
			__instance.m_hasTriggeredPropagation = false;
		}
	}
	[HarmonyPatch]
	internal static class EnemyTargetPatches
	{
		[HarmonyPatch(typeof(EnemyUpdateManager), "MasterMindUpdateFixed")]
		[HarmonyPostfix]
		private static void PostManagerUpdate(EnemyUpdateManager __instance)
		{
			ForceIntervalUpdate(__instance.m_detectionUpdatesClose);
			ForceIntervalUpdate(__instance.m_detectionUpdatesNear);
			ForceIntervalUpdate(__instance.m_detectionUpdatesFar);
		}

		private static void ForceIntervalUpdate(UpdateDetectionGroup group)
		{
			Enumerator<EnemyBehaviour> enumerator = ((SteppedUpdateGroup<EnemyBehaviour>)(object)group).m_members.GetEnumerator();
			while (enumerator.MoveNext())
			{
				enumerator.Current.m_ai.m_enemyAgent.m_validTargetInterval = 0f;
			}
		}
	}
	[HarmonyPatch]
	internal static class NetworkingPatches
	{
		[HarmonyPatch(typeof(SNet_SyncManager), "OnFoundMaster")]
		[HarmonyPatch(typeof(SNet_SyncManager), "OnFoundNewMasterDuringMigration")]
		[HarmonyPostfix]
		private static void Post_Joined()
		{
			if (!SNet.IsMaster)
			{
				NotifyManager.SendNotify(SNet.Master);
			}
			else
			{
				NotifyManager.SetMaster();
			}
		}

		[HarmonyPatch(typeof(SNet_SyncManager), "OnPlayerJoinedSessionHub")]
		[HarmonyPostfix]
		private static void Post_Joined(SNet_Player player)
		{
			if (SNet.IsMaster && !player.IsLocal)
			{
				NotifyManager.SendNotify(player);
			}
		}

		[HarmonyPatch(typeof(SNet_SessionHub), "OnLeftLobby")]
		[HarmonyPatch(typeof(SNet_SessionHub), "RemovePlayerFromSession")]
		[HarmonyPrefix]
		private static void Pre_Eject(SNet_Player player)
		{
			if (SNet.IsMaster)
			{
				NotifyManager.RemoveClient(player);
			}
		}

		[HarmonyPatch(typeof(SNet_SyncManager), "OnResetSession")]
		[HarmonyPrefix]
		private static void Pre_OnReset()
		{
			NotifyManager.Reset();
		}
	}
}
namespace EnemyAnimationFix.Networking
{
	public abstract class SyncedEvent<T> where T : struct
	{
		public delegate void ReceiveHandler(T packet);

		private bool _isSetup;

		public abstract string GUID { get; }

		public bool IsSetup => _isSetup;

		public string EventName { get; private set; } = string.Empty;


		public event ReceiveHandler? OnReceive;

		public event ReceiveHandler? OnReceiveLocal;

		public void Setup()
		{
			if (!_isSetup)
			{
				EventName = "EWC" + GUID;
				NetworkAPI.RegisterEvent<T>(EventName, (Action<ulong, T>)ReceiveClient_Callback);
				_isSetup = true;
			}
		}

		public void Send(T packetData, SNet_Player? target = null, SNet_ChannelType priority = 4)
		{
			//IL_0020: 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)
			if ((Object)(object)target != (Object)null)
			{
				NetworkAPI.InvokeEvent<T>(EventName, packetData, target, priority);
			}
			else
			{
				NetworkAPI.InvokeEvent<T>(EventName, packetData, priority);
			}
			ReceiveLocal_Callback(packetData);
		}

		private void ReceiveLocal_Callback(T packet)
		{
			ReceiveLocal(packet);
			this.OnReceiveLocal?.Invoke(packet);
		}

		private void ReceiveClient_Callback(ulong sender, T packet)
		{
			Receive(packet);
			this.OnReceive?.Invoke(packet);
		}

		protected virtual void ReceiveLocal(T packet)
		{
		}

		protected virtual void Receive(T packet)
		{
		}
	}
}
namespace EnemyAnimationFix.Networking.Notify
{
	internal static class NotifyManager
	{
		private static readonly NotifySync Sync = new NotifySync();

		public static readonly List<SNet_Player> FixedClients = new List<SNet_Player>();

		public static bool MasterHasFix { get; private set; } = false;


		internal static void Init()
		{
			Sync.Setup();
		}

		internal static void SendNotify(SNet_Player player)
		{
			Sync.Send(new NotifyData
			{
				lookup = SNet.LocalPlayer.Lookup
			}, player, (SNet_ChannelType)4);
		}

		internal static void ReceiveNotify(SNet_Player player)
		{
			if (SNet.IsMaster)
			{
				FixedClients.Add(player);
			}
			else
			{
				MasterHasFix = true;
			}
		}

		internal static void SetMaster()
		{
			MasterHasFix = true;
		}

		internal static void Reset()
		{
			MasterHasFix = false;
			FixedClients.Clear();
		}

		internal static void RemoveClient(SNet_Player player)
		{
			for (int num = FixedClients.Count - 1; num >= 0; num--)
			{
				if ((Object)(object)FixedClients[num] == (Object)null || FixedClients[num].Lookup == player.Lookup)
				{
					FixedClients.RemoveAt(num);
				}
			}
		}
	}
	internal sealed class NotifySync : SyncedEvent<NotifyData>
	{
		public override string GUID => "EAFNF";

		protected override void Receive(NotifyData packet)
		{
			SNet_Player player = default(SNet_Player);
			if (SNet.TryGetPlayer(packet.lookup, ref player))
			{
				NotifyManager.ReceiveNotify(player);
			}
		}
	}
	public struct NotifyData
	{
		public ulong lookup;
	}
}
namespace EnemyAnimationFix.NativePatches
{
	internal static class ChangeStatePatches
	{
		private unsafe delegate void d_ChangeStateFromQueue(IntPtr _this, Il2CppMethodInfo* methodInfo);

		private static INativeDetour? ChangeStateDetour;

		private static d_ChangeStateFromQueue? orig_ChangeStateFromQueue;

		internal unsafe static void ApplyNativePatch()
		{
			NativePatchAPI.AddChangeStatePrefix(FixMeleeCancel);
			NativePatchAPI.AddChangeStatePrefix(EnemyMovementPatches.Pre_ChangeState);
			INativeClassStruct val = UnityVersionHandler.Wrap((Il2CppClass*)(void*)Il2CppClassPointerStore<StateMachine<ES_Base>>.NativeClassPtr);
			for (int i = 0; i < val.MethodCount; i++)
			{
				INativeMethodInfoStruct val2 = UnityVersionHandler.Wrap(val.Methods[i]);
				if (Marshal.PtrToStringAnsi(val2.Name) == "ChangeStateFromQueue")
				{
					ChangeStateDetour = INativeDetour.CreateAndApply<d_ChangeStateFromQueue>(val2.MethodPointer, (d_ChangeStateFromQueue)ChangeStatePatch, ref orig_ChangeStateFromQueue);
					break;
				}
			}
		}

		private unsafe static void ChangeStatePatch(IntPtr _this, Il2CppMethodInfo* methodInfo)
		{
			StateMachine<ES_Base> val = new StateMachine<ES_Base>(_this);
			if (val.CurrentState == null)
			{
				orig_ChangeStateFromQueue(_this, methodInfo);
				return;
			}
			ES_Base state = val.m_stateQueue.Peek();
			if (NativePatchAPI.RunChangeStatePrefix(val, state))
			{
				orig_ChangeStateFromQueue(_this, methodInfo);
			}
			else
			{
				val.m_stateQueue.Dequeue();
			}
			NativePatchAPI.RunChangeStatePostfix(val, state);
		}

		private static bool FixMeleeCancel(StateMachine<ES_Base> __instance, ES_Base newState)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			ES_Base currentState = __instance.CurrentState;
			if (!NotifyManager.MasterHasFix || (int)newState.m_stateEnum != 2 || (int)currentState.m_stateEnum != 23)
			{
				return true;
			}
			ES_StrikerMelee val = ((Il2CppObjectBase)currentState).Cast<ES_StrikerMelee>();
			return (Clock.Time - val.m_startTime) * val.m_animSpeed >= val.m_attackData.Duration;
		}
	}
}
namespace EnemyAnimationFix.API
{
	public static class NativePatchAPI
	{
		public delegate bool ChangeStatePrefix(StateMachine<ES_Base> __instance, ES_Base state);

		public delegate void ChangeStatePostfix(StateMachine<ES_Base> __instance, ES_Base state);

		private static readonly List<ChangeStatePrefix> s_changePrefix = new List<ChangeStatePrefix>();

		private static readonly List<ChangeStatePostfix> s_changePostfix = new List<ChangeStatePostfix>();

		public static void AddChangeStatePrefix(ChangeStatePrefix detectPrefix)
		{
			s_changePrefix.Add(detectPrefix);
		}

		public static void AddChangeStatePostfix(ChangeStatePostfix detectPostfix)
		{
			s_changePostfix.Add(detectPostfix);
		}

		internal static bool RunChangeStatePrefix(StateMachine<ES_Base> __instance, ES_Base state)
		{
			bool flag = true;
			foreach (ChangeStatePrefix item in s_changePrefix)
			{
				flag &= item(__instance, state);
			}
			return flag;
		}

		internal static void RunChangeStatePostfix(StateMachine<ES_Base> __instance, ES_Base state)
		{
			foreach (ChangeStatePostfix item in s_changePostfix)
			{
				item(__instance, state);
			}
		}
	}
}

plugins/Dinorush-ExtraToolCustomization/ExtraToolCustomization.dll

Decompiled 7 hours ago
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CellMenu;
using ExtraToolCustomization.Dependencies;
using ExtraToolCustomization.JSON;
using ExtraToolCustomization.Networking.MineDeployer;
using ExtraToolCustomization.Patches;
using ExtraToolCustomization.ToolData;
using ExtraToolCustomization.ToolData.Templates;
using ExtraToolCustomization.Utils;
using GTFO.API;
using GTFO.API.JSON.Converters;
using GTFO.API.Utilities;
using GameData;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ExtraToolCustomization")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+3897628d5d352ad3128662cc02a786688b8718b5")]
[assembly: AssemblyProduct("ExtraToolCustomization")]
[assembly: AssemblyTitle("ExtraToolCustomization")]
[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 ExtraToolCustomization
{
	[BepInPlugin("Dinorush.ExtraToolCustomization", "ExtraToolCustomization", "1.2.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal sealed class EntryPoint : BasePlugin
	{
		public const string MODNAME = "ExtraToolCustomization";

		public override void Load()
		{
			//IL_003e: 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)
			((BasePlugin)this).Log.LogMessage((object)"Loading ExtraToolCustomization");
			if (MTFOWrapper.HasMTFO && MTFOWrapper.HasCustomContent)
			{
				new Harmony("ExtraToolCustomization").PatchAll();
				ToolDataManager.Current.Init();
			}
			else
			{
				new Harmony("ExtraToolCustomization").PatchAll(typeof(SentryGunPatches_BurstFix));
			}
			((BasePlugin)this).Log.LogMessage((object)"Loaded ExtraToolCustomization");
		}
	}
}
namespace ExtraToolCustomization.Utils
{
	internal static class DinoLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("ExtraToolCustomization");

		public static void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		public static void Log(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)8, (object)str);
			}
		}

		public static void Warning(string format, params object[] args)
		{
			Warning(string.Format(format, args));
		}

		public static void Warning(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)4, (object)str);
			}
		}

		public static void Error(string format, params object[] args)
		{
			Error(string.Format(format, args));
		}

		public static void Error(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)2, (object)str);
			}
		}

		public static void Debug(string format, params object[] args)
		{
			Debug(string.Format(format, args));
		}

		public static void Debug(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)32, (object)str);
			}
		}
	}
	internal static class GearIDRangeExtensions
	{
		public static uint GetOfflineID(this GearIDRange gearIDRange)
		{
			string playfabItemInstanceId = gearIDRange.PlayfabItemInstanceId;
			if (!playfabItemInstanceId.Contains("OfflineGear_ID_"))
			{
				DinoLogger.Error("Find PlayfabItemInstanceId without substring 'OfflineGear_ID_'! " + playfabItemInstanceId);
				return 0u;
			}
			try
			{
				return uint.Parse(playfabItemInstanceId.Substring("OfflineGear_ID_".Length));
			}
			catch
			{
				DinoLogger.Error("Caught exception while trying to parse persistentID of PlayerOfflineGearDB from GearIDRange, which means itemInstanceId could be ill-formated");
				return 0u;
			}
		}
	}
}
namespace ExtraToolCustomization.ToolData
{
	public interface IToolData
	{
		uint OfflineID { get; set; }

		uint ItemID { get; set; }

		uint ArchetypeID { get; set; }

		string Name { get; set; }
	}
	public sealed class MineData : IToolData
	{
		public uint OfflineID { get; set; }

		public uint ItemID { get; set; }

		[JsonIgnore]
		public uint ArchetypeID { get; set; }

		public string Name { get; set; } = string.Empty;


		public float Delay { get; set; }

		public float Radius { get; set; }

		public float DistanceMin { get; set; }

		public float DistanceMax { get; set; }

		public float DamageMin { get; set; }

		public float DamageMax { get; set; }

		public float Force { get; set; }

		public float PlacementTime { get; set; } = 0.5f;


		public float PlacementCooldown { get; set; } = 2f;


		public float PickupTime { get; set; } = 0.5f;

	}
	public sealed class SentryData : IToolData
	{
		[JsonIgnore]
		public uint OfflineID { get; set; }

		[JsonIgnore]
		public uint ItemID { get; set; }

		public uint ArchetypeID { get; set; }

		public string Name { get; set; } = string.Empty;


		public bool BackDamage { get; set; }
	}
	internal static class ToolDataDict<T> where T : IToolData
	{
		public static string Name = string.Empty;

		public static readonly Dictionary<string, List<T>> FileData = new Dictionary<string, List<T>>();

		public static readonly Dictionary<uint, T> OfflineData = new Dictionary<uint, T>();

		public static readonly Dictionary<uint, T> ItemData = new Dictionary<uint, T>();

		public static readonly Dictionary<uint, T> ArchData = new Dictionary<uint, T>();
	}
	public sealed class ToolDataManager
	{
		public static readonly ToolDataManager Current = new ToolDataManager();

		private readonly LiveEditListener _liveEditListener;

		private void FileChanged<T>(LiveEditEventArgs e) where T : IToolData
		{
			LiveEditEventArgs e2 = e;
			DinoLogger.Warning("LiveEdit File Changed: " + e2.FullPath);
			LiveEdit.TryReadFileContent(e2.FullPath, (Action<string>)delegate(string content)
			{
				ReadFileContent<T>(e2.FullPath, content);
				PrintCustomIDs<T>();
			});
		}

		private void FileDeleted<T>(LiveEditEventArgs e) where T : IToolData
		{
			DinoLogger.Warning("LiveEdit File Removed: " + e.FullPath);
			RemoveFile<T>(e.FullPath);
			PrintCustomIDs<T>();
		}

		private void FileCreated<T>(LiveEditEventArgs e) where T : IToolData
		{
			LiveEditEventArgs e2 = e;
			DinoLogger.Warning("LiveEdit File Created: " + e2.FullPath);
			LiveEdit.TryReadFileContent(e2.FullPath, (Action<string>)delegate(string content)
			{
				ReadFileContent<T>(e2.FullPath, content);
				PrintCustomIDs<T>();
			});
		}

		private void ReadFileContent<T>(string file, string content) where T : IToolData
		{
			RemoveFile<T>(file);
			List<T> list = null;
			try
			{
				list = TCJson.Deserialize<List<T>>(content);
			}
			catch (JsonException ex)
			{
				DinoLogger.Error("Error parsing " + ToolDataDict<T>.Name + " json " + file);
				DinoLogger.Error(ex.Message);
			}
			if (list != null)
			{
				AddFile(file, list);
			}
		}

		private static void RemoveFile<T>(string file) where T : IToolData
		{
			if (!ToolDataDict<T>.FileData.ContainsKey(file))
			{
				return;
			}
			foreach (T item in ToolDataDict<T>.FileData[file])
			{
				ToolDataDict<T>.OfflineData.Remove(item.OfflineID);
				ToolDataDict<T>.ItemData.Remove(item.ItemID);
				ToolDataDict<T>.ArchData.Remove(item.ArchetypeID);
			}
			ToolDataDict<T>.FileData.Remove(file);
		}

		private static void AddFile<T>(string file, List<T> dataList) where T : IToolData
		{
			ToolDataDict<T>.FileData.Add(file, dataList);
			foreach (T data in dataList)
			{
				if (data.OfflineID != 0)
				{
					if (ToolDataDict<T>.OfflineData.ContainsKey(data.OfflineID))
					{
						DinoLogger.Warning($"Duplicate {ToolDataDict<T>.Name} offline ID {data.OfflineID} detected. Previous name: {ToolDataDict<T>.OfflineData[data.OfflineID].Name}, new name: {data.Name}");
					}
					ToolDataDict<T>.OfflineData[data.OfflineID] = data;
				}
				if (data.ItemID != 0)
				{
					if (ToolDataDict<T>.ItemData.ContainsKey(data.ItemID))
					{
						DinoLogger.Warning($"Duplicate {ToolDataDict<T>.Name} item ID {data.ItemID} detected. Previous name: {ToolDataDict<T>.ItemData[data.ItemID].Name}, new name: {data.Name}");
					}
					ToolDataDict<T>.ItemData[data.ItemID] = data;
				}
				if (data.ArchetypeID != 0)
				{
					if (ToolDataDict<T>.ItemData.ContainsKey(data.ArchetypeID))
					{
						DinoLogger.Warning($"Duplicate {ToolDataDict<T>.Name} item ID {data.ArchetypeID} detected. Previous name: {ToolDataDict<T>.ArchData[data.ArchetypeID].Name}, new name: {data.Name}");
					}
					ToolDataDict<T>.ArchData[data.ArchetypeID] = data;
				}
			}
		}

		private void PrintCustomIDs<T>() where T : IToolData
		{
			if (ToolDataDict<T>.OfflineData.Count > 0)
			{
				StringBuilder stringBuilder = new StringBuilder("Found custom blocks for " + ToolDataDict<T>.Name + " offline IDs: ");
				stringBuilder.AppendJoin(", ", ToolDataDict<T>.OfflineData.Keys.ToImmutableSortedSet());
				DinoLogger.Log(stringBuilder.ToString());
			}
			if (ToolDataDict<T>.ItemData.Count > 0)
			{
				StringBuilder stringBuilder2 = new StringBuilder("Found custom blocks for " + ToolDataDict<T>.Name + " item IDs: ");
				stringBuilder2.AppendJoin(", ", ToolDataDict<T>.ItemData.Keys.ToImmutableSortedSet());
				DinoLogger.Log(stringBuilder2.ToString());
			}
			if (ToolDataDict<T>.ArchData.Count > 0)
			{
				StringBuilder stringBuilder3 = new StringBuilder("Found custom blocks for " + ToolDataDict<T>.Name + " archetype IDs: ");
				stringBuilder3.AppendJoin(", ", ToolDataDict<T>.ArchData.Keys.ToImmutableSortedSet());
				DinoLogger.Log(stringBuilder3.ToString());
			}
		}

		private ToolDataManager()
		{
			string text = Path.Combine(MTFOWrapper.CustomPath, "ExtraToolCustomization");
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
			_liveEditListener = LiveEdit.CreateListener(text, "*.json", true);
			_liveEditListener.StopListen();
			LoadDirectory("Mine", MineTemplate.Template);
			LoadDirectory("Sentry", SentryTemplate.Template);
			_liveEditListener.StartListen();
		}

		private void LoadDirectory<T>(string name, params T[] defaultT) where T : IToolData
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Expected O, but got Unknown
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Expected O, but got Unknown
			ToolDataDict<T>.Name = name;
			string text = Path.Combine(MTFOWrapper.CustomPath, "ExtraToolCustomization", name);
			if (!Directory.Exists(text))
			{
				DinoLogger.Log($"No {name} directory detected. Creating {text}/Template.json");
				Directory.CreateDirectory(text);
				StreamWriter streamWriter = File.CreateText(Path.Combine(text, "Template.json"));
				streamWriter.WriteLine(TCJson.Serialize(new List<T>(defaultT)));
				streamWriter.Flush();
				streamWriter.Close();
			}
			else
			{
				DinoLogger.Log(name + " directory detected. " + text);
			}
			foreach (string item in Directory.EnumerateFiles(text, "*.json", SearchOption.AllDirectories))
			{
				string content = File.ReadAllText(item);
				ReadFileContent<T>(item, content);
			}
			PrintCustomIDs<T>();
			_liveEditListener.FileCreated += new LiveEditEventHandler(FileCreated<T>);
			_liveEditListener.FileChanged += new LiveEditEventHandler(FileChanged<T>);
			_liveEditListener.FileDeleted += new LiveEditEventHandler(FileDeleted<T>);
		}

		internal void Init()
		{
		}

		public static T? GetItemData<T>(uint id) where T : IToolData
		{
			return ToolDataDict<T>.ItemData.GetValueOrDefault(id);
		}

		public static T? GetOfflineData<T>(uint id) where T : IToolData
		{
			return ToolDataDict<T>.OfflineData.GetValueOrDefault(id);
		}

		public static T? GetArchData<T>(uint id) where T : IToolData
		{
			return ToolDataDict<T>.OfflineData.GetValueOrDefault(id);
		}

		public static T? GetData<T>(uint offlineID, uint itemID, uint archID) where T : IToolData
		{
			T val = default(T);
			if (offlineID != 0)
			{
				val = GetOfflineData<T>(offlineID);
			}
			if (val == null && itemID != 0)
			{
				val = GetItemData<T>(itemID);
			}
			if (val == null && archID != 0)
			{
				val = GetArchData<T>(archID);
			}
			return val;
		}
	}
}
namespace ExtraToolCustomization.ToolData.Templates
{
	internal static class MineTemplate
	{
		public static MineData[] Template = new MineData[2]
		{
			new MineData
			{
				Name = "Mine Deployer",
				Delay = 0.25f,
				Radius = 2.5f,
				DistanceMin = 3f,
				DistanceMax = 15f,
				DamageMin = 15f,
				DamageMax = 50f,
				Force = 1000f
			},
			new MineData
			{
				Name = "Consumable Mine",
				Delay = 0.25f,
				Radius = 2f,
				DistanceMin = 2.5f,
				DistanceMax = 12f,
				DamageMin = 10f,
				DamageMax = 35f,
				Force = 700f
			}
		};
	}
	internal static class SentryTemplate
	{
		public static SentryData[] Template = new SentryData[1]
		{
			new SentryData
			{
				OfflineID = 0u,
				Name = "Sentry Gun",
				BackDamage = false
			}
		};
	}
}
namespace ExtraToolCustomization.Patches
{
	[HarmonyPatch]
	internal static class MineDeployerPatches
	{
		[HarmonyPatch(typeof(MineDeployerFirstPerson), "OnGearSpawnComplete")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_Setup(MineDeployerFirstPerson __instance)
		{
			MineData data = ToolDataManager.GetData<MineData>(((ItemEquippable)__instance).GearIDRange?.GetOfflineID() ?? 0, ((GameDataBlockBase<ItemDataBlock>)(object)((Item)__instance).ItemDataBlock).persistentID, 0u);
			if (data != null)
			{
				((Interact_Timed)__instance.m_interactPlaceItem).InteractDuration = data.PlacementTime;
				__instance.m_timeBetweenPlacements = data.PlacementCooldown;
			}
		}

		[HarmonyPatch(typeof(PlayerBotActionDeployTripMine), "PlaceTripMine")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_PlaceMineBot(PlayerBotActionDeployTripMine __instance)
		{
			if (Object.op_Implicit((Object)(object)SNet.Master))
			{
				ItemEquippable val = ((Il2CppObjectBase)__instance.m_desc.BackpackItem.Instance).TryCast<ItemEquippable>();
				uint offlineID = val.GearIDRange?.GetOfflineID() ?? 0;
				MineDeployerManager.SendMineDeployerID(((PlayerBotActionBase)__instance).m_agent.Owner, offlineID, ((GameDataBlockBase<ItemDataBlock>)(object)((Item)val).ItemDataBlock).persistentID);
			}
		}

		[HarmonyPatch(typeof(MineDeployerFirstPerson), "PlaceMine")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_PlaceMine(MineDeployerFirstPerson __instance)
		{
			if (__instance.CheckCanPlace())
			{
				uint offlineID = ((ItemEquippable)__instance).GearIDRange?.GetOfflineID() ?? 0;
				MineDeployerManager.SendMineDeployerID(((Item)__instance).Owner.Owner, offlineID, ((GameDataBlockBase<ItemDataBlock>)(object)((Item)__instance).ItemDataBlock).persistentID);
			}
		}

		[HarmonyPatch(typeof(MineDeployerInstance), "OnSpawn")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_MineSpawned(MineDeployerInstance __instance, ref pItemSpawnData spawnData)
		{
			SNet_Player source = default(SNet_Player);
			if (!Object.op_Implicit((Object)(object)SNet.Master) || !((pPlayer)(ref spawnData.owner)).GetPlayer(ref source))
			{
				return;
			}
			MineDeployerInstance_Detonate_Explosive val = ((Il2CppObjectBase)__instance.m_detonation).TryCast<MineDeployerInstance_Detonate_Explosive>();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			if (!MineDeployerManager.HasMineDeployerID(source))
			{
				MineDeployerManager.StoreMineDeployer(source, val);
				return;
			}
			MineData mineData = MineDeployerManager.GetMineData(MineDeployerManager.PopMineDeployerID(source));
			if (mineData != null)
			{
				MineDeployerManager.ApplyDataToMine(val, mineData);
			}
		}

		[HarmonyPatch(typeof(MineDeployerFirstPerson), "OnStickyMineSpawned")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_DeployedMine(MineDeployerFirstPerson __instance, ISyncedItem item)
		{
			if (__instance.m_isConsumable)
			{
				return;
			}
			MineData data = ToolDataManager.GetData<MineData>(((ItemEquippable)__instance).GearIDRange?.GetOfflineID() ?? 0, ((GameDataBlockBase<ItemDataBlock>)(object)((Item)__instance).ItemDataBlock).persistentID, 0u);
			if (data != null)
			{
				MineDeployerInstance val = ((Il2CppObjectBase)item.GetItem()).TryCast<MineDeployerInstance>();
				if ((Object)(object)val != (Object)null)
				{
					((Il2CppObjectBase)((Item)val).PickupInteraction).Cast<Interact_Timed>().InteractDuration = data.PickupTime;
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class SentryGunPatches
	{
		private static GearIDRange? _cachedRange;

		private static ArchetypeDataBlock? _cachedArchetype;

		[HarmonyPatch(typeof(CM_InventorySlotItem), "LoadData")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_LoadData(GearIDRange idRange)
		{
			CacheArchetype(idRange);
		}

		[HarmonyPatch(typeof(CM_InventorySlotItem), "LoadData")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_LoadData(CM_InventorySlotItem __instance)
		{
			if (_cachedArchetype != null)
			{
				__instance.GearDescription = LocalizedText.op_Implicit(_cachedArchetype.Description);
				__instance.GearArchetypeName = LocalizedText.op_Implicit(_cachedArchetype.PublicName);
				((TMP_Text)((CM_LobbyScrollItem)__instance).m_subTitleText).text = __instance.m_archetypePrefix + __instance.GearArchetypeName;
				TMP_UpdateManager.RegisterTextElementForGraphicRebuild((TMP_Text)(object)((CM_LobbyScrollItem)__instance).m_subTitleText);
			}
		}

		[HarmonyPatch(typeof(CM_PageExpeditionSuccess), "TryGetArchetypeName")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_GetArchetypeName(PlayerBackpack backpack, InventorySlot slot)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			BackpackItem val = default(BackpackItem);
			if (backpack.TryGetBackpackItem(slot, ref val))
			{
				CacheArchetype(val.GearIDRange);
			}
		}

		[HarmonyPatch(typeof(SentryGunFirstPerson), "OnGearSpawnComplete")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_FPGearSpawn(SentryGunFirstPerson __instance)
		{
			CacheArchetype(((ItemEquippable)__instance).GearIDRange);
		}

		[HarmonyPatch(typeof(SentryGunInstance), "OnGearSpawnComplete")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_InstanceGearSpawn(SentryGunInstance __instance)
		{
			CacheArchetype(((ItemEquippable)__instance).GearIDRange);
		}

		private static void CacheArchetype(GearIDRange idRange)
		{
			//IL_0069: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected I4, but got Unknown
			if (_cachedRange != null && ((Il2CppObjectBase)_cachedRange).Pointer == ((Il2CppObjectBase)idRange).Pointer)
			{
				return;
			}
			_cachedRange = idRange;
			_cachedArchetype = null;
			if (_cachedRange == null || (int)_cachedRange.GetCompID((eGearComponent)1) < 10)
			{
				return;
			}
			uint compID = _cachedRange.GetCompID((eGearComponent)2);
			if (compID == 0)
			{
				return;
			}
			GearCategoryDataBlock block = GameDataBlockBase<GearCategoryDataBlock>.GetBlock(compID);
			if (block == null)
			{
				return;
			}
			eWeaponFireMode val = (eWeaponFireMode)_cachedRange.GetCompID((eGearComponent)1);
			uint num = (val - 10) switch
			{
				0 => block.SemiArchetype, 
				1 => block.AutoArchetype, 
				2 => block.BurstArchetype, 
				3 => block.SemiArchetype, 
				_ => 0u, 
			};
			if (num != 0)
			{
				ArchetypeDataBlock block2 = GameDataBlockBase<ArchetypeDataBlock>.GetBlock(num);
				if (block2 != null)
				{
					_cachedArchetype = block2;
				}
			}
		}

		[HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "GetArchetypeDataForFireMode")]
		[HarmonyPostfix]
		private static void CorrectArchetype(ref ArchetypeDataBlock __result)
		{
			if (_cachedArchetype != null)
			{
				__result = _cachedArchetype;
			}
		}

		[HarmonyPatch(typeof(BulletWeapon), "BulletHit")]
		[HarmonyPriority(200)]
		[HarmonyPrefix]
		private static void SetBackDamage(ref WeaponHitData weaponRayData, ref bool allowDirectionalBonus)
		{
			PlayerBackpack val = default(PlayerBackpack);
			BackpackItem val2 = default(BackpackItem);
			if ((!allowDirectionalBonus || weaponRayData.vfxBulletHit != null) && PlayerBackpackManager.TryGetBackpack(weaponRayData.owner.Owner, ref val) && val.TryGetBackpackItem((InventorySlot)3, ref val2))
			{
				SentryData archData = ToolDataManager.GetArchData<SentryData>(((Il2CppObjectBase)val2.Instance).Cast<ItemEquippable>().ArchetypeID);
				if (archData != null)
				{
					allowDirectionalBonus = archData.BackDamage;
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class SentryGunPatches_BurstFix
	{
		[HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "StartFiring")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_StartFiring(SentryGunInstance_Firing_Bullets __instance)
		{
			__instance.m_burstClipCurr = __instance.m_archetypeData.BurstShotCount;
		}

		[HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "StopFiring")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_StopFiring(SentryGunInstance_Firing_Bullets __instance)
		{
			__instance.m_burstTimer = Clock.Time + __instance.m_archetypeData.BurstDelay;
		}
	}
	[HarmonyPatch]
	internal static class SentryGunPatches_ShotgunFix
	{
		private static Vector3? _cachedDir;

		[HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "TriggerSingleFireAudio")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Pre_ShotgunFireBullet(SentryGunInstance_Firing_Bullets __instance)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = default(Vector3);
			if ((int)__instance.m_fireMode == 13 && __instance.m_archetypeData.Sentry_FireTowardsTargetInsteadOfForward && __instance.m_core.TryGetTargetAimPos(ref val))
			{
				_cachedDir = __instance.MuzzleAlign.forward;
				Transform muzzleAlign = __instance.MuzzleAlign;
				Vector3 val2 = val - __instance.MuzzleAlign.position;
				muzzleAlign.forward = ((Vector3)(ref val2)).normalized;
			}
		}

		[HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "UpdateAmmo")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_ShotgunFireBullet(SentryGunInstance_Firing_Bullets __instance)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (_cachedDir.HasValue)
			{
				__instance.MuzzleAlign.forward = _cachedDir.Value;
				_cachedDir = null;
			}
		}
	}
}
namespace ExtraToolCustomization.Networking
{
	public abstract class SyncedEvent<T> where T : struct
	{
		public delegate void ReceiveHandler(T packet);

		private bool _isSetup;

		public abstract string GUID { get; }

		public bool IsSetup => _isSetup;

		public string EventName { get; private set; } = string.Empty;


		public event ReceiveHandler? OnReceive;

		public event ReceiveHandler? OnReceiveLocal;

		public void Setup()
		{
			if (!_isSetup)
			{
				EventName = "ETC" + GUID;
				NetworkAPI.RegisterEvent<T>(EventName, (Action<ulong, T>)ReceiveClient_Callback);
				_isSetup = true;
			}
		}

		public void Send(T packetData, SNet_Player? target = null, SNet_ChannelType priority = 4)
		{
			//IL_0020: 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)
			if ((Object)(object)target != (Object)null)
			{
				NetworkAPI.InvokeEvent<T>(EventName, packetData, target, priority);
			}
			else
			{
				NetworkAPI.InvokeEvent<T>(EventName, packetData, priority);
			}
			ReceiveLocal_Callback(packetData);
		}

		private void ReceiveLocal_Callback(T packet)
		{
			ReceiveLocal(packet);
			this.OnReceiveLocal?.Invoke(packet);
		}

		private void ReceiveClient_Callback(ulong sender, T packet)
		{
			Receive(packet);
			this.OnReceive?.Invoke(packet);
		}

		protected virtual void ReceiveLocal(T packet)
		{
		}

		protected virtual void Receive(T packet)
		{
		}
	}
	public abstract class SyncedEventMasterOnly<T> : SyncedEvent<T> where T : struct
	{
		public void Send(T packet, SNet_ChannelType priority = 4)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (!SNet.IsMaster)
			{
				Send(packet, SNet.Master, priority);
			}
			else
			{
				Receive(packet);
			}
		}
	}
}
namespace ExtraToolCustomization.Networking.MineDeployer
{
	public static class MineDeployerManager
	{
		private static readonly MineDeployerSync _sync = new MineDeployerSync();

		internal static Dictionary<ulong, MineDeployerID> _storedPackets = new Dictionary<ulong, MineDeployerID>();

		internal static Dictionary<ulong, MineDeployerInstance_Detonate_Explosive> _storedMines = new Dictionary<ulong, MineDeployerInstance_Detonate_Explosive>();

		internal static void Init()
		{
			_sync.Setup();
		}

		public static void SendMineDeployerID(SNet_Player source, uint offlineID, uint itemID)
		{
			MineDeployerID packet = default(MineDeployerID);
			((pPlayer)(ref packet.source)).SetPlayer(source);
			packet.itemID = (ushort)itemID;
			packet.offlineID = (ushort)offlineID;
			_sync.Send(packet, (SNet_ChannelType)4);
		}

		public static bool HasMineDeployerID(SNet_Player source)
		{
			if (SNet.IsMaster)
			{
				return _storedPackets.ContainsKey(source.Lookup);
			}
			return false;
		}

		public static void StoreMineDeployer(SNet_Player source, MineDeployerInstance_Detonate_Explosive instance)
		{
			_storedMines[source.Lookup] = instance;
		}

		public static MineDeployerID PopMineDeployerID(SNet_Player source)
		{
			if (!HasMineDeployerID(source))
			{
				return default(MineDeployerID);
			}
			MineDeployerID result = _storedPackets[source.Lookup];
			_storedPackets.Remove(source.Lookup);
			return result;
		}

		internal static void Internal_ReceiveMineDeployerPacket(ulong lookup, MineDeployerID packet)
		{
			if (!_storedMines.ContainsKey(lookup))
			{
				_storedPackets[lookup] = packet;
				return;
			}
			MineData mineData = GetMineData(packet);
			MineDeployerInstance_Detonate_Explosive explosive = _storedMines[lookup];
			_storedMines.Remove(lookup);
			if (mineData != null)
			{
				ApplyDataToMine(explosive, mineData);
			}
		}

		public static MineData? GetMineData(MineDeployerID deployerID)
		{
			return ToolDataManager.GetData<MineData>(deployerID.offlineID, deployerID.itemID, 0u);
		}

		public static void ApplyDataToMine(MineDeployerInstance_Detonate_Explosive explosive, MineData data)
		{
			explosive.m_explosionDelay = data.Delay;
			explosive.m_radius = data.Radius;
			explosive.m_distanceMin = data.DistanceMin;
			explosive.m_distanceMax = data.DistanceMax;
			explosive.m_damageMin = data.DamageMin;
			explosive.m_damageMax = data.DamageMax - data.DamageMin;
			explosive.m_explosionForce = data.Force;
		}
	}
	public struct MineDeployerID
	{
		public pPlayer source;

		public ushort offlineID;

		public ushort itemID;
	}
	internal class MineDeployerSync : SyncedEventMasterOnly<MineDeployerID>
	{
		public override string GUID => "MineID";

		protected override void Receive(MineDeployerID packet)
		{
			SNet_Player val = default(SNet_Player);
			if (((pPlayer)(ref packet.source)).GetPlayer(ref val))
			{
				MineDeployerManager.Internal_ReceiveMineDeployerPacket(val.Lookup, packet);
			}
		}
	}
}
namespace ExtraToolCustomization.JSON
{
	public static class TCJson
	{
		private static readonly JsonSerializerOptions _setting;

		static TCJson()
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			_setting = new JsonSerializerOptions
			{
				ReadCommentHandling = JsonCommentHandling.Skip,
				IncludeFields = true,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true,
				IgnoreReadOnlyProperties = true
			};
			_setting.Converters.Add(new JsonStringEnumConverter());
			_setting.Converters.Add((JsonConverter)new LocalizedTextConverter());
		}

		public static T? Deserialize<T>(string json)
		{
			return JsonSerializer.Deserialize<T>(json, _setting);
		}

		public static object? Deserialize(Type type, string json)
		{
			return JsonSerializer.Deserialize(json, type, _setting);
		}

		public static string Serialize<T>(T value)
		{
			return JsonSerializer.Serialize(value, _setting);
		}
	}
}
namespace ExtraToolCustomization.Dependencies
{
	internal static class MTFOWrapper
	{
		public const string GUID = "com.dak.MTFO";

		public static string GameDataPath => MTFOPathAPI.RundownPath;

		public static string CustomPath => MTFOPathAPI.CustomPath;

		public static bool HasCustomContent => MTFOPathAPI.HasCustomPath;

		public static bool HasMTFO { get; private set; }

		static MTFOWrapper()
		{
			HasMTFO = ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.ContainsKey("com.dak.MTFO");
		}
	}
}

plugins/Dinorush-ExtraWeaponCustomization/ExtraWeaponCustomization.dll

Decompiled 7 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
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 System.Text.Json;
using System.Text.Json.Serialization;
using AIGraph;
using AK;
using Agents;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using CharacterDestruction;
using CullingSystem;
using EWC.API;
using EWC.CustomWeapon;
using EWC.CustomWeapon.KillTracker;
using EWC.CustomWeapon.ObjectWrappers;
using EWC.CustomWeapon.Properties;
using EWC.CustomWeapon.Properties.Effects;
using EWC.CustomWeapon.Properties.Effects.Heal;
using EWC.CustomWeapon.Properties.Effects.Hit.DOT;
using EWC.CustomWeapon.Properties.Effects.Hit.Explosion;
using EWC.CustomWeapon.Properties.Effects.Hit.Explosion.EEC_ExplosionFX;
using EWC.CustomWeapon.Properties.Effects.Hit.Explosion.EEC_ExplosionFX.Handlers;
using EWC.CustomWeapon.Properties.Effects.Triggers;
using EWC.CustomWeapon.Properties.Traits;
using EWC.CustomWeapon.Properties.Traits.CustomProjectile;
using EWC.CustomWeapon.Properties.Traits.CustomProjectile.Components;
using EWC.CustomWeapon.Properties.Traits.CustomProjectile.Managers;
using EWC.CustomWeapon.WeaponContext;
using EWC.CustomWeapon.WeaponContext.Contexts;
using EWC.Dependencies;
using EWC.JSON;
using EWC.JSON.Converters;
using EWC.Networking;
using EWC.Networking.Structs;
using EWC.Patches;
using EWC.Patches.Melee;
using EWC.Patches.Native;
using EWC.Utils;
using EWC.Utils.Log;
using EndskApi.Api;
using EndskApi.Enums.EnemyKill;
using EndskApi.Information.EnemyKill;
using Enemies;
using ExtraRecoilData.API;
using ExtraRecoilData.CustomRecoil;
using FX_EffectSystem;
using FirstPersonItem;
using GTFO.API;
using GTFO.API.JSON.Converters;
using GTFO.API.Utilities;
using GTFuckingXP.Extensions;
using GTFuckingXP.Information.Level;
using GameData;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using KillIndicatorFix;
using LevelGeneration;
using LevelGeneration.Core;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using UnityEngine;

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

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace EWC
{
	internal static class Configuration
	{
		private static readonly ConfigFile configFile;

		private static ConfigEntry<bool> ForceCreateTemplate { get; set; }

		public static bool ShowExplosionEffect { get; set; }

		public static bool PlayExplosionSFX { get; set; }

		public static float ExplosionSFXCooldown { get; set; }

		public static int ExplosionSFXShotOverride { get; set; }

		public static float AutoAimTickDelay { get; set; }

		public static float HomingTickDelay { get; set; }

		static Configuration()
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			ShowExplosionEffect = true;
			PlayExplosionSFX = true;
			ExplosionSFXCooldown = 0.08f;
			ExplosionSFXShotOverride = 8;
			AutoAimTickDelay = 0.1f;
			HomingTickDelay = 0.1f;
			configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, "ExtraWeaponCustomization.cfg"), true);
			BindAll(configFile);
		}

		internal static void Init()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			LiveEdit.CreateListener(Paths.ConfigPath, "ExtraWeaponCustomization.cfg", false).FileChanged += new LiveEditEventHandler(OnFileChanged);
		}

		private static void OnFileChanged(LiveEditEventArgs _)
		{
			configFile.Reload();
			string text = "Auto Aim Settings";
			AutoAimTickDelay = (float)configFile[text, "Search Cooldown"].BoxedValue;
			text = "Explosion Settings";
			ShowExplosionEffect = (bool)configFile[text, "Show Effect"].BoxedValue;
			PlayExplosionSFX = (bool)configFile[text, "Play Sound"].BoxedValue;
			ExplosionSFXCooldown = (float)configFile[text, "SFX Cooldown"].BoxedValue;
			ExplosionSFXShotOverride = (int)configFile[text, "Shots to Override SFX Cooldown"].BoxedValue;
			text = "Projectile Settings";
			HomingTickDelay = (float)configFile[text, "Homing Search Cooldown"].BoxedValue;
			CheckAndRefreshTemplate();
		}

		[MemberNotNull("ForceCreateTemplate")]
		private static void BindAll(ConfigFile config)
		{
			string text = "Auto Aim Settings";
			AutoAimTickDelay = config.Bind<float>(text, "Search Cooldown", AutoAimTickDelay, "Time between attempted searches to acquire targets.").Value;
			text = "Explosion Settings";
			ShowExplosionEffect = config.Bind<bool>(text, "Show Effect", ShowExplosionEffect, "Enables explosion visual FX.").Value;
			PlayExplosionSFX = config.Bind<bool>(text, "Play Sound", PlayExplosionSFX, "Enables explosion sound FX.").Value;
			ExplosionSFXCooldown = config.Bind<float>(text, "SFX Cooldown", ExplosionSFXCooldown, "Minimum time between explosion sound effects, to prevent obnoxiously loud sounds.").Value;
			ExplosionSFXShotOverride = config.Bind<int>(text, "Shots to Override SFX Cooldown", ExplosionSFXShotOverride, "Amount of shots fired before another explosion sound effect is forced, regardless of cooldown.\nSmaller numbers let fast-firing weapons and shotguns make more sounds in a short span of time.").Value;
			text = "Projectile Settings";
			HomingTickDelay = config.Bind<float>(text, "Homing Search Cooldown", HomingTickDelay, "Minimum time between attempted searches to acquire a new target.").Value;
			text = "Tools";
			ForceCreateTemplate = config.Bind<bool>(text, "Force Create Template", false, "Creates the template file again.");
		}

		private static void CheckAndRefreshTemplate()
		{
			if (ForceCreateTemplate.Value)
			{
				ForceCreateTemplate.Value = false;
				CustomWeaponManager.Current.CreateTemplate();
				configFile.Save();
			}
		}
	}
	[BepInPlugin("Dinorush.ExtraWeaponCustomization", "ExtraWeaponCustomization", "2.8.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal sealed class EntryPoint : BasePlugin
	{
		public const string MODNAME = "ExtraWeaponCustomization";

		public override void Load()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			EWCLogger.Log("Loading ExtraWeaponCustomization");
			if (!MTFOAPIWrapper.HasCustomContent)
			{
				EWCLogger.Error("No MTFO datablocks detected. Not loading EWC...");
				return;
			}
			new Harmony("ExtraWeaponCustomization").PatchAll();
			EnemyDetectionPatches.ApplyNativePatch();
			Configuration.Init();
			LevelAPI.OnLevelCleanup += LevelAPI_OnLevelCleanup;
			LevelAPI.OnEnterLevel += LevelAPI_OnLevelEnter;
			AssetAPI.OnStartupAssetsLoaded += AssetAPI_OnStartupAssetsLoaded;
			EWCLogger.Log("Loaded ExtraWeaponCustomization");
		}

		private void LevelAPI_OnLevelCleanup()
		{
			CustomWeaponManager.Current.ResetCWCs(activate: false);
			EWCProjectileManager.Reset();
		}

		private void LevelAPI_OnLevelEnter()
		{
			CustomWeaponManager.Current.ActivateCWCs();
		}

		private void AssetAPI_OnStartupAssetsLoaded()
		{
			ClassInjector.RegisterTypeInIl2Cpp<ExplosionEffectHandler>();
			ClassInjector.RegisterTypeInIl2Cpp<CustomWeaponComponent>();
			ClassInjector.RegisterTypeInIl2Cpp<EWCProjectileComponentBase>();
			ClassInjector.RegisterTypeInIl2Cpp<EWCProjectileComponentShooter>();
			LayerUtil.Init();
			ExplosionManager.Init();
			DOTDamageManager.Init();
			HealManager.Init();
			TriggerManager.Init();
			KillAPIWrapper.Init();
			EWCProjectileManager.Init();
			CustomWeaponManager.Current.GetCustomGunData(0u);
		}
	}
}
namespace EWC.Utils
{
	internal static class DamageableUtil
	{
		public static IDamageable? GetDamageableFromRayHit(RaycastHit rayHit)
		{
			if (!((Object)(object)((RaycastHit)(ref rayHit)).collider == (Object)null))
			{
				return GetDamageableFromCollider(((RaycastHit)(ref rayHit)).collider);
			}
			return null;
		}

		public static IDamageable? GetDamageableFromCollider(Collider? collider)
		{
			if (!((Object)(object)collider == (Object)null))
			{
				return GetDamageableFromGO(((Component)collider).gameObject);
			}
			return null;
		}

		public static IDamageable? GetDamageableFromGO(GameObject? go)
		{
			if ((Object)(object)go == (Object)null)
			{
				return null;
			}
			ColliderMaterial component = go.GetComponent<ColliderMaterial>();
			IDamageable val = ((component != null) ? component.Damageable : null);
			if (val != null)
			{
				return val;
			}
			return go.GetComponent<IDamageable>();
		}
	}
	public sealed class DelayedCallback
	{
		private readonly Func<float> _endTime;

		private readonly Action? _onStart;

		private readonly Action? _onRefresh;

		private readonly Action? _onEnd;

		private Coroutine? _routine;

		public DelayedCallback(Func<float> endTime, Action? onStart, Action? onRefresh, Action? onEnd)
		{
			_endTime = endTime;
			_onStart = onStart;
			_onRefresh = onRefresh;
			_onEnd = onEnd;
		}

		public void Start()
		{
			_onRefresh?.Invoke();
			if (_routine == null)
			{
				_routine = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(Update()), (Action)null);
			}
		}

		public IEnumerator Update()
		{
			_onStart?.Invoke();
			for (float num = _endTime(); num > Clock.Time; num = _endTime())
			{
				yield return (object)new WaitForSeconds(num - Clock.Time);
			}
			_routine = null;
			_onEnd?.Invoke();
		}

		public void Stop()
		{
			if (_routine != null)
			{
				CoroutineManager.StopCoroutine(_routine);
				_routine = null;
				_onEnd?.Invoke();
			}
		}

		public void Cancel()
		{
			if (_routine != null)
			{
				CoroutineManager.StopCoroutine(_routine);
				_routine = null;
			}
		}
	}
	internal static class DictExtensions
	{
		public static bool TryGetValueAs<Key, Value, ValueAs>(this IDictionary<Key, Value> dict, Key key, [MaybeNullWhen(false)] out ValueAs valueAs) where Key : notnull where ValueAs : Value
		{
			if (dict.TryGetValue(key, out Value value))
			{
				valueAs = (ValueAs)(object)value;
				return true;
			}
			valueAs = default(ValueAs);
			return false;
		}
	}
	internal static class FloatExtensions
	{
		public static float Map(this float orig, float fromMin, float fromMax, float toMin, float toMax)
		{
			if (fromMin == fromMax)
			{
				if (!(orig < fromMin))
				{
					return toMax;
				}
				return toMin;
			}
			orig = Mathf.Clamp(orig, fromMin, fromMax);
			return (orig - fromMin) / (fromMax - fromMin) * (toMax - toMin) + toMin;
		}
	}
	public sealed class HitData
	{
		public float damage;

		public Vector2 damageFalloff;

		public float falloff;

		public float precisionMulti;

		public float staggerMulti;

		public float maxRayDist;

		public PlayerAgent owner;

		public Vector3 fireDir;

		public Vector3 hitPos;

		public IDamageable? damageable;

		private RaycastHit _rayHit;

		private WeaponHitData? _weaponHitData;

		private MeleeWeaponFirstPerson? _meleeWeapon;

		public RaycastHit RayHit
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return _rayHit;
			}
			set
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_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_001a: Unknown result type (might be due to invalid IL or missing references)
				_rayHit = value;
				hitPos = ((RaycastHit)(ref _rayHit)).point;
				damageable = DamageableUtil.GetDamageableFromRayHit(_rayHit);
			}
		}

		public HitData(WeaponHitData hitData, float additionalDist = 0f)
		{
			Setup(hitData, additionalDist);
		}

		public HitData(MeleeWeaponFirstPerson melee, MeleeWeaponDamageData hitData)
		{
			Setup(melee, hitData);
		}

		public HitData()
		{
		}

		public void Setup(WeaponHitData hitData, float additionalDist = 0f)
		{
			//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_004c: 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_0064: Unknown result type (might be due to invalid IL or missing references)
			_weaponHitData = hitData;
			_meleeWeapon = null;
			damage = hitData.damage;
			damageFalloff = hitData.damageFalloff;
			precisionMulti = hitData.precisionMulti;
			staggerMulti = hitData.staggerMulti;
			owner = hitData.owner;
			fireDir = hitData.fireDir;
			maxRayDist = hitData.maxRayDist;
			RayHit = hitData.rayHit;
			SetFalloff(additionalDist);
		}

		public void Setup(MeleeWeaponFirstPerson melee, MeleeWeaponDamageData hitData)
		{
			//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)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			_weaponHitData = null;
			_meleeWeapon = melee;
			damage = melee.m_damageToDeal;
			precisionMulti = melee.m_precisionMultiToDeal;
			staggerMulti = melee.m_staggerMultiToDeal;
			falloff = 1f;
			fireDir = hitData.hitPos - hitData.sourcePos;
			hitPos = hitData.hitPos;
			damageable = DamageableUtil.GetDamageableFromGO(hitData.damageGO);
		}

		public void Apply()
		{
			if (_weaponHitData != null)
			{
				Apply(_weaponHitData);
			}
			else if ((Object)(object)_meleeWeapon != (Object)null)
			{
				Apply(_meleeWeapon);
			}
		}

		public WeaponHitData Apply(WeaponHitData hitData)
		{
			//IL_0032: 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)
			hitData.owner = owner;
			hitData.damage = damage;
			hitData.precisionMulti = precisionMulti;
			hitData.staggerMulti = staggerMulti;
			hitData.rayHit = RayHit;
			hitData.fireDir = fireDir;
			hitData.maxRayDist = maxRayDist;
			return hitData;
		}

		public MeleeWeaponFirstPerson Apply(MeleeWeaponFirstPerson melee)
		{
			melee.m_damageToDeal = damage;
			melee.m_precisionMultiToDeal = precisionMulti;
			melee.m_staggerMultiToDeal = staggerMulti;
			return melee;
		}

		public void SetFalloff(float additionalDist = 0f)
		{
			//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)
			RaycastHit rayHit = RayHit;
			falloff = (((RaycastHit)(ref rayHit)).distance + additionalDist).Map(damageFalloff.x, damageFalloff.y, 1f, BulletWeapon.s_falloffMin);
		}

		public WeaponHitData ToWeaponHitData()
		{
			//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_0011: 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_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: 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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			return new WeaponHitData
			{
				damage = damage,
				damageFalloff = damageFalloff,
				precisionMulti = precisionMulti,
				staggerMulti = staggerMulti,
				owner = owner,
				rayHit = RayHit,
				fireDir = fireDir,
				maxRayDist = maxRayDist
			};
		}
	}
	public static class LayerUtil
	{
		public static int MaskDynamic { get; private set; }

		public static int MaskEntityAndWorld { get; private set; }

		public static int MaskEntityAndWorld3P { get; private set; }

		public static int MaskWorld { get; private set; }

		public static int MaskWorldExcProj { get; private set; }

		public static int MaskDecalValid { get; private set; }

		public static int MaskEntityDynamic3P { get; private set; }

		public static int MaskEntity { get; private set; }

		public static int MaskEntity3P { get; private set; }

		public static int MaskOwner { get; private set; }

		public static int MaskFriendly { get; private set; }

		public static int MaskEnemy { get; private set; }

		public static int MaskEnemyDynamic { get; private set; }

		internal static void Init()
		{
			MaskOwner = LayerMask.GetMask(new string[1] { "PlayerMover" });
			MaskFriendly = LayerMask.GetMask(new string[1] { "PlayerSynced" });
			MaskEnemy = LayerMask.GetMask(new string[1] { "EnemyDamagable" });
			MaskDynamic = LayerMask.GetMask(new string[1] { "Dynamic" });
			MaskEnemyDynamic = MaskEnemy | MaskDynamic;
			MaskEntity3P = MaskFriendly | MaskEnemy;
			MaskEntity = MaskOwner | MaskEntity3P;
			MaskDecalValid = LayerMask.GetMask(new string[3] { "Default", "Default_NoGraph", "Default_BlockGraph" });
			MaskWorldExcProj = MaskDecalValid | MaskDynamic;
			MaskWorld = MaskWorldExcProj | LayerMask.GetMask(new string[1] { "ProjectileBlocker" });
			MaskEntityAndWorld = MaskEntity | MaskWorld;
			MaskEntityDynamic3P = MaskEntity3P | MaskDynamic;
			MaskEntityAndWorld3P = MaskEntity3P | MaskWorld;
		}
	}
	[Flags]
	internal enum SearchSetting
	{
		None = 0,
		Alloc = 1,
		CacheHit = 2,
		CheckLOS = 4,
		CheckDoors = 8,
		CheckOwner = 0x10,
		CheckFriendly = 0x20,
		IgnoreDupes = 0x40
	}
	internal static class SearchUtil
	{
		private static readonly List<EnemyAgent> s_enemyCache = new List<EnemyAgent>();

		private static readonly List<(EnemyAgent, RaycastHit)> s_combinedCache = new List<(EnemyAgent, RaycastHit)>();

		private static readonly List<(PlayerAgent, RaycastHit)> s_combinedCachePlayer = new List<(PlayerAgent, RaycastHit)>();

		private static readonly Queue<AIG_CourseNode> s_nodeQueue = new Queue<AIG_CourseNode>();

		private static readonly List<RaycastHit> s_lockCache = new List<RaycastHit>();

		public static HashSet<IntPtr>? DupeCheckSet;

		public static int SightBlockLayer = 0;

		public const float WeakspotBufferDist = 0.1f;

		private static Ray s_ray;

		private static RaycastHit s_rayHit;

		private const float Epsilon = 1E-05f;

		private static Vector3 ClosestPointOnBounds(Bounds bounds, Vector3 point)
		{
			//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_0014: 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_0037: 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_004e: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(Mathf.Clamp(point.x, ((Bounds)(ref bounds)).min.x, ((Bounds)(ref bounds)).max.x), Mathf.Clamp(point.y, ((Bounds)(ref bounds)).min.y, ((Bounds)(ref bounds)).max.y), Mathf.Clamp(point.z, ((Bounds)(ref bounds)).min.z, ((Bounds)(ref bounds)).max.z));
		}

		private static bool PortalInRange(Ray ray, float range, float angle, AIG_CoursePortal portal)
		{
			//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_000c: 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_0019: 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_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_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_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_0068: 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_006c: 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_008e: 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_009f: 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_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_011e: 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_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: 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_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			Bounds portalBounds = portal.m_cullPortal.m_portalBounds;
			Vector3 val = ClosestPointOnBounds(portalBounds, ((Ray)(ref ray)).origin);
			Vector3 val2 = ((Ray)(ref ray)).origin - val;
			if (((Vector3)(ref val2)).sqrMagnitude > range * range)
			{
				return false;
			}
			if (angle >= 180f || ((Bounds)(ref portalBounds)).Contains(((Ray)(ref ray)).origin))
			{
				return true;
			}
			Vector3 val3 = portal.m_cullPortal.m_center - ((Ray)(ref ray)).origin;
			float num = Vector3.Dot(val3, ((Ray)(ref ray)).direction);
			if (angle == 90f)
			{
				return num >= 0f;
			}
			val = Vector3.Project(val3, ((Ray)(ref ray)).direction);
			Bounds portalBounds2 = portal.m_cullPortal.m_portalBounds;
			val2 = ((Bounds)(ref portalBounds2)).extents;
			float magnitude = ((Vector3)(ref val2)).magnitude;
			float num2 = ((Vector3)(ref val)).magnitude * Mathf.Tan(angle * (MathF.PI / 180f));
			if (num2 < 0f)
			{
				if (num >= 0f)
				{
					return true;
				}
				num2 = Mathf.Max(0f, num2 + magnitude);
				val2 = val3 - val;
				return ((Vector3)(ref val2)).sqrMagnitude >= num2 * num2;
			}
			if (num <= 0f)
			{
				return false;
			}
			num2 += magnitude;
			val2 = val3 - val;
			return ((Vector3)(ref val2)).sqrMagnitude <= num2 * num2;
		}

		private static bool RaycastEnsured(Collider collider, Vector3 backupOrigin, float range, out RaycastHit hit)
		{
			//IL_0001: 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_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_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_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_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0073: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			if (collider.Raycast(s_ray, ref hit, range))
			{
				return true;
			}
			Vector3 val = collider.ClosestPoint(backupOrigin);
			Bounds bounds = collider.bounds;
			Vector3 val2 = val - ((Bounds)(ref bounds)).center;
			Vector3 normalized = ((Vector3)(ref val2)).normalized;
			bounds = collider.bounds;
			((Ray)(ref s_ray)).origin = ((Bounds)(ref bounds)).center + val2 + normalized * Mathf.Min(0.1f, range / 2f);
			((Ray)(ref s_ray)).direction = -normalized;
			return collider.Raycast(s_ray, ref hit, range);
		}

		private static bool TryGetClosestHit(Ray ray, float range, float angle, Agent agent, out RaycastHit hit, SearchSetting settings)
		{
			//IL_0002: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			//IL_005f: 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_00cb: Invalid comparison between Unknown and I4
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Invalid comparison between Unknown and I4
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: 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_02b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: 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_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: 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_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			hit = default(RaycastHit);
			if ((Object)(object)agent == (Object)null || !agent.Alive)
			{
				return false;
			}
			if (settings.HasFlag(SearchSetting.IgnoreDupes))
			{
				if ((int)agent.Type == 1)
				{
					HashSet<IntPtr>? dupeCheckSet = DupeCheckSet;
					if (dupeCheckSet != null && dupeCheckSet.Contains(((Il2CppObjectBase)((Il2CppObjectBase)agent).Cast<EnemyAgent>().Damage).Pointer))
					{
						return false;
					}
				}
				if ((int)agent.Type == 0)
				{
					HashSet<IntPtr>? dupeCheckSet2 = DupeCheckSet;
					if (dupeCheckSet2 != null && dupeCheckSet2.Contains(((Il2CppObjectBase)((Il2CppObjectBase)agent).Cast<PlayerAgent>().Damage).Pointer))
					{
						return false;
					}
				}
			}
			((Ray)(ref s_ray)).origin = ((Ray)(ref ray)).origin;
			float num = range * range;
			float num2 = num;
			Collider val = null;
			bool flag = false;
			foreach (Collider componentsInChild in ((Component)agent).GetComponentsInChildren<Collider>())
			{
				Dam_EnemyDamageLimb val2 = null;
				if ((int)agent.Type == 1)
				{
					val2 = ((Component)componentsInChild).GetComponent<Dam_EnemyDamageLimb>();
					if ((Object)(object)val2 == (Object)null || val2.IsDestroyed)
					{
						continue;
					}
				}
				else if ((int)agent.Type == 0 && ((Component)componentsInChild).GetComponent<IDamageable>() == null)
				{
					continue;
				}
				Vector3 val3 = componentsInChild.ClosestPoint(((Ray)(ref ray)).origin);
				Vector3 direction = val3 - ((Ray)(ref ray)).origin;
				float num3 = ((Vector3)(ref direction)).sqrMagnitude;
				float num4 = num3;
				if (val2 != null && (int)val2.m_type == 1 && num3 < num)
				{
					float num5 = Math.Max(((Vector3)(ref direction)).magnitude - 0.1f, 0f);
					num3 = num5 * num5;
				}
				if (!(num3 < num2) || !(Vector3.Angle(((Ray)(ref ray)).direction, val3 - ((Ray)(ref ray)).origin) <= angle) || (settings.HasFlag(SearchSetting.CheckLOS) && Physics.Linecast(((Ray)(ref ray)).origin, val3, SightBlockLayer)))
				{
					continue;
				}
				num2 = num3;
				val = componentsInChild;
				if (!settings.HasFlag(SearchSetting.CacheHit))
				{
					break;
				}
				if (num2 < 1E-05f)
				{
					if (!(num4 > 1E-05f))
					{
						((Ray)(ref s_ray)).origin = ((Ray)(ref s_ray)).origin - ((Ray)(ref ray)).direction * Math.Min(0.1f, range / 2f);
						((Ray)(ref s_ray)).direction = val3 - ((Ray)(ref s_ray)).origin;
						if (RaycastEnsured(componentsInChild, ((Ray)(ref ray)).origin, range, out hit))
						{
							((RaycastHit)(ref hit)).point = val3;
							((RaycastHit)(ref hit)).distance = 0f;
							flag = true;
						}
						else
						{
							val = null;
						}
					}
					break;
				}
				((Ray)(ref s_ray)).direction = direction;
			}
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			if (settings.HasFlag(SearchSetting.CacheHit) && !flag && !RaycastEnsured(val, ((Ray)(ref ray)).origin, range, out hit))
			{
				return false;
			}
			return true;
		}

		private static void CacheEnemiesInRange(Ray ray, float range, float angle, AIG_CourseNode origin, SearchSetting settings)
		{
			//IL_0083: 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_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: 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_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			AIG_SearchID.IncrementSearchID();
			ushort searchID = AIG_SearchID.SearchID;
			float num = range * range;
			s_nodeQueue.Enqueue(origin);
			((AIG_CourseGraphMember)origin).m_searchID = searchID;
			s_combinedCache.Clear();
			AIG_CourseNode result;
			while (s_nodeQueue.TryDequeue(out result))
			{
				Enumerator<AIG_CoursePortal> enumerator = result.m_portals.GetEnumerator();
				while (enumerator.MoveNext())
				{
					AIG_CoursePortal current = enumerator.Current;
					AIG_CourseNode oppositeNode = current.GetOppositeNode(result);
					if ((!settings.HasFlag(SearchSetting.CheckDoors) || current.IsTraversable) && ((AIG_CourseGraphMember)oppositeNode).m_searchID != searchID && PortalInRange(ray, range, angle, current))
					{
						((AIG_CourseGraphMember)oppositeNode).m_searchID = searchID;
						s_nodeQueue.Enqueue(oppositeNode);
					}
				}
				Enumerator<EnemyAgent> enumerator2 = result.m_enemiesInNode.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					EnemyAgent current2 = enumerator2.Current;
					if (!((Object)(object)current2 == (Object)null) && ((Agent)current2).Alive)
					{
						Vector3 val = ClosestPointOnBounds(((C_Cullable)current2.MovingCuller.Culler).Bounds, ((Ray)(ref ray)).origin) - ((Ray)(ref ray)).origin;
						if (!(((Vector3)(ref val)).sqrMagnitude > num) && TryGetClosestHit(ray, range, angle, (Agent)(object)current2, out s_rayHit, settings))
						{
							s_combinedCache.Add((current2, s_rayHit));
						}
					}
				}
			}
		}

		public static List<EnemyAgent> GetEnemiesInRange(Ray ray, float range, float angle, AIG_CourseNode origin, SearchSetting settings = SearchSetting.None)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			s_enemyCache.Clear();
			if (range == 0f || angle == 0f)
			{
				if (!settings.HasFlag(SearchSetting.Alloc))
				{
					return s_enemyCache;
				}
				return new List<EnemyAgent>();
			}
			CacheEnemiesInRange(ray, range, angle, origin, settings);
			if (settings.HasFlag(SearchSetting.Alloc))
			{
				return s_combinedCache.ConvertAll(((EnemyAgent, RaycastHit) pair) => pair.Item1);
			}
			foreach (var item2 in s_combinedCache)
			{
				EnemyAgent item = item2.Item1;
				s_enemyCache.Add(item);
			}
			return s_enemyCache;
		}

		public static List<(EnemyAgent enemy, RaycastHit hit)> GetEnemyHitsInRange(Ray ray, float range, float angle, AIG_CourseNode origin, SearchSetting settings = SearchSetting.CacheHit)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (range == 0f || angle == 0f)
			{
				s_combinedCache.Clear();
				if (!settings.HasFlag(SearchSetting.Alloc))
				{
					return s_combinedCache;
				}
				return new List<(EnemyAgent, RaycastHit)>();
			}
			settings |= SearchSetting.CacheHit;
			CacheEnemiesInRange(ray, range, angle, origin, settings);
			if (settings.HasFlag(SearchSetting.Alloc))
			{
				return new List<(EnemyAgent, RaycastHit)>(s_combinedCache);
			}
			return s_combinedCache;
		}

		public static List<RaycastHit> GetLockHitsInRange(Ray ray, float range, float angle, SearchSetting settings = SearchSetting.None)
		{
			//IL_003b: 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_0105: 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)
			//IL_011c: 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_00c5: 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_013f: Unknown result type (might be due to invalid IL or missing references)
			s_lockCache.Clear();
			if (range == 0f || angle == 0f)
			{
				if (!settings.HasFlag(SearchSetting.Alloc))
				{
					return s_lockCache;
				}
				return new List<RaycastHit>();
			}
			Collider[] array = Il2CppArrayBase<Collider>.op_Implicit((Il2CppArrayBase<Collider>)(object)Physics.OverlapSphere(((Ray)(ref ray)).origin, range, LayerUtil.MaskDynamic));
			Vector3 direction = ((Ray)(ref ray)).direction;
			Collider[] array2 = array;
			foreach (Collider val in array2)
			{
				IDamageable damageableFromCollider = DamageableUtil.GetDamageableFromCollider(val);
				if (damageableFromCollider == null)
				{
					continue;
				}
				if (settings.HasFlag(SearchSetting.IgnoreDupes))
				{
					HashSet<IntPtr>? dupeCheckSet = DupeCheckSet;
					if (dupeCheckSet != null && dupeCheckSet.Contains(((Il2CppObjectBase)damageableFromCollider.GetBaseDamagable()).Pointer))
					{
						continue;
					}
				}
				if (!settings.HasFlag(SearchSetting.CheckLOS) || !Physics.Linecast(((Ray)(ref ray)).origin, damageableFromCollider.DamageTargetPos, ref s_rayHit, SightBlockLayer) || !(((Il2CppObjectBase)((Component)((RaycastHit)(ref s_rayHit)).collider).gameObject).Pointer != ((Il2CppObjectBase)((Component)val).gameObject).Pointer))
				{
					((Ray)(ref ray)).direction = damageableFromCollider.DamageTargetPos - ((Ray)(ref ray)).origin;
					if (val.Raycast(ray, ref s_rayHit, range) && Vector3.Angle(((Ray)(ref ray)).direction, direction) < angle)
					{
						s_lockCache.Add(s_rayHit);
					}
				}
			}
			if (settings.HasFlag(SearchSetting.Alloc))
			{
				return new List<RaycastHit>(s_lockCache);
			}
			return s_lockCache;
		}

		public static List<(PlayerAgent, RaycastHit)> GetPlayerHitsInRange(Ray ray, float range, float angle, SearchSetting settings = SearchSetting.CheckOwner | SearchSetting.CheckFriendly)
		{
			//IL_0076: 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_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)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: 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_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_00fb: 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_0122: 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)
			s_combinedCachePlayer.Clear();
			if (range == 0f || angle == 0f)
			{
				if (!settings.HasFlag(SearchSetting.Alloc))
				{
					return s_combinedCachePlayer;
				}
				return new List<(PlayerAgent, RaycastHit)>();
			}
			float num = range * range;
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if ((Object)(object)current == (Object)null || !((Agent)current).Alive)
				{
					continue;
				}
				Vector3 val = ClosestPointOnBounds(((C_Cullable)current.m_movingCuller.Culler).Bounds, ((Ray)(ref ray)).origin) - ((Ray)(ref ray)).origin;
				if (((Vector3)(ref val)).sqrMagnitude > num)
				{
					continue;
				}
				if (((Agent)current).IsLocallyOwned)
				{
					if (!settings.HasFlag(SearchSetting.CheckOwner))
					{
						continue;
					}
					((Ray)(ref s_ray)).origin = ((Ray)(ref ray)).origin;
					((Ray)(ref s_ray)).direction = ((Dam_SyncedDamageBase)current.Damage).DamageTargetPos - ((Ray)(ref ray)).origin;
					if (!((Component)current).GetComponent<Collider>().Raycast(s_ray, ref s_rayHit, range) || (settings.HasFlag(SearchSetting.CheckLOS) && Physics.Linecast(((Ray)(ref ray)).origin, ((RaycastHit)(ref s_rayHit)).point, SightBlockLayer)))
					{
						continue;
					}
				}
				else if (!settings.HasFlag(SearchSetting.CheckFriendly) || !TryGetClosestHit(ray, range, angle, (Agent)(object)current, out s_rayHit, settings))
				{
					continue;
				}
				s_combinedCachePlayer.Add((current, s_rayHit));
			}
			if (settings.HasFlag(SearchSetting.Alloc))
			{
				return new List<(PlayerAgent, RaycastHit)>(s_combinedCachePlayer);
			}
			return s_combinedCachePlayer;
		}

		private static bool HasCluster(AIG_VoxelNodePillar pillar)
		{
			Enumerator<AIG_VoxelNode> enumerator = pillar.m_nodes.GetEnumerator();
			AIG_NodeCluster val = default(AIG_NodeCluster);
			while (enumerator.MoveNext())
			{
				AIG_VoxelNode current = enumerator.Current;
				if (current.ClusterID != 0 && AIG_NodeCluster.TryGetNodeCluster(current.ClusterID, ref val))
				{
					return true;
				}
			}
			return false;
		}

		public static AIG_CourseNode GetCourseNode(Vector3 position, Agent agent)
		{
			//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_0007: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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_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_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_0071: 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_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position2 = agent.Position;
			if (TryGetGeomorphVolumeSilent(Dimension.GetDimensionFromPos(position).DimensionIndex, position, out AIG_GeomorphNodeVolume resultingGeoVolume))
			{
				position.y = ((AIG_NodeVolume)resultingGeoVolume).Position.y;
				position2.y = position.y;
				Vector3 val = position2 - position;
				Vector3 normalized = ((Vector3)(ref val)).normalized;
				AIG_VoxelNodePillar val2 = null;
				for (int i = 0; i < 10; i++)
				{
					if (((AIG_NodeVolume)resultingGeoVolume).m_voxelNodeVolume.TryGetPillar(position, ref val2) && HasCluster(val2))
					{
						break;
					}
					position += normalized;
				}
				if (val2 == null)
				{
					return agent.CourseNode;
				}
				Enumerator<AIG_VoxelNode> enumerator = val2.m_nodes.GetEnumerator();
				AIG_NodeCluster val3 = default(AIG_NodeCluster);
				while (enumerator.MoveNext())
				{
					AIG_VoxelNode current = enumerator.Current;
					if (current.ClusterID != 0 && AIG_NodeCluster.TryGetNodeCluster(current.ClusterID, ref val3) && val3.CourseNode != null)
					{
						return val3.CourseNode;
					}
				}
			}
			return agent.CourseNode;
		}

		private static bool TryGetGeomorphVolumeSilent(eDimensionIndex dimensionIndex, Vector3 pos, [MaybeNullWhen(false)] out AIG_GeomorphNodeVolume resultingGeoVolume)
		{
			//IL_001a: 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)
			resultingGeoVolume = null;
			LG_Floor currentFloor = Builder.Current.m_currentFloor;
			if ((Object)(object)currentFloor == (Object)null)
			{
				return false;
			}
			Dimension val = default(Dimension);
			if (!currentFloor.GetDimension(dimensionIndex, ref val))
			{
				return false;
			}
			if (val.Grid == null || !TryGetCell(val.Grid, pos, out LG_Cell cell))
			{
				return false;
			}
			if (((CellBase<LG_Tile, LG_Cell>)(object)cell).m_grouping == null || (Object)(object)((CellBase<LG_Tile, LG_Cell>)(object)cell).m_grouping.m_geoRoot == (Object)null)
			{
				return false;
			}
			resultingGeoVolume = ((Il2CppObjectBase)((CellBase<LG_Tile, LG_Cell>)(object)cell).m_grouping.m_geoRoot.m_nodeVolume).TryCast<AIG_GeomorphNodeVolume>();
			return (Object)(object)resultingGeoVolume != (Object)null;
		}

		private static bool TryGetCell(LG_Grid grid, Vector3 pos, [MaybeNullWhen(false)] out LG_Cell cell)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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_0028: Unknown result type (might be due to invalid IL or missing references)
			pos -= ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_gridPosition;
			int num = Mathf.RoundToInt((pos.x - ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_cellDimHalf) / ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_cellDim);
			int num2 = Mathf.RoundToInt((pos.z - ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_cellDimHalf) / ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_cellDim);
			if (num < 0 || num2 < 0 || num >= ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_sizeX || num2 >= ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_sizeZ)
			{
				cell = null;
				return false;
			}
			cell = ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetCell(num, num2);
			return true;
		}
	}
	internal static class SortUtil
	{
		private static List<(RaycastHit hit, float distance)> s_limbCache = new List<(RaycastHit, float)>();

		private static List<(EnemyAgent enemy, float value)> s_enemyTupleCache = new List<(EnemyAgent, float)>();

		public static int Rayhit(RaycastHit x, RaycastHit y)
		{
			if (((RaycastHit)(ref x)).distance == ((RaycastHit)(ref y)).distance)
			{
				return 0;
			}
			if (!(((RaycastHit)(ref x)).distance < ((RaycastHit)(ref y)).distance))
			{
				return 1;
			}
			return -1;
		}

		public static int EnemyRayhit((EnemyAgent, RaycastHit hit) x, (EnemyAgent, RaycastHit hit) y)
		{
			if (((RaycastHit)(ref x.hit)).distance == ((RaycastHit)(ref y.hit)).distance)
			{
				return 0;
			}
			if (!(((RaycastHit)(ref x.hit)).distance < ((RaycastHit)(ref y.hit)).distance))
			{
				return 1;
			}
			return -1;
		}

		public static void SortWithWeakspotBuffer(IList<RaycastHit> list)
		{
			//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_0010: 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_0059: 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_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)
			foreach (RaycastHit item in list)
			{
				RaycastHit current = item;
				IDamageable? damageableFromRayHit = DamageableUtil.GetDamageableFromRayHit(current);
				int num;
				if (damageableFromRayHit == null)
				{
					num = 0;
				}
				else
				{
					Dam_EnemyDamageLimb obj = ((Il2CppObjectBase)damageableFromRayHit).TryCast<Dam_EnemyDamageLimb>();
					num = ((((obj != null) ? new eLimbDamageType?(obj.m_type) : null) == (eLimbDamageType?)1) ? 1 : 0);
				}
				bool flag = (byte)num != 0;
				s_limbCache.Add((current, flag ? Mathf.Max(((RaycastHit)(ref current)).distance - 0.1f, 0f) : ((RaycastHit)(ref current)).distance));
			}
			s_limbCache.Sort(FloatTuple);
			CopySortedList(s_limbCache, list);
			s_limbCache.Clear();
		}

		public static void CopySortedList<T>(IList<(T, float)> sortedList, IList<T> list)
		{
			for (int i = 0; i < list.Count; i++)
			{
				list[i] = sortedList[i].Item1;
			}
		}

		public static void CopySortedList<T>(IList<(T, float, float)> sortedList, IList<T> list)
		{
			for (int i = 0; i < list.Count; i++)
			{
				list[i] = sortedList[i].Item1;
			}
		}

		public static int FloatTuple<T>((T, float val) x, (T, float val) y)
		{
			if (x.val == y.val)
			{
				return 0;
			}
			if (!(x.val < y.val))
			{
				return 1;
			}
			return -1;
		}

		public static int FloatTuple<T>((T, float val1, float val2) x, (T, float val1, float val2) y)
		{
			if (x.val1 == y.val1)
			{
				if (x.val2 == y.val2)
				{
					return 0;
				}
				if (!(x.val2 < y.val2))
				{
					return 1;
				}
				return -1;
			}
			if (!(x.val1 < y.val1))
			{
				return 1;
			}
			return -1;
		}
	}
	internal static class StringExtensions
	{
		public static T ToEnum<T>(this string? value, T defaultValue) where T : struct
		{
			if (string.IsNullOrEmpty(value))
			{
				return defaultValue;
			}
			if (!Enum.TryParse<T>(value.Replace(" ", null), ignoreCase: true, out var result))
			{
				return defaultValue;
			}
			return result;
		}
	}
}
namespace EWC.Utils.Log
{
	internal static class EWCLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("ExtraWeaponCustomization");

		public static void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		public static void Log(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)8, (object)str);
			}
		}

		public static void Warning(string format, params object[] args)
		{
			Warning(string.Format(format, args));
		}

		public static void Warning(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)4, (object)str);
			}
		}

		public static void Error(string format, params object[] args)
		{
			Error(string.Format(format, args));
		}

		public static void Error(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)2, (object)str);
			}
		}

		public static void Debug(string format, params object[] args)
		{
			Debug(string.Format(format, args));
		}

		public static void Debug(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)32, (object)str);
			}
		}
	}
}
namespace EWC.Patches
{
	[HarmonyPatch]
	internal static class EnemyLimbPatches
	{
		private static float _cachedArmor;

		[HarmonyPatch(typeof(Dam_EnemyDamageLimb), "BulletDamage")]
		[HarmonyPatch(typeof(Dam_EnemyDamageLimb), "MeleeDamage")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_Damage(Dam_EnemyDamageLimb __instance)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			ContextController cachedHitCC = WeaponPatches.CachedHitCC;
			if (cachedHitCC != null && (int)__instance.m_type == 2)
			{
				_cachedArmor = __instance.m_armorDamageMulti;
				__instance.m_armorDamageMulti = cachedHitCC.Invoke(new WeaponArmorContext(_cachedArmor)).ArmorMulti;
			}
		}

		[HarmonyPatch(typeof(Dam_EnemyDamageLimb), "BulletDamage")]
		[HarmonyPatch(typeof(Dam_EnemyDamageLimb), "MeleeDamage")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_Damage(Dam_EnemyDamageLimb __instance)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			if (WeaponPatches.CachedHitCC != null && (int)__instance.m_type == 2)
			{
				__instance.m_armorDamageMulti = _cachedArmor;
			}
		}

		[HarmonyPatch(typeof(Dam_EnemyDamageLimb_Custom), "ApplyWeakspotAndArmorModifiers")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static bool Pre_WeakspotModifiers(Dam_EnemyDamageLimb_Custom __instance, float dam, float precisionMulti, ref float __result)
		{
			if (!WeaponPatches.CachedBypassTumorCap)
			{
				return true;
			}
			__result = dam * Mathf.Max(((Dam_EnemyDamageLimb)__instance).m_weakspotDamageMulti * precisionMulti, 1f) * ((Dam_EnemyDamageLimb)__instance).m_armorDamageMulti;
			return false;
		}
	}
	[HarmonyPatch]
	internal static class FPISPatches
	{
		private static CustomWeaponComponent? _cachedCWC;

		[HarmonyPatch(typeof(FPIS_Aim), "Enter")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_AimEnter(FPIS_Aim __instance)
		{
			_cachedCWC = ((Component)((FPItemState)__instance).Holder.WieldedItem).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)_cachedCWC == (Object)null))
			{
				_cachedCWC.Invoke(StaticContext<WeaponAimContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(FPIS_Aim), "Exit")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_AimExit()
		{
			if (!((Object)(object)_cachedCWC == (Object)null))
			{
				_cachedCWC.Invoke(StaticContext<WeaponAimEndContext>.Instance);
			}
		}
	}
	[HarmonyPatch]
	internal static class PlayerInventoryPatches
	{
		private static bool _allowReload = true;

		[HarmonyPatch(typeof(PUI_Inventory), "SetSlotAmmo")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void SetAmmoUICallback(PUI_Inventory __instance, InventorySlot slot, ref int clipAbs, ref int inPackAbs, ref float inPackRel)
		{
			//IL_0000: 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)
			if ((int)slot == 0)
			{
				return;
			}
			SNet_Player owner = __instance.m_owner;
			object obj;
			if (owner == null)
			{
				obj = null;
			}
			else
			{
				SNet_IPlayerAgent playerAgent = owner.PlayerAgent;
				if (playerAgent == null)
				{
					obj = null;
				}
				else
				{
					PlayerAgent obj2 = ((Il2CppObjectBase)playerAgent).TryCast<PlayerAgent>();
					if (obj2 == null)
					{
						obj = null;
					}
					else
					{
						FirstPersonItemHolder fPItemHolder = obj2.FPItemHolder;
						if (fPItemHolder == null)
						{
							obj = null;
						}
						else
						{
							ItemEquippable wieldedItem = fPItemHolder.WieldedItem;
							if (wieldedItem == null)
							{
								obj = null;
							}
							else
							{
								BulletWeapon obj3 = ((Il2CppObjectBase)wieldedItem).TryCast<BulletWeapon>();
								obj = ((obj3 != null) ? ((Component)obj3).GetComponent<CustomWeaponComponent>() : null);
							}
						}
					}
				}
			}
			CustomWeaponComponent customWeaponComponent = (CustomWeaponComponent)obj;
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				PUI_InventoryItem val = __instance.m_inventorySlots[slot];
				WeaponPreAmmoUIContext weaponPreAmmoUIContext = new WeaponPreAmmoUIContext(clipAbs, inPackAbs, inPackRel, val.ShowAmmoClip, val.ShowAmmoPack, val.ShowAmmoTotalRel, val.ShowAmmoInfinite);
				customWeaponComponent.Invoke(weaponPreAmmoUIContext);
				clipAbs = weaponPreAmmoUIContext.Clip;
				inPackAbs = weaponPreAmmoUIContext.Reserve;
				inPackRel = weaponPreAmmoUIContext.TotalRel;
				val.ShowAmmoClip = weaponPreAmmoUIContext.ShowClip;
				val.ShowAmmoPack = weaponPreAmmoUIContext.ShowReserve;
				val.ShowAmmoTotalRel = weaponPreAmmoUIContext.ShowRel;
				val.ShowAmmoInfinite = weaponPreAmmoUIContext.ShowInfinite;
			}
		}

		private static InventorySlot AmmoToSlot(AmmoType ammo)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected I4, but got Unknown
			//IL_0015: 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_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_0021: Unknown result type (might be due to invalid IL or missing references)
			return (InventorySlot)((int)ammo switch
			{
				0 => 1, 
				1 => 2, 
				2 => 3, 
				_ => 0, 
			});
		}

		[HarmonyPatch(typeof(PlayerAmmoStorage), "PickupAmmo")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void AmmoPackCallback(PlayerAmmoStorage __instance, AmmoType ammoType, ref float ammoAmount)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			BackpackItem val = default(BackpackItem);
			if (__instance.m_playerBackpack.TryGetBackpackItem(AmmoToSlot(ammoType), ref val))
			{
				Item instance = val.Instance;
				CustomWeaponComponent customWeaponComponent = ((instance != null) ? ((Component)instance).GetComponent<CustomWeaponComponent>() : null);
				if ((Object)(object)customWeaponComponent != (Object)null)
				{
					ammoAmount = customWeaponComponent.Invoke(new WeaponPreAmmoPackContext(ammoAmount)).AmmoAmount;
				}
			}
		}

		[HarmonyPatch(typeof(PlayerAmmoStorage), "PickupAmmo")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostAmmoPackCallback(PlayerAmmoStorage __instance, AmmoType ammoType)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			BackpackItem val = default(BackpackItem);
			if (__instance.m_playerBackpack.TryGetBackpackItem(AmmoToSlot(ammoType), ref val))
			{
				Item instance = val.Instance;
				((instance != null) ? ((Component)instance).GetComponent<CustomWeaponComponent>() : null)?.Invoke(new WeaponPostAmmoPackContext(__instance));
			}
		}

		[HarmonyPatch(typeof(PlayerInventoryLocal), "DoReload")]
		[HarmonyPatch(typeof(PlayerInventoryBase), "DoReload")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void ReloadCallback(PlayerInventoryBase __instance)
		{
			ItemEquippable wieldedItem = __instance.m_wieldedItem;
			CustomWeaponComponent customWeaponComponent = ((wieldedItem != null) ? ((Component)wieldedItem).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				customWeaponComponent.Invoke(StaticContext<WeaponPostReloadContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(PlayerInventoryLocal), "TriggerReload")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static bool ReloadPreStartCallback(PlayerInventoryLocal __instance)
		{
			_allowReload = true;
			ItemEquippable wieldedItem = ((PlayerInventoryBase)__instance).m_wieldedItem;
			CustomWeaponComponent customWeaponComponent = ((wieldedItem != null) ? ((Component)wieldedItem).GetComponent<CustomWeaponComponent>() : null);
			if ((Object)(object)customWeaponComponent == (Object)null)
			{
				return true;
			}
			_allowReload = customWeaponComponent.Invoke(new WeaponPreReloadContext()).Allow;
			return _allowReload;
		}

		[HarmonyPatch(typeof(PlayerInventoryLocal), "TriggerReload")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void ReloadStartCallback(PlayerInventoryLocal __instance)
		{
			if (_allowReload)
			{
				ItemEquippable wieldedItem = ((PlayerInventoryBase)__instance).m_wieldedItem;
				CustomWeaponComponent customWeaponComponent = ((wieldedItem != null) ? ((Component)wieldedItem).GetComponent<CustomWeaponComponent>() : null);
				if (!((Object)(object)customWeaponComponent == (Object)null) && customWeaponComponent.Weapon.IsReloading)
				{
					customWeaponComponent.Invoke(StaticContext<WeaponReloadStartContext>.Instance);
				}
			}
		}

		[HarmonyPatch(typeof(PlayerAmmoStorage), "FillAllClips")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostFillAllClipsCallback(PlayerAmmoStorage __instance)
		{
			BackpackItem val = default(BackpackItem);
			if (__instance.m_playerBackpack.TryGetBackpackItem((InventorySlot)1, ref val))
			{
				Item instance = val.Instance;
				((instance != null) ? ((Component)instance).GetComponent<CustomWeaponComponent>() : null)?.Invoke(new WeaponPostAmmoInitContext(__instance, __instance.StandardAmmo));
			}
			BackpackItem val2 = default(BackpackItem);
			if (__instance.m_playerBackpack.TryGetBackpackItem((InventorySlot)2, ref val2))
			{
				Item instance2 = val2.Instance;
				((instance2 != null) ? ((Component)instance2).GetComponent<CustomWeaponComponent>() : null)?.Invoke(new WeaponPostAmmoInitContext(__instance, __instance.SpecialAmmo));
			}
		}
	}
	[HarmonyPatch]
	internal static class ShotgunPatches
	{
		[HarmonyPatch(typeof(Shotgun), "Fire")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_Fire(Shotgun __instance)
		{
			WeaponRayPatches.CachedWeapon = (BulletWeapon?)(object)__instance;
		}

		[HarmonyPatch(typeof(Shotgun), "Fire")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_Fire(Shotgun __instance)
		{
			WeaponRayPatches.CachedWeapon = null;
		}
	}
	[HarmonyPatch]
	internal static class WeaponArchetypePatches
	{
		[HarmonyPatch(typeof(BulletWeaponArchetype), "SetOwner")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void SetupCallback(BulletWeaponArchetype __instance, PlayerAgent owner)
		{
			if (!((Object)(object)owner == (Object)null))
			{
				CustomWeaponComponent component = ((Component)__instance.m_weapon).GetComponent<CustomWeaponComponent>();
				if (!((Object)(object)component == (Object)null))
				{
					component.OwnerInit();
				}
			}
		}

		[HarmonyPatch(typeof(BWA_Burst), "OnStartFiring")]
		[HarmonyPatch(typeof(BWA_Auto), "OnStartFiring")]
		[HarmonyPatch(typeof(BulletWeaponArchetype), "OnStartFiring")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static bool StartFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if ((Object)(object)customWeaponComponent == (Object)null)
			{
				return true;
			}
			customWeaponComponent.CancelShot = false;
			WeaponPreStartFireContext weaponPreStartFireContext = new WeaponPreStartFireContext();
			customWeaponComponent.Invoke(weaponPreStartFireContext);
			customWeaponComponent.UpdateStoredFireRate();
			if (!weaponPreStartFireContext.Allow)
			{
				customWeaponComponent.StoreCancelShot();
			}
			return weaponPreStartFireContext.Allow;
		}

		[HarmonyPatch(typeof(BWA_Burst), "OnStartFiring")]
		[HarmonyPatch(typeof(BWA_Auto), "OnStartFiring")]
		[HarmonyPatch(typeof(BulletWeaponArchetype), "OnStartFiring")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostStartFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				if (customWeaponComponent.ResetShotIfCancel(__instance))
				{
					customWeaponComponent.CancelShot = false;
					__instance.m_readyToFire = false;
				}
				else
				{
					customWeaponComponent.Invoke(StaticContext<WeaponPostStartFireContext>.Instance);
				}
			}
		}

		[HarmonyPatch(typeof(BWA_Auto), "OnFireShot")]
		[HarmonyPatch(typeof(BWA_Burst), "OnFireShot")]
		[HarmonyPatch(typeof(BWA_Semi), "OnFireShot")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static bool PreFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if ((Object)(object)customWeaponComponent == (Object)null)
			{
				return true;
			}
			if (customWeaponComponent.CancelShot)
			{
				return false;
			}
			WeaponFireCancelContext weaponFireCancelContext = new WeaponFireCancelContext();
			customWeaponComponent.Invoke(weaponFireCancelContext);
			if (!weaponFireCancelContext.Allow)
			{
				customWeaponComponent.StoreCancelShot();
			}
			else
			{
				customWeaponComponent.Invoke(StaticContext<WeaponPreFireContext>.Instance);
			}
			return weaponFireCancelContext.Allow;
		}

		[HarmonyPatch(typeof(BWA_Auto), "OnFireShot")]
		[HarmonyPatch(typeof(BWA_Burst), "OnFireShot")]
		[HarmonyPatch(typeof(BWA_Semi), "OnFireShot")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null) && !customWeaponComponent.CancelShot)
			{
				customWeaponComponent.Invoke(StaticContext<WeaponPostFireContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(BulletWeaponArchetype), "PostFireCheck")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void PrePostFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				customWeaponComponent.ResetShotIfCancel(__instance);
			}
		}

		[HarmonyPatch(typeof(BulletWeaponArchetype), "PostFireCheck")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostPostFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				if (customWeaponComponent.CancelShot)
				{
					customWeaponComponent.CancelShot = false;
					return;
				}
				customWeaponComponent.UpdateStoredFireRate();
				customWeaponComponent.ModifyFireRate();
			}
		}

		[HarmonyPatch(typeof(BWA_Burst), "OnStopFiring")]
		[HarmonyPatch(typeof(BWA_Auto), "OnStopFiring")]
		[HarmonyPatch(typeof(BulletWeaponArchetype), "OnStopFiring")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void StopFiringCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				customWeaponComponent.Invoke(StaticContext<WeaponPostStopFiringContext>.Instance);
			}
		}
	}
	[HarmonyPatch]
	internal static class WeaponPatches
	{
		private static uint s_lastSearchID = 0u;

		private static float s_origHitDamage = 0f;

		private static float s_origHitPrecision = 0f;

		private static readonly HitData s_hitData = new HitData();

		private static ContextController? _cachedHitCC = null;

		public static ContextController? CachedHitCC
		{
			get
			{
				return _cachedHitCC;
			}
			set
			{
				_cachedHitCC = value;
				CachedBypassTumorCap = false;
			}
		}

		public static bool CachedBypassTumorCap { get; private set; } = false;


		[HarmonyPatch(typeof(BulletWeapon), "OnGearSpawnComplete")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void SetupCallback(BulletWeapon __instance)
		{
			CustomWeaponManager.Current.AddWeaponListener((ItemEquippable)(object)__instance);
			CustomWeaponData customGunData = CustomWeaponManager.Current.GetCustomGunData(((GameDataBlockBase<ArchetypeDataBlock>)(object)((ItemEquippable)__instance).ArchetypeData).persistentID);
			if (customGunData != null && !((Object)(object)((Component)__instance).gameObject.GetComponent<CustomWeaponComponent>() != (Object)null))
			{
				((Component)__instance).gameObject.AddComponent<CustomWeaponComponent>().Register(customGunData);
			}
		}

		[HarmonyPatch(typeof(BulletWeapon), "OnWield")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void UpdateCurrentWeapon(BulletWeapon __instance)
		{
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponWieldContext>.Instance);
				component.RefreshSoundDelay();
				s_lastSearchID = 0u;
			}
		}

		[HarmonyPatch(typeof(BulletWeapon), "OnUnWield")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void UpdateWeaponUnwielded(BulletWeapon __instance)
		{
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponUnWieldContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(BulletWeapon), "BulletHit")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void HitCallback(ref WeaponHitData weaponRayData, bool doDamage, float additionalDis, uint damageSearchID, ref bool allowDirectionalBonus)
		{
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Invalid comparison between Unknown and I4
			CachedHitCC = null;
			if (!allowDirectionalBonus || weaponRayData.vfxBulletHit != null || !doDamage || (!((Agent)weaponRayData.owner).IsLocallyOwned && (!SNet.IsMaster || !weaponRayData.owner.Owner.IsBot)))
			{
				return;
			}
			s_hitData.Setup(weaponRayData, additionalDis);
			IDamageable damageable = s_hitData.damageable;
			IDamageable val = ((((damageable != null) ? damageable.GetBaseDamagable() : null) != null) ? damageable.GetBaseDamagable() : damageable);
			if (damageSearchID != 0 && val != null && val.TempSearchID == damageSearchID)
			{
				return;
			}
			ItemEquippable wieldedItem = s_hitData.owner.Inventory.WieldedItem;
			CustomWeaponComponent customWeaponComponent = ((wieldedItem != null) ? ((Component)wieldedItem).GetComponent<CustomWeaponComponent>() : null);
			if ((Object)(object)customWeaponComponent == (Object)null)
			{
				Agent val2 = ((damageable != null) ? damageable.GetBaseAgent() : null);
				if ((Object)(object)val2 != (Object)null && (int)val2.Type == 1 && val2.Alive)
				{
					KillTrackerManager.ClearHit(((Il2CppObjectBase)val2).TryCast<EnemyAgent>());
				}
				return;
			}
			if (damageable != null && damageSearchID != 0)
			{
				if (s_lastSearchID != damageSearchID)
				{
					s_lastSearchID = damageSearchID;
					s_origHitDamage = s_hitData.damage;
					s_origHitPrecision = s_hitData.precisionMulti;
				}
				s_hitData.damage = s_origHitDamage;
				s_hitData.precisionMulti = s_origHitPrecision;
			}
			ApplyEWCHit(customWeaponComponent, damageable, s_hitData, damageSearchID != 0, ref s_origHitDamage, ref allowDirectionalBonus);
		}

		public static void ApplyEWCHit(CustomWeaponComponent cwc, IDamageable? damageable, HitData hitData, bool pierce, ref float pierceDamage, ref bool doBackstab)
		{
			ApplyEWCHit(cwc.GetContextController(), cwc.Weapon, damageable, hitData, pierce, ref pierceDamage, ref doBackstab);
		}

		public static void ApplyEWCHit(ContextController cc, ItemEquippable weapon, IDamageable? damageable, HitData hitData, bool pierce, ref float pierceDamage, ref bool doBackstab)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Invalid comparison between Unknown and I4
			//IL_00ae: 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)
			CachedHitCC = cc;
			if (damageable != null)
			{
				WeaponDamageContext weaponDamageContext = new WeaponDamageContext(hitData.damage, hitData.precisionMulti, damageable);
				cc.Invoke(weaponDamageContext);
				hitData.damage = weaponDamageContext.Damage.Value;
				hitData.precisionMulti = weaponDamageContext.Precision.Value;
				CachedBypassTumorCap = weaponDamageContext.BypassTumorCap;
				if (pierce)
				{
					WeaponPierceContext weaponPierceContext = new WeaponPierceContext(pierceDamage, damageable);
					cc.Invoke(weaponPierceContext);
					pierceDamage = weaponPierceContext.Value;
				}
			}
			Agent val = ((damageable != null) ? damageable.GetBaseAgent() : null);
			if ((Object)(object)val != (Object)null && (int)val.Type == 1 && val.Alive)
			{
				Dam_EnemyDamageLimb val2 = ((Il2CppObjectBase)damageable).TryCast<Dam_EnemyDamageLimb>();
				float num = val2.ApplyDamageFromBehindBonus(1f, hitData.hitPos, ((Vector3)(ref hitData.fireDir)).normalized, 1f);
				WeaponBackstabContext weaponBackstabContext = new WeaponBackstabContext();
				cc.Invoke(weaponBackstabContext);
				WeaponPreHitEnemyContext weaponPreHitEnemyContext = new WeaponPreHitEnemyContext(hitData, CachedBypassTumorCap, num.Map(1f, 2f, 1f, weaponBackstabContext.Value), val2, DamageType.Bullet);
				cc.Invoke(weaponPreHitEnemyContext);
				KillTrackerManager.RegisterHit(weapon, weaponPreHitEnemyContext);
				if (weaponBackstabContext.Value > 1f)
				{
					hitData.damage *= weaponPreHitEnemyContext.Backstab / num;
				}
				else
				{
					doBackstab = false;
				}
			}
			else
			{
				cc.Invoke(new WeaponPreHitContext(hitData));
			}
			hitData.Apply();
		}
	}
	[HarmonyPatch]
	internal static class WeaponRayPatches
	{
		public static BulletWeapon? CachedWeapon = null;

		private static HitData s_hitData = new HitData();

		private static CustomWeaponComponent? _cachedCWC = null;

		[HarmonyTargetMethod]
		private static MethodBase FindWeaponRayFunc(Harmony harmony)
		{
			return AccessTools.Method(typeof(Weapon), "CastWeaponRay", new Type[4]
			{
				typeof(Transform),
				typeof(WeaponHitData).MakeByRefType(),
				typeof(Vector3),
				typeof(int)
			}, (Type[])null);
		}

		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void PreRayCallback(ref WeaponHitData weaponRayData, Vector3 originPos, int altRayCastMask)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			if (altRayCastMask != -1)
			{
				return;
			}
			if ((Object)(object)CachedWeapon != (Object)null)
			{
				_cachedCWC = ((Component)CachedWeapon).GetComponent<CustomWeaponComponent>();
			}
			else
			{
				PlayerAgent owner = weaponRayData.owner;
				object cachedCWC;
				if (owner == null)
				{
					cachedCWC = null;
				}
				else
				{
					ItemEquippable wieldedItem = owner.Inventory.WieldedItem;
					cachedCWC = ((wieldedItem != null) ? ((Component)wieldedItem).GetComponent<CustomWeaponComponent>() : null);
				}
				_cachedCWC = (CustomWeaponComponent?)cachedCWC;
			}
			if (!((Object)(object)_cachedCWC == (Object)null))
			{
				s_hitData.Setup(weaponRayData);
				_cachedCWC.Invoke(new WeaponPreRayContext(s_hitData, originPos));
				s_hitData.Apply();
			}
		}

		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostRayCallback(ref WeaponHitData weaponRayData, Vector3 originPos, int altRayCastMask, ref bool __result)
		{
			//IL_002e: 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)
			if (altRayCastMask == -1 && !((Object)(object)_cachedCWC == (Object)null))
			{
				s_hitData.Setup(weaponRayData);
				if (!_cachedCWC.Invoke(new WeaponCancelRayContext(s_hitData, originPos)).Result)
				{
					__result = false;
					return;
				}
				__result = _cachedCWC.Invoke(new WeaponPostRayContext(s_hitData, originPos, __result)).Result;
				s_hitData.Apply();
			}
		}
	}
	[HarmonyPatch]
	internal static class WeaponRecoilPatches
	{
		private static BulletWeapon? _cachedWeapon;

		private static CustomWeaponComponent? _cachedComponent;

		[HarmonyPatch(typeof(BulletWeapon), "OnWield")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void UpdateCurrentWeapon(BulletWeapon __instance)
		{
			PlayerAgent owner = ((Item)__instance).Owner;
			if (owner != null && ((Agent)owner).IsLocallyOwned)
			{
				_cachedWeapon = __instance;
				_cachedComponent = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			}
		}

		[HarmonyAfter(new string[] { "Dinorush.ExtraRecoilData" })]
		[HarmonyPatch(typeof(FPS_RecoilSystem), "ApplyRecoil")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostApplyRecoilCallback(FPS_RecoilSystem __instance, bool resetSimilarity, RecoilDataBlock recoilData)
		{
			//IL_0031: 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_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_0075: 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_00a9: 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_00b8: 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_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: 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_0113: 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)
			if (!((Object)(object)_cachedComponent == (Object)null))
			{
				WeaponRecoilContext weaponRecoilContext = new WeaponRecoilContext();
				_cachedComponent.Invoke(weaponRecoilContext);
				if (weaponRecoilContext.Value != 1f)
				{
					Vector2 val = default(Vector2);
					((Vector2)(ref val))..ctor(__instance.recoilDir.x * (weaponRecoilContext.Value - 1f), __instance.recoilDir.y * (weaponRecoilContext.Value - 1f));
					Vector2 currentRecoilForce = __instance.currentRecoilForce;
					currentRecoilForce.x -= val.x * (1f - recoilData.worldToViewSpaceBlendVertical);
					currentRecoilForce.y -= val.y * (1f - recoilData.worldToViewSpaceBlendHorizontal);
					Vector2 currentRecoilForceVP = __instance.currentRecoilForceVP;
					currentRecoilForceVP.x -= val.x * recoilData.worldToViewSpaceBlendVertical;
					currentRecoilForceVP.y -= val.y * recoilData.worldToViewSpaceBlendHorizontal;
					Vector2 recoilDir = __instance.recoilDir;
					((Vector2)(ref recoilDir)).Set(__instance.recoilDir.x * weaponRecoilContext.Value, __instance.recoilDir.y * weaponRecoilContext.Value);
					__instance.currentRecoilForce = currentRecoilForce;
					__instance.currentRecoilForceVP = currentRecoilForceVP;
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class WeaponSyncPatches
	{
		[HarmonyPatch(typeof(BulletWeaponSynced), "OnGearSpawnComplete")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_SetupSynced(BulletWeaponSynced __instance)
		{
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.SetToSync();
			}
		}

		[HarmonyPatch(typeof(ShotgunSynced), "Fire")]
		[HarmonyPatch(typeof(BulletWeaponSynced), "Fire")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_FireSynced(BulletWeaponSynced __instance)
		{
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponPreFireContextSync>.Instance);
			}
		}

		[HarmonyPatch(typeof(ShotgunSynced), "Fire")]
		[HarmonyPatch(typeof(BulletWeaponSynced), "Fire")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_FireSynced(BulletWeaponSynced __instance)
		{
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.UpdateStoredFireRate();
				component.ModifyFireRate();
				component.Invoke(StaticContext<WeaponPostFireContextSync>.Instance);
			}
		}
	}
	[HarmonyPatch]
	internal static class PlayerLocalPatches
	{
		[HarmonyPatch(typeof(PUI_LocalPlayerStatus), "UpdateHealth")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void UpdateHealth(PUI_LocalPlayerStatus __instance, float health, bool meleeBuffActive)
		{
			if (__instance.m_lastHealthVal <= 0.14f && health > 0.14f && __instance.m_warningRoutine != null)
			{
				__instance.m_healthWarningLooping = true;
			}
		}
	}
}
namespace EWC.Patches.Native
{
	internal static class EnemyDetectionPatches
	{
		private unsafe delegate void d_DetectOnNoise(IntPtr _this, IntPtr agentTarget, float movementDetectionDistance, float shootDetectionDistance, float delta, out float output, Il2CppMethodInfo* methodInfo);

		private struct CWCHolder
		{
			public CustomWeaponComponent? primary;

			public bool hasPrimary;

			public CustomWeaponComponent? special;

			public bool hasSpecial;

			public readonly bool IsValid
			{
				get
				{
					if ((Object)(object)primary != (Object)null == hasPrimary)
					{
						return (Object)(object)special != (Object)null == hasSpecial;
					}
					return false;
				}
			}
		}

		private static INativeDetour? DetectOnNoiseDetour;

		private static d_DetectOnNoise? orig_DetectOnNoise;

		private static readonly Dictionary<int, CWCHolder> s_cachedCWCs = new Dictionary<int, CWCHolder>();

		internal unsafe static void ApplyNativePatch()
		{
			DetectOnNoiseDetour = INativeDetour.CreateAndApply<d_DetectOnNoise>((IntPtr)(nint)Il2CppAPI.GetIl2CppMethod<EnemyDetection>("DetectOnNoiseDistance_Conditional_AnimatedWindow", typeof(void).Name, false, new string[5]
			{
				"AgentTarget",
				typeof(float).Name,
				typeof(float).Name,
				typeof(float).Name,
				typeof(float).MakeByRefType().Name
			}), (d_DetectOnNoise)DetectOnNoisePatch, ref orig_DetectOnNoise);
			NativePatchAPI.AddDetectPostfix(Post_DetectAgentNoise);
		}

		private unsafe static void DetectOnNoisePatch(IntPtr _this, IntPtr agentTarget, float movementDetectionDistance, float shootDetectionDistance, float delta, out float output, Il2CppMethodInfo* methodInfo)
		{
			//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: Expected O, but got Unknown
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0044: Expected O, but got Unknown
			output = 0f;
			EnemyDetection val = new EnemyDetection(_this);
			AgentTarget agentTarget2 = new AgentTarget(agentTarget);
			if (NativePatchAPI.RunDetectPrefix(val, agentTarget2, movementDetectionDistance, shootDetectionDistance, delta, ref output))
			{
				orig_DetectOnNoise(_this, agentTarget, movementDetectionDistance, shootDetectionDistance, delta, out output, methodInfo);
			}
			NativePatchAPI.RunDetectPostfix(val, agentTarget2, movementDetectionDistance, shootDetectionDistance, delta, ref output);
		}

		private static void UpdateCache()
		{
			if (s_cachedCWCs.Count == PlayerManager.PlayerAgentsInLevel.Count && !s_cachedCWCs.Values.Any((CWCHolder holder) => !holder.IsValid))
			{
				return;
			}
			s_cachedCWCs.Clear();
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			PlayerBackpack val = default(PlayerBackpack);
			BackpackItem val2 = default(BackpackItem);
			BackpackItem val3 = default(BackpackItem);
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (PlayerBackpackManager.TryGetBackpack(current.Owner, ref val) && val.TryGetBackpackItem((InventorySlot)1, ref val2) && val.TryGetBackpackItem((InventorySlot)2, ref val3))
				{
					Item instance = val2.Instance;
					CustomWeaponComponent customWeaponComponent = ((instance != null) ? ((Component)instance).GetComponent<CustomWeaponComponent>() : null);
					Item instance2 = val3.Instance;
					CustomWeaponComponent customWeaponComponent2 = ((instance2 != null) ? ((Component)instance2).GetComponent<CustomWeaponComponent>() : null);
					s_cachedCWCs.Add(((Agent)current).GlobalID, new CWCHolder
					{
						primary = customWeaponComponent,
						hasPrimary = ((Object)(object)customWeaponComponent != (Object)null),
						special = customWeaponComponent2,
						hasSpecial = ((Object)(object)customWeaponComponent2 != (Object)null)
					});
				}
			}
		}

		private static void Post_DetectAgentNoise(EnemyDetection __instance, AgentTarget agentTarget, float _mv, float _wp, float _delta, ref float output)
		{
			UpdateCache();
			if (s_cachedCWCs.TryGetValue(agentTarget.m_globalID, out var value) && (value.hasPrimary || value.hasSpecial))
			{
				WeaponStealthUpdateContext weaponStealthUpdateContext = new WeaponStealthUpdateContext(__instance.m_ai.m_enemyAgent, __instance.m_noiseDetectionOn, output);
				value.primary?.Invoke(weaponStealthUpdateContext);
				value.special?.Invoke(weaponStealthUpdateContext);
				output = weaponStealthUpdateContext.Output;
			}
		}
	}
}
namespace EWC.Patches.Melee
{
	[HarmonyPatch]
	internal static class MeleePatches
	{
		private static readonly HitData s_hitData = new HitData();

		private static float s_origHitDamage = 0f;

		private static float s_origHitPrecision = 0f;

		public static float CachedCharge { get; private set; } = 0f;


		[HarmonyPatch(typeof(MeleeWeaponFirstPerson), "SetupMeleeAnimations")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void SetupCallback(MeleeWeaponFirstPerson __instance)
		{
			CachedCharge = 0f;
			CustomWeaponManager.Current.AddWeaponListener((ItemEquippable)(object)__instance);
			CustomWeaponData customMeleeData = CustomWeaponManager.Current.GetCustomMeleeData(((GameDataBlockBase<MeleeArchetypeDataBlock>)(object)((ItemEquippable)__instance).MeleeArchetypeData).persistentID);
			if (customMeleeData != null && !((Object)(object)((Component)__instance).gameObject.GetComponent<CustomWeaponComponent>() != (Object)null))
			{
				((Component)__instance).gameObject.AddComponent<CustomWeaponComponent>().Register(customMeleeData);
			}
		}

		[HarmonyPatch(typeof(MeleeWeaponFirstPerson), "OnWield")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void UpdateCurrentWeapon(MeleeWeaponFirstPerson __instance)
		{
			CachedCharge = 0f;
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponWieldContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(MeleeWeaponFirstPerson), "OnUnWield")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void ClearCharge(MeleeWeaponFirstPerson __instance)
		{
			CachedCharge = 0f;
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponUnWieldContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(MeleeWeaponFirstPerson), "SetNextDamageToDeal")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void SetDamageCallback(MeleeWeaponFirstPerson __instance, eMeleeWeaponDamage dam, float scale)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Invalid comparison between Unknown and I4
			s_origHitDamage = __instance.m_damageToDeal;
			s_origHitPrecision = __instance.m_precisionMultiToDeal;
			CachedCharge = (((int)dam == 2) ? scale : 0f);
		}

		[HarmonyPatch(typeof(MeleeWeaponFirstPerson), "DoAttackDamage")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void HitCallback(MeleeWeaponFirstPerson __instance, MeleeWeaponDamageData data, bool isPush)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Invalid comparison between Unknown and I4
			if (isPush)
			{
				return;
			}
			s_hitData.Setup(__instance, data);
			IDamageable damageable = s_hitData.damageable;
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if ((Object)(object)component == (Object)null)
			{
				Agent val = ((damageable != null) ? damageable.GetBaseAgent() : null);
				if ((Object)(object)val != (Object)null && (int)val.Type == 1 && val.Alive)
				{
					KillTrackerManager.ClearHit(((Il2CppObjectBase)val).TryCast<EnemyAgent>());
				}
				WeaponPatches.CachedHitCC = null;
			}
			else
			{
				s_hitData.damage = s_origHitDamage;
				s_hitData.precisionMulti = s_origHitPrecision;
				bool doBackstab = true;
				WeaponPatches.ApplyEWCHit(component, damageable, s_hitData, pierce: false, ref s_origHitDamage, ref doBackstab);
			}
		}
	}
	[HarmonyPatch]
	internal static class MWSPatches
	{
		[HarmonyPatch(typeof(MWS_ChargeUp), "Enter")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void ChargeCallback(MWS_ChargeUp __instance)
		{
			CustomWeaponComponent component = ((Component)((MWS_Base)__instance).m_weapon).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				WeaponFireRateContext weaponFireRateContext = new WeaponFireRateContext(1f);
				component.Invoke(weaponFireRateContext);
				__instance.m_maxDamageTime /= weaponFireRateContext.Value;
			}
		}

		[HarmonyPatch(typeof(MWS_Push), "Enter")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PushCallback(MWS_Push __instance)
		{
			CustomWeaponComponent component = ((Component)((MWS_Base)__instance).m_weapon).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				WeaponFireRateContext weaponFireRateContext = new WeaponFireRateContext(1f);
				component.Invoke(weaponFireRateContext);
				Animator weaponAnimator = ((MWS_Base)__instance).m_weapon.WeaponAnimator;
				weaponAnimator.speed *= weaponFireRateContext.Value;
			}
		}

		[HarmonyPatch(typeof(MWS_AttackSwingBase), "Enter")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PreSwingCallback(MWS_AttackSwingBase __instance)
		{
			CustomWeaponComponent component = ((Component)((MWS_Base)__instance).m_weapon).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponPreFireContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(MWS_AttackSwingBase), "Exit")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostSwingCallback(MWS_AttackSwingBase __instance)
		{
			CustomWeaponComponent component = ((Component)((MWS_Base)__instance).m_weapon).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponPostFireContext>.Instance);
			}
		}
	}
}
namespace EWC.Networking
{
	public abstract class SyncedEvent<T> where T : struct
	{
		public delegate void ReceiveHandler(T packet);

		private bool _isSetup;

		public abstract string GUID { get; }

		public bool IsSetup => _isSetup;

		public string EventName { get; private set; } = string.Empty;


		public event ReceiveHandler? OnReceive;

		public event ReceiveHandler? OnReceiveLocal;

		public void Setup()
		{
			if (!_isSetup)
			{
				EventName = "EWC" + GUID;
				NetworkAPI.RegisterEvent<T>(EventName, (Action<ulong, T>)ReceiveClient_Callback);
				_isSetup = true;
			}
		}

		public void Send(T packetData, SNet_Player? target = null, SNet_ChannelType priority = 4)
		{
			//IL_0020: 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)
			if ((Object)(object)target != (Object)null)
			{
				NetworkAPI.InvokeEvent<T>(EventName, packetData, target, priority);
			}
			else
			{
				NetworkAPI.InvokeEvent<T>(EventName, packetData, priority);
			}
			ReceiveLocal_Callback(packetData);
		}

		private void ReceiveLocal_Callback(T packet)
		{
			ReceiveLocal(packet);
			this.OnReceiveLocal?.Invoke(packet);
		}

		private void ReceiveClient_Callback(ulong sender, T packet)
		{
			Receive(packet);
			this.OnReceive?.Invoke(packet);
		}

		protected virtual void ReceiveLocal(T packet)
		{
		}

		protected virtual void Receive(T packet)
		{
		}
	}
	public abstract class SyncedEventMasterOnly<T> : SyncedEvent<T> where T : struct
	{
		public void Send(T packet, SNet_ChannelType priority = 4)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (!SNet.IsMaster)
			{
				Send(packet, SNet.Master, priority);
			}
			else
			{
				Receive(packet);
			}
		}
	}
}
namespace EWC.Networking.Structs
{
	public struct LowResColor
	{
		public byte r;

		public byte g;

		public byte b;

		public byte a;

		private static Color s_color = Color.black;

		public static implicit operator Color(LowResColor lowResColor)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			s_color.r = (float)(int)lowResColor.r / 255f;
			s_color.g = (float)(int)lowResColor.g / 255f;
			s_color.b = (float)(int)lowResColor.b / 255f;
			s_color.a = (float)(int)lowResColor.a / 255f;
			return s_color;
		}

		public static implicit operator LowResColor(Color color)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			LowResColor result = default(LowResColor);
			result.r = (byte)(color.r * 255f);
			result.g = (byte)(color.g * 255f);
			result.b = (byte)(color.b * 255f);
			result.a = (byte)(color.a * 255f);
			return result;
		}
	}
}
namespace EWC.JSON
{
	internal static class CustomWeaponTemplate
	{
		internal static CustomWeaponData CreateTemplate()
		{
			return new CustomWeaponData
			{
				ArchetypeID = 0u,
				Name = "Example",
				Properties = new PropertyList(new List<WeaponPropertyBase>
				{
					new AmmoMod(),
					new AmmoRegen(),
					new DamageMod(),
					new DamageModPerTarget(),
					new DamageOverTime(),
					new Explosive(),
					new FireRateMod(),
					new HealthMod(),
					new RecoilMod(),
					new TempProperties(),
					new Accelerate(),
					new AmmoCap(),
					new ArmorPierce(),
					new AutoAim(),
					new AutoTrigger(),
					new BackstabMulti(),
					new BioPing(),
					new DataSwap(),
					new EnforceFireRate(),
					new HoldBurst(),
					new MultiShot(),
					new PierceMulti(),
					new Projectile(),
					new ReserveClip(),
					new Silence(),
					new ThickBullet(),
					new TumorMulti(),
					new WallPierce()
				})
			};
		}
	}
	public static class EWCJson
	{
		private static readonly JsonSerializerOptions _setting;

		static EWCJson()
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			_setting = new JsonSerializerOptions
			{
				ReadCommentHandling = JsonCommentHandling.Skip,
				IncludeFields = true,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true,
				IgnoreReadOnlyProperties = true
			};
			_setting.Converters.Add(new JsonStringEnumConverter());
			_setting.Converters.Add(new TriggerConverter());
			_setting.Converters.Add(new TriggerCoordinatorConverter());
			_setting.Converters.Add(new WeaponPropertyConverter());
			_setting.Converters.Add(new PropertyListConverter());
			_setting.Converters.Add((JsonConverter)new ColorConverter());
			if (PDAPIWrapper.HasPData)
			{
				_setting.Converters.Add(PDAPIWrapper.PersistentIDConverter);
			}
		}

		public static T? Deserialize<T>(string json)
		{
			return JsonSerializer.Deserialize<T>(json, _setting);
		}

		public static T? Deserialize<T>(ref Utf8JsonReader reader)
		{
			return JsonSerializer.Deserialize<T>(ref reader, _setting);
		}

		public static object? Deserialize(Type type, string json)
		{
			return JsonSerializer.Deserialize(json, type, _setting);
		}

		public static string Serialize<T>(T value)
		{
			return JsonSerializer.Serialize(value, _setting);
		}

		public static void Serialize<T>(Utf8JsonWriter writer, T value)
		{
			JsonSerializer.Serialize(writer, value, _setting);
		}
	}
}
namespace EWC.JSON.Converters
{
	public sealed class PropertyListConverter : JsonConverter<PropertyList>
	{
		public override PropertyList Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			return new PropertyList(EWCJson.Deserialize<List<WeaponPropertyBase>>(ref reader) ?? throw new JsonException("Unable to deserialize property list"));
		}

		public override void Write(Utf8JsonWriter writer, PropertyList value, JsonSerializerOptions options)
		{
			EWCJson.Serialize(writer, value.Properties);
		}
	}
	public sealed class TriggerConverter : JsonConverter<ITrigger>
	{
		public override ITrigger? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
	

plugins/Extra-MyCoolPlugin3/MyCoolPlugin3.dll

Decompiled 7 hours ago
using System;
using System.CodeDom.Compiler;
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 AssetShards;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using Enemies;
using GTFO.API;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppSystem;
using LevelGeneration;
using Microsoft.CodeAnalysis;
using UnityEngine;
using XXHashing;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("MyCoolPlugin3")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MyCoolPlugin3")]
[assembly: AssemblyTitle("MyCoolPlugin3")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
}
namespace MyCoolPlugin3
{
	[BepInPlugin("com.MyName.MyGTFOPlugin", "MyGTFOPlugin", "0.0.00001")]
	public class EntryPoint : BasePlugin
	{
		private unsafe delegate nint d_GetLoadedAsset(IntPtr assetPath, bool forceAssetDatabase, Il2CppMethodInfo* methodInfo);

		private static d_GetLoadedAsset s_Original;

		private unsafe static d_GetLoadedAsset s_Patch = Patch_GetLoadedAsset;

		private static INativeDetour PaymentsProcessedThroughTheLoanPaymentCenterBefore900pm;

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			m_Harmony = new Harmony("com.MyName.MyGTFOPlugin");
			m_Harmony.PatchAll();
			L.Verbose("Applied all patches!");
			PaymentsProcessedThroughTheLoanPaymentCenterBefore900pm = Il2CppAPI.CreateGenericDetour<AssetShardManager, d_GetLoadedAsset>("GetLoadedAsset", "T", new string[2] { "string", "bool" }, new Type[1] { typeof(Object) }, s_Patch, ref s_Original);
		}

		public unsafe static nint Patch_GetLoadedAsset(IntPtr assetPathPtr, bool forceAssetDatabase, Il2CppMethodInfo* methodInfo)
		{
			string text = IL2CPP.Il2CppStringToManaged(assetPathPtr).ToUpper();
			if (!AssetShardManager.s_loadedAssetsLookup.ContainsKey(text))
			{
				L.Error("Kasuromi says: \"" + text + " does not exist in the loaded asset lookup!\" Is the asset path valid or included in your asset bundle? Please come to croatia for debug");
				return 0;
			}
			return ((Il2CppObjectBase)AssetShardManager.s_loadedAssetsLookup[text]).Pointer;
		}
	}
	internal static class L
	{
		private static readonly ManualLogSource _logger;

		static L()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			_logger = new ManualLogSource("MyGTFOPlugin");
			Logger.Sources.Add((ILogSource)(object)_logger);
		}

		private static string Format(object msg)
		{
			return msg.ToString();
		}

		public static void Info(object data)
		{
			_logger.LogMessage((object)Format(data));
		}

		public static void Verbose(object data)
		{
		}

		public static void Debug(object data)
		{
			_logger.LogDebug((object)Format(data));
		}

		public static void Error(object data)
		{
			_logger.LogError((object)Format(data));
		}
	}
	[HarmonyPatch]
	public class Patch
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(EnemyPrefabManager), "BuildEnemyPrefab")]
		public static void Pre_BuildEnemyPrefab(EnemyDataBlock data)
		{
			L.Debug($"EnemyDB {((GameDataBlockBase<EnemyDataBlock>)(object)data).name} - {((GameDataBlockBase<EnemyDataBlock>)(object)data).persistentID}, EnemyPrefab {data.ModelDatas[0].ModelFile} CustomPrefab {data.ModelDatas[0].ModelCustomization} ");
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(CB_CustomPrefab), "Customize")]
		public static bool Replace_Customize(CB_CustomPrefab __instance, GameObject go)
		{
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, Transform> dictionary = new Dictionary<string, Transform>();
			Queue<Transform> queue = new Queue<Transform>();
			queue.Enqueue(go.transform);
			while (queue.Count > 0)
			{
				Transform val = queue.Dequeue();
				if (!dictionary.ContainsKey(((Object)val).name))
				{
					dictionary.Add(((Object)val).name, val);
				}
				else
				{
					L.Error("Duplicate transform key! " + ((Object)val).name + "\n Skipping this transform...");
				}
				int childCount = val.childCount;
				for (int i = 0; i < childCount; i++)
				{
					queue.Enqueue(val.GetChild(i));
				}
			}
			for (int j = 0; j < ((Il2CppArrayBase<sCB_CustomPrefabDef>)(object)__instance.prefabs).Length; j++)
			{
				sCB_CustomPrefabDef val2 = ((Il2CppArrayBase<sCB_CustomPrefabDef>)(object)__instance.prefabs)[j];
				if (!dictionary.ContainsKey(val2.Align))
				{
					Debug.LogError(Object.op_Implicit("ERROR : CB_CustomPrefab : Unable to find " + val2.Align));
					continue;
				}
				Transform val3 = dictionary[val2.Align];
				Object.Instantiate<GameObject>(val2.Prefab, val3, false).transform.localScale = Vector3.one * val2.ScaleTweak;
			}
			dictionary.Clear();
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_Factory), "GetNewJob")]
		public static void LG_Factory_GetNewJob(LG_Factory __instance)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			Builder.CombinedCheckSum = new ChecksumGenerator_64();
			Builder.BuildSeedRandom.SeedDebugger.GenerateChecksum(Builder.CombinedCheckSum);
			Builder.HostIDSeedRandom.SeedDebugger.GenerateChecksum(Builder.CombinedCheckSum);
			Builder.SessionSeedRandom.SeedDebugger.GenerateChecksum(Builder.CombinedCheckSum);
			Builder.CombinedCheckSum.Insert = XXHash.Checksum;
			L.Debug($"{__instance.m_currentBatchName} :: TOTAL CHECKSUM: {Builder.CombinedCheckSum.Checksum}");
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "MyCoolPlugin3";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = null;

		public const string SemVer = "1.0.0";

		public const string GitRevShort = null;

		public const string GitRevLong = null;

		public const string GitBranch = null;

		public const string GitTag = null;

		public const bool GitIsDirty = false;
	}
}

plugins/Flowaria-FlowGeos/FlowGeos.dll

Decompiled 7 hours ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using GTFO.API;
using HarmonyLib;
using LevelGeneration;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("FlowGeos")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("FlowGeos")]
[assembly: AssemblyTitle("FlowGeos")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace FlowGeos;

[BepInPlugin("FlowGeos", "FlowGeos", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class EntryPoint : BasePlugin
{
	private Harmony m_Harmony;

	public override void Load()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		m_Harmony = new Harmony("FlowGeos");
		m_Harmony.PatchAll();
	}
}
internal static class FlowGeosLogger
{
	private static readonly ManualLogSource _logger;

	static FlowGeosLogger()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Expected O, but got Unknown
		_logger = new ManualLogSource("FlowGeos");
		Logger.Sources.Add((ILogSource)(object)_logger);
	}

	private static string Format(object msg)
	{
		return msg.ToString();
	}

	public static void Info(object data)
	{
		_logger.LogMessage((object)Format(data));
	}

	public static void Verbose(object data)
	{
	}

	public static void Debug(object data)
	{
		_logger.LogDebug((object)Format(data));
	}

	public static void Error(object data)
	{
		_logger.LogError((object)Format(data));
	}
}
[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "Start")]
internal static class Inject_WO_Reactor
{
	private static void Postfix(LG_WardenObjective_Reactor __instance)
	{
		if ((Object)(object)__instance.m_terminalPrefab == (Object)null)
		{
			FlowGeosLogger.Info("Resolving Terminal Prefab for reactor!");
			__instance.m_terminalPrefab = AssetAPI.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/Complex/Generic/FunctionMarkers/Terminal_Floor.prefab");
			if ((Object)(object)__instance.m_terminalPrefab == (Object)null)
			{
				FlowGeosLogger.Error("We tried to resolve terminal prefab for reactor but it doesn't work...");
			}
		}
	}
}

plugins/Frog-GearPartCustomization/GearPartCustomization.dll

Decompiled 7 hours ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.Json;
using System.Text.Json.Serialization;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using GameData;
using Gear;
using HarmonyLib;
using MTFO.Managers;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("GearPartCustomization")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+gitbc5dc70-dirty-main")]
[assembly: AssemblyProduct("GearPartCustomization")]
[assembly: AssemblyTitle("GearPartCustomization")]
[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 GearPartCustomization
{
	public class GearPartTransformDatablock
	{
		public uint OfflineID { get; set; }

		public string Name { get; set; } = "Internal Name";


		public List<PartsConfig> Parts { get; set; } = new List<PartsConfig>
		{
			new PartsConfig()
		};


		public bool InternalEnabled { get; set; }

		[JsonIgnore]
		public static List<GearPartTransformDatablock> NewConfig => new List<GearPartTransformDatablock>
		{
			new GearPartTransformDatablock
			{
				Parts = new List<PartsConfig>
				{
					new PartsConfig
					{
						Children = new List<ChildrenConfig>
						{
							new ChildrenConfig()
						}
					}
				}
			}
		};
	}
	public class PartsConfig
	{
		public string PartHolderObject { get; set; } = "FrontPart";


		public eGearComponent PartType { get; set; }

		public bool Enabled { get; set; } = true;


		public PartTransformConfig PartTransform { get; set; } = new PartTransformConfig();


		public List<ChildrenConfig> Children { get; set; } = new List<ChildrenConfig>();

	}
	public class PartTransformConfig
	{
		public Vector3Wrapper LocalPosition { get; set; } = new Vector3Wrapper(0f, 0f, 0f);


		public Vector3Wrapper Scale { get; set; } = new Vector3Wrapper(1f, 1f, 1f);


		public Vector3Wrapper Rotation { get; set; } = new Vector3Wrapper(0f, 0f, 0f);

	}
	public class ChildrenConfig
	{
		public string ChildName { get; set; } = "";


		public bool Enabled { get; set; }

		public PartTransformConfig PartTransform { get; set; } = new PartTransformConfig();


		public List<ChildrenConfig> Children { get; set; } = new List<ChildrenConfig>();

	}
	public class Vector3Wrapper
	{
		public float X { get; set; }

		public float Y { get; set; }

		public float Z { get; set; }

		public Vector3Wrapper(float x, float y, float z)
		{
			X = x;
			Y = y;
			Z = z;
		}

		public static implicit operator Vector3(Vector3Wrapper wrapper)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(wrapper.X, wrapper.Y, wrapper.Z);
		}
	}
	internal class GearPartTransformManager
	{
		public static string FilePath;

		public static string FileContent;

		public static List<GearPartTransformDatablock> Config;

		public static Dictionary<uint, GearPartTransformDatablock> Settings = new Dictionary<uint, GearPartTransformDatablock>();

		public static JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions
		{
			WriteIndented = true,
			AllowTrailingCommas = true
		};

		public static Dictionary<uint, uint> CheckSumLookup = new Dictionary<uint, uint>();

		public static void Initialize()
		{
			Log.Message("Mccad.GearPartCustomization version 1.3.1 by Mccad00 | Setting up custom datablocks");
			FilePath = Path.Combine(ConfigManager.CustomPath, "mccad00");
			if (!Directory.Exists(FilePath))
			{
				Directory.CreateDirectory(FilePath);
			}
			FilePath = Path.Combine(FilePath, "GearPartTransform.json");
			if (File.Exists(FilePath))
			{
				Log.Message("Reading the custom datablock");
				FileContent = File.ReadAllText(FilePath);
				Config = JsonSerializer.Deserialize<List<GearPartTransformDatablock>>(FileContent, JsonSerializerOptions);
			}
			else
			{
				Log.Message("First time setup | Writing the custom datablock");
				Config = GearPartTransformDatablock.NewConfig;
				FileContent = JsonSerializer.Serialize(Config, JsonSerializerOptions);
				File.WriteAllText(FilePath, FileContent);
			}
			if (Config == null)
			{
				Log.Message("Error reading custom datablock content!");
				return;
			}
			foreach (GearPartTransformDatablock item in Config)
			{
				Settings.Add(item.OfflineID, item);
			}
		}

		public static void ApplyCustomization(GearPartHolder partHolder)
		{
			if (!TryGetConfig(partHolder, out var config))
			{
				return;
			}
			Log.Message("Applying customization config " + config.Name);
			Log.Verbose("Modify " + ((Object)partHolder).name + " - Start\n\n\n");
			foreach (PartsConfig part in config.Parts)
			{
				ModifyPart(config, part, partHolder);
			}
			Log.Verbose("Modify " + ((Object)partHolder).name + " - Complete\n\n\n");
		}

		public static bool TryGetConfig(GearPartHolder partHolder, out GearPartTransformDatablock config)
		{
			config = null;
			if (CheckSumLookup.ContainsKey(partHolder.GearIDRange.m_checksum) && CheckSumLookup.TryGetValue(partHolder.GearIDRange.m_checksum, out var value))
			{
				if (!Settings.TryGetValue(value, out config))
				{
					return false;
				}
			}
			else
			{
				if (!TryConvertToOfflineID(partHolder.GearIDRange.PlayfabItemInstanceId, out value) || value == 0)
				{
					return false;
				}
				if (!Settings.TryGetValue(value, out config))
				{
					return false;
				}
				CheckSumLookup.Add(partHolder.GearIDRange.m_checksum, config.OfflineID);
			}
			return true;
		}

		public static void ModifyPart(GearPartTransformDatablock config, PartsConfig partConfig, GearPartHolder partHolder)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (partConfig.PartHolderObject == null)
			{
				if ((int)partConfig.PartType == 0)
				{
					Log.Verbose("Modify part fail - missing part reference\n");
					return;
				}
				eGearComponent partType = partConfig.PartType;
				partConfig.PartHolderObject = ((object)(eGearComponent)(ref partType)).ToString();
			}
			Log.Verbose("Modify part " + partConfig.PartHolderObject);
			if (!TryGetPart(partConfig.PartHolderObject, partHolder, out var part))
			{
				Log.Verbose("Modify part fail - " + partConfig.PartHolderObject + " not found in " + ((Object)partHolder).name + "\n");
				return;
			}
			part.active = partConfig.Enabled;
			ApplyPartTransform(partConfig.PartTransform, part);
			if (partConfig.Children == null || partConfig.Children.Count == 0)
			{
				Log.Verbose("Part " + partConfig.PartHolderObject + " has no children\n");
				return;
			}
			foreach (ChildrenConfig child in partConfig.Children)
			{
				ModifyChild(config, child, part.transform, partHolder);
			}
		}

		public static void ModifyChild(GearPartTransformDatablock config, ChildrenConfig childConfig, Transform parent, GearPartHolder partHolder)
		{
			if (childConfig.ChildName == null)
			{
				Log.Verbose("Modify child fail - missing child reference\n");
				return;
			}
			if (!TryGetChild(childConfig.ChildName, parent, partHolder, out var part))
			{
				Log.Verbose("Modify child fail - " + childConfig.ChildName + " not found in " + ((Object)((Component)parent).gameObject).name + "\n");
				return;
			}
			Log.Verbose("Modify child " + childConfig.ChildName);
			part.active = childConfig.Enabled;
			ApplyPartTransform(childConfig.PartTransform, part);
			if (childConfig.Children == null || childConfig.Children.Count == 0)
			{
				Log.Verbose("Child " + childConfig.ChildName + " has no children\n");
				return;
			}
			foreach (ChildrenConfig child in childConfig.Children)
			{
				ModifyChild(config, child, part.transform, partHolder);
			}
		}

		public static void ApplyPartTransform(PartTransformConfig partTransform, GameObject part)
		{
			//IL_000c: 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_0038: Unknown result type (might be due to invalid IL or missing references)
			part.transform.localPosition = partTransform.LocalPosition;
			part.transform.localEulerAngles = partTransform.Rotation;
			part.transform.localScale = partTransform.Scale;
		}

		public static bool TryGetPart(string partHolderObject, GearPartHolder partHolder, out GameObject part)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			PropertyInfo property = ((object)partHolder).GetType().GetProperty(partHolderObject);
			if (property == null)
			{
				part = null;
				return false;
			}
			part = (GameObject)property.GetValue(partHolder);
			return (Object)(object)part != (Object)null;
		}

		public static bool TryGetChild(string childObject, Transform parent, GearPartHolder partHolder, out GameObject part)
		{
			Transform val = parent.FindChild(childObject);
			if ((Object)(object)val == (Object)null)
			{
				part = null;
				return false;
			}
			part = ((Component)val).gameObject;
			return true;
		}

		public static bool TryConvertToOfflineID(string? itemInstanceID, out uint offlineID)
		{
			offlineID = 0u;
			if (string.IsNullOrEmpty(itemInstanceID))
			{
				return false;
			}
			return uint.TryParse(itemInstanceID.Substring("OfflineGear_ID_".Length), out offlineID);
		}
	}
	internal static class Log
	{
		public static ManualLogSource s_Source;

		public static void Debug(object value)
		{
			s_Source.LogDebug(value);
		}

		public static void Error(object value)
		{
			s_Source.LogError(value);
		}

		public static void Fatal(object value)
		{
			s_Source.LogFatal(value);
		}

		public static void Info(object value)
		{
			s_Source.LogInfo(value);
		}

		public static void Message(object value)
		{
			s_Source.LogMessage(value);
		}

		public static void Warning(object value)
		{
			s_Source.LogWarning(value);
		}

		public static void Verbose(object value)
		{
			if (Plugin.VerboseLogging.Value)
			{
				s_Source.LogDebug(value);
			}
		}
	}
	internal class Patch_GameDataInit
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameDataInit), "Initialize")]
		public static void Initialize()
		{
			GearPartTransformManager.Initialize();
		}
	}
	internal class Patch_GearPartHolder
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(GearPartHolder), "OnAllPartsSpawned")]
		public static void OnAllPartsSpawned(GearPartHolder __instance)
		{
			GearPartTransformManager.ApplyCustomization(__instance);
		}
	}
	[BepInPlugin("com.Mccad.GearPartCustomization", "Mccad.GearPartCustomization", "1.3.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BasePlugin
	{
		public static readonly Harmony m_Harmony = new Harmony("com.Mccad.GearPartCustomization");

		public static ConfigEntry<bool> VerboseLogging;

		public const string GUID = "com.Mccad.GearPartCustomization";

		public const string NAME = "Mccad.GearPartCustomization";

		public const string VERSION = "1.3.1";

		public override void Load()
		{
			VerboseLogging = ((BasePlugin)this).Config.Bind<bool>("Logging", "Verbose", false, (ConfigDescription)null);
			Log.s_Source = ((BasePlugin)this).Log;
			m_Harmony.PatchAll(typeof(Patch_GameDataInit));
			m_Harmony.PatchAll(typeof(Patch_GearPartHolder));
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "GearPartCustomization";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "gitbc5dc70-dirty-main";

		public const string SemVer = "1.0.0+gitbc5dc70-dirty-main";

		public const string GitRevShort = "bc5dc70-dirty";

		public const string GitRevLong = "bc5dc70054f7c168a0e78c35a6f6db7bd2ed5b71-dirty";

		public const string GitBranch = "main";

		public const string GitTag = null;

		public const bool GitIsDirty = true;
	}
}

plugins/GTFO-API.dll

Decompiled 7 hours ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using AIGraph;
using AssetShards;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using BepInEx.Unity.IL2CPP.Utils;
using GTFO.API.Attributes;
using GTFO.API.Components;
using GTFO.API.Extensions;
using GTFO.API.Impl;
using GTFO.API.JSON;
using GTFO.API.JSON.Converters;
using GTFO.API.Native;
using GTFO.API.Resources;
using GTFO.API.Utilities;
using GTFO.API.Utilities.Impl;
using GTFO.API.Wrappers;
using GameData;
using Gear;
using Globals;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.Class;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using ItemSetup;
using LevelGeneration;
using Localization;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using UnityEngine;
using UnityEngine.Analytics;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("GTFO-API")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.4.1")]
[assembly: AssemblyInformationalVersion("0.4.1+git1e8fe81-main")]
[assembly: AssemblyProduct("GTFO-API")]
[assembly: AssemblyTitle("GTFO-API")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.4.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace GTFO.API
{
	internal static class APILogger
	{
		private static readonly ManualLogSource _logger;

		static APILogger()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			_logger = new ManualLogSource("GTFO-API");
			Logger.Sources.Add((ILogSource)(object)_logger);
		}

		private static string Format(string module, object msg)
		{
			return $"[{module}]: {msg}";
		}

		public static void Info(string module, object data)
		{
			_logger.LogMessage((object)Format(module, data));
		}

		public static void Verbose(string module, object data)
		{
		}

		public static void Debug(string module, object data)
		{
			_logger.LogDebug((object)Format(module, data));
		}

		public static void Warn(string module, object data)
		{
			_logger.LogWarning((object)Format(module, data));
		}

		public static void Error(string module, object data)
		{
			_logger.LogError((object)Format(module, data));
		}
	}
	[API("Asset")]
	public static class AssetAPI
	{
		internal static ConcurrentDictionary<string, Object> s_RegistryCache = new ConcurrentDictionary<string, Object>();

		public static ApiStatusInfo Status => APIStatus.Asset;

		public static event Action OnStartupAssetsLoaded;

		public static event Action OnAssetBundlesLoaded;

		public static event Action OnImplReady;

		public static bool ContainsAsset(string assetName)
		{
			string text = assetName.ToUpper();
			if (!APIStatus.Asset.Ready)
			{
				return s_RegistryCache.ContainsKey(text);
			}
			return AssetShardManager.s_loadedAssetsLookup.ContainsKey(text);
		}

		public static Object GetLoadedAsset(string path)
		{
			string text = path.ToUpper();
			APILogger.Verbose("Asset", "Requested Asset: " + text);
			try
			{
				if (!APIStatus.Asset.Ready && s_RegistryCache.TryGetValue(text, out var value))
				{
					return value;
				}
				return AssetShardManager.GetLoadedAsset(text, false);
			}
			catch
			{
				return null;
			}
		}

		public static TAsset GetLoadedAsset<TAsset>(string path) where TAsset : Object
		{
			Object loadedAsset = GetLoadedAsset(path);
			if (loadedAsset == null)
			{
				return default(TAsset);
			}
			return ((Il2CppObjectBase)loadedAsset).Cast<TAsset>();
		}

		public static void RegisterAsset(string name, Object gameObject)
		{
			string text = name.ToUpper();
			if (!APIStatus.Asset.Ready)
			{
				if (s_RegistryCache.ContainsKey(text))
				{
					throw new ArgumentException("The asset with " + text + " has already been registered.", "name");
				}
				s_RegistryCache.TryAdd(text, gameObject);
			}
			else
			{
				AssetAPI_Impl.Instance.RegisterAsset(text, gameObject);
			}
		}

		public static void RegisterAssetBundle(AssetBundle bundle)
		{
			string[] array = Il2CppArrayBase<string>.op_Implicit((Il2CppArrayBase<string>)(object)bundle.AllAssetNames());
			APILogger.Verbose("Asset", "Bundle names: [" + string.Join(", ", array) + "]");
			string[] array2 = array;
			foreach (string text in array2)
			{
				Object val = bundle.LoadAsset(text);
				if (val != (Object)null)
				{
					RegisterAsset(text, val);
				}
				else
				{
					APILogger.Warn("Asset", "Skipping asset " + text);
				}
			}
		}

		public static void LoadAndRegisterAssetBundle(string pathToBundle)
		{
			AssetBundle obj = AssetBundle.LoadFromFile(pathToBundle);
			if ((Object)(object)obj == (Object)null)
			{
				throw new Exception("Failed to load asset bundle");
			}
			RegisterAssetBundle(obj);
		}

		public static void LoadAndRegisterAssetBundle(byte[] bundleBytes)
		{
			AssetBundle obj = AssetBundle.LoadFromMemory(Il2CppStructArray<byte>.op_Implicit(bundleBytes));
			if ((Object)(object)obj == (Object)null)
			{
				throw new Exception("Failed to load asset bundle");
			}
			RegisterAssetBundle(obj);
		}

		public static Object InstantiateAsset(string assetName, string copyName)
		{
			if (ContainsAsset(copyName))
			{
				throw new ArgumentException("The asset you're trying to copy into is already registered", "copyName");
			}
			RegisterAsset(copyName, Object.Instantiate(GetLoadedAsset(assetName) ?? throw new ArgumentException("Couldn't find an asset with the name '" + assetName + "'", "assetName")));
			return GetLoadedAsset(copyName);
		}

		public static TAsset InstantiateAsset<TAsset>(string assetName, string copyName) where TAsset : Object
		{
			Object obj = InstantiateAsset(assetName, copyName);
			if (obj == null)
			{
				return default(TAsset);
			}
			return ((Il2CppObjectBase)obj).Cast<TAsset>();
		}

		public static bool TryInstantiateAsset<TAsset>(string assetName, string copyName, out TAsset clonedObj) where TAsset : Object
		{
			Object obj = InstantiateAsset(assetName, copyName);
			clonedObj = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<TAsset>() : default(TAsset));
			return (Object)(object)clonedObj != (Object)null;
		}

		private static void OnAssetsLoaded()
		{
			if (!APIStatus.Asset.Created)
			{
				APIStatus.CreateApi<AssetAPI_Impl>("Asset");
			}
			AssetAPI.OnStartupAssetsLoaded?.Invoke();
		}

		internal static void InvokeImplReady()
		{
			AssetAPI.OnImplReady?.Invoke();
		}

		internal static void Setup()
		{
			EventAPI.OnAssetsLoaded += OnAssetsLoaded;
			OnImplReady += LoadAssetBundles;
		}

		private static void LoadAssetBundles()
		{
			string assetBundlesDir = Path.Combine(Paths.BepInExRootPath, "Assets", "AssetBundles");
			string assetBundlesDir2 = Path.Combine(Paths.ConfigPath, "Assets", "AssetBundles");
			if (LoadAssetBundles(assetBundlesDir) | LoadAssetBundles(assetBundlesDir2, outdated: true))
			{
				AssetAPI.OnAssetBundlesLoaded?.Invoke();
			}
		}

		private static bool LoadAssetBundles(string assetBundlesDir, bool outdated = false)
		{
			if (outdated)
			{
				if (!Directory.Exists(assetBundlesDir))
				{
					return false;
				}
				APILogger.Warn("AssetAPI", "Storing asset bundles in the config path is deprecated and will be removed in a future version of GTFO-API. The path has been moved to 'BepInEx\\Assets\\AssetBundles'.");
			}
			if (!Directory.Exists(assetBundlesDir))
			{
				Directory.CreateDirectory(assetBundlesDir);
				return false;
			}
			string[] array = (from x in Directory.GetFiles(assetBundlesDir, "*", SearchOption.AllDirectories)
				where !x.EndsWith(".manifest", StringComparison.InvariantCultureIgnoreCase)
				select x).ToArray();
			if (array.Length == 0)
			{
				return false;
			}
			for (int i = 0; i < array.Length; i++)
			{
				try
				{
					LoadAndRegisterAssetBundle(array[i]);
				}
				catch (Exception ex)
				{
					APILogger.Warn("AssetAPI", $"Failed to load asset bundle '{array[i]}' ({ex.Message})");
				}
			}
			return true;
		}
	}
	[API("Event")]
	public static class EventAPI
	{
		public static ApiStatusInfo Status => APIStatus.Event;

		public static event Action OnManagersSetup;

		public static event Action OnExpeditionStarted;

		public static event Action OnAssetsLoaded;

		internal static void Setup()
		{
			Global.OnAllManagersSetup += Action.op_Implicit((Action)ManagersSetup);
			AssetShardManager.OnStartupAssetsLoaded += Action.op_Implicit((Action)AssetsLoaded);
			RundownManager.OnExpeditionGameplayStarted += Action.op_Implicit((Action)ExpeditionStarted);
		}

		private static void ManagersSetup()
		{
			EventAPI.OnManagersSetup?.Invoke();
		}

		private static void ExpeditionStarted()
		{
			EventAPI.OnExpeditionStarted?.Invoke();
		}

		private static void AssetsLoaded()
		{
			EventAPI.OnAssetsLoaded?.Invoke();
		}
	}
	[API("GameData")]
	public class GameDataAPI
	{
		public static ApiStatusInfo Status => APIStatus.GameData;

		public static event Action OnGameDataInitialized;

		static GameDataAPI()
		{
			Status.Created = true;
			Status.Ready = true;
		}

		internal static void InvokeGameDataInit()
		{
			GameDataAPI.OnGameDataInitialized?.Invoke();
		}
	}
	[API("Il2Cpp")]
	public static class Il2CppAPI
	{
		public static ApiStatusInfo Status => APIStatus.Il2Cpp;

		static Il2CppAPI()
		{
			Status.Created = true;
			Status.Ready = true;
		}

		public unsafe static void InjectWithInterface<T>() where T : Il2CppObjectBase
		{
			//IL_007e: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			List<INativeClassStruct> list = new List<INativeClassStruct>();
			foreach (Il2CppInterfaceAttribute item in GetCustomAttributesInType<T, Il2CppInterfaceAttribute>())
			{
				Il2CppClass* ptr = (Il2CppClass*)(void*)(IntPtr)typeof(Il2CppClassPointerStore<>).MakeGenericType(item.Type).GetField("NativeClassPtr").GetValue(null);
				IL2CPP.il2cpp_runtime_class_init((IntPtr)ptr);
				list.Add(UnityVersionHandler.Wrap(ptr));
			}
			RegisterTypeOptions val = new RegisterTypeOptions();
			val.set_LogSuccess(true);
			val.set_Interfaces(Il2CppInterfaceCollection.op_Implicit(list.ToArray()));
			ClassInjector.RegisterTypeInIl2Cpp<T>(val);
		}

		public unsafe static void* GetIl2CppMethod<T>(string methodName, string returnTypeName, bool isGeneric, params string[] argTypes) where T : Il2CppObjectBase
		{
			void** ptr = (void**)IL2CPP.GetIl2CppMethod(Il2CppClassPointerStore<T>.NativeClassPtr, isGeneric, methodName, returnTypeName, argTypes).ToPointer();
			if (ptr == null)
			{
				return ptr;
			}
			return *ptr;
		}

		public unsafe static TDelegate GetIl2CppMethod<T, TDelegate>(string methodName, string returnTypeName, bool isGeneric, params string[] argTypes) where T : Il2CppObjectBase where TDelegate : Delegate
		{
			void* il2CppMethod = GetIl2CppMethod<T>(methodName, returnTypeName, isGeneric, argTypes);
			if (il2CppMethod == null)
			{
				return null;
			}
			return Marshal.GetDelegateForFunctionPointer<TDelegate>((IntPtr)il2CppMethod);
		}

		public unsafe static INativeDetour CreateGenericDetour<TClass, TDelegate>(string methodName, string returnType, string[] paramTypes, Type[] genericArguments, TDelegate to, out TDelegate original) where TClass : Object where TDelegate : Delegate
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			IntPtr nativeClassPtr = Il2CppClassPointerStore<TClass>.NativeClassPtr;
			if (nativeClassPtr == IntPtr.Zero)
			{
				throw new ArgumentException(typeof(TClass).Name + " does not exist in il2cpp domain");
			}
			return INativeDetour.CreateAndApply<TDelegate>(UnityVersionHandler.Wrap((Il2CppMethodInfo*)(void*)IL2CPP.il2cpp_method_get_from_reflection(((Il2CppObjectBase)new MethodInfo(IL2CPP.il2cpp_method_get_object(IL2CPP.GetIl2CppMethod(nativeClassPtr, true, methodName, returnType, paramTypes), nativeClassPtr)).MakeGenericMethod(((IEnumerable<Type>)genericArguments).Select((Func<Type, Type>)Il2CppType.From).ToArray())).Pointer)).MethodPointer, to, ref original);
		}

		private static IEnumerable<TAttribute> GetCustomAttributesInType<T, TAttribute>() where TAttribute : Attribute
		{
			Type attributeType = typeof(TAttribute);
			return typeof(T).GetCustomAttributes(attributeType, inherit: true).Union(typeof(T).GetInterfaces().SelectMany((Type interfaceType) => interfaceType.GetCustomAttributes(attributeType, inherit: true))).Distinct()
				.Cast<TAttribute>();
		}
	}
	public delegate void LevelDataUpdateEvent(ActiveExpedition activeExp, ExpeditionInTierData expData);
	public delegate void LevelSelectedEvent(eRundownTier expTier, int expIndexInTier, ExpeditionInTierData expData);
	[API("Level")]
	public static class LevelAPI
	{
		private static eRundownTier s_LatestExpTier = (eRundownTier)99;

		private static int s_LatestExpIndex = -1;

		public static ApiStatusInfo Status => APIStatus.Level;

		public static event LevelDataUpdateEvent OnLevelDataUpdated;

		public static event LevelSelectedEvent OnLevelSelected;

		public static event Action OnBuildStart;

		public static event Action OnBuildDone;

		public static event Action OnEnterLevel;

		public static event Action OnLevelCleanup;

		internal static void Setup()
		{
			Status.Created = true;
			Status.Ready = true;
			EventAPI.OnExpeditionStarted += EnterLevel;
		}

		internal static void ExpeditionUpdated(pActiveExpedition activeExp, ExpeditionInTierData expData)
		{
			//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_0026: 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_0048: 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)
			LevelAPI.OnLevelDataUpdated?.Invoke(ActiveExpedition.CreateFrom(activeExp), expData);
			eRundownTier tier = activeExp.tier;
			int expeditionIndex = activeExp.expeditionIndex;
			if (tier != s_LatestExpTier || expeditionIndex != s_LatestExpIndex)
			{
				LevelAPI.OnLevelSelected?.Invoke(tier, expeditionIndex, expData);
				s_LatestExpTier = tier;
				s_LatestExpIndex = expeditionIndex;
			}
		}

		internal static void BuildStart()
		{
			LevelAPI.OnBuildStart?.Invoke();
		}

		internal static void BuildDone()
		{
			LevelAPI.OnBuildDone?.Invoke();
		}

		internal static void EnterLevel()
		{
			LevelAPI.OnEnterLevel?.Invoke();
		}

		internal static void LevelCleanup()
		{
			LevelAPI.OnLevelCleanup?.Invoke();
		}
	}
	public struct ActiveExpedition
	{
		public pPlayer player;

		public eRundownKey rundownType;

		public string rundownKey;

		public eRundownTier tier;

		public int expeditionIndex;

		public int hostIDSeed;

		public int sessionSeed;

		public static ActiveExpedition CreateFrom(pActiveExpedition pActiveExp)
		{
			ActiveExpedition result = default(ActiveExpedition);
			result.CopyFrom(pActiveExp);
			return result;
		}

		public void CopyFrom(pActiveExpedition pActiveExp)
		{
			//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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			player = pActiveExp.player;
			rundownType = pActiveExp.rundownType;
			rundownKey = pActiveExp.rundownKey.data;
			tier = pActiveExp.tier;
			expeditionIndex = pActiveExp.expeditionIndex;
			hostIDSeed = pActiveExp.hostIDSeed;
			sessionSeed = pActiveExp.sessionSeed;
		}
	}
	[API("Localization")]
	public static class LocalizationAPI
	{
		private sealed class Entry
		{
			private readonly string?[] m_ValuesByLanguage = new string[12];

			private TextDBOptions m_Options;

			public uint? TextBlockId { get; private set; }

			private bool TryGetStringInAnyLanguage([NotNullWhen(true)] out string? value)
			{
				for (int i = 0; i < m_ValuesByLanguage.Length; i++)
				{
					value = m_ValuesByLanguage[i];
					if (value != null)
					{
						return true;
					}
				}
				value = null;
				return false;
			}

			private bool TryGetStringInLanguage(Language language, [NotNullWhen(true)] out string? value)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0004: Expected I4, but got Unknown
				int num = language - 1;
				value = m_ValuesByLanguage[num];
				return value != null;
			}

			public bool TryGetString(Language language, FallbackValueOptions options, [NotNullWhen(true)] out string? value)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				if (TryGetStringInLanguage(language, out value))
				{
					return true;
				}
				if (options.UseFallbackLanguage && TryGetStringInLanguage(options.FallbackLanguage.Value, out value))
				{
					return true;
				}
				if (options.UseAnyLanguage && TryGetStringInAnyLanguage(out value))
				{
					return true;
				}
				value = null;
				return false;
			}

			private string GetStringForTextDB(Language language, string key, FallbackValueOptions options)
			{
				//IL_0001: 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 (TryGetString(language, options, out string value))
				{
					return value;
				}
				ValidateUseKey(key, language, options, "GenerateTextDB");
				return key;
			}

			[MemberNotNull("TextBlockId")]
			public void GenerateTextDataBlock(string key, TextDBOptions options, bool force = false)
			{
				m_Options = options;
				GenerateTextDataBlock(key, force);
			}

			[MemberNotNull("TextBlockId")]
			public void GenerateTextDataBlock(string key, bool force = false)
			{
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0062: Unknown result type (might be due to invalid IL or missing references)
				//IL_0069: Expected O, but got Unknown
				//IL_0069: 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_0077: Unknown result type (might be due to invalid IL or missing references)
				//IL_0082: Unknown result type (might be due to invalid IL or missing references)
				//IL_0091: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cd: 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_00f5: 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_011d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0132: Unknown result type (might be due to invalid IL or missing references)
				//IL_0147: Unknown result type (might be due to invalid IL or missing references)
				//IL_015c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0171: Unknown result type (might be due to invalid IL or missing references)
				//IL_0178: Expected O, but got Unknown
				//IL_0178: 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_0186: Unknown result type (might be due to invalid IL or missing references)
				//IL_018d: Expected O, but got Unknown
				//IL_018e: Expected O, but got Unknown
				if (!TextBlockId.HasValue || force)
				{
					FallbackValueOptions options = m_Options.FallbackOptions ?? FallbackValueOptions.AnyLangOrKey;
					TextDataBlock val = new TextDataBlock
					{
						CharacterMetaData = (m_Options.CharacterMetadataId ?? 1)
					};
					((GameDataBlockBase<TextDataBlock>)val).internalEnabled = true;
					val.ExportVersion = 1;
					val.ImportVersion = 1;
					val.Description = string.Empty;
					val.English = GetStringForTextDB((Language)1, key, options);
					val.French = LanguageData.op_Implicit(GetStringForTextDB((Language)2, key, options));
					val.Italian = LanguageData.op_Implicit(GetStringForTextDB((Language)3, key, options));
					val.German = LanguageData.op_Implicit(GetStringForTextDB((Language)4, key, options));
					val.Spanish = LanguageData.op_Implicit(GetStringForTextDB((Language)5, key, options));
					val.Russian = LanguageData.op_Implicit(GetStringForTextDB((Language)6, key, options));
					val.Portuguese_Brazil = LanguageData.op_Implicit(GetStringForTextDB((Language)7, key, options));
					val.Polish = LanguageData.op_Implicit(GetStringForTextDB((Language)8, key, options));
					val.Japanese = LanguageData.op_Implicit(GetStringForTextDB((Language)9, key, options));
					val.Korean = LanguageData.op_Implicit(GetStringForTextDB((Language)10, key, options));
					val.Chinese_Traditional = LanguageData.op_Implicit(GetStringForTextDB((Language)11, key, options));
					val.Chinese_Simplified = LanguageData.op_Implicit(GetStringForTextDB((Language)12, key, options));
					((GameDataBlockBase<TextDataBlock>)val).name = key;
					val.MachineTranslation = false;
					val.SkipLocalization = false;
					((GameDataBlockBase<TextDataBlock>)val).persistentID = 0u;
					TextDataBlock val2 = val;
					GameDataBlockBase<TextDataBlock>.AddBlock(val2, -1);
					TextBlockId = ((GameDataBlockBase<TextDataBlock>)(object)val2).persistentID;
				}
			}

			public bool TryGetString(Language language, string key, FallbackValueOptions options, out string? value)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				if (TryGetString(language, options, out value))
				{
					return true;
				}
				if (options.UseKey)
				{
					value = key;
					return true;
				}
				value = null;
				return false;
			}

			public string GetString(Language language, string key, FallbackValueOptions options)
			{
				//IL_0001: 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 (TryGetString(language, options, out string value))
				{
					return value;
				}
				ValidateUseKey(key, language, options, "GetString");
				return key;
			}

			public string FormatString(Language language, string key, FallbackValueOptions options, object?[] args)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				if (TryGetString(language, options, out string value))
				{
					return string.Format(value, args);
				}
				ValidateUseKey(key, language, options, "FormatString");
				return key;
			}

			public bool HasValueInLanguage(Language language)
			{
				//IL_0000: 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_0013: Unknown result type (might be due to invalid IL or missing references)
				ValidateLanguage(language, "language");
				return m_ValuesByLanguage[language - 1] != null;
			}

			public void AddValue(Language language, string value, bool force = false)
			{
				//IL_000b: 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: Expected I4, but got Unknown
				//IL_006b: Unknown result type (might be due to invalid IL or missing references)
				ArgumentNullException.ThrowIfNull(value, "value");
				int num = language - 1;
				if (num < 0 || num >= m_ValuesByLanguage.Length)
				{
					throw new ArgumentOutOfRangeException("language");
				}
				ref string reference = ref m_ValuesByLanguage[num];
				if (reference != null && !force)
				{
					return;
				}
				reference = value;
				if (TextBlockId.HasValue)
				{
					TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock(TextBlockId.Value);
					if (block != null)
					{
						UpdateTextDataBlock(block, language, reference);
					}
				}
			}
		}

		[Flags]
		public enum FallbackValueFlags
		{
			None = 0,
			FallbackLanguage = 1,
			AnyLanguage = 2,
			Key = 4,
			FallbackOrAnyLanguage = 3,
			FallbackLanguageOrKey = 5,
			AnyLanguageOrKey = 6,
			FallbackOrAnyLanguageOrKey = 7
		}

		public readonly struct FallbackValueOptions : IEquatable<FallbackValueOptions>
		{
			public static readonly FallbackValueOptions None = default(FallbackValueOptions);

			public static readonly FallbackValueOptions Key = new FallbackValueOptions(FallbackValueFlags.Key);

			public static readonly FallbackValueOptions AnyLang = new FallbackValueOptions(FallbackValueFlags.AnyLanguage);

			public static readonly FallbackValueOptions AnyLangOrKey = new FallbackValueOptions(FallbackValueFlags.AnyLanguageOrKey);

			public FallbackValueFlags Flags { get; }

			public Language? FallbackLanguage { get; }

			public bool UseKey => Flags.HasFlag(FallbackValueFlags.Key);

			[MemberNotNullWhen(true, "FallbackLanguage")]
			public bool UseFallbackLanguage
			{
				[MemberNotNullWhen(true, "FallbackLanguage")]
				get
				{
					return Flags.HasFlag(FallbackValueFlags.FallbackLanguage);
				}
			}

			public bool UseAnyLanguage => Flags.HasFlag(FallbackValueFlags.AnyLanguage);

			public FallbackValueOptions(FallbackValueFlags flags, Language? fallbackLanguage = null)
			{
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				if (flags.HasFlag(FallbackValueFlags.FallbackLanguage))
				{
					if (!fallbackLanguage.HasValue)
					{
						throw new ArgumentNullException("fallbackLanguage", "A fallback language is required if specifying the flag FallbackLanguage");
					}
					ValidateLanguage(fallbackLanguage.Value, "fallbackLanguage");
				}
				Flags = flags;
				FallbackLanguage = fallbackLanguage;
			}

			public override int GetHashCode()
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				return HashCode.Combine<FallbackValueFlags, Language>(Flags, FallbackLanguage.GetValueOrDefault());
			}

			public override bool Equals([NotNullWhen(true)] object? obj)
			{
				if (obj is FallbackValueOptions other)
				{
					return Equals(other);
				}
				return false;
			}

			public bool Equals(FallbackValueOptions other)
			{
				//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)
				if (Flags == other.Flags)
				{
					return FallbackLanguage == other.FallbackLanguage;
				}
				return false;
			}

			public FallbackValueOptions IncludeKey()
			{
				return new FallbackValueOptions(Flags | FallbackValueFlags.Key, FallbackLanguage);
			}

			public FallbackValueOptions ExcludeKey()
			{
				return new FallbackValueOptions(Flags & ~FallbackValueFlags.Key, FallbackLanguage);
			}

			public FallbackValueOptions IncludeFallbackLanguage(Language language)
			{
				//IL_0000: 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)
				ValidateLanguage(language, "language");
				return new FallbackValueOptions(Flags | FallbackValueFlags.FallbackLanguage, language);
			}

			public FallbackValueOptions ExcludeFallbackLanguage()
			{
				return new FallbackValueOptions(Flags & ~FallbackValueFlags.FallbackLanguage);
			}

			public FallbackValueOptions IncludeAnyLanguage()
			{
				return new FallbackValueOptions(Flags | FallbackValueFlags.AnyLanguage, FallbackLanguage);
			}

			public FallbackValueOptions ExcludeAnyLanguage()
			{
				return new FallbackValueOptions(Flags & ~FallbackValueFlags.AnyLanguage, FallbackLanguage);
			}

			public FallbackValueOptions Combine(FallbackValueOptions other)
			{
				return new FallbackValueOptions(Flags | other.Flags, FallbackLanguage ?? other.FallbackLanguage);
			}

			public static bool operator ==(FallbackValueOptions left, FallbackValueOptions right)
			{
				return left.Equals(right);
			}

			public static bool operator !=(FallbackValueOptions left, FallbackValueOptions right)
			{
				return !(left == right);
			}

			public static FallbackValueOptions FallbackLang(Language fallbackLanguage)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return new FallbackValueOptions(FallbackValueFlags.FallbackLanguage, fallbackLanguage);
			}

			public static FallbackValueOptions FallbackOrAnyLang(Language fallbackLanguage)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return new FallbackValueOptions(FallbackValueFlags.FallbackOrAnyLanguage, fallbackLanguage);
			}

			public static FallbackValueOptions FallbackLangOrKey(Language fallbackLanguage)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return new FallbackValueOptions(FallbackValueFlags.FallbackLanguageOrKey, fallbackLanguage);
			}

			public static FallbackValueOptions FallbackOrAnyLangOrKey(Language fallbackLanguage)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return new FallbackValueOptions(FallbackValueFlags.FallbackOrAnyLanguageOrKey, fallbackLanguage);
			}
		}

		public struct TextDBOptions
		{
			private FallbackValueOptions? m_FallbackOptions;

			private uint? m_CharacterMetadataId;

			public uint? CharacterMetadataId
			{
				readonly get
				{
					return m_CharacterMetadataId;
				}
				set
				{
					m_CharacterMetadataId = value;
				}
			}

			public FallbackValueOptions? FallbackOptions
			{
				readonly get
				{
					return m_FallbackOptions;
				}
				set
				{
					m_FallbackOptions = value;
				}
			}
		}

		private static readonly Dictionary<string, Entry> s_Entries = new Dictionary<string, Entry>();

		private static readonly List<string> s_EntriesToGenerateTextDBs = new List<string>();

		private static bool s_GameDataInitialized = false;

		private static readonly string STR_NoValueFoundExceptionMsg = "No localization value exists for key '{1}' in language '{0}'.";

		private static readonly string STR_UseKeyGeneric = "{2}: No localization value exists for key '{1}' in language '{0}', defaulting to key.";

		public static ApiStatusInfo Status => APIStatus.Localization;

		public static Language CurrentLanguage => Text.TextLocalizationService.CurrentLanguage;

		public static event Action? OnLanguageChange;

		internal static void Setup()
		{
			GameDataAPI.OnGameDataInitialized += OnGameDataInitialized;
			EventAPI.OnAssetsLoaded += OnGameAssetsLoaded;
			Status.Created = true;
		}

		internal static void OnGameDataInitialized()
		{
			s_GameDataInitialized = true;
			foreach (string s_EntriesToGenerateTextDB in s_EntriesToGenerateTextDBs)
			{
				if (s_Entries.TryGetValue(s_EntriesToGenerateTextDB, out Entry value))
				{
					value.GenerateTextDataBlock(s_EntriesToGenerateTextDB, force: true);
				}
			}
		}

		internal static void OnGameAssetsLoaded()
		{
			Status.Ready = true;
		}

		internal static void LanguageChanged()
		{
			LocalizationAPI.OnLanguageChange?.Invoke();
		}

		public static string FormatString(string key, params object?[] args)
		{
			return FormatString(key, FallbackValueOptions.None, args);
		}

		public static string FormatString(string key, Language fallbackLanguage, params object?[] args)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return FormatString(key, FallbackValueOptions.FallbackLang(fallbackLanguage), args);
		}

		public static string FormatString(string key, FallbackValueOptions options, params object?[] args)
		{
			//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_0030: 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)
			ValidateLocalizationKey(key, "key");
			Language currentLanguage = CurrentLanguage;
			if (!s_Entries.TryGetValue(key, out Entry value))
			{
				ValidateUseKey(key, currentLanguage, options, "FormatString");
				return key;
			}
			return value.FormatString(currentLanguage, key, options, args);
		}

		public static string GetString(string key)
		{
			return GetString(key, FallbackValueOptions.None);
		}

		public static string GetString(string key, Language fallbackLanguage)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return GetString(key, FallbackValueOptions.FallbackLang(fallbackLanguage));
		}

		public static string GetString(string key, FallbackValueOptions options)
		{
			//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_0030: 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)
			ValidateLocalizationKey(key, "key");
			Language currentLanguage = CurrentLanguage;
			if (!s_Entries.TryGetValue(key, out Entry value))
			{
				ValidateUseKey(key, currentLanguage, options, "GetString");
				return key;
			}
			return value.GetString(currentLanguage, key, options);
		}

		public static bool TryGetString(string key, [NotNullWhen(true)] out string? value)
		{
			return TryGetString(key, FallbackValueOptions.None, out value);
		}

		public static bool TryGetString(string key, Language fallbackLanguage, [NotNullWhen(true)] out string? value)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return TryGetString(key, FallbackValueOptions.FallbackLang(fallbackLanguage), out value);
		}

		public static bool TryGetString(string key, FallbackValueOptions options, [NotNullWhen(true)] out string? value)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			ValidateLocalizationKey(key, "key");
			if (!s_Entries.TryGetValue(key, out Entry value2))
			{
				if (options.UseKey)
				{
					value = key;
					return false;
				}
				value = null;
				return false;
			}
			return value2.TryGetString(CurrentLanguage, key, options, out value);
		}

		public static bool HasKey([NotNullWhen(true)] string? key)
		{
			if (!string.IsNullOrWhiteSpace(key))
			{
				return s_Entries.ContainsKey(key);
			}
			return false;
		}

		public static bool HasLocalizedValue([NotNullWhen(true)] string? key, Language language)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			if (!string.IsNullOrWhiteSpace(key) && s_Entries.TryGetValue(key, out Entry value))
			{
				return value.HasValueInLanguage(language);
			}
			return false;
		}

		public static uint GenerateTextBlock(string key, TextDBOptions? textDataBlockOptions = null)
		{
			ValidateLocalizationKey(key, "key");
			Entry entry = s_Entries[key];
			if (entry.TextBlockId.HasValue)
			{
				return entry.TextBlockId.Value;
			}
			if (textDataBlockOptions.HasValue)
			{
				entry.GenerateTextDataBlock(key, textDataBlockOptions.Value);
			}
			else
			{
				entry.GenerateTextDataBlock(key);
			}
			s_EntriesToGenerateTextDBs.Add(key);
			return entry.TextBlockId.Value;
		}

		public static bool TryGetTextBlockId(string key, out uint blockId)
		{
			ValidateLocalizationKey(key, "key");
			if (!s_Entries.TryGetValue(key, out Entry value) || !value.TextBlockId.HasValue)
			{
				blockId = 0u;
				return false;
			}
			blockId = value.TextBlockId.Value;
			return true;
		}

		public static void AddEntry(string key, Language language, string value, TextDBOptions? textDataBlockOptions = null)
		{
			//IL_000b: 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)
			ValidateLocalizationKey(key, "key");
			ValidateLanguage(language, "language");
			if (value == null)
			{
				value = string.Empty;
			}
			bool exists;
			ref Entry valueRefOrAddDefault = ref CollectionsMarshal.GetValueRefOrAddDefault(s_Entries, key, out exists);
			if (valueRefOrAddDefault == null)
			{
				valueRefOrAddDefault = new Entry();
			}
			valueRefOrAddDefault.AddValue(language, value);
			if (textDataBlockOptions.HasValue && !exists)
			{
				s_EntriesToGenerateTextDBs.Add(key);
				if (s_GameDataInitialized)
				{
					valueRefOrAddDefault.GenerateTextDataBlock(key, textDataBlockOptions.Value);
				}
			}
		}

		public static void LoadFromResources(string baseName, TextDBOptions? textDataBlockOptions = null)
		{
			LoadFromResources(baseName, Assembly.GetCallingAssembly(), textDataBlockOptions);
		}

		public static void LoadFromResources(string baseName, Assembly assembly, TextDBOptions? textDataBlockOptions = null)
		{
			//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_0033: 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)
			ResourceManager resourceManager = new ResourceManager(baseName, assembly);
			List<Exception> list = new List<Exception>();
			CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
			foreach (CultureInfo cultureInfo in cultures)
			{
				bool isNeutralCulture = cultureInfo.IsNeutralCulture;
				Language language = GetLanguage(cultureInfo);
				if ((int)language == 0)
				{
					continue;
				}
				ResourceSet resourceSet;
				try
				{
					resourceSet = resourceManager.GetResourceSet(cultureInfo, createIfNotExists: true, tryParents: true);
				}
				catch (MissingManifestResourceException)
				{
					continue;
				}
				catch (Exception item)
				{
					list.Add(item);
					continue;
				}
				if (resourceSet == null)
				{
					continue;
				}
				foreach (DictionaryEntry item2 in resourceSet)
				{
					if (!(item2.Key is string text) || !(item2.Value is string value))
					{
						continue;
					}
					bool exists;
					ref Entry valueRefOrAddDefault = ref CollectionsMarshal.GetValueRefOrAddDefault(s_Entries, text, out exists);
					if (valueRefOrAddDefault == null)
					{
						valueRefOrAddDefault = new Entry();
					}
					valueRefOrAddDefault.AddValue(language, value, isNeutralCulture);
					if (textDataBlockOptions.HasValue && !exists)
					{
						s_EntriesToGenerateTextDBs.Add(text);
						if (s_GameDataInitialized)
						{
							valueRefOrAddDefault.GenerateTextDataBlock(text, textDataBlockOptions.Value);
						}
					}
				}
			}
			resourceManager.ReleaseAllResources();
			if (list.Count > 0)
			{
				throw new AggregateException(list);
			}
		}

		private static void ValidateLocalizationKey([NotNull] string key, [CallerArgumentExpression("key")] string? paramName = null)
		{
			ArgumentNullException.ThrowIfNull(key, paramName);
			if (string.IsNullOrWhiteSpace(paramName))
			{
				throw new ArgumentException("Localization key cannot be empty/whitespace", paramName ?? "key");
			}
		}

		private static void ValidateLanguage(Language language, [CallerArgumentExpression("language")] string? paramName = null)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			if (!Enum.IsDefined<Language>(language))
			{
				throw new ArgumentException($"'{language}' is not a valid language", paramName ?? "language");
			}
		}

		private static void ValidateUseKey(string key, Language language, FallbackValueOptions options, string useCategory)
		{
			//IL_002a: 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)
			if (!options.UseKey)
			{
				throw new KeyNotFoundException(string.Format(STR_NoValueFoundExceptionMsg, language, key));
			}
			APILogger.Warn("LocalizationAPI", string.Format(STR_UseKeyGeneric, language, key, useCategory));
		}

		private static Language GetLanguage(CultureInfo info)
		{
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: 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_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			while (!info.IsNeutralCulture)
			{
				info = info.Parent;
				if (string.IsNullOrEmpty(info.Name))
				{
					return (Language)0;
				}
			}
			return (Language)(info.Name switch
			{
				"en" => 1, 
				"fr" => 2, 
				"it" => 3, 
				"de" => 4, 
				"es" => 5, 
				"ru" => 6, 
				"pt" => 7, 
				"pl" => 8, 
				"ja" => 9, 
				"ko" => 10, 
				"zh-Hans" => 12, 
				"zh-Hant" => 11, 
				_ => 0, 
			});
		}

		private static void UpdateTextDataBlock(TextDataBlock block, Language language, string text)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected I4, but got Unknown
			switch (language - 1)
			{
			case 0:
				block.English = text;
				break;
			case 1:
				block.French = LanguageData.op_Implicit(text);
				break;
			case 2:
				block.Italian = LanguageData.op_Implicit(text);
				break;
			case 3:
				block.German = LanguageData.op_Implicit(text);
				break;
			case 4:
				block.Spanish = LanguageData.op_Implicit(text);
				break;
			case 5:
				block.Russian = LanguageData.op_Implicit(text);
				break;
			case 6:
				block.Portuguese_Brazil = LanguageData.op_Implicit(text);
				break;
			case 7:
				block.Polish = LanguageData.op_Implicit(text);
				break;
			case 8:
				block.Japanese = LanguageData.op_Implicit(text);
				break;
			case 9:
				block.Korean = LanguageData.op_Implicit(text);
				break;
			case 10:
				block.Chinese_Traditional = LanguageData.op_Implicit(text);
				break;
			case 11:
				block.Chinese_Simplified = LanguageData.op_Implicit(text);
				break;
			}
		}
	}
	[API("Network")]
	public static class NetworkAPI
	{
		internal class CachedEvent
		{
			public string EventName { get; set; }

			public Type PayloadType { get; set; }

			public object OnReceive { get; set; }

			public bool IsFreeSize { get; set; }
		}

		internal static ConcurrentDictionary<string, CachedEvent> s_EventCache = new ConcurrentDictionary<string, CachedEvent>();

		public static ApiStatusInfo Status => APIStatus.Network;

		public static bool IsEventRegistered(string eventName)
		{
			return NetworkAPI_Impl.Instance.EventExists(eventName);
		}

		public static void RegisterEvent<T>(string eventName, Action<ulong, T> onReceive) where T : struct
		{
			if (!APIStatus.Network.Ready)
			{
				if (s_EventCache.ContainsKey(eventName))
				{
					throw new ArgumentException("An event with the name " + eventName + " has already been registered.", "eventName");
				}
				s_EventCache.TryAdd(eventName, new CachedEvent
				{
					EventName = eventName,
					PayloadType = typeof(T),
					OnReceive = onReceive,
					IsFreeSize = false
				});
			}
			else
			{
				NetworkAPI_Impl.Instance.RegisterEvent(eventName, onReceive);
			}
		}

		public static void InvokeEvent<T>(string eventName, T payload, SNet_ChannelType channelType = 2) where T : struct
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			SNet_SendGroup val = default(SNet_SendGroup);
			SNet_SendQuality val2 = default(SNet_SendQuality);
			int num = default(int);
			SNet.GetSendSettings(ref channelType, ref val, ref val2, ref num);
			SNet.Core.SendBytes(MakeBytes(eventName, payload), val, val2, num);
		}

		public static void InvokeEvent<T>(string eventName, T payload, SNet_Player target, SNet_ChannelType channelType = 2) where T : struct
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			SNet_SendGroup val = default(SNet_SendGroup);
			SNet_SendQuality val2 = default(SNet_SendQuality);
			int num = default(int);
			SNet.GetSendSettings(ref channelType, ref val, ref val2, ref num);
			SNet.Core.SendBytes(MakeBytes(eventName, payload), val2, num, target);
		}

		public static void InvokeEvent<T>(string eventName, T payload, List<SNet_Player> targets, SNet_ChannelType channelType = 2) where T : struct
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			SNet_SendGroup val = default(SNet_SendGroup);
			SNet_SendQuality val2 = default(SNet_SendQuality);
			int num = default(int);
			SNet.GetSendSettings(ref channelType, ref val, ref val2, ref num);
			SNet.Core.SendBytes(MakeBytes(eventName, payload), val2, num, targets.ToIl2Cpp());
		}

		public static void RegisterFreeSizedEvent(string eventName, Action<ulong, byte[]> onReceiveBytes)
		{
			if (!APIStatus.Network.Ready)
			{
				if (s_EventCache.ContainsKey(eventName))
				{
					throw new ArgumentException("An event with the name " + eventName + " has already been registered.", "eventName");
				}
				s_EventCache.TryAdd(eventName, new CachedEvent
				{
					EventName = eventName,
					PayloadType = null,
					OnReceive = onReceiveBytes,
					IsFreeSize = true
				});
			}
			else
			{
				NetworkAPI_Impl.Instance.RegisterFreeSizedEvent(eventName, onReceiveBytes);
			}
		}

		public static void InvokeFreeSizedEvent(string eventName, byte[] payload, SNet_ChannelType channelType = 2)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			SNet_SendGroup val = default(SNet_SendGroup);
			SNet_SendQuality val2 = default(SNet_SendQuality);
			int num = default(int);
			SNet.GetSendSettings(ref channelType, ref val, ref val2, ref num);
			SNet.Core.SendBytes(MakeBytes(eventName, payload), val, val2, num);
		}

		public static void InvokeFreeSizedEvent(string eventName, byte[] payload, SNet_Player target, SNet_ChannelType channelType = 2)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			SNet_SendGroup val = default(SNet_SendGroup);
			SNet_SendQuality val2 = default(SNet_SendQuality);
			int num = default(int);
			SNet.GetSendSettings(ref channelType, ref val, ref val2, ref num);
			SNet.Core.SendBytes(MakeBytes(eventName, payload), val2, num, target);
		}

		public static void InvokeFreeSizedEvent(string eventName, byte[] payload, IEnumerable<SNet_Player> targets, SNet_ChannelType channelType = 2)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			SNet_SendGroup val = default(SNet_SendGroup);
			SNet_SendQuality val2 = default(SNet_SendQuality);
			int num = default(int);
			SNet.GetSendSettings(ref channelType, ref val, ref val2, ref num);
			SNet.Core.SendBytes(MakeBytes(eventName, payload), val2, num, targets.ToList().ToIl2Cpp());
		}

		private static Il2CppStructArray<byte> MakeBytes<T>(string eventName, T payload) where T : struct
		{
			return Il2CppStructArray<byte>.op_Implicit(NetworkAPI_Impl.Instance.MakePacketBytes(eventName, payload));
		}

		private static Il2CppStructArray<byte> MakeBytes(string eventName, byte[] payload)
		{
			return Il2CppStructArray<byte>.op_Implicit(NetworkAPI_Impl.Instance.MakeFreeSizedPacketBytes(eventName, payload));
		}
	}
	[API("Prefab")]
	public static class PrefabAPI
	{
		private static Shader s_CustomGearShader;

		private static readonly Dictionary<uint, Action<SyringeFirstPerson>> s_SyringeActions = new Dictionary<uint, Action<SyringeFirstPerson>>();

		public static ApiStatusInfo Status => APIStatus.Prefab;

		private static Shader CustomGearShader
		{
			get
			{
				if ((Object)(object)s_CustomGearShader == (Object)null)
				{
					s_CustomGearShader = Shader.Find("Cell/Player/CustomGearShader");
				}
				return s_CustomGearShader;
			}
		}

		public static void CreateConsumable(string assetName, bool enableEmissive = false)
		{
			Object loadedAsset = AssetAPI.GetLoadedAsset(assetName);
			GameObject val = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).TryCast<GameObject>() : null) ?? null;
			if ((Object)(object)val == (Object)null)
			{
				throw new ArgumentException("Couldn't find a game object asset with the name " + assetName, "assetName");
			}
			ItemEquippable obj = val.AddComponent<ItemEquippable>();
			obj.m_isFirstPerson = false;
			((Item)obj).m_itemModelHolder = val.transform;
			ReplaceShaderInAssetMaterials(val, CustomGearShader, enableEmissive ? "ENABLE_EMISSIVE" : null);
		}

		public static void CreateConsumablePickup(string assetName, bool enableEmissive = false)
		{
			Object loadedAsset = AssetAPI.GetLoadedAsset(assetName);
			GameObject val = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).TryCast<GameObject>() : null) ?? null;
			if ((Object)(object)val == (Object)null)
			{
				throw new ArgumentException("Couldn't find a game object asset with the name " + assetName, "assetName");
			}
			BoxCollider componentInChildren = val.GetComponentInChildren<BoxCollider>();
			if ((Object)(object)componentInChildren == (Object)null)
			{
				throw new Exception("The Consumable Pickup prefab doesn't contain a BoxCollider for interaction");
			}
			GameObject gameObject = ((Component)componentInChildren).gameObject;
			gameObject.layer = LayerMask.NameToLayer("Interaction");
			Interact_Pickup_PickupItem val2 = gameObject.AddComponent<Interact_Pickup_PickupItem>();
			((Interact_Base)val2).m_colliderToOwn = (Collider)(object)componentInChildren;
			ConsumablePickup_Core obj = val.AddComponent<ConsumablePickup_Core>();
			obj.m_syncComp = (Component)(object)val.AddComponent<LG_PickupItem_Sync>();
			obj.m_interactComp = (Component)(object)val2;
			ReplaceShaderInAssetMaterials(val, CustomGearShader, enableEmissive ? "ENABLE_EMISSIVE" : null);
		}

		public static void CreateConsumableInstance<T>(string assetName) where T : ConsumableInstance
		{
			Object loadedAsset = AssetAPI.GetLoadedAsset(assetName);
			GameObject obj = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).TryCast<GameObject>() : null) ?? null;
			if ((Object)(object)obj == (Object)null)
			{
				throw new ArgumentException("Couldn't find a game object asset with the name " + assetName, "assetName");
			}
			if (!ClassInjector.IsTypeRegisteredInIl2Cpp<T>())
			{
				ClassInjector.RegisterTypeInIl2Cpp<T>();
			}
			obj.layer = LayerMask.NameToLayer("Debris");
			Rigidbody component = obj.GetComponent<Rigidbody>();
			obj.AddComponent<ColliderMaterial>().PhysicsBody = component ?? throw new Exception("The Consumable Instance prefab doesn't contain a Rigidbody");
			obj.AddComponent<T>();
		}

		public static void CreateGearComponent(string assetName, bool enableEmissive = false)
		{
			Object loadedAsset = AssetAPI.GetLoadedAsset(assetName);
			GameObject obj = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).TryCast<GameObject>() : null) ?? null;
			if ((Object)(object)obj == (Object)null)
			{
				throw new ArgumentException("Couldnt find a game object asset with the name " + assetName, "assetName");
			}
			obj.layer = LayerMask.NameToLayer("FirstPersonItem");
			ReplaceShaderInAssetMaterials(obj, CustomGearShader, "ENABLE_FPS_RENDERING", enableEmissive ? "ENABLE_EMISSIVE" : null);
		}

		public static void CreateSyringe(uint itemPersistentId, Action<SyringeFirstPerson> onUse)
		{
			if (s_SyringeActions.ContainsKey(itemPersistentId))
			{
				throw new ArgumentException($"{itemPersistentId} is already registered with a syringe action.");
			}
			s_SyringeActions.Add(itemPersistentId, onUse);
		}

		internal static bool OnSyringeUsed(SyringeFirstPerson syringe)
		{
			if (s_SyringeActions.TryGetValue(((GameDataBlockBase<ItemDataBlock>)(object)((Item)syringe).ItemDataBlock).persistentID, out var value))
			{
				value(syringe);
				return true;
			}
			return false;
		}

		private static void ReplaceShaderInAssetMaterials(GameObject asset, Shader newShader, params string[] addedKeywords)
		{
			addedKeywords = addedKeywords.Where((string x) => !string.IsNullOrEmpty(x)).ToArray();
			foreach (MeshRenderer componentsInChild in asset.GetComponentsInChildren<MeshRenderer>(true))
			{
				foreach (Material item in (Il2CppArrayBase<Material>)(object)((Renderer)componentsInChild).materials)
				{
					item.shader = newShader;
					if (addedKeywords.Length != 0)
					{
						string[] array = Il2CppArrayBase<string>.op_Implicit((Il2CppArrayBase<string>)(object)item.shaderKeywords);
						int num = array.Length;
						Array.Resize(ref array, array.Length + addedKeywords.Length);
						for (int i = 0; i < addedKeywords.Length; i++)
						{
							array[num + i] = addedKeywords[i];
						}
						item.shaderKeywords = Il2CppStringArray.op_Implicit(array);
					}
				}
			}
		}
	}
	[API("SoundBank")]
	public static class SoundBankAPI
	{
		public static ApiStatusInfo Status => APIStatus.SoundBank;

		public static event Action OnSoundBanksLoaded;

		internal static void Setup()
		{
			EventAPI.OnManagersSetup += OnLoadSoundBanks;
		}

		private static void OnLoadSoundBanks()
		{
			FileInfo[] array = (from file in Directory.CreateDirectory(Path.Combine(Paths.BepInExRootPath, "Assets", "SoundBank")).EnumerateFiles()
				where file.Extension.Contains(".bnk")
				select file).ToArray();
			CollectionExtensions.Do<FileInfo>((IEnumerable<FileInfo>)array, (Action<FileInfo>)LoadBank);
			if (array.Any())
			{
				SoundBankAPI.OnSoundBanksLoaded?.Invoke();
			}
		}

		private unsafe static void LoadBank(FileInfo file)
		{
			//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_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Invalid comparison between Unknown and I4
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			using FileStream fileStream = file.OpenRead();
			uint num = (uint)fileStream.Length;
			byte[] array = new byte[num];
			if (fileStream.Read(array, 0, (int)num) != 0)
			{
				void* intPtr = NativeMemory.AlignedAlloc(num, 16u);
				Unsafe.CopyBlock(ref Unsafe.AsRef<byte>(intPtr), ref array[0], num);
				uint value = default(uint);
				AKRESULT val = AkSoundEngine.LoadBank((IntPtr)(nint)intPtr, num, ref value);
				if ((int)val == 1)
				{
					APILogger.Info("SoundBankAPI", $"Loaded sound bank '{file.Name}' (bankId: {value:X2})");
				}
				else
				{
					APILogger.Error("SoundBankAPI", $"Error while loading sound bank '{file.Name}' ({val})");
				}
			}
		}
	}
	[BepInPlugin("dev.gtfomodding.gtfo-api", "GTFO-API", "0.4.1")]
	internal class EntryPoint : BasePlugin
	{
		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			APILogger.Verbose("Core", "Registering API Implementations");
			ClassInjector.RegisterTypeInIl2Cpp<NetworkAPI_Impl>();
			ClassInjector.RegisterTypeInIl2Cpp<AssetAPI_Impl>();
			APILogger.Verbose("Core", "Registering Wrappers");
			ClassInjector.RegisterTypeInIl2Cpp<ItemWrapped>();
			APILogger.Verbose("Core", "Registering Utilities Implementations");
			ClassInjector.RegisterTypeInIl2Cpp<ThreadDispatcher_Impl>();
			ClassInjector.RegisterTypeInIl2Cpp<CoroutineDispatcher_Impl>();
			APILogger.Verbose("Core", "Applying Patches");
			m_Harmony = new Harmony("dev.gtfomodding.gtfo-api");
			m_Harmony.PatchAll();
			EventAPI.Setup();
			AssetAPI.Setup();
			SoundBankAPI.Setup();
			LevelAPI.Setup();
			LocalizationAPI.Setup();
			APILogger.Verbose("Core", "Plugin Load Complete");
			APILogger.Warn("GTFO-API", "Syringes are currently disabled in this version");
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "GTFO.API";

		public const string Version = "0.4.1";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "git1e8fe81-main";

		public const string SemVer = "0.4.1+git1e8fe81-main";

		public const string GitRevShort = "1e8fe81";

		public const string GitRevLong = "1e8fe816dac645ea837fe046d35f0b1ec044f6db";

		public const string GitBranch = "main";

		public const string GitTag = "0.4.0";

		public const bool GitIsDirty = false;
	}
}
namespace GTFO.API.Wrappers
{
	public class ItemWrapped : Item
	{
		private static readonly Item__Get_pItemData Get_pItemDataBase = Il2CppAPI.GetIl2CppMethod<Item, Item__Get_pItemData>("Get_pItemData", "Player.pItemData", isGeneric: false, Array.Empty<string>());

		private static readonly Item__Set_pItemData Set_pItemDataBase = Il2CppAPI.GetIl2CppMethod<Item, Item__Set_pItemData>("Set_pItemData", "System.Void", isGeneric: false, new string[1] { "Player.pItemData" });

		private static readonly Item__GetCustomData GetCustomDataBase = Il2CppAPI.GetIl2CppMethod<Item, Item__GetCustomData>("GetCustomData", "Player.pItemData_Custom", isGeneric: false, Array.Empty<string>());

		private static readonly Item__SetCustomData SetCustomDataBase = Il2CppAPI.GetIl2CppMethod<Item, Item__SetCustomData>("SetCustomData", "System.Void", isGeneric: false, new string[2] { "Player.pItemData_Custom", "System.Boolean" });

		private static readonly Item__OnCustomDataUpdated OnCustomDataUpdatedBase = Il2CppAPI.GetIl2CppMethod<Item, Item__OnCustomDataUpdated>("OnCustomDataUpdated", "System.Void", isGeneric: false, new string[1] { "Player.pItemData_Custom" });

		private static readonly Item__Awake AwakeBase = Il2CppAPI.GetIl2CppMethod<Item, Item__Awake>("Awake", "System.Void", isGeneric: false, Array.Empty<string>());

		private static readonly Item__OnDespawn OnDespawnBase = Il2CppAPI.GetIl2CppMethod<Item, Item__OnDespawn>("OnDespawn", "System.Void", isGeneric: false, Array.Empty<string>());

		private static readonly Item__Setup SetupBase = Il2CppAPI.GetIl2CppMethod<Item, Item__Setup>("Setup", "System.Void", isGeneric: false, new string[1] { "GameData.ItemDataBlock" });

		private static readonly Item__OnGearSpawnComplete OnGearSpawnCompleteBase = Il2CppAPI.GetIl2CppMethod<Item, Item__OnGearSpawnComplete>("OnGearSpawnComplete", "System.Void", isGeneric: false, Array.Empty<string>());

		private static readonly Item__OnPickUp OnPickUpBase = Il2CppAPI.GetIl2CppMethod<Item, Item__OnPickUp>("OnPickUp", "System.Void", isGeneric: false, new string[1] { "Player.PlayerAgent" });

		private static readonly Item__SetupBaseModel SetupBaseModelBase = Il2CppAPI.GetIl2CppMethod<Item, Item__SetupBaseModel>("SetupBaseModel", "System.Void", isGeneric: false, new string[1] { "ItemSetup.ItemModelSetup" });

		private static readonly Item__SyncedTurnOn SyncedTurnOnBase = Il2CppAPI.GetIl2CppMethod<Item, Item__SyncedTurnOn>("SyncedTurnOn", "System.Void", isGeneric: false, new string[2] { "Player.PlayerAgent", "AIGraph.AIG_CourseNode" });

		private static readonly Item__SyncedTurnOff SyncedTurnOffBase = Il2CppAPI.GetIl2CppMethod<Item, Item__SyncedTurnOff>("SyncedTurnOff", "System.Void", isGeneric: false, new string[1] { "Player.PlayerAgent" });

		private static readonly Item__SyncedTrigger SyncedTriggerBase = Il2CppAPI.GetIl2CppMethod<Item, Item__SyncedTrigger>("SyncedTrigger", "System.Void", isGeneric: false, new string[1] { "Player.PlayerAgent" });

		private static readonly Item__SyncedTriggerSecondary SyncedTriggerSecondaryBase = Il2CppAPI.GetIl2CppMethod<Item, Item__SyncedTriggerSecondary>("SyncedTriggerSecondary", "System.Void", isGeneric: false, new string[1] { "Player.PlayerAgent" });

		private static readonly Item__SyncedThrow SyncedThrowBase = Il2CppAPI.GetIl2CppMethod<Item, Item__SyncedThrow>("SyncedThrow", "System.Void", isGeneric: false, new string[1] { "Player.PlayerAgent" });

		private static readonly Item__SyncedPickup SyncedPickupBase = Il2CppAPI.GetIl2CppMethod<Item, Item__SyncedPickup>("SyncedPickup", "System.Void", isGeneric: false, new string[1] { "Player.PlayerAgent" });

		private static readonly Item__SyncedSetKeyValue SyncedSetKeyValueBase = Il2CppAPI.GetIl2CppMethod<Item, Item__SyncedSetKeyValue>("SyncedSetKeyValue", "System.Void", isGeneric: false, new string[2] { "System.Int32", "System.Single" });

		private static readonly Item__GetPickupInteraction GetPickupInteractionBase = Il2CppAPI.GetIl2CppMethod<Item, Item__GetPickupInteraction>("GetPickupInteraction", "Interact_Base", isGeneric: false, Array.Empty<string>());

		private static readonly Item__GetItem GetItemBase = Il2CppAPI.GetIl2CppMethod<Item, Item__GetItem>("GetItem", "Item", isGeneric: false, Array.Empty<string>());

		public ItemWrapped(IntPtr hdl)
			: base(hdl)
		{
		}

		public unsafe override pItemData Get_pItemData()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			pItemData* retstr = (pItemData*)stackalloc pItemData[1];
			return *Get_pItemDataBase(retstr, ((Il2CppObjectBase)this).Pointer.ToPointer());
		}

		public unsafe override void Set_pItemData(pItemData data)
		{
			Set_pItemDataBase(((Il2CppObjectBase)this).Pointer.ToPointer(), &data);
		}

		public unsafe override pItemData_Custom GetCustomData()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			return *GetCustomDataBase(((Il2CppObjectBase)this).Pointer.ToPointer());
		}

		public unsafe override void SetCustomData(pItemData_Custom custom, bool sync)
		{
			SetCustomDataBase(((Il2CppObjectBase)this).Pointer.ToPointer(), &custom, sync);
		}

		public unsafe override void OnCustomDataUpdated(pItemData_Custom customDataCopy)
		{
			OnCustomDataUpdatedBase(((Il2CppObjectBase)this).Pointer.ToPointer(), &customDataCopy);
		}

		public unsafe override void Awake()
		{
			AwakeBase(((Il2CppObjectBase)this).Pointer.ToPointer());
		}

		public unsafe override void OnDespawn()
		{
			OnDespawnBase(((Il2CppObjectBase)this).Pointer.ToPointer());
		}

		public unsafe override void Setup(ItemDataBlock data)
		{
			SetupBase(((Il2CppObjectBase)this).Pointer.ToPointer(), ((Il2CppObjectBase)data).Pointer.ToPointer());
		}

		public unsafe override void OnGearSpawnComplete()
		{
			OnGearSpawnCompleteBase(((Il2CppObjectBase)this).Pointer.ToPointer());
		}

		public unsafe override void OnPickUp(PlayerAgent player)
		{
			OnPickUpBase(((Il2CppObjectBase)this).Pointer.ToPointer(), ((Il2CppObjectBase)player).Pointer.ToPointer());
		}

		public unsafe override void SetupBaseModel(ItemModelSetup setup)
		{
			SetupBaseModelBase(((Il2CppObjectBase)this).Pointer.ToPointer(), ((Il2CppObjectBase)setup).Pointer.ToPointer());
		}

		public unsafe override void SyncedTurnOn(PlayerAgent agent, AIG_CourseNode courseNode)
		{
			SyncedTurnOnBase(((Il2CppObjectBase)this).Pointer.ToPointer(), ((Il2CppObjectBase)agent).Pointer.ToPointer(), ((Il2CppObjectBase)courseNode).Pointer.ToPointer());
		}

		public unsafe override void SyncedTurnOff(PlayerAgent agent)
		{
			SyncedTurnOffBase(((Il2CppObjectBase)this).Pointer.ToPointer(), ((Il2CppObjectBase)agent).Pointer.ToPointer());
		}

		public unsafe override void SyncedTrigger(PlayerAgent agent)
		{
			SyncedTriggerBase(((Il2CppObjectBase)this).Pointer.ToPointer(), ((Il2CppObjectBase)agent).Pointer.ToPointer());
		}

		public unsafe override void SyncedTriggerSecondary(PlayerAgent agent)
		{
			SyncedTriggerSecondaryBase(((Il2CppObjectBase)this).Pointer.ToPointer(), ((Il2CppObjectBase)agent).Pointer.ToPointer());
		}

		public unsafe override void SyncedThrow(PlayerAgent agent)
		{
			SyncedThrowBase(((Il2CppObjectBase)this).Pointer.ToPointer(), ((Il2CppObjectBase)agent).Pointer.ToPointer());
		}

		public unsafe override void SyncedPickup(PlayerAgent agent)
		{
			SyncedPickupBase(((Il2CppObjectBase)this).Pointer.ToPointer(), ((Il2CppObjectBase)agent).Pointer.ToPointer());
		}

		public unsafe override void SyncedSetKeyValue(int key, float value)
		{
			SyncedSetKeyValueBase(((Il2CppObjectBase)this).Pointer.ToPointer(), key, value);
		}

		public unsafe override Interact_Base GetPickupInteraction()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			return new Interact_Base((IntPtr)GetPickupInteractionBase(((Il2CppObjectBase)this).Pointer.ToPointer()));
		}

		public unsafe override Item GetItem()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			return new Item((IntPtr)GetItemBase(((Il2CppObjectBase)this).Pointer.ToPointer()));
		}
	}
	public unsafe delegate pItemData* Item__Get_pItemData(pItemData* retstr, void* _this);
	public unsafe delegate void Item__Set_pItemData(void* _this, void* data);
	public unsafe delegate pItemData_Custom* Item__GetCustomData(void* _this);
	public unsafe delegate void Item__SetCustomData(void* _this, pItemData_Custom* custom, bool sync);
	public unsafe delegate void Item__OnCustomDataUpdated(void* _this, pItemData_Custom* customDataCopy);
	public unsafe delegate void Item__Awake(void* _this);
	public unsafe delegate void Item__OnDespawn(void* _this);
	public unsafe delegate void Item__Setup(void* _this, void* data);
	public unsafe delegate void Item__OnGearSpawnComplete(void* _this);
	public unsafe delegate void Item__OnPickUp(void* _this, void* player);
	public unsafe delegate void Item__SetupBaseModel(void* _this, void* setup);
	public unsafe delegate void Item__SyncedTurnOn(void* _this, void* agent, void* courseNode);
	public unsafe delegate void Item__SyncedTurnOff(void* _this, void* agent);
	public unsafe delegate void Item__SyncedTrigger(void* _this, void* agent);
	public unsafe delegate void Item__SyncedTriggerSecondary(void* _this, void* agent);
	public unsafe delegate void Item__SyncedThrow(void* _this, void* agent);
	public unsafe delegate void Item__SyncedPickup(void* _this, void* agent);
	public unsafe delegate void Item__SyncedSetKeyValue(void* _this, int key, float value);
	public unsafe delegate void* Item__GetPickupInteraction(void* _this);
	public unsafe delegate void* Item__GetItem(void* _this);
	[Il2CppInterface(typeof(iTerminalItem))]
	public interface iTerminalItemWrapper
	{
		uint TerminalItemId { get; set; }

		string TerminalItemKey { get; set; }

		string OverrideCode { get; set; }

		Vector3 LocatorBeaconPosition { get; set; }

		AIG_CourseNode SpawnNode { get; set; }

		bool ShowInFloorInventory { get; set; }

		string FloorItemLocation { get; set; }

		eFloorInventoryObjectType FloorItemType { get; set; }

		eFloorInventoryObjectStatus FloorItemStatus { get; set; }

		Func<List<string>, List<string>> OnWantDetailedInfo { get; set; }

		void Setup(string key);

		List<string> GetDetailedInfo(List<string> defaultDetails);

		void PlayPing();
	}
	[Il2CppInterface(typeof(iResourcePackReceiver))]
	public interface iResourcePackReceiverWrapper
	{
		bool IsLocallyOwned { get; }

		string InteractionName { get; }

		bool NeedHealth();

		bool NeedDisinfection();

		bool NeedWeaponAmmo();

		bool NeedToolAmmo();

		void GiveAmmoRel(float ammoStandardRel, float ammoSpecialRel, float ammoClassRel);

		void GiveHealth(float health);

		void GiveDisinfection(float disinfection);
	}
	[Il2CppInterface(typeof(iPlayerPingTarget))]
	public interface iPlayerPingTargetWrapper
	{
		eNavMarkerStyle PingTargetStyle { get; set; }
	}
	[Il2CppInterface(typeof(iWardenObjectiveItem))]
	public interface iWardenObjectiveItemWrapper
	{
		LG_LayerType OriginLayer { get; }

		AIG_CourseNode SpawnNode { get; }

		string PublicName { get; }

		Transform transform { get; }

		bool ObjectiveItemSolved { get; }

		ePickupItemStatus PickupItemStatus { get; }

		PlayerAgent PickedUpByPlayer { get; }

		void ActivateWardenObjectiveItem();

		void DeactivateWardenObjectiveItem();
	}
}
namespace GTFO.API.Utilities
{
	public static class CoroutineDispatcher
	{
		public static Coroutine StartCoroutine(IEnumerator routine)
		{
			return CoroutineDispatcher_Impl.Instance.RunCoroutine(routine);
		}

		public static Coroutine StartInLevelCoroutine(IEnumerator routine)
		{
			return CoroutineDispatcher_Impl.Instance.RunInLevelCoroutine(routine);
		}
	}
	public delegate void LiveEditEventHandler(LiveEditEventArgs e);
	public class LiveEditEventArgs
	{
		public LiveEditEventType Type { get; set; }

		public string FullPath { get; set; }

		public string FileName { get; set; }
	}
	public enum LiveEditEventType
	{
		Created,
		Deleted,
		Renamed,
		Changed
	}
	public static class LiveEdit
	{
		internal const int RETRY_COUNT = 5;

		internal const float RETRY_INTERVAL = 0.1f;

		internal static readonly List<LiveEditListener> s_Listeners = new List<LiveEditListener>();

		public static LiveEditListener CreateListener(string path, string filter, bool includeSubDir)
		{
			LiveEditListener liveEditListener = new LiveEditListener(path, filter, includeSubDir);
			s_Listeners.Add(liveEditListener);
			return liveEditListener;
		}

		public static void TryReadFileContent(string filepath, Action<string> onReaded)
		{
			CoroutineDispatcher.StartCoroutine(GetFileStream(filepath, 5, 0.1f, delegate(FileStream stream)
			{
				try
				{
					using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
					onReaded?.Invoke(streamReader.ReadToEnd());
				}
				catch
				{
				}
			}));
		}

		private static IEnumerator GetFileStream(string filepath, int retryCount, float retryInterval, Action<FileStream> onFileStreamOpened)
		{
			retryCount = Math.Max(retryCount, 1);
			retryInterval = Math.Max(retryInterval, 0f);
			WaitForSecondsRealtime wait = new WaitForSecondsRealtime(retryInterval);
			for (int i = 0; i < retryCount; i++)
			{
				try
				{
					FileStream fileStream = new FileStream(filepath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
					onFileStreamOpened?.Invoke(fileStream);
					fileStream.Close();
					break;
				}
				catch
				{
				}
				yield return wait;
			}
		}
	}
	public sealed class LiveEditListener : IDisposable
	{
		private FileSystemWatcher m_Watcher;

		private bool m_Allocated = true;

		private float m_ChangedCooldownTimer;

		public float FileChangedEventCooldown { get; set; } = 0.05f;


		public event LiveEditEventHandler FileChanged;

		public event LiveEditEventHandler FileDeleted;

		public event LiveEditEventHandler FileCreated;

		public event LiveEditEventHandler FileRenamed;

		private LiveEditListener()
		{
		}

		internal LiveEditListener(string path, string filter, bool includeSubDir)
		{
			LiveEditListener liveEditListener = this;
			m_Watcher = new FileSystemWatcher
			{
				Path = path,
				Filter = filter,
				IncludeSubdirectories = includeSubDir,
				NotifyFilter = (NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.CreationTime)
			};
			m_Watcher.Deleted += delegate(object sender, FileSystemEventArgs e)
			{
				FileSystemEventArgs e5 = e;
				ThreadDispatcher.Dispatch(delegate
				{
					liveEditListener.FileDeleted?.Invoke(CreateArgs(e5, LiveEditEventType.Deleted));
				});
			};
			m_Watcher.Created += delegate(object sender, FileSystemEventArgs e)
			{
				FileSystemEventArgs e4 = e;
				ThreadDispatcher.Dispatch(delegate
				{
					liveEditListener.FileCreated?.Invoke(CreateArgs(e4, LiveEditEventType.Created));
				});
			};
			m_Watcher.Renamed += delegate(object sender, RenamedEventArgs e)
			{
				RenamedEventArgs e3 = e;
				ThreadDispatcher.Dispatch(delegate
				{
					liveEditListener.FileRenamed?.Invoke(CreateArgs(e3, LiveEditEventType.Renamed));
				});
			};
			m_Watcher.Changed += delegate(object sender, FileSystemEventArgs e)
			{
				FileSystemEventArgs e2 = e;
				ThreadDispatcher.Dispatch(delegate
				{
					float time = Time.time;
					if (!(liveEditListener.m_ChangedCooldownTimer > time))
					{
						liveEditListener.m_ChangedCooldownTimer = time + liveEditListener.FileChangedEventCooldown;
						liveEditListener.FileChanged?.Invoke(CreateArgs(e2, LiveEditEventType.Changed));
					}
				});
			};
			m_Watcher.Error += delegate(object sender, ErrorEventArgs e)
			{
				APILogger.Error("LiveEdit", $"Path: {path} error reported! - {e.GetException()}");
			};
			StartListen();
		}

		private static LiveEditEventArgs CreateArgs(FileSystemEventArgs args, LiveEditEventType type)
		{
			return new LiveEditEventArgs
			{
				FullPath = args.FullPath,
				FileName = Path.GetFileName(args.FullPath),
				Type = type
			};
		}

		public void Dispose()
		{
			if (m_Allocated)
			{
				LiveEdit.s_Listeners.Remove(this);
				m_Allocated = false;
			}
			if (m_Watcher != null)
			{
				StopListen();
				this.FileChanged = null;
				this.FileDeleted = null;
				this.FileCreated = null;
				this.FileRenamed = null;
				m_Watcher.Dispose();
			}
			m_Watcher = null;
		}

		public void StopListen()
		{
			if (m_Watcher != null)
			{
				m_Watcher.EnableRaisingEvents = false;
			}
		}

		public void StartListen()
		{
			if (m_Watcher != null)
			{
				m_Watcher.EnableRaisingEvents = true;
			}
		}
	}
	internal static class MemoryUtils
	{
		private static byte[] _trampolineShellcode = new byte[12]
		{
			72, 184, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 208
		};

		public unsafe static void* FindSignatureInBlock(void* block, ulong blockSize, string pattern, string mask, ulong sigOffset = 0uL)
		{
			return FindSignatureInBlock(block, blockSize, pattern.ToCharArray(), mask.ToCharArray(), sigOffset);
		}

		public unsafe static void* FindSignatureInBlock(void* block, ulong blockSize, char[] pattern, char[] mask, ulong sigOffset = 0uL)
		{
			for (ulong num = 0uL; num < blockSize; num++)
			{
				bool flag = true;
				for (uint num2 = 0u; num2 < mask.Length; num2++)
				{
					if (*(byte*)((long)num + (long)block + num2) != (byte)pattern[num2] && mask[num2] != '?')
					{
						flag = false;
						break;
					}
				}
				if (flag)
				{
					return (void*)((ulong)((long)num + (long)block) + sigOffset);
				}
			}
			return null;
		}

		public unsafe static byte[] MakeTrampoline(void* destination)
		{
			byte[] array = new byte[_trampolineShellcode.Length];
			Array.Copy(_trampolineShellcode, 0, array, 0, _trampolineShellcode.Length);
			fixed (byte* ptr = array)
			{
				*(long*)(ptr + 2) = (long)destination;
			}
			return array;
		}

		public unsafe static void CreateTrampolineBetween(void* start, void* end, void* destination)
		{
			ulong num = (ulong)end - (ulong)start;
			if (num < (ulong)_trampolineShellcode.Length)
			{
				throw new Exception("Trampoline block size is not enough to create.");
			}
			uint flNewProtect = default(uint);
			if (!Kernel32.VirtualProtect(start, num, 64u, &flNewProtect))
			{
				throw new Exception("Failed to change protection of trampoline block.");
			}
			APILogger.Verbose("MemoryUtils", "NOPing trampoline block");
			for (ulong num2 = 0uL; num2 < num; num2++)
			{
				*(sbyte*)((ulong)start + num2) = -112;
			}
			APILogger.Verbose("MemoryUtils", "Creating trampoline shellcode");
			byte[] array = MakeTrampoline(destination);
			APILogger.Verbose("MemoryUtils", "Writing trampoline shellcode");
			for (ulong num3 = 0uL; num3 < (ulong)array.Length; num3++)
			{
				*(byte*)((ulong)start + num3) = array[num3];
			}
			if (!Kernel32.VirtualProtect(start, num, flNewProtect, &flNewProtect))
			{
				throw new Exception("Failed to revert trampoline block protection.");
			}
		}
	}
	public class PersistentData<T> where T : PersistentData<T>, new()
	{
		private const string VERSION_REGEX = "\"PersistentDataVersion\": \"(.+?)\"";

		private static T s_CurrentData;

		public static T CurrentData
		{
			get
			{
				if (s_CurrentData != null)
				{
					return s_CurrentData;
				}
				s_CurrentData = Load();
				return s_CurrentData;
			}
			set
			{
				s_CurrentData = value;
			}
		}

		protected static string persistentPath => Path.Combine(Paths.BepInExRootPath, "GameData", "PersistentData", typeof(T).Assembly.GetName().Name, typeof(T).Name + ".json");

		public virtual string PersistentDataVersion { get; set; } = "1.0.0";


		public static T Load()
		{
			return Load(persistentPath);
		}

		public static T Load(string path)
		{
			T val = new T();
			if (File.Exists(path))
			{
				string text = File.ReadAllText(path);
				T val2;
				try
				{
					val2 = GTFO.API.JSON.JsonSerializer.Deserialize<T>(text);
				}
				catch (JsonException)
				{
					APILogger.Warn("JSON", "Failed to deserialize " + typeof(T).Name + ", replacing with default");
					string text2 = "FAILED";
					Match match = Regex.Match(text, "\"PersistentDataVersion\": \"(.+?)\"");
					if (match.Success)
					{
						text2 = match.Groups[1].Value + "-FAILED";
					}
					File.WriteAllText(Path.ChangeExtension(path, null) + "-" + text2 + ".json", text);
					val2 = new T();
					val2.Save(path);
				}
				if (val2.PersistentDataVersion != val.PersistentDataVersion)
				{
					val2.Save(Path.ChangeExtension(path, null) + "-" + val2.PersistentDataVersion + ".json");
					val.Save(path);
				}
				else
				{
					val = val2;
				}
			}
			else
			{
				val.Save(path);
			}
			return val;
		}

		public void Save()
		{
			Save(persistentPath);
		}

		public void Save(string path)
		{
			string contents = GTFO.API.JSON.JsonSerializer.Serialize((T)this);
			string directoryName = Path.GetDirectoryName(path);
			if (!Directory.Exists(directoryName))
			{
				Directory.CreateDirectory(directoryName);
			}
			File.WriteAllText(path, contents);
		}
	}
	public static class RegexUtils
	{
		private static readonly Regex s_VectorRegex = new Regex("-?[0-9.]+");

		public static bool TryParseVectorString(string input, out float[] vectorArray)
		{
			try
			{
				MatchCollection matchCollection = s_VectorRegex.Matches(input);
				int count = matchCollection.Count;
				if (count < 1)
				{
					throw new Exception();
				}
				vectorArray = new float[count];
				for (int i = 0; i < count; i++)
				{
					Match match = matchCollection[i];
					vectorArray[i] = float.Parse(match.Value, CultureInfo.InvariantCulture);
				}
				return true;
			}
			catch
			{
				vectorArray = null;
				return false;
			}
		}
	}
	public static class StringUtils
	{
		private static readonly uint[] _lookup32 = ((Func<uint[]>)delegate
		{
			uint[] array = new uint[256];
			for (int i = 0; i < 256; i++)
			{
				string text = i.ToString("X2");
				if (BitConverter.IsLittleEndian)
				{
					array[i] = text[0] + ((uint)text[1] << 16);
				}
				else
				{
					array[i] = text[1] + ((uint)text[0] << 16);
				}
			}
			return array;
		})();

		private unsafe static readonly uint* _lookup32Ptr = (uint*)(void*)GCHandle.Alloc(_lookup32, GCHandleType.Pinned).AddrOfPinnedObject();

		public unsafe static string FromByteArrayAsHex(byte[] bytes)
		{
			char[] array = new char[bytes.Length * 2];
			fixed (byte* ptr3 = bytes)
			{
				fixed (char* ptr = array)
				{
					uint* ptr2 = (uint*)ptr;
					for (int i = 0; i < bytes.Length; i++)
					{
						ptr2[i] = _lookup32Ptr[(int)ptr3[i]];
					}
				}
			}
			return new string(array);
		}
	}
	public static class ThreadDispatcher
	{
		public static void Dispatch(Action action)
		{
			ThreadDispatcher_Impl.Instance.EnqueueAction(action);
		}
	}
}
namespace GTFO.API.Utilities.Impl
{
	internal class CoroutineDispatcher_Impl : MonoBehaviour
	{
		private bool m_HasInLevelCoroutines;

		private readonly List<Coroutine> m_InLevelCoroutines;

		private static CoroutineDispatcher_Impl s_Instance;

		public static CoroutineDispatcher_Impl Instance
		{
			get
			{
				if ((Object)(object)s_Instance == (Object)null)
				{
					CoroutineDispatcher_Impl coroutineDispatcher_Impl = Object.FindObjectOfType<CoroutineDispatcher_Impl>();
					if ((Object)(object)coroutineDispatcher_Impl != (Object)null)
					{
						s_Instance = coroutineDispatcher_Impl;
					}
				}
				return s_Instance;
			}
		}

		static CoroutineDispatcher_Impl()
		{
			AssetAPI.OnStartupAssetsLoaded += OnAssetsLoaded;
		}

		private static void OnAssetsLoaded()
		{
			//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_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			if (!((Object)(object)s_Instance != (Object)null))
			{
				GameObject val = new GameObject();
				CoroutineDispatcher_Impl coroutineDispatcher_Impl = val.AddComponent<CoroutineDispatcher_Impl>();
				((Object)val).name = "GTFO-API Coroutine Dispatcher";
				((Object)val).hideFlags = (HideFlags)61;
				Object.DontDestroyOnLoad((Object)val);
				s_Instance = coroutineDispatcher_Impl;
			}
		}

		private void Update()
		{
			if (m_HasInLevelCoroutines && !GameStateManager.IsInExpedition)
			{
				m_InLevelCoroutines.ForEach(delegate(Coroutine coroutine)
				{
					((MonoBehaviour)this).StopCoroutine(coroutine);
				});
				m_HasInLevelCoroutines = false;
			}
		}

		[HideFromIl2Cpp]
		internal Coroutine RunCoroutine(IEnumerator routine)
		{
			return MonoBehaviourExtensions.StartCoroutine((MonoBehaviour)(object)this, routine);
		}

		[HideFromIl2Cpp]
		internal Coroutine RunInLevelCoroutine(IEnumerator routine)
		{
			if (!GameStateManager.IsInExpedition)
			{
				APILogger.Error("CoroutineDispatcher", "Cannot run InLevelCoroutine while you're not in level!");
				return null;
			}
			Coroutine val = MonoBehaviourExtensions.StartCoroutine((MonoBehaviour)(object)this, routine);
			m_InLevelCoroutines.Add(val);
			m_HasInLevelCoroutines = true;
			return val;
		}
	}
	internal class ThreadDispatcher_Impl : MonoBehaviour
	{
		private readonly Queue<Action> s_ActionQueue = new Queue<Action>();

		private static ThreadDispatcher_Impl s_Instance;

		public static ThreadDispatcher_Impl Instance
		{
			get
			{
				if ((Object)(object)s_Instance == (Object)null)
				{
					ThreadDispatcher_Impl threadDispatcher_Impl = Object.FindObjectOfType<ThreadDispatcher_Impl>();
					if ((Object)(object)threadDispatcher_Impl != (Object)null)
					{
						s_Instance = threadDispatcher_Impl;
					}
				}
				return s_Instance;
			}
		}

		public ThreadDispatcher_Impl(IntPtr intPtr)
			: base(intPtr)
		{
		}

		static ThreadDispatcher_Impl()
		{
			AssetAPI.OnStartupAssetsLoaded += OnAssetsLoaded;
		}

		private static void OnAssetsLoaded()
		{
			//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_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			if (!((Object)(object)s_Instance != (Object)null))
			{
				GameObject val = new GameObject();
				ThreadDispatcher_Impl threadDispatcher_Impl = val.AddComponent<ThreadDispatcher_Impl>();
				((Object)val).name = "GTFO-API Thread Dispatcher";
				((Object)val).hideFlags = (HideFlags)61;
				Object.DontDestroyOnLoad((Object)val);
				s_Instance = threadDispatcher_Impl;
			}
		}

		[HideFromIl2Cpp]
		internal void EnqueueAction(Action action)
		{
			lock (s_ActionQueue)
			{
				s_ActionQueue.Enqueue(action);
			}
		}

		internal void Update()
		{
			lock (s_ActionQueue)
			{
				while (s_ActionQueue.Count > 0)
				{
					s_ActionQueue.Dequeue()?.Invoke();
				}
			}
		}
	}
}
namespace GTFO.API.Resources
{
	public class ApiStatusInfo
	{
		public bool Created { get; internal set; }

		public bool Ready { get; internal set; }
	}
	public static class APIStatus
	{
		private static GameObject s_ScriptHolder;

		public static ApiStatusInfo Asset { get; internal set; } = new ApiStatusInfo();


		public static ApiStatusInfo Event { get; internal set; } = new ApiStatusInfo();


		public static ApiStatusInfo GameData { get; internal set; } = new ApiStatusInfo();


		public static ApiStatusInfo Localization { get; internal set; } = new ApiStatusInfo();


		public static ApiStatusInfo Il2Cpp { get; internal set; } = new ApiStatusInfo();


		public static ApiStatusInfo Level { get; internal set; } = new ApiStatusInfo();


		public static ApiStatusInfo Network { get; internal set; } = new ApiStatusInfo();


		public static ApiStatusInfo Prefab { get; internal set; } = new ApiStatusInfo();


		public static ApiStatusInfo SoundBank { get; internal set; } = new ApiStatusInfo();


		internal static GameObject ScriptHolder
		{
			get
			{
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Expected O, but got Unknown
				if ((Object)(object)s_ScriptHolder == (Object)null)
				{
					s_ScriptHolder = new GameObject();
					((Object)s_ScriptHolder).name = "GTFO-API Script Holder";
					((Object)s_ScriptHolder).hideFlags = (HideFlags)61;
					Object.DontDestroyOnLoad((Object)(object)s_ScriptHolder);
				}
				return s_ScriptHolder;
			}
		}

		internal static void CreateApi<T>(string apiName) where T : Component
		{
			ApiStatusInfo apiStatusInfo = (ApiStatusInfo)(typeof(APIStatus).GetProperty(apiName)?.GetValue(null));
			if (apiStatusInfo == null)
			{
				throw new ArgumentException("Couldn't find API status for " + apiName, "apiName");
			}
			if (!apiStatusInfo.Created && !((Object)(object)ScriptHolder.GetComponent<T>() != (Object)null))
			{
				APILogger.Verbose("Core", "Creating API " + apiName);
				ScriptHolder.AddComponent<T>();
				apiStatusInfo.Created = true;
			}
		}
	}
	internal static class RuntimeData
	{
		public static Dictionary<InventorySlot, string[]> BotFavorites;
	}
	public static class ShaderConstants
	{
		public const string CUSTOM_GEAR_SHADER = "Cell/Player/CustomGearShader";
	}
	public static class NetworkConstants
	{
		public const string Magic = "GAPI_KSQK";

		public const byte MagicSize = 9;

		public const ulong VersionSignature = 18374688171108015565uL;
	}
}
namespace GTFO.API.Patches
{
	[HarmonyPatch(typeof(CellSettingsApply), "ApplyLanguage")]
	internal static class ApplyLanguage_Patches
	{
		private static bool s_LanguageChanged;

		[HarmonyWrapSafe]
		public static void Prefix(int value)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			s_LanguageChanged = (int)Text.TextLocalizationService.CurrentLanguage != value;
		}

		[HarmonyWrapSafe]
		public static void Postfix()
		{
			if (s_LanguageChanged)
			{
				LocalizationAPI.LanguageChanged();
			}
		}
	}
	[HarmonyPatch(typeof(AssetShardManager))]
	internal class AssetShardManager_Patches
	{
		[HarmonyPatch("Setup")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		public static void Setup_Postfix()
		{
			if (!APIStatus.Asset.Created)
			{
				APIStatus.CreateApi<AssetAPI_Impl>("Asset");
			}
		}
	}
	[HarmonyPatch(typeof(Builder))]
	internal class Builder_Patches
	{
		[HarmonyPatch("Build")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void BuildStart_Postfix()
		{
			LevelAPI.BuildStart();
		}

		[HarmonyPatch("BuildDone")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void BuildDone_Postfix()
		{
			LevelAPI.BuildDone();
		}
	}
	[HarmonyPatch(typeof(GameDataInit))]
	internal class GameDataInit_Patches
	{
		private struct PluginWhitelistInfo
		{
			public string GUID;

			public string Name;

			public string Version;

			public string Checksum;
		}

		private static PluginWhitelistInfo[] FetchPluginWhitelist()
		{
			using HttpClient httpClient = new HttpClient();
			using Stream stream = httpClient.GetStreamAsync("https://raw.githubusercontent.com/GTFO-Modding/GTFO-API-PluginWhitelist/main/whitelist.txt").GetAwaiter().GetResult();
			using StreamReader streamReader = new StreamReader(stream);
			string[] array = streamReader.ReadToEnd().Split('\n', StringSplitOptions.RemoveEmptyEntries);
			PluginWhitelistInfo[] array2 = new PluginWhitelistInfo[array.Length];
			for (int i = 0; i < array2.Length; i++)
			{
				string[] array3 = array[i].Split(":");
				array2[i] = new PluginWhitelistInfo
				{
					GUID = array3[0],
					Name = array3[1],
					Version = array3[2],
					Checksum = array3[3].TrimEnd('\r')
				};
			}
			return array2;
		}

		[HarmonyPatch("Initialize")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		public static void Initialize_Postfix()
		{
			Analytics.enabled = false;
			GameDataAPI.InvokeGameDataInit();
			if (!APIStatus.Network.Created)
			{
				APIStatus.CreateApi<NetworkAPI_Impl>("Network");
			}
		}

		private static void RemoveRequirementFromList(List<ExpeditionInTierData> list)
		{
			//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_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)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Invalid comparison between Unknown and I4
			Enumerator<ExpeditionInTierData> enumerator = list.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ExpeditionInTierData current = enumerator.Current;
				if (current.Enabled)
				{
					eExpeditionAccessibility accessibility = current.Accessibility;
					if ((int)accessibility == 0 || accessibility - 4 <= 1)
					{
						current.Accessibility = (eExpeditionAccessibility)2;
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(GearManager))]
	internal static class GearManager_Patches
	{
		private unsafe delegate IntPtr ReadFromDiskDelegate(IntPtr path, byte* createNew, Il2CppMethodInfo* methodInfo);

		private unsafe delegate void SaveToDiskDelegate(IntPtr path, IntPtr obj, Il2CppMethodInfo* methodInfo);

		private static bool m_PatchApplied;

		private static INativeDetour s_ReadFromDiskDetour;

		private static ReadFromDiskDelegate s_ReadFromDiskOriginal;

		private static INativeDetour s_SaveToDiskDetour;

		private static SaveToDiskDelegate s_SaveToDiskOriginal;

		private static string FavoritesDirectory => Path.Combine(Paths.BepInExRootPath, "GameData", "Favorites");

		private static string FavoritePath => Path.Combine(FavoritesDirectory, "Gear.json");

		private static string BotFavoritePath => Path.Combine(FavoritesDirectory, "BotGear.json");

		[HarmonyPatch("Setup")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private unsafe static void Setup_Prefix()
		{
			if (!m_PatchApplied)
			{
				if (!Directory.Exists(FavoritesDirectory))
				{
					Directory.CreateDirectory(FavoritesDirectory);
				}
				string methodName = "SaveToDisk";
				APILogger.Verbose("GearManager_Patches", "Applying ReadFromDisk Patch");
				s_ReadFromDiskDetour = Il2CppAPI.CreateGenericDetour<CellJSON, ReadFromDiskDelegate>("ReadFromDisk", "T", new string[2]
				{
					typeof(string).FullName,
					typeof(bool).MakeByRefType().FullName
				}, new Type[1] { typeof(GearFavoritesData) }, (ReadFromDiskDelegate)Patch_ReadFromDisk, out s_ReadFromDiskOriginal);
				APILogger.Verbose("GearManager_Patches", "Applying SaveToDisk Patch");
				s_SaveToDiskDetour = Il2CppAPI.CreateGenericDetour<CellJSON, SaveToDiskDelegate>(methodName, typeof(void).FullName, new string[2]
				{
					typeof(string).FullName,
					"T"
				}, new Type[1] { typeof(GearFavoritesData) }, (SaveToDiskDelegate)Patch_SaveToDisk, out s_SaveToDiskOriginal);
				m_PatchApplied = true;
			}
		}

		private unsafe static IntPtr Patch_ReadFromDisk(IntPtr path, byte* createNew, Il2CppMethodInfo* methodInfo)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			string text = String.op_Implicit(new String(path));
			if (text.EndsWith("GTFO_Favorites.txt", StringComparison.OrdinalIgnoreCase))
			{
				return s_ReadFromDiskOriginal(IL2CPP.ManagedStringToIl2Cpp(FavoritePath), createNew, methodInfo);
			}
			if (text.EndsWith("GTFO_BotFavorites.txt", StringComparison.OrdinalIgnoreCase))
			{
				return s_ReadFromDiskOriginal(IL2CPP.ManagedStringToIl2Cpp(BotFavoritePath), createNew, methodInfo);
			}
			return s_ReadFromDiskOriginal(path, createNew, methodInfo);
		}

		private unsafe static void Patch_SaveToDisk(IntPtr path, IntPtr favData, Il2CppMethodInfo* methodInfo)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			string text = String.op_Implicit(new String(path));
			if (text.EndsWith("GTFO_Favorites.txt", StringComparison.OrdinalIgnoreCase))
			{
				s_SaveToDiskOriginal(IL2CPP.ManagedStringToIl2Cpp(FavoritePath), favData, methodInfo);
			}
			else if (text.EndsWith("GTFO_BotFavorites.txt", StringComparison.OrdinalIgnoreCase))
			{
				s_SaveToDiskOriginal(IL2CPP.ManagedStringToIl2Cpp(BotFavoritePath), favData, methodInfo);
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
			else
			{
				s_SaveToDiskOriginal(path, favData, methodInfo);
			}
		}
	}
	[HarmonyPatch(typeof(Global))]
	internal class Global_Patches
	{
		[HarmonyPatch("OnLevelCleanup")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void LevelCleanup_Postfix()
		{
			LevelAPI.LevelCleanup();
		}
	}
	[HarmonyPatch(typeof(RundownManager))]
	internal class RundownManager_Patches
	{
		[HarmonyPatch("SetActiveExpedition")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void SetActiveExpedition_Postfix(pActiveExpedition expPackage, ExpeditionInTierData expTierData)
		{
			LevelAPI.ExpeditionUpdated(expPackage, expTierData);
		}
	}
	[HarmonyPatch(typeof(SNet_Replication))]
	internal class SNet_Replication_Patches
	{
		[HarmonyPatch("RecieveBytes")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		public static bool RecieveBytes_Prefix(Il2CppStructArray<byte> bytes, uint size, ulong messagerID)
		{
			if (size < 12)
			{
				return true;
			}
			byte[] array = Il2CppArrayBase<byte>.op_Implicit((Il2CppArrayBase<byte>)(object)bytes);
			ushort num = BitConverter.ToUInt16(array, 0);
			if (NetworkAPI_Impl.Instance.m_ReplicatorKey == num)
			{
				string @string = Encoding.ASCII.GetString(array, 2, 9);
				if (@string != "GAPI_KSQK")
				{
					APILogger.Verbose("NetworkApi", $"Received invalid magic from {messagerID} ({@string} != {9}).");
					return true;
				}
				ulong num2 = BitConverter.ToUInt64(array, 11);
				if ((num2 & 0xFF00000000000000uL) != 18374686479671623680uL)
				{
					APILogger.Verbose("NetworkApi", $"Received invalid version signature from {messagerID}.");
					return true;
				}
				if (num2 != NetworkAPI_Impl.Instance.m_Signature)
				{
					APILogger.Error("NetworkApi", $"Received incompatible version signature, cannot unmask packet. Is {messagerID} on the same version?. ({num2} != {NetworkAPI_Impl.Instance.m_Signature})");
					return false;
				}
				ushort num3 = BitConverter.ToUInt16(array, 19);
				string string2 = Encoding.UTF8.GetString(array, 21, num3);
				if (!NetworkAPI.IsEventRegistered(string2))
				{
					APILogger.Error("NetworkApi", $"{messagerID} invoked an event {string2} which isn't registered.");
					return false;
				}
				NetworkAPI_Impl.Instance.HandlePacket(string2, messagerID, array, 21 + num3);
				return false;
			}
			return true;
		}
	}
}
namespace GTFO.API.Patches.Native
{
	internal class SyringeFirstPerson_Patch : NativePatch<SyringeFirstPerson_Patch.SyringeUsedDelegate>
	{
		[UnmanagedFunctionPointer(CallingConvention.FastCall)]
		public unsafe delegate eSyringeType SyringeUsedDelegate(void* pSyringe);

		public unsafe override void* MethodPtr => Il2CppAPI.GetIl2CppMethod<_ApplySyringe_d__18>("MoveNext", "System.Boolean", isGeneric: false, Array.Empty<string>());

		public override string JmpStartSig => "Æ\u0081\u00b4\0\0\0\u0001\u008b\u0087Ð\u0001\0\0\u0085À";

		public override string JmpStartMask => "xxxxxxxxxxxxxxx";

		public override byte[] CodeCave => new byte[10] { 198, 129, 180, 0, 0, 0, 1, 72, 137, 249 };

		public override uint TrampolineSize => 13u;

		public unsafe override SyringeUsedDelegate To => OnSyringeApplyEffect;

		public unsafe static eSyringeType OnSyringeApplyEffect(void* pSyringe)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			SyringeFirstPerson val = new SyringeFirstPerson(new IntPtr(pSyringe));
			if (PrefabAPI.OnSyringeUsed(val))
			{
				return (eSyringeType)(-1);
			}
			return val.m_type;
		}
	}
}
namespace GTFO.API.Native
{
	internal static class Kernel32
	{
		[DllImport("kernel32.dll")]
		public unsafe static extern void* VirtualAlloc(void* lpAddress, ulong dwSize, uint flAllocationType, uint flProtect);

		[DllImport("kernel32.dll")]
		public unsafe static extern bool VirtualProtect(void* lpAddress, ulong dwSize, uint flNewProtect, uint* lpflOldProtect);
	}
	internal static class MSVCRT
	{
		[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
		public unsafe static extern void* memcpy(void* destination, void* source, long num);
	}
	public abstract class NativePatch<T> where T : Delegate
	{
		private static readonly byte[] s_CodeCaveHeader = new byte[4] { 72, 131, 236, 40 };

		private static readonly byte[] s_CodeCaveFooter = new byte[17]
		{
			72, 184, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 208, 72, 131,

plugins/GTFOModding-BetterMaps/BetterMaps.dll

Decompiled 7 hours ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using AIGraph;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CellMenu;
using GTFO.API;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using LevelGeneration;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Rendering;

[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("BetterMaps")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("BetterMaps")]
[assembly: AssemblyTitle("BetterMaps")]
[assembly: TargetPlatform("Windows7.0")]
[assembly: SupportedOSPlatform("Windows7.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 BetterMaps
{
	[BepInPlugin("BetterMaps", "BetterMaps", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class EntryPoint : BasePlugin
	{
		private Harmony _Harmony = null;

		private ConfigEntry<float> _BlurFactor;

		private ConfigEntry<float> _OutlineFactor;

		public override void Load()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			_BlurFactor = ((BasePlugin)this).Config.Bind<float>("Map Quality", "Blur Scale", 0.15f, (ConfigDescription)null);
			_OutlineFactor = ((BasePlugin)this).Config.Bind<float>("Map Quality", "Outline Scale", 0.05f, (ConfigDescription)null);
			_Harmony = new Harmony("BetterMaps.Harmony");
			_Harmony.PatchAll();
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(32, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin has loaded with ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_Harmony.GetPatchedMethods().Count());
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" patches!");
			}
			Logger.Info(val);
			LevelAPI.OnBuildDone += OnBuildDone;
		}

		private void OnBuildDone()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: 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_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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_009a: 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_00a2: Unknown result type (might be due to invalid IL or missing references)
			MapDetails current = MapDetails.Current;
			current.m_mapResolution = Mathf.Min(current.m_mapResolution, current.m_mapRenderResolution);
			current.m_navmesh = CreateNavMesh(flipMesh: true);
			current.SetupMeshRendering();
			current.m_bounds = ((Renderer)current.m_mapMeshRenderer).bounds;
			Bounds bounds = current.m_bounds;
			((Bounds)(ref bounds)).Expand(new Vector3(64f, 0f, 64f));
			bounds = current.m_bounds;
			current.s_boundsCenter = ((Bounds)(ref bounds)).center;
			bounds = current.m_bounds;
			current.s_boundsExtentsX = ((Bounds)(ref bounds)).extents.x;
			bounds = current.m_bounds;
			current.s_boundsExtentsZ = ((Bounds)(ref bounds)).extents.z;
			DrawMapBasis(current);
		}

		private void DrawMapBasis(MapDetails md)
		{
			//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_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_00d0: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Expected O, but got Unknown
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			//IL_013b: 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_015d: 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_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			Bounds bounds = md.m_bounds;
			int num = (int)((Bounds)(ref bounds)).size.x * md.m_mapRenderResolution;
			bounds = md.m_bounds;
			int num2 = (int)((Bounds)(ref bounds)).size.z * md.m_mapRenderResolution;
			float num3 = default(float);
			bool flag = default(bool);
			float num4 = default(float);
			md.GetClampedRes(1024, ref num, ref num2, ref num3, ref flag, ref num4);
			float num5 = 0.005f * num4;
			float num6 = num5 * _BlurFactor.Value;
			float num7 = num5 * _OutlineFactor.Value;
			int num8 = Shader.PropertyToID("_SamplingScale");
			md.m_findMapOutline_Material.SetFloat(num8, num7);
			md.m_SDF_Material.SetFloat(num8, num7);
			md.m_blurX.SetFloat(num8, num6);
			md.m_blurY.SetFloat(num8, num6);
			RenderTexture val = new RenderTexture(num, num2, 16, (RenderTextureFormat)0, (RenderTextureReadWrite)1);
			RenderTexture val2 = new RenderTexture(num, num2, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)1);
			RenderTexture val3 = new RenderTexture(((Texture)md.m_mapTexture).width, ((Texture)md.m_mapTexture).height, 0, (RenderTextureFormat)11, (RenderTextureReadWrite)1);
			((Texture)val).filterMode = (FilterMode)2;
			((Texture)val2).filterMode = (FilterMode)2;
			((Texture)val3).filterMode = (FilterMode)2;
			val.Create();
			val2.Create();
			val3.Create();
			CommandBuffer val4 = new CommandBuffer();
			val4.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)(object)val));
			val4.ClearRenderTarget(true, true, Color.black);
			val4.SetProjectionMatrix(md.m_camera.projectionMatrix);
			val4.SetViewMatrix(md.m_camera.worldToCameraMatrix);
			val4.DrawRenderer((Renderer)(object)md.m_mapMeshRenderer, md.m_navmeshMaterial);
			val4.Blit((Texture)(object)val, RenderTargetIdentifier.op_Implicit((Texture)(object)val2), md.m_findMapOutline_Material);
			val4.Blit((Texture)(object)val2, RenderTargetIdentifier.op_Implicit((Texture)(object)md.m_mapTexture), md.m_SDF_Material);
			val4.Blit((Texture)(object)md.m_mapTexture, RenderTargetIdentifier.op_Implicit((Texture)(object)val3), md.m_blurX);
			val4.Blit((Texture)(object)val3, RenderTargetIdentifier.op_Implicit((Texture)(object)md.m_mapTexture), md.m_blurY);
			val4.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)(object)md.m_mapTexture));
			((Renderer)md.m_mapMeshRenderer).enabled = true;
			Graphics.ExecuteCommandBuffer(val4);
			val4.Dispose();
			((Renderer)md.m_mapMeshRenderer).enabled = false;
			Object.Destroy((Object)(object)((Component)md.m_mapMeshRenderer).gameObject);
			md.m_mapMeshRenderer = null;
			val.Release();
			val2.Release();
			val3.Release();
			if ((Object)(object)md.m_navmesh != (Object)null)
			{
				Object.Destroy((Object)(object)md.m_navmesh);
				md.m_navmesh = null;
			}
		}

		private Mesh CreateNavMesh(bool flipMesh)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//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)
			//IL_0064: 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_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: 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_007f: 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_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)
			NavMeshTriangulation val = NavMesh.CalculateTriangulation();
			Mesh val2 = new Mesh();
			List<int> list = new List<int>();
			for (int i = 0; i < ((Il2CppArrayBase<int>)(object)val.indices).Length; i += 3)
			{
				int num = ((Il2CppArrayBase<int>)(object)val.indices)[i];
				int num2 = ((Il2CppArrayBase<int>)(object)val.indices)[i + 1];
				int num3 = ((Il2CppArrayBase<int>)(object)val.indices)[i + 2];
				Vector3 p = ((Il2CppArrayBase<Vector3>)(object)val.vertices)[num];
				Vector3 p2 = ((Il2CppArrayBase<Vector3>)(object)val.vertices)[num2];
				Vector3 p3 = ((Il2CppArrayBase<Vector3>)(object)val.vertices)[num3];
				CalcTriangleProps(p, p2, p3, out var center, out var heightDifference);
				Dimension dimensionFromPos = Dimension.GetDimensionFromPos(center);
				if (dimensionFromPos != null)
				{
					float voxelSearchTolerance = Mathf.Max(1.5f, heightDifference * 1.5f);
					if (IsPositionValid(dimensionFromPos.DimensionIndex, center, voxelSearchTolerance, out var _))
					{
						list.Add(num);
						list.Add(num2);
						list.Add(num3);
					}
				}
			}
			int num4 = Mathf.Max(((Il2CppArrayBase<Vector3>)(object)val.vertices).Length, list.Count);
			val2.indexFormat = (IndexFormat)(num4 >= 65534);
			val2.SetVertices(val.vertices);
			if (flipMesh)
			{
				list.Reverse();
			}
			val2.SetTriangles(Il2CppStructArray<int>.op_Implicit(list.ToArray()), 0);
			val2.RecalculateNormals();
			return val2;
		}

		private void CalcTriangleProps(Vector3 p1, Vector3 p2, Vector3 p3, out Vector3 center, out float heightDifference)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: 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_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			center = (p1 + p2 + p3) * 0.333333f;
			float num = Mathf.Min(new float[3] { p1.y, p2.y, p3.y });
			float num2 = Mathf.Max(new float[3] { p1.y, p2.y, p3.y });
			heightDifference = num2 - num;
		}

		private bool IsPositionValid(eDimensionIndex dimensionIndex, Vector3 position, float voxelSearchTolerance, out AIG_CourseNode courseNode)
		{
			//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_0024: 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)
			AIG_GeomorphNodeVolume val = default(AIG_GeomorphNodeVolume);
			if (!AIG_GeomorphNodeVolume.TryGetGeomorphVolume(0, dimensionIndex, position, ref val))
			{
				courseNode = null;
				return false;
			}
			AIG_VoxelNodePillar val2 = default(AIG_VoxelNodePillar);
			if (!((AIG_NodeVolume)val).m_voxelNodeVolume.TryGetPillar(position, ref val2))
			{
				courseNode = null;
				return false;
			}
			float y = position.y;
			AIG_INode val3 = default(AIG_INode);
			if (!val2.TryGetVoxelNode(y - voxelSearchTolerance, y + voxelSearchTolerance, ref val3))
			{
				courseNode = null;
				return false;
			}
			AIG_NodeCluster val4 = default(AIG_NodeCluster);
			if (!AIG_NodeCluster.TryGetNodeCluster(val3.ClusterID, ref val4))
			{
				courseNode = null;
				return false;
			}
			courseNode = val4.CourseNode;
			return true;
		}

		public override bool Unload()
		{
			_Harmony.UnpatchSelf();
			return ((BasePlugin)this).Unload();
		}
	}
	[HarmonyPatch(typeof(CM_MapGUIItemBase), "PlaceInGUI")]
	internal static class Inject_CM_MapGUIItemBase
	{
		[HarmonyPatch(new Type[]
		{
			typeof(Vector3),
			typeof(Vector3),
			typeof(Vector3),
			typeof(bool)
		})]
		private static void Prefix(ref bool adjustUpSideDown)
		{
			adjustUpSideDown = true;
		}
	}
	internal static class Logger
	{
		private static readonly ManualLogSource _Logger;

		static Logger()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			_Logger = new ManualLogSource("BetterMaps");
			Logger.Sources.Add((ILogSource)(object)_Logger);
		}

		private static string Format(object msg)
		{
			return msg.ToString();
		}

		public static void Info(BepInExInfoLogInterpolatedStringHandler handler)
		{
			_Logger.LogInfo(handler);
		}

		public static void Info(string str)
		{
			_Logger.LogMessage((object)str);
		}

		public static void Info(object data)
		{
			_Logger.LogMessage((object)Format(data));
		}

		public static void Debug(BepInExDebugLogInterpolatedStringHandler handler)
		{
			_Logger.LogDebug(handler);
		}

		public static void Debug(string str)
		{
			_Logger.LogDebug((object)str);
		}

		public static void Debug(object data)
		{
			_Logger.LogDebug((object)Format(data));
		}

		public static void Error(BepInExErrorLogInterpolatedStringHandler handler)
		{
			_Logger.LogError(handler);
		}

		public static void Error(string str)
		{
			_Logger.LogError((object)str);
		}

		public static void Error(object data)
		{
			_Logger.LogError((object)Format(data));
		}

		public static void Fatal(BepInExFatalLogInterpolatedStringHandler handler)
		{
			_Logger.LogFatal(handler);
		}

		public static void Fatal(string str)
		{
			_Logger.LogFatal((object)str);
		}

		public static void Fatal(object data)
		{
			_Logger.LogFatal((object)Format(data));
		}

		public static void Warn(BepInExWarningLogInterpolatedStringHandler handler)
		{
			_Logger.LogWarning(handler);
		}

		public static void Warn(string str)
		{
			_Logger.LogWarning((object)str);
		}

		public static void Warn(object data)
		{
			_Logger.LogWarning((object)Format(data));
		}

		[Conditional("DEBUG")]
		public static void DebugOnly(object data)
		{
			_Logger.LogDebug((object)Format(data));
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.1.3+git35c0c2a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "BetterMaps";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = null;

		public const string SemVer = "1.0.0";

		public const string GitRevShort = null;

		public const string GitRevLong = null;

		public const string GitBranch = null;

		public const string GitTag = null;

		public const int GitCommitsSinceTag = 0;

		public const bool GitIsDirty = false;
	}
}

plugins/GTFOModding-InjectLib/InjectLib.dll

Decompiled 7 hours ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using GTFO.API;
using GTFO.API.JSON;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.Runtime;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.Class;
using Il2CppJsonNet;
using Il2CppJsonNet.Converters;
using Il2CppJsonNet.Linq;
using Il2CppJsonNet.Serialization;
using Il2CppSystem;
using Il2CppSystem.Runtime.InteropServices;
using InjectLib.FieldInjection;
using InjectLib.JsonNETInjection;
using InjectLib.JsonNETInjection.Converter;
using InjectLib.JsonNETInjection.Detours;
using InjectLib.JsonNETInjection.Handler;
using InjectLib.Utils;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("InjectLib")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+gitc83a124-master")]
[assembly: AssemblyProduct("InjectLib")]
[assembly: AssemblyTitle("InjectLib")]
[assembly: TargetPlatform("Windows7.0")]
[assembly: SupportedOSPlatform("Windows7.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[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 NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
}
namespace InjectLib
{
	[BepInPlugin("GTFO.InjectLib", "InjectLib", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class EntryPoint : BasePlugin
	{
		public override void Load()
		{
			NativeJsonProcessorStore.Initialize();
		}

		public override bool Unload()
		{
			return ((BasePlugin)this).Unload();
		}
	}
	internal static class Logger
	{
		private static readonly ManualLogSource _Logger;

		static Logger()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			_Logger = new ManualLogSource("InjectLib");
			Logger.Sources.Add((ILogSource)(object)_Logger);
		}

		private static string Format(object msg)
		{
			return msg.ToString();
		}

		public static void Info(BepInExInfoLogInterpolatedStringHandler handler)
		{
			_Logger.LogInfo(handler);
		}

		public static void Info(string str)
		{
			_Logger.LogMessage((object)str);
		}

		public static void Info(object data)
		{
			_Logger.LogMessage((object)Format(data));
		}

		public static void Debug(BepInExDebugLogInterpolatedStringHandler handler)
		{
			_Logger.LogDebug(handler);
		}

		public static void Debug(string str)
		{
			_Logger.LogDebug((object)str);
		}

		public static void Debug(object data)
		{
			_Logger.LogDebug((object)Format(data));
		}

		public static void Error(BepInExErrorLogInterpolatedStringHandler handler)
		{
			_Logger.LogError(handler);
		}

		public static void Error(string str)
		{
			_Logger.LogError((object)str);
		}

		public static void Error(object data)
		{
			_Logger.LogError((object)Format(data));
		}

		public static void Fatal(BepInExFatalLogInterpolatedStringHandler handler)
		{
			_Logger.LogFatal(handler);
		}

		public static void Fatal(string str)
		{
			_Logger.LogFatal((object)str);
		}

		public static void Fatal(object data)
		{
			_Logger.LogFatal((object)Format(data));
		}

		public static void Warn(BepInExWarningLogInterpolatedStringHandler handler)
		{
			_Logger.LogWarning(handler);
		}

		public static void Warn(string str)
		{
			_Logger.LogWarning((object)str);
		}

		public static void Warn(object data)
		{
			_Logger.LogWarning((object)Format(data));
		}

		[Conditional("DEBUG")]
		public static void DebugOnly(object data)
		{
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.1.3+git35c0c2a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "InjectLib";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "gitc83a124-master";

		public const string SemVer = "1.0.0+gitc83a124-master";

		public const string GitRevShort = "c83a124";

		public const string GitRevLong = "c83a124696b1272397115ca04d902622f35ba87e";

		public const string GitBranch = "master";

		public const string GitTag = null;

		public const int GitCommitsSinceTag = 0;

		public const bool GitIsDirty = false;
	}
}
namespace InjectLib.Utils
{
	internal static class FieldsExtension
	{
		public static void SetNativeJsonProcessor(this DataSetConverter converter, NativeJsonProcessor processor)
		{
			FieldInjector<DataSetConverter>.TrySetManagedField(converter, "m_JsonProcessor", processor);
		}

		public static NativeJsonProcessor GetNativeJsonProcessor(this DataSetConverter converter)
		{
			FieldInjector<DataSetConverter>.TryGetManagedField<NativeJsonProcessor>(converter, "m_JsonProcessor", out var value);
			return value;
		}
	}
	internal static class ObjectCopier
	{
		public static void CopyProperties<T>(T source, T target) where T : Il2CppObjectBase
		{
			PropertyInfo[] properties = typeof(T).GetProperties();
			foreach (PropertyInfo propertyInfo in properties)
			{
				Type propertyType = propertyInfo.PropertyType;
				if (!propertyInfo.Name.Contains("_k__BackingField") && !(propertyType == typeof(IntPtr)) && propertyInfo.CanRead && propertyInfo.CanWrite)
				{
					propertyInfo.SetValue(target, propertyInfo.GetValue(source));
				}
			}
		}
	}
}
namespace InjectLib.JsonNETInjection
{
	public static class JsonInjector
	{
		static JsonInjector()
		{
			FieldInjector<DataSetConverter>.DefineManagedField<NativeJsonProcessor>("m_JsonProcessor");
		}

		public static void SetConverter<T>(Il2CppJsonReferenceTypeConverter<T> converter) where T : Il2CppObjectBase
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Expected O, but got Unknown
			if (converter == null)
			{
				throw new ArgumentNullException("converter");
			}
			if (!NativeJsonProcessorStore.Prepare<T>(out var processor))
			{
				return;
			}
			if (processor.Converter != null)
			{
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(76, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Converter (type: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(typeof(T).FullName);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") will be replaced! This would leads to unwanted behaviour!");
				}
				Logger.Warn(val);
				Logger.Warn(" - Suggetion: If your converter does not require to deep-level altering of JSON, consider use Il2CppJsonReferenceTypeHandler instead.");
				val = new BepInExWarningLogInterpolatedStringHandler(19, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Previous Owner: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(processor.Converter.GetType().Assembly.FullName);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" / ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(processor.Converter.GetType().FullName);
				}
				Logger.Warn(val);
				val = new BepInExWarningLogInterpolatedStringHandler(14, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("New Owner: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(converter.GetType().Assembly.FullName);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" / ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(converter.GetType().FullName);
				}
				Logger.Warn(val);
			}
			processor.Converter = converter;
		}

		public static void SetConverter<T>(Il2CppJsonUnmanagedTypeConverter<T> converter) where T : unmanaged
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Expected O, but got Unknown
			if (converter == null)
			{
				throw new ArgumentNullException("converter");
			}
			if (!NativeJsonProcessorStore.Prepare<T>(out var processor))
			{
				return;
			}
			if (processor.Converter != null)
			{
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(76, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Converter (type: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(typeof(T).FullName);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") will be replaced! This would leads to unwanted behaviour!");
				}
				Logger.Warn(val);
				Logger.Warn(" - Suggetion: If your converter does not require to deep-level altering of JSON, consider use Il2CppJsonUnmanagedTypeHandler instead.");
				val = new BepInExWarningLogInterpolatedStringHandler(22, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" - Previous Owner: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(processor.Converter.GetType().Assembly.FullName);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" / ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(processor.Converter.GetType().FullName);
				}
				Logger.Warn(val);
				val = new BepInExWarningLogInterpolatedStringHandler(17, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" - New Owner: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(converter.GetType().Assembly.FullName);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" / ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(converter.GetType().FullName);
				}
				Logger.Warn(val);
			}
			processor.Converter = converter;
		}

		public static void AddHandler<T>(Il2CppJsonReferenceTypeHandler<T> handler) where T : Il2CppObjectBase
		{
			if (handler == null)
			{
				throw new ArgumentNullException("handler");
			}
			if (NativeJsonProcessorStore.Prepare<T>(out var processor))
			{
				processor.Handlers.Add(handler);
			}
		}

		public static void AddHandler<T>(Il2CppJsonUnmanagedTypeHandler<T> handler) where T : unmanaged
		{
			if (handler == null)
			{
				throw new ArgumentNullException("handler");
			}
			if (NativeJsonProcessorStore.Prepare<T>(out var processor))
			{
				processor.Handlers.Add(handler);
			}
		}
	}
	internal class NativeJsonProcessor
	{
		public Type Type { get; set; }

		public DataSetConverter DummyConverter { get; set; }

		public INativeJsonConverter Converter { get; set; }

		public IList<INativeJsonHandler> Handlers { get; } = new List<INativeJsonHandler>();


		public bool Enabled { get; set; } = true;


		public IntPtr ProcessRead(JsonReader reader, IntPtr existingValue, JsonSerializer serializer)
		{
			JToken jToken = JToken.ReadFrom(reader);
			IntPtr pointer;
			if (Converter != null)
			{
				pointer = ((Il2CppObjectBase)Converter.ReadJson(jToken, existingValue, serializer)).Pointer;
			}
			else
			{
				SetUsingContractConverter(serializer, use: false);
				pointer = ((Il2CppObjectBase)serializer.Deserialize(jToken.CreateReader(), Type)).Pointer;
				SetUsingContractConverter(serializer, use: true);
			}
			Object result = PtrToObject(pointer);
			foreach (INativeJsonHandler handler in Handlers)
			{
				handler.OnRead(in result, in jToken);
			}
			return pointer;
		}

		public void ProcessWrite(JsonWriter writer, IntPtr valueToWrite, JsonSerializer serializer)
		{
			if (Converter != null)
			{
				Converter.WriteJson(writer, valueToWrite, serializer);
				return;
			}
			SetUsingContractConverter(serializer, use: false);
			serializer.Serialize(writer, PtrToObject(valueToWrite));
			SetUsingContractConverter(serializer, use: true);
		}

		private static Object PtrToObject(IntPtr ptr)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			if (ptr == IntPtr.Zero)
			{
				return null;
			}
			return new Object(ptr);
		}

		private void SetUsingContractConverter(JsonSerializer serializer, bool use)
		{
			JsonContract val = serializer.ContractResolver.ResolveContract(Type);
			if (use)
			{
				val.Converter = (JsonConverter)(object)DummyConverter;
				val.InternalConverter = (JsonConverter)(object)DummyConverter;
			}
			else
			{
				val.Converter = null;
				val.InternalConverter = null;
			}
		}
	}
	internal static class NativeJsonProcessorStore
	{
		private static readonly Dictionary<IntPtr, NativeJsonProcessor> _RegisteredProcessors = new Dictionary<IntPtr, NativeJsonProcessor>();

		internal static void Initialize()
		{
			Detour_JsonConverterTrampoline.Patch();
			Detour_NativeConverterLink.Patch();
		}

		public static bool Prepare<T>(out NativeJsonProcessor processor)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			Type val = Il2CppType.From(typeof(T));
			if (val != (Type)null && ((Il2CppObjectBase)val).Pointer != IntPtr.Zero)
			{
				if (_RegisteredProcessors.TryGetValue(((Il2CppObjectBase)val).Pointer, out processor))
				{
					return true;
				}
				DataSetConverter val2 = new DataSetConverter();
				NativeJsonProcessor nativeJsonProcessor2 = (_RegisteredProcessors[((Il2CppObjectBase)val).Pointer] = new NativeJsonProcessor());
				processor = nativeJsonProcessor2;
				processor.Type = val;
				processor.DummyConverter = val2;
				val2.SetNativeJsonProcessor(processor);
				return true;
			}
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(33, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Type: '");
				((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(typeof(T).Name);
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("' is not in il2cpp domain!");
			}
			Logger.Error(val3);
			processor = null;
			return false;
		}

		public static bool TryGetConverterPointer(IntPtr typePtr, out IntPtr converterPtr)
		{
			if (TryGetProcessor(typePtr, out var processor) && processor.DummyConverter != null)
			{
				converterPtr = ((Il2CppObjectBase)processor.DummyConverter).Pointer;
				return converterPtr != IntPtr.Zero;
			}
			converterPtr = IntPtr.Zero;
			return false;
		}

		public static bool TryGetProcessor(IntPtr typePtr, out NativeJsonProcessor processor)
		{
			if (_RegisteredProcessors.TryGetValue(typePtr, out processor) && processor != null && processor.Enabled)
			{
				return processor != null;
			}
			processor = null;
			return false;
		}
	}
}
namespace InjectLib.JsonNETInjection.Supports
{
	internal interface IBaseConnector
	{
		NativeJsonProcessor Processor { get; set; }
	}
	public sealed class InjectLibConnector : JsonConverterFactory
	{
		public override bool CanConvert(Type typeToConvert)
		{
			Type val = Il2CppType.From(typeToConvert, false);
			if (val != (Type)null && NativeJsonProcessorStore.TryGetProcessor(((Il2CppObjectBase)val).Pointer, out var _))
			{
				return true;
			}
			return false;
		}

		public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
		{
			if (!NativeJsonProcessorStore.TryGetProcessor(((Il2CppObjectBase)Il2CppType.From(typeToConvert, false)).Pointer, out var processor))
			{
				return null;
			}
			if (typeToConvert.IsAssignableTo(typeof(Il2CppObjectBase)))
			{
				JsonConverter obj = (JsonConverter)Activator.CreateInstance(typeof(ReferenceTypeConnector<>).MakeGenericType(typeToConvert), BindingFlags.Instance | BindingFlags.Public, null, null, null);
				((IBaseConnector)obj).Processor = processor;
				return obj;
			}
			if (typeToConvert.IsValueType)
			{
				JsonConverter obj2 = (JsonConverter)Activator.CreateInstance(typeof(ValueTypeConnector<>).MakeGenericType(typeToConvert), BindingFlags.Instance | BindingFlags.Public, null, null, null);
				((IBaseConnector)obj2).Processor = processor;
				return obj2;
			}
			return null;
		}
	}
	public class InjectLibJSON
	{
		public static JsonSerializerOptions JsonOptions => new JsonSerializerOptions(JsonSerializer.DefaultSerializerSettingsWithLocalizedText)
		{
			Converters = { (JsonConverter)new InjectLibConnector() }
		};

		public static T Deserialize<T>(string json, params JsonConverter[] converters)
		{
			JsonSerializerOptions jsonOptions = JsonOptions;
			if (converters != null)
			{
				foreach (JsonConverter item in converters)
				{
					jsonOptions.Converters.Add(item);
				}
			}
			return JsonSerializer.Deserialize<T>(json, jsonOptions);
		}

		public static object Deserialize(string json, Type type, params JsonConverter[] converters)
		{
			JsonSerializerOptions jsonOptions = JsonOptions;
			if (converters != null)
			{
				foreach (JsonConverter item in converters)
				{
					jsonOptions.Converters.Add(item);
				}
			}
			return JsonSerializer.Deserialize(json, type, jsonOptions);
		}

		public static string Serialize<T>(T obj, params JsonConverter[] converters)
		{
			JsonSerializerOptions jsonOptions = JsonOptions;
			if (converters != null)
			{
				foreach (JsonConverter item in converters)
				{
					jsonOptions.Converters.Add(item);
				}
			}
			return JsonSerializer.Serialize(obj, JsonOptions);
		}

		public static string Serialize(object obj, params JsonConverter[] converters)
		{
			JsonSerializerOptions jsonOptions = JsonOptions;
			if (converters != null)
			{
				foreach (JsonConverter item in converters)
				{
					jsonOptions.Converters.Add(item);
				}
			}
			return JsonSerializer.Serialize(obj, JsonOptions);
		}
	}
	internal class ReferenceTypeConnector<T> : JsonConverter<T>, IBaseConnector where T : Il2CppObjectBase
	{
		public NativeJsonProcessor Processor { get; set; }

		public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			Type val = Il2CppType.From(typeToConvert, false);
			JsonNode jsonNode = JsonNode.Parse(ref reader);
			return (T)Activator.CreateInstance(typeof(T), ((Il2CppObjectBase)JsonConvert.DeserializeObject(jsonNode.ToJsonString(), val, (JsonSerializerSettings)null)).Pointer);
		}

		public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
		{
			JsonSerializer.Serialize(writer, value);
		}
	}
	internal class ValueTypeConnector<T> : JsonConverter<T>, IBaseConnector where T : unmanaged
	{
		public NativeJsonProcessor Processor { get; set; }

		public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			Type val = Il2CppType.From(typeToConvert, false);
			return ((Il2CppObjectBase)JsonConvert.DeserializeObject(JsonNode.Parse(ref reader).ToJsonString(), val, (JsonSerializerSettings)null)).Unbox<T>();
		}

		public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
		{
			JsonSerializer.Serialize(writer, value);
		}
	}
}
namespace InjectLib.JsonNETInjection.Handler
{
	public abstract class Il2CppJsonReferenceTypeHandler<T> : INativeJsonHandler where T : Il2CppObjectBase
	{
		public abstract void OnRead(in Object result, in JToken jToken);
	}
	public abstract class Il2CppJsonUnmanagedTypeHandler<T> : INativeJsonHandler where T : unmanaged
	{
		public abstract void OnRead(in Object result, in JToken jToken);
	}
	internal interface INativeJsonHandler
	{
		void OnRead(in Object result, in JToken jToken);
	}
}
namespace InjectLib.JsonNETInjection.Detours
{
	internal class Detour_JsonConverterTrampoline
	{
		public unsafe delegate IntPtr GetMatchingConverterDel(IntPtr converters, IntPtr objectType, Il2CppMethodInfo* methodInfo);

		private static INativeDetour _Detour;

		private static GetMatchingConverterDel _Original;

		public unsafe static void Patch()
		{
			_Detour = INativeDetour.CreateAndApply<GetMatchingConverterDel>((IntPtr)(nint)Il2CppAPI.GetIl2CppMethod<JsonSerializer>("GetMatchingConverter", "Newtonsoft.Json.JsonConverter", false, new string[2]
			{
				"System.Collections.Generic.IList<Newtonsoft.Json.JsonConverter>",
				typeof(Type).FullName
			}), (GetMatchingConverterDel)Detour, ref _Original);
		}

		private unsafe static IntPtr Detour(IntPtr converters, IntPtr objectType, Il2CppMethodInfo* methodInfo)
		{
			if (NativeJsonProcessorStore.TryGetConverterPointer(objectType, out var converterPtr))
			{
				return converterPtr;
			}
			return _Original(converters, objectType, methodInfo);
		}
	}
	internal class Detour_NativeConverterLink
	{
		public delegate IntPtr ReadJsonDel(IntPtr _this, IntPtr reader, IntPtr objectType, IntPtr existingValue, IntPtr serializer);

		public delegate void WriteJsonDel(IntPtr _this, IntPtr writer, IntPtr value, IntPtr serializer);

		private static INativeDetour _ReadDetour;

		private static INativeDetour _WriteDetour;

		private static ReadJsonDel _ReadOriginal;

		private static WriteJsonDel _WriteOriginal;

		public unsafe static void Patch()
		{
			void* il2CppMethod = Il2CppAPI.GetIl2CppMethod<DataSetConverter>("ReadJson", "System.Object", false, new string[4] { "Newtonsoft.Json.JsonReader", "System.Type", "System.Object", "Newtonsoft.Json.JsonSerializer" });
			void* il2CppMethod2 = Il2CppAPI.GetIl2CppMethod<DataSetConverter>("WriteJson", typeof(void).FullName, false, new string[3] { "Newtonsoft.Json.JsonWriter", "System.Object", "Newtonsoft.Json.JsonSerializer" });
			_ReadDetour = INativeDetour.CreateAndApply<ReadJsonDel>((IntPtr)(nint)il2CppMethod, (ReadJsonDel)Detour_Read, ref _ReadOriginal);
			_WriteDetour = INativeDetour.CreateAndApply<WriteJsonDel>((IntPtr)(nint)il2CppMethod2, (WriteJsonDel)Detour_Write, ref _WriteOriginal);
		}

		private static IntPtr Detour_Read(IntPtr _this, IntPtr reader, IntPtr objectType, IntPtr existingValue, IntPtr serializer)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			NativeJsonProcessor nativeJsonProcessor = FieldsExtension.GetNativeJsonProcessor(new DataSetConverter(_this));
			if (nativeJsonProcessor != null)
			{
				JsonReader reader2 = new JsonReader(reader);
				JsonSerializer serializer2 = new JsonSerializer(serializer);
				return nativeJsonProcessor.ProcessRead(reader2, existingValue, serializer2);
			}
			return _ReadOriginal(_this, reader, objectType, existingValue, serializer);
		}

		private static void Detour_Write(IntPtr _this, IntPtr writer, IntPtr value, IntPtr serializer)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			NativeJsonProcessor nativeJsonProcessor = FieldsExtension.GetNativeJsonProcessor(new DataSetConverter(_this));
			if (nativeJsonProcessor != null)
			{
				JsonWriter writer2 = new JsonWriter(writer);
				JsonSerializer serializer2 = new JsonSerializer(serializer);
				nativeJsonProcessor.ProcessWrite(writer2, value, serializer2);
			}
			else
			{
				_WriteOriginal(_this, writer, value, serializer);
			}
		}
	}
}
namespace InjectLib.JsonNETInjection.Converter
{
	public abstract class Il2CppJsonReferenceTypeConverter<T> : INativeJsonConverter where T : Il2CppObjectBase
	{
		public virtual string Name => GetType().Name;

		public Object ReadJson(JToken jToken, IntPtr existingValue, JsonSerializer serializer)
		{
			if (existingValue == IntPtr.Zero)
			{
				return ((Il2CppObjectBase)Read(jToken, default(T), serializer)).Cast<Object>();
			}
			T existingValue2 = (T)Activator.CreateInstance(typeof(T), existingValue);
			return ((Il2CppObjectBase)Read(jToken, existingValue2, serializer)).Cast<Object>();
		}

		public void WriteJson(JsonWriter writer, IntPtr valueToWrite, JsonSerializer serializer)
		{
			if (valueToWrite == IntPtr.Zero)
			{
				Write(writer, default(T), serializer);
				return;
			}
			T value = (T)Activator.CreateInstance(typeof(T), valueToWrite);
			Write(writer, value, serializer);
		}

		protected abstract T Read(JToken jToken, T existingValue, JsonSerializer serializer);

		protected abstract void Write(JsonWriter writer, T value, JsonSerializer serializer);
	}
	public abstract class Il2CppJsonUnmanagedTypeConverter<T> : INativeJsonConverter where T : unmanaged
	{
		public virtual string Name => GetType().Name;

		public Object ReadJson(JToken jToken, IntPtr existingValue, JsonSerializer serializer)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			if (existingValue == IntPtr.Zero)
			{
				return ToIl2CppObject(Read(jToken, default(T), serializer));
			}
			Object val = new Object(existingValue);
			return ToIl2CppObject(Read(jToken, ((Il2CppObjectBase)val).Unbox<T>(), serializer));
		}

		public void WriteJson(JsonWriter writer, IntPtr valueToWrite, JsonSerializer serializer)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			if (valueToWrite == IntPtr.Zero)
			{
				Write(writer, default(T), serializer);
				return;
			}
			Object val = new Object(valueToWrite);
			Write(writer, ((Il2CppObjectBase)val).Unbox<T>(), serializer);
		}

		protected abstract T Read(JToken jToken, T existingValue, JsonSerializer serializer);

		protected abstract void Write(JsonWriter writer, T value, JsonSerializer serializer);

		protected abstract Object ToIl2CppObject(T value);
	}
	internal interface INativeJsonConverter
	{
		string Name { get; }

		Object ReadJson(JToken jToken, IntPtr existingValue, JsonSerializer serializer);

		void WriteJson(JsonWriter writer, IntPtr valueToWrite, JsonSerializer serializer);
	}
}
namespace InjectLib.FieldInjection
{
	public static class FieldInjector<Il2CppType> where Il2CppType : Il2CppObjectBase
	{
		private static readonly Dictionary<string, InjectedFieldInfo> _OffsetLookup = new Dictionary<string, InjectedFieldInfo>();

		public static void DefineValueField<Value>(string fieldName) where Value : unmanaged
		{
			if (!_OffsetLookup.ContainsKey(fieldName))
			{
				InjectValueField<Value>(fieldName);
			}
		}

		public static void DefineManagedField<Value>(string fieldName) where Value : class
		{
			if (!_OffsetLookup.ContainsKey(fieldName))
			{
				InjectManagedField<Value>(fieldName);
			}
		}

		private unsafe static void InjectManagedField<Value>(string fieldName) where Value : class
		{
			int num = 8;
			INativeClassStruct val = UnityVersionHandler.Wrap((Il2CppClass*)(void*)Il2CppClassPointerStore<Il2CppType>.NativeClassPtr);
			val.InstanceSize += (uint)num;
			val.ActualSize = val.InstanceSize;
			_OffsetLookup[fieldName] = new InjectedFieldInfo
			{
				FieldOffset = (nint)(val.InstanceSize - num),
				FieldSize = num
			};
		}

		public unsafe static bool TryGetManagedField<Value>(Il2CppType obj, string fieldName, out Value value) where Value : class
		{
			if (obj == null)
			{
				value = null;
				return false;
			}
			if (((Il2CppObjectBase)obj).Pointer == IntPtr.Zero)
			{
				value = null;
				return false;
			}
			if (!_OffsetLookup.TryGetValue(fieldName, out var value2))
			{
				value = null;
				return false;
			}
			if (8 != value2.FieldSize)
			{
				value = null;
				return false;
			}
			ulong num = *(ulong*)((nint)((Il2CppObjectBase)obj).Pointer + value2.FieldOffset);
			if (num == 0L)
			{
				value = null;
				return false;
			}
			value = ManagedReferenceStore<Il2CppType, Value>.Get(num);
			return value != null;
		}

		public unsafe static bool TrySetManagedField<Value>(Il2CppType obj, string fieldName, Value value) where Value : class
		{
			if (obj == null)
			{
				return false;
			}
			if (((Il2CppObjectBase)obj).Pointer == IntPtr.Zero)
			{
				return false;
			}
			if (!_OffsetLookup.TryGetValue(fieldName, out var value2))
			{
				return false;
			}
			if (8 != value2.FieldSize)
			{
				return false;
			}
			ulong num = *(ulong*)((nint)((Il2CppObjectBase)obj).Pointer + value2.FieldOffset);
			if (num == 0L)
			{
				ulong uniqueKey = ManagedReferenceStore<Il2CppType, Value>.UniqueKey;
				ManagedReferenceStore<Il2CppType, Value>.Set(uniqueKey, value);
				*(ulong*)((nint)((Il2CppObjectBase)obj).Pointer + value2.FieldOffset) = uniqueKey;
				return true;
			}
			ManagedReferenceStore<Il2CppType, Value>.Set(num, value);
			return true;
		}

		private static int SizeOfUnmanagedType<Value>() where Value : unmanaged
		{
			if (typeof(Value) == typeof(bool))
			{
				return 1;
			}
			return Marshal.SizeOf<Value>();
		}

		private unsafe static void InjectValueField<Value>(string fieldName) where Value : unmanaged
		{
			int num = SizeOfUnmanagedType<Value>();
			INativeClassStruct val = UnityVersionHandler.Wrap((Il2CppClass*)(void*)Il2CppClassPointerStore<Il2CppType>.NativeClassPtr);
			val.InstanceSize += (uint)num;
			val.ActualSize = val.InstanceSize;
			_OffsetLookup[fieldName] = new InjectedFieldInfo
			{
				FieldOffset = (nint)(val.InstanceSize - num),
				FieldSize = num
			};
		}

		public unsafe static bool TryGetValueField<Value>(Il2CppType obj, string fieldName, out Value value) where Value : unmanaged
		{
			if (obj == null)
			{
				value = default(Value);
				return false;
			}
			if (((Il2CppObjectBase)obj).Pointer == IntPtr.Zero)
			{
				value = default(Value);
				return false;
			}
			if (!_OffsetLookup.TryGetValue(fieldName, out var value2))
			{
				value = default(Value);
				return false;
			}
			if (SizeOfUnmanagedType<Value>() != value2.FieldSize)
			{
				value = default(Value);
				return false;
			}
			value = *(Value*)((nint)((Il2CppObjectBase)obj).Pointer + value2.FieldOffset);
			return true;
		}

		public unsafe static bool TrySetValueField<Value>(Il2CppType obj, string fieldName, Value value) where Value : unmanaged
		{
			if (obj == null)
			{
				return false;
			}
			if (((Il2CppObjectBase)obj).Pointer == IntPtr.Zero)
			{
				return false;
			}
			if (!_OffsetLookup.TryGetValue(fieldName, out var value2))
			{
				return false;
			}
			if (SizeOfUnmanagedType<Value>() != value2.FieldSize)
			{
				return false;
			}
			*(Value*)((nint)((Il2CppObjectBase)obj).Pointer + value2.FieldOffset) = value;
			return true;
		}
	}
	internal struct InjectedFieldInfo
	{
		public nint FieldOffset;

		public int FieldSize;
	}
	public static class ManagedReferenceStore<C, T> where C : Il2CppObjectBase where T : class
	{
		private static readonly Dictionary<ulong, T> _Lookup = new Dictionary<ulong, T>();

		private static ulong _Key = 1uL;

		public static ulong UniqueKey => _Key++;

		public static T Get(ulong key)
		{
			_Lookup.TryGetValue(key, out var value);
			return value;
		}

		public static void Set(ulong key, T value)
		{
			_Lookup[key] = value;
		}

		public static void Remove(ulong key)
		{
			_Lookup.Remove(key);
		}
	}
}

plugins/GTFOModding-ScanPositionOverride/ScanPositionOverride.dll

Decompiled 7 hours 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.Text.Json;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using ChainedPuzzles;
using GTFO.API;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ScanPositionOverride")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ScanPositionOverride")]
[assembly: AssemblyTitle("ScanPositionOverride")]
[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 ScanPositionOverride
{
	internal sealed class JsonFile
	{
		public uint MainLevelLayout { get; set; }

		public List<PuzzleFile> Puzzles { get; set; } = new List<PuzzleFile>();

	}
	[BepInPlugin("ScanPositionOverride", "ScanPositionOverride", "1.0.0")]
	internal sealed class Plugin : BasePlugin
	{
		private PUI_GameEventLog? gameEventLog;

		private Action<byte, CP_Bioscan_Core>? OnBioscan;

		private Action<byte, CP_Cluster_Core>? OnClusterscan;

		private JsonSerializerOptions JsonOptions = new JsonSerializerOptions
		{
			PropertyNameCaseInsensitive = false,
			WriteIndented = true
		};

		private Dictionary<uint, List<PuzzleOverride>> PuzzleOverrides = new Dictionary<uint, List<PuzzleOverride>>();

		private PUI_GameEventLog GameEventLog
		{
			get
			{
				if ((Object)(object)gameEventLog == (Object)null)
				{
					gameEventLog = GuiManager.PlayerLayer.m_gameEventLog;
				}
				return gameEventLog;
			}
		}

		private uint ActiveExpedition => RundownManager.ActiveExpedition.LevelLayoutData;

		public override void Load()
		{
			OnBioscan = (Action<byte, CP_Bioscan_Core>)Delegate.Combine(OnBioscan, new Action<byte, CP_Bioscan_Core>(MoveBio));
			OnBioscan = (Action<byte, CP_Bioscan_Core>)Delegate.Combine(OnBioscan, new Action<byte, CP_Bioscan_Core>(LogBio));
			OnClusterscan = (Action<byte, CP_Cluster_Core>)Delegate.Combine(OnClusterscan, new Action<byte, CP_Cluster_Core>(MoveCluster));
			OnClusterscan = (Action<byte, CP_Cluster_Core>)Delegate.Combine(OnClusterscan, new Action<byte, CP_Cluster_Core>(LogCluster));
			EventAPI.OnExpeditionStarted += OnExpeditionStarted;
			string text = Path.Combine(Paths.BepInExRootPath, "GameData", "ScanPositionOverrides");
			CollectionExtensions.Do<FileInfo>(from file in Directory.CreateDirectory(text).EnumerateFiles()
				where file.Extension.Contains(".json")
				where !file.Name.Contains("Template")
				select file, (Action<FileInfo>)Deserialize);
			string path = Path.Combine(text, "Template.json");
			if (!File.Exists(path))
			{
				FileStream utf8Json = File.OpenWrite(path);
				JsonFile jsonFile = new JsonFile();
				PuzzleFile item = new PuzzleFile
				{
					TPositions = 
					{
						new Vec3()
					}
				};
				jsonFile.Puzzles.Add(item);
				JsonSerializer.Serialize(utf8Json, jsonFile, JsonOptions);
			}
		}

		private void Deserialize(FileInfo info)
		{
			//IL_0078: 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_00d5: Unknown result type (might be due to invalid IL or missing references)
			JsonFile jsonFile = JsonSerializer.Deserialize<JsonFile>(info.OpenRead(), JsonOptions);
			if (jsonFile == null)
			{
				return;
			}
			if (!PuzzleOverrides.TryGetValue(jsonFile.MainLevelLayout, out List<PuzzleOverride> value))
			{
				value = new List<PuzzleOverride>();
				PuzzleOverrides.Add(jsonFile.MainLevelLayout, value);
			}
			for (int i = 0; i < jsonFile.Puzzles.Count; i++)
			{
				PuzzleOverride puzzleOverride = new PuzzleOverride
				{
					PuzzleIndex = jsonFile.Puzzles[i].Index,
					position = jsonFile.Puzzles[i].Position.ToVector3(),
					rotation = jsonFile.Puzzles[i].Rotation.ToQuaternion(),
					positions = new List<Vector3>()
				};
				foreach (Vec3 tPosition in jsonFile.Puzzles[i].TPositions)
				{
					puzzleOverride.positions.Add(tPosition.ToVector3());
				}
				value.Add(puzzleOverride);
			}
		}

		private void OnExpeditionStarted()
		{
			byte b = 0;
			for (int i = 0; i < ChainedPuzzleManager.Current.m_instances.Count; i++)
			{
				Il2CppArrayBase<CP_Bioscan_Core> componentsInChildren = ((Component)ChainedPuzzleManager.Current.m_instances[i].m_parent).GetComponentsInChildren<CP_Bioscan_Core>();
				if (componentsInChildren != null)
				{
					for (int j = 0; j < componentsInChildren.Count; j++)
					{
						OnBioscan?.Invoke(b, componentsInChildren[j]);
						b++;
					}
				}
				Il2CppArrayBase<CP_Cluster_Core> componentsInChildren2 = ((Component)ChainedPuzzleManager.Current.m_instances[i].m_parent).GetComponentsInChildren<CP_Cluster_Core>();
				if (componentsInChildren2 != null)
				{
					for (int k = 0; k < componentsInChildren2.Count; k++)
					{
						OnClusterscan?.Invoke(b, componentsInChildren2[k]);
						b++;
					}
				}
			}
		}

		private PuzzleOverride? GetModifaction(byte count)
		{
			if (PuzzleOverrides.TryGetValue(ActiveExpedition, out List<PuzzleOverride> value))
			{
				for (int i = 0; i < value.Count; i++)
				{
					if (value[i].PuzzleIndex == count)
					{
						return value[i];
					}
				}
			}
			return null;
		}

		private void MoveBio(byte count, CP_Bioscan_Core scan)
		{
			//IL_0018: 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)
			PuzzleOverride modifaction = GetModifaction(count);
			if (modifaction != null)
			{
				((Component)scan).gameObject.transform.position = modifaction.position;
				((Component)scan).gameObject.transform.rotation = modifaction.rotation;
				if (scan.m_isMovable && modifaction.positions.Count > 0)
				{
					scan.m_movingComp.ScanPositions = modifaction.positions;
				}
			}
		}

		private void LogBio(byte count, CP_Bioscan_Core scan)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			LogScan(count, ((Component)scan).gameObject);
			if (!scan.m_isMovable)
			{
				return;
			}
			((BasePlugin)this).Log.LogDebug((object)"move positions");
			bool flag = default(bool);
			for (int i = 0; i < scan.m_movingComp.ScanPositions.Count; i++)
			{
				Vector3 val = scan.m_movingComp.ScanPositions[i];
				ManualLogSource log = ((BasePlugin)this).Log;
				BepInExDebugLogInterpolatedStringHandler val2 = new BepInExDebugLogInterpolatedStringHandler(2, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(val.x);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(",");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(val.y);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(",");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(val.z);
				}
				log.LogDebug(val2);
			}
		}

		private void MoveCluster(byte count, CP_Cluster_Core scan)
		{
			//IL_0018: 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)
			PuzzleOverride modifaction = GetModifaction(count);
			if (modifaction != null)
			{
				((Component)scan).gameObject.transform.position = modifaction.position;
				((Component)scan).gameObject.transform.rotation = modifaction.rotation;
			}
		}

		private void LogCluster(byte count, CP_Cluster_Core scan)
		{
			LogScan(count, ((Component)scan).gameObject);
		}

		private void LogScan(byte count, GameObject scan)
		{
			//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_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_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_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			//IL_006e: 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_009c: 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_00ca: 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)
			Vector3 position = scan.transform.position;
			Quaternion rotation = scan.transform.rotation;
			Vector3 val = ((Quaternion)(ref rotation)).ToEulerAngles();
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val2 = new BepInExDebugLogInterpolatedStringHandler(34, 9, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("layout:");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<uint>(ActiveExpedition);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" index:");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<byte>(count);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" pos:");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(position.x);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(",");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(position.y);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(",");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(position.z);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" rot:");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(val.x);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(",");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(val.y);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(",");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(val.z);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" name:");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)scan).name);
			}
			log.LogDebug(val2);
		}
	}
	internal sealed class PuzzleFile
	{
		public byte Index { get; set; }

		public Vec3 Position { get; set; } = new Vec3();


		public Vec3 Rotation { get; set; } = new Vec3();


		public List<Vec3> TPositions { get; set; } = new List<Vec3>();

	}
	internal sealed class PuzzleOverride
	{
		public byte PuzzleIndex { get; set; }

		public Vector3 position { get; set; }

		public Quaternion rotation { get; set; }

		public List<Vector3> positions { get; set; }
	}
	internal sealed class Vec3
	{
		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public Vector3 ToVector3()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(x, y, z);
		}

		public Quaternion ToQuaternion()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return Quaternion.Euler(x, y, z);
		}
	}
}

plugins/hirnukuono-AdvancedWardenObjective/AdvancedWardenObjective.dll

Decompiled 7 hours ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using AIGraph;
using AK;
using AWO.CustomFields;
using AWO.Events;
using AWO.Jsons;
using AWO.Modules.WEE;
using AWO.Modules.WOE;
using AWO.Networking;
using AWO.Networking.CommonReplicator.Inject;
using AWO.Networking.Inject;
using AWO.Sessions;
using AWO.Utils;
using AWO.WEE.Detours;
using AWO.WEE.Events;
using AWO.WEE.JsonInjects;
using AWO.WEE.Replicators;
using Agents;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using BepInEx.Unity.IL2CPP.Utils;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using CellMenu;
using ChainedPuzzles;
using Enemies;
using Expedition;
using GTFO.API;
using GameData;
using Globals;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.InteropTypes.Fields;
using Il2CppInterop.Runtime.Runtime;
using Il2CppJsonNet;
using Il2CppJsonNet.Linq;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using InjectLib.FieldInjection;
using InjectLib.JsonNETInjection;
using InjectLib.JsonNETInjection.Converter;
using InjectLib.JsonNETInjection.Handler;
using InjectLib.JsonNETInjection.Supports;
using LevelGeneration;
using Localization;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using TMPro;
using UnityEngine;

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

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace AWO
{
	[BepInPlugin("GTFO.AWO", "AWO", "1.2.7")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class EntryPoint : BasePlugin
	{
		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public struct Coroutines
		{
			public static float CountdownStarted { get; set; }

			public static float TPFStarted { get; set; }
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public struct TimerMods
		{
			public static float TimeModifier { get; set; }

			public static Color TimerColor { get; set; }

			public static float SpeedModifier { get; set; }

			public static LocaleText CountupText { get; set; }
		}

		public class AWOTerminalCommands
		{
			public WEE_EventData data;

			public bool hidden;

			public bool used;

			public AWOTerminalCommands(WEE_EventData e)
			{
				used = false;
				hidden = false;
				data = e;
			}
		}

		public static List<AWOTerminalCommands> AWOCommandList = new List<AWOTerminalCommands>();

		public static HashSet<int> ActiveEventLoops { get; set; } = new HashSet<int>();


		public static HashSet<LG_WorldEventNavMarker> NavMarkers { get; set; } = new HashSet<LG_WorldEventNavMarker>();


		public static Dictionary<GlobalZoneIndex, LG_DimensionPortal> Portals { get; set; } = new Dictionary<GlobalZoneIndex, LG_DimensionPortal>();


		public static Random SessionSeed { get; set; } = new Random();


		public override void Load()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			WardenEventExt.Initialize();
			new Harmony("AWO.Harmony").PatchAll();
			AssetAPI.OnStartupAssetsLoaded += AssetAPI_OnStartupAssetsLoaded;
			WOEventDataFields.Init();
			WODataBlockFields.Init();
		}

		private void AssetAPI_OnStartupAssetsLoaded()
		{
			BlackoutState.AssetLoaded();
			LevelFailUpdateState.AssetLoaded();
		}
	}
	internal static class Logger
	{
		private static readonly ManualLogSource _Logger;

		static Logger()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			_Logger = new ManualLogSource("AWO");
			Logger.Sources.Add((ILogSource)(object)_Logger);
		}

		private static string Format(object msg)
		{
			return msg.ToString();
		}

		public static void Info(BepInExInfoLogInterpolatedStringHandler handler)
		{
			_Logger.LogInfo(handler);
		}

		public static void Info(string str)
		{
			_Logger.LogMessage((object)str);
		}

		public static void Info(object data)
		{
			_Logger.LogMessage((object)Format(data));
		}

		public static void Debug(BepInExDebugLogInterpolatedStringHandler handler)
		{
			_Logger.LogDebug(handler);
		}

		public static void Debug(string str)
		{
			_Logger.LogDebug((object)str);
		}

		public static void Debug(object data)
		{
			_Logger.LogDebug((object)Format(data));
		}

		public static void Error(BepInExErrorLogInterpolatedStringHandler handler)
		{
			_Logger.LogError(handler);
		}

		public static void Error(string str)
		{
			_Logger.LogError((object)str);
		}

		public static void Error(object data)
		{
			_Logger.LogError((object)Format(data));
		}

		public static void Fatal(BepInExFatalLogInterpolatedStringHandler handler)
		{
			_Logger.LogFatal(handler);
		}

		public static void Fatal(string str)
		{
			_Logger.LogFatal((object)str);
		}

		public static void Fatal(object data)
		{
			_Logger.LogFatal((object)Format(data));
		}

		public static void Warn(BepInExWarningLogInterpolatedStringHandler handler)
		{
			_Logger.LogWarning(handler);
		}

		public static void Warn(string str)
		{
			_Logger.LogWarning((object)str);
		}

		public static void Warn(object data)
		{
			_Logger.LogWarning((object)Format(data));
		}

		[Conditional("DEBUG")]
		public static void DebugOnly(object data)
		{
			_Logger.LogDebug((object)Format(data));
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "AWO";

		public const string Version = "1.2.7";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "gitcfa2d23-dirty-master";

		public const string SemVer = "1.2.7+gitcfa2d23-dirty-master";

		public const string GitRevShort = "cfa2d23-dirty";

		public const string GitRevLong = "cfa2d2353c0d0a953e5206ca0175fd822be44365-dirty";

		public const string GitBranch = "master";

		public const string GitTag = null;

		public const bool GitIsDirty = true;
	}
}
namespace AWO.Utils
{
	internal static class LocalizedTextExtensions
	{
		public static string ToText(this LocalizedText text)
		{
			return text.HasTranslation ? Text.Get(text.Id) : text.UntranslatedText;
		}
	}
	internal static class RandomExtensions
	{
		public static bool MeetProbability(this Random rand, float prob)
		{
			if (prob >= 1f)
			{
				return true;
			}
			if (prob <= 0f)
			{
				return false;
			}
			return prob >= rand.NextFloat01();
		}

		public static float NextRange(this Random rand, float min, float max)
		{
			return rand.NextFloat01() * (max - min) + min;
		}

		public static float NextFloat01(this Random rand)
		{
			return (float)rand.NextDouble();
		}
	}
	internal static class RNG
	{
		private static readonly Random _Rand = new Random();

		public static float Float01 => (float)_Rand.NextDouble();

		public static int Int0Positive => _Rand.Next(0, int.MaxValue);

		public static int Int0Negative => _Rand.Next(int.MinValue, 1);

		public static int Int => _Rand.Next(int.MinValue, int.MaxValue);

		public static bool MeetProbability(float prob)
		{
			if (prob >= 1f)
			{
				return true;
			}
			if (prob <= 0f)
			{
				return false;
			}
			return prob >= Float01;
		}
	}
}
namespace AWO.Sessions
{
	internal struct BlackoutStatus
	{
		public bool blackoutEnabled;
	}
	internal static class BlackoutState
	{
		private static StateReplicator<BlackoutStatus> _Replicator;

		public static bool BlackoutEnabled { get; private set; }

		internal static void AssetLoaded()
		{
			if (_Replicator == null)
			{
				_Replicator = StateReplicator<BlackoutStatus>.Create(1u, new BlackoutStatus
				{
					blackoutEnabled = false
				}, LifeTimeType.Permanent);
				_Replicator.OnStateChanged += OnStateChanged;
				LevelEvents.OnLevelCleanup += LevelCleanup;
			}
		}

		private static void LevelCleanup()
		{
			SetEnabled(enabled: false);
		}

		public static void SetEnabled(bool enabled)
		{
			_Replicator.SetState(new BlackoutStatus
			{
				blackoutEnabled = enabled
			});
		}

		private static void OnStateChanged(BlackoutStatus _, BlackoutStatus state, bool isRecall)
		{
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Invalid comparison between Unknown and I4
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0362: Invalid comparison between Unknown and I4
			bool flag = !state.blackoutEnabled;
			foreach (LG_LabDisplay labDisplay in LG_Objects.LabDisplays)
			{
				if (!((Object)(object)labDisplay == (Object)null) && !((Object)(object)labDisplay.m_Text == (Object)null))
				{
					((Behaviour)labDisplay.m_Text).enabled = flag;
				}
			}
			foreach (LG_ComputerTerminal terminal in LG_Objects.Terminals)
			{
				if ((Object)(object)terminal == (Object)null)
				{
					continue;
				}
				terminal.OnProximityExit();
				Interact_ComputerTerminal componentInChildren = ((Component)terminal).GetComponentInChildren<Interact_ComputerTerminal>(true);
				if ((Object)(object)componentInChildren != (Object)null)
				{
					((Behaviour)componentInChildren).enabled = flag;
					((Interact_Base)componentInChildren).SetActive(flag);
				}
				GUIX_VirtualSceneLink component = ((Component)terminal).GetComponent<GUIX_VirtualSceneLink>();
				if ((Object)(object)component != (Object)null && (Object)(object)component.m_virtualScene != (Object)null)
				{
					GUIX_VirtualCamera virtualCamera = component.m_virtualScene.virtualCamera;
					float num = (flag ? 0.3f : 0f);
					float num2 = (flag ? 1000f : 0f);
					virtualCamera.SetFovAndClip(virtualCamera.paramCamera.fieldOfView, num, num2);
				}
				if ((Object)(object)terminal.m_text != (Object)null)
				{
					((Behaviour)terminal.m_text).enabled = flag;
				}
				if (!flag)
				{
					PlayerAgent localInteractionSource = terminal.m_localInteractionSource;
					if ((Object)(object)localInteractionSource != (Object)null && localInteractionSource.FPItemHolder.InTerminalTrigger)
					{
						terminal.ExitFPSView();
					}
				}
			}
			foreach (LG_DoorButton doorButton in LG_Objects.DoorButtons)
			{
				if ((Object)(object)doorButton == (Object)null)
				{
					continue;
				}
				((Component)doorButton.m_anim).gameObject.SetActive(flag);
				doorButton.m_enabled = flag;
				if (flag)
				{
					LG_WeakLock componentInChildren2 = ((Component)doorButton).GetComponentInChildren<LG_WeakLock>();
					if ((Object)(object)componentInChildren2 == (Object)null)
					{
						doorButton.m_enabled = true;
					}
					else if ((int)componentInChildren2.Status == 3)
					{
						doorButton.m_enabled = true;
					}
				}
			}
			foreach (LG_WeakLock weakLock in LG_Objects.WeakLocks)
			{
				if ((Object)(object)weakLock == (Object)null)
				{
					continue;
				}
				((Interact_Base)weakLock.m_intHack).m_isActive = flag;
				Transform val = ((Component)weakLock).transform.FindChild("HackableLock/SecurityLock/g_WeakLock/Security_Display_Locked");
				if ((Object)(object)val != (Object)null)
				{
					((Component)val).gameObject.active = flag;
					continue;
				}
				val = ((Component)weakLock).transform.FindChild("HackableLock/Security_Display_Locked");
				if ((Object)(object)val != (Object)null)
				{
					((Component)val).gameObject.active = flag;
				}
			}
			foreach (LG_HSUActivator_Core hSUActivator in LG_Objects.HSUActivators)
			{
				if ((Object)(object)hSUActivator == (Object)null || !hSUActivator.m_isWardenObjective || (int)hSUActivator.m_stateReplicator.State.status != 0)
				{
					continue;
				}
				hSUActivator.m_insertHSUInteraction.SetActive(flag);
				foreach (GameObject item in (Il2CppArrayBase<GameObject>)(object)hSUActivator.m_activateWhenActive)
				{
					item.SetActive(flag);
				}
			}
			BlackoutEnabled = state.blackoutEnabled;
		}
	}
	internal enum LevelFailMode
	{
		Default,
		Never,
		AnyPlayerDown
	}
	internal struct LevelFailCheck
	{
		public LevelFailMode mode;
	}
	internal sealed class LevelFailUpdateState
	{
		private static StateReplicator<LevelFailCheck> _Replicator;

		internal static void AssetLoaded()
		{
			if (_Replicator == null)
			{
				_Replicator = StateReplicator<LevelFailCheck>.Create(1u, new LevelFailCheck
				{
					mode = LevelFailMode.Default
				}, LifeTimeType.Permanent);
				LG_Factory.OnFactoryBuildStart += Action.op_Implicit((Action)delegate
				{
					_Replicator.ClearAllRecallSnapshot();
					_Replicator.SetState(new LevelFailCheck
					{
						mode = LevelFailMode.Default
					});
				});
				_Replicator.OnStateChanged += OnStateChanged;
				LevelEvents.OnLevelCleanup += LevelCleanup;
			}
		}

		private static void LevelCleanup()
		{
			SetFailAllowed(allowed: true);
		}

		public static void SetFailAllowed(bool allowed)
		{
			_Replicator.SetState(new LevelFailCheck
			{
				mode = ((!allowed) ? LevelFailMode.Never : LevelFailMode.Default)
			});
		}

		public static void SetFailWhenAnyPlayerDown(bool enabled)
		{
			_Replicator.SetState(new LevelFailCheck
			{
				mode = (enabled ? LevelFailMode.AnyPlayerDown : LevelFailMode.Default)
			});
		}

		private static void OnStateChanged(LevelFailCheck _, LevelFailCheck state, bool __)
		{
			switch (state.mode)
			{
			case LevelFailMode.Default:
				Inject_LevelFailCheck.LevelFailAllowed = true;
				Inject_LevelFailCheck.LevelFailWhenAnyPlayerDown = false;
				break;
			case LevelFailMode.Never:
				Inject_LevelFailCheck.LevelFailAllowed = false;
				Inject_LevelFailCheck.LevelFailWhenAnyPlayerDown = false;
				break;
			case LevelFailMode.AnyPlayerDown:
				Inject_LevelFailCheck.LevelFailAllowed = true;
				Inject_LevelFailCheck.LevelFailWhenAnyPlayerDown = true;
				break;
			}
		}
	}
	public static class LG_Objects
	{
		private static readonly List<LG_ComputerTerminal> _TerminalList;

		private static readonly List<LG_LabDisplay> _LabDisplayList;

		private static readonly List<LG_DoorButton> _DoorButtonList;

		private static readonly List<LG_WeakLock> _WeakLockList;

		private static readonly List<LG_HSUActivator_Core> _HSUActivatorList;

		public static IEnumerable<LG_ComputerTerminal> Terminals => _TerminalList;

		public static IEnumerable<LG_LabDisplay> LabDisplays => _LabDisplayList;

		public static IEnumerable<LG_DoorButton> DoorButtons => _DoorButtonList;

		public static IEnumerable<LG_WeakLock> WeakLocks => _WeakLockList;

		public static IEnumerable<LG_HSUActivator_Core> HSUActivators => _HSUActivatorList;

		static LG_Objects()
		{
			_TerminalList = new List<LG_ComputerTerminal>();
			_LabDisplayList = new List<LG_LabDisplay>();
			_DoorButtonList = new List<LG_DoorButton>();
			_WeakLockList = new List<LG_WeakLock>();
			_HSUActivatorList = new List<LG_HSUActivator_Core>();
			LevelEvents.OnLevelCleanup += OnLevelCleanup;
		}

		private static void OnLevelCleanup()
		{
			Clear();
		}

		internal static void Clear()
		{
			_TerminalList.Clear();
			_LabDisplayList.Clear();
			_DoorButtonList.Clear();
			_WeakLockList.Clear();
			_HSUActivatorList.Clear();
			EntryPoint.AWOCommandList.Clear();
			EntryPoint.Portals.Clear();
		}

		public static void AddTerminal(LG_ComputerTerminal terminal)
		{
			AddToList<LG_ComputerTerminal>(in _TerminalList, terminal);
		}

		public static void RemoveTerminal(LG_ComputerTerminal terminal)
		{
			RemoveFromList<LG_ComputerTerminal>(in _TerminalList, terminal);
		}

		public static void AddLabDisplay(LG_LabDisplay display)
		{
			AddToList<LG_LabDisplay>(in _LabDisplayList, display);
		}

		public static void RemoveLabDisplay(LG_LabDisplay display)
		{
			RemoveFromList<LG_LabDisplay>(in _LabDisplayList, display);
		}

		public static void AddDoorButton(LG_DoorButton button)
		{
			AddToList<LG_DoorButton>(in _DoorButtonList, button);
		}

		public static void RemoveDoorButton(LG_DoorButton button)
		{
			RemoveFromList<LG_DoorButton>(in _DoorButtonList, button);
		}

		public static void AddWeakLock(LG_WeakLock weaklock)
		{
			AddToList<LG_WeakLock>(in _WeakLockList, weaklock);
		}

		public static void RemoveWeakLock(LG_WeakLock weaklock)
		{
			RemoveFromList<LG_WeakLock>(in _WeakLockList, weaklock);
		}

		public static void AddHSUActivator(LG_HSUActivator_Core activator)
		{
			AddToList<LG_HSUActivator_Core>(in _HSUActivatorList, activator);
		}

		public static void RemoveHSUActivator(LG_HSUActivator_Core activator)
		{
			RemoveFromList<LG_HSUActivator_Core>(in _HSUActivatorList, activator);
		}

		private static void AddToList<O>(in List<O> list, O itemToAdd) where O : Component
		{
			int id = ((Object)(object)itemToAdd).GetInstanceID();
			if (!list.Any((O t) => ((Object)(object)t).GetInstanceID() == id))
			{
				list.Add(itemToAdd);
			}
		}

		private static void RemoveFromList<O>(in List<O> list, O itemToRemove) where O : Component
		{
			int id = ((Object)(object)itemToRemove).GetInstanceID();
			int num = list.FindIndex((O i) => ((Object)(object)i).GetInstanceID() == id);
			if (num > -1)
			{
				list.RemoveAt(num);
			}
		}
	}
}
namespace AWO.Sessions.Inject
{
	[HarmonyPatch(typeof(LG_DoorButton), "OnWeakLockUnlocked")]
	internal static class Inject_PreventDoorButtonUnlock
	{
		private static bool Prefix()
		{
			return !BlackoutState.BlackoutEnabled;
		}
	}
	[HarmonyPatch(typeof(LG_ComputerTerminal), "OnProximityEnter")]
	[HarmonyPatch(typeof(LG_ComputerTerminal), "OnProximityExit")]
	internal static class Inject_PreventTerminalProximity
	{
		private static bool Prefix()
		{
			return !BlackoutState.BlackoutEnabled;
		}
	}
}
namespace AWO.Sessions.Inject.LG
{
	[HarmonyPatch(typeof(LG_ComputerTerminal))]
	internal static class Inject_LG_ComputerTerminal_Track
	{
		[HarmonyPatch("Setup")]
		[HarmonyPostfix]
		private static void Post_Spawn(LG_ComputerTerminal __instance)
		{
			LG_Objects.AddTerminal(__instance);
		}
	}
	[HarmonyPatch(typeof(LG_DoorButton))]
	internal static class Inject_LG_DoorButton_Track
	{
		[HarmonyPatch("Setup")]
		[HarmonyPostfix]
		private static void Post_Spawn(LG_DoorButton __instance)
		{
			LG_Objects.AddDoorButton(__instance);
		}
	}
	[HarmonyPatch(typeof(LG_HSUActivator_Core))]
	internal static class Inject_LG_HSUActivator_Track
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void Post_Spawn(LG_HSUActivator_Core __instance)
		{
			LG_Objects.AddHSUActivator(__instance);
		}
	}
	[HarmonyPatch(typeof(LG_LabDisplay))]
	internal static class Inject_LG_LabDisplay_Track
	{
		[HarmonyPatch("GenerateText")]
		[HarmonyPatch(new Type[]
		{
			typeof(int),
			typeof(SubComplex)
		})]
		[HarmonyPostfix]
		private static void Post_Spawn(LG_LabDisplay __instance)
		{
			LG_Objects.AddLabDisplay(__instance);
		}
	}
	[HarmonyPatch(typeof(LG_WeakLock))]
	internal static class Inject_LG_WeakLock_Track
	{
		[HarmonyPatch("Setup")]
		[HarmonyPostfix]
		private static void Post_Spawn(LG_WeakLock __instance)
		{
			LG_Objects.AddWeakLock(__instance);
		}
	}
}
namespace AWO.Networking
{
	public interface IStateReplicatorHolder<S> where S : struct
	{
		StateReplicator<S> Replicator { get; }

		void OnStateChange(S oldState, S state, bool isRecall);
	}
	public sealed class ReplicatorHandshake
	{
		public delegate void ClientRequestedSyncDel(SNet_Player requestedPlayer);

		public struct Packet
		{
			public uint replicatorID;

			public PacketAction action;
		}

		public enum PacketAction : byte
		{
			Created,
			Destroyed,
			SyncRequest
		}

		public sealed class Data
		{
			public bool SetupOnHost = false;

			public bool SetupOnClient = false;
		}

		private readonly Dictionary<uint, Data> _Lookup = new Dictionary<uint, Data>();

		public string EventName { get; private set; }

		public bool IsReadyToSync { get; private set; }

		public event ClientRequestedSyncDel OnClientSyncRequested;

		public static ReplicatorHandshake Create(string guid)
		{
			if (string.IsNullOrWhiteSpace(guid))
			{
				return null;
			}
			string text = "RHs" + guid;
			return NetworkAPI.IsEventRegistered(text) ? null : new ReplicatorHandshake(text);
		}

		private ReplicatorHandshake(string eventName)
		{
			EventName = eventName;
			NetworkAPI.RegisterEvent<Packet>(eventName, (Action<ulong, Packet>)OnSyncAction);
		}

		public void Reset()
		{
			_Lookup.Clear();
		}

		private void OnSyncAction(ulong sender, Packet packet)
		{
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			if (!SNet.IsMaster && sender == SNet.Master.Lookup)
			{
				if (packet.action == PacketAction.Created)
				{
					SetHostState(packet.replicatorID, isSetup: true);
				}
				else if (packet.action == PacketAction.Destroyed)
				{
					SetHostState(packet.replicatorID, isSetup: false);
				}
			}
			else
			{
				if (!SNet.IsMaster)
				{
					return;
				}
				if (packet.action == PacketAction.Created)
				{
					SetClientState(packet.replicatorID, isSetup: true);
				}
				else if (packet.action == PacketAction.Destroyed)
				{
					SetClientState(packet.replicatorID, isSetup: false);
				}
				else
				{
					if (packet.action != PacketAction.SyncRequest)
					{
						return;
					}
					SNet_Player requestedPlayer = default(SNet_Player);
					if (!SNet.TryGetPlayer(sender, ref requestedPlayer))
					{
						bool flag = default(bool);
						BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(32, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Cannot find player from sender: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<ulong>(sender);
						}
						Logger.Error(val);
					}
					else
					{
						this.OnClientSyncRequested?.Invoke(requestedPlayer);
					}
				}
			}
		}

		public void UpdateCreated(uint id)
		{
			if (SNet.IsInLobby)
			{
				if (SNet.IsMaster)
				{
					SetHostState(id, isSetup: true);
					NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
					{
						replicatorID = id,
						action = PacketAction.Created
					}, (SNet_ChannelType)2);
				}
				else if (SNet.HasMaster)
				{
					SetClientState(id, isSetup: true);
					NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
					{
						replicatorID = id,
						action = PacketAction.Created
					}, SNet.Master, (SNet_ChannelType)2);
				}
				else
				{
					Logger.Error("Handshake::MASTER is NULL in lobby; This should NOT happen!!!!!!!!!!!!");
				}
			}
			else
			{
				Logger.Error("Handshake::Session Type StateReplicator cannot be created without lobby!");
			}
		}

		public void UpdateDestroyed(uint id)
		{
			if (SNet.IsInLobby)
			{
				if (SNet.IsMaster)
				{
					SetHostState(id, isSetup: true);
					NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
					{
						replicatorID = id,
						action = PacketAction.Destroyed
					}, (SNet_ChannelType)2);
				}
				else if (SNet.HasMaster)
				{
					SetClientState(id, isSetup: true);
					NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
					{
						replicatorID = id,
						action = PacketAction.Destroyed
					}, SNet.Master, (SNet_ChannelType)2);
				}
				else
				{
					Logger.Error("Handshake::MASTER is NULL in lobby; This should NOT happen!!!!!!!!!!!!");
				}
			}
			else
			{
				Logger.Error("Handshake::Session Type StateReplicator cannot be created without lobby!");
			}
		}

		private void SetHostState(uint id, bool isSetup)
		{
			if (_Lookup.TryGetValue(id, out Data value))
			{
				value.SetupOnHost = isSetup;
			}
			else
			{
				_Lookup[id] = new Data
				{
					SetupOnHost = isSetup
				};
			}
			UpdateSyncState(id);
		}

		private void SetClientState(uint id, bool isSetup)
		{
			if (_Lookup.TryGetValue(id, out Data value))
			{
				value.SetupOnClient = isSetup;
			}
			else
			{
				_Lookup[id] = new Data
				{
					SetupOnClient = isSetup
				};
			}
			UpdateSyncState(id);
		}

		private void UpdateSyncState(uint id)
		{
			bool isReadyToSync = IsReadyToSync;
			if (_Lookup.TryGetValue(id, out Data value))
			{
				IsReadyToSync = value.SetupOnHost && value.SetupOnClient;
			}
			else
			{
				IsReadyToSync = false;
			}
			if (IsReadyToSync && isReadyToSync != IsReadyToSync && SNet.HasMaster && !SNet.IsMaster)
			{
				NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
				{
					replicatorID = id,
					action = PacketAction.SyncRequest
				}, SNet.Master, (SNet_ChannelType)2);
			}
		}
	}
	public delegate void OnReceiveDel<S>(ulong sender, uint replicatorID, S newState) where S : struct;
	public static class StatePayloads
	{
		public enum Size
		{
			State4Byte = 4,
			State8Byte = 8,
			State16Byte = 16,
			State32Byte = 32,
			State48Byte = 48,
			State64Byte = 64,
			State80Byte = 80,
			State96Byte = 96,
			State128Byte = 128,
			State196Byte = 196,
			State256Byte = 256
		}

		public static Size GetSizeType(int size)
		{
			Size size2 = Size.State8Byte;
			foreach (object value in Enum.GetValues(typeof(Size)))
			{
				if (size <= (int)value && (int)size2 < (int)value)
				{
					size2 = (Size)value;
					break;
				}
			}
			return size2;
		}

		public static IReplicatorEvent<S> CreateEvent<S>(Size size, string eventName, OnReceiveDel<S> onReceiveCallback) where S : struct
		{
			return size switch
			{
				Size.State4Byte => ReplicatorPayloadWrapper<S, StatePayload4Byte>.Create(eventName, onReceiveCallback), 
				Size.State8Byte => ReplicatorPayloadWrapper<S, StatePayload8Byte>.Create(eventName, onReceiveCallback), 
				Size.State16Byte => ReplicatorPayloadWrapper<S, StatePayload16Byte>.Create(eventName, onReceiveCallback), 
				Size.State32Byte => ReplicatorPayloadWrapper<S, StatePayload32Byte>.Create(eventName, onReceiveCallback), 
				Size.State48Byte => ReplicatorPayloadWrapper<S, StatePayload48Byte>.Create(eventName, onReceiveCallback), 
				Size.State64Byte => ReplicatorPayloadWrapper<S, StatePayload64Byte>.Create(eventName, onReceiveCallback), 
				Size.State80Byte => ReplicatorPayloadWrapper<S, StatePayload80Byte>.Create(eventName, onReceiveCallback), 
				Size.State96Byte => ReplicatorPayloadWrapper<S, StatePayload96Byte>.Create(eventName, onReceiveCallback), 
				Size.State128Byte => ReplicatorPayloadWrapper<S, StatePayload128Byte>.Create(eventName, onReceiveCallback), 
				Size.State196Byte => ReplicatorPayloadWrapper<S, StatePayload196Byte>.Create(eventName, onReceiveCallback), 
				Size.State256Byte => ReplicatorPayloadWrapper<S, StatePayload256Byte>.Create(eventName, onReceiveCallback), 
				_ => null, 
			};
		}

		public static S Get<S>(byte[] bytes, int bytesLength) where S : struct
		{
			int num = Marshal.SizeOf(typeof(S));
			if (num > bytesLength)
			{
				throw new ArgumentException($"StateData Exceed size of {bytesLength} : Unable to Deserialize", "S");
			}
			IntPtr intPtr = Marshal.AllocHGlobal(num);
			Marshal.Copy(bytes, 0, intPtr, num);
			S result = (S)Marshal.PtrToStructure(intPtr, typeof(S));
			Marshal.FreeHGlobal(intPtr);
			return result;
		}

		public static void Set<S>(S stateData, int size, ref byte[] payloadBytes) where S : struct
		{
			int num = Marshal.SizeOf(stateData);
			if (num > size)
			{
				throw new ArgumentException($"StateData Exceed size of {size} : Unable to Serialize", "S");
			}
			byte[] array = new byte[size];
			IntPtr intPtr = Marshal.AllocHGlobal(size);
			Marshal.StructureToPtr(stateData, intPtr, fDeleteOld: false);
			Marshal.Copy(intPtr, array, 0, size);
			Marshal.FreeHGlobal(intPtr);
			payloadBytes = array;
		}
	}
	public interface IReplicatorEvent<S> where S : struct
	{
		string Name { get; }

		bool IsRegistered { get; }

		void Invoke(uint replicatorID, S data);

		void Invoke(uint replicatorID, S data, SNet_ChannelType channelType);

		void Invoke(uint replicatorID, S data, SNet_Player target);

		void Invoke(uint replicatorID, S data, SNet_Player target, SNet_ChannelType channelType);
	}
	public class ReplicatorPayloadWrapper<S, P> : IReplicatorEvent<S> where S : struct where P : struct, IStatePayload
	{
		public string Name { get; private set; }

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


		public static IReplicatorEvent<S> Create(string eventName, OnReceiveDel<S> onReceiveCallback)
		{
			ReplicatorPayloadWrapper<S, P> replicatorPayloadWrapper = new ReplicatorPayloadWrapper<S, P>();
			replicatorPayloadWrapper.Register(eventName, onReceiveCallback);
			object result;
			if (!replicatorPayloadWrapper.IsRegistered)
			{
				result = null;
			}
			else
			{
				IReplicatorEvent<S> replicatorEvent = replicatorPayloadWrapper;
				result = replicatorEvent;
			}
			return (IReplicatorEvent<S>)result;
		}

		public void Register(string eventName, OnReceiveDel<S> onReceiveCallback)
		{
			OnReceiveDel<S> onReceiveCallback2 = onReceiveCallback;
			if (!IsRegistered && !NetworkAPI.IsEventRegistered(eventName))
			{
				NetworkAPI.RegisterEvent<P>(eventName, (Action<ulong, P>)delegate(ulong sender, P payload)
				{
					onReceiveCallback2?.Invoke(sender, payload.ID, payload.Get<S>());
				});
				IsRegistered = true;
				Name = eventName;
			}
		}

		public void Invoke(uint replicatorID, S data)
		{
			P val = new P
			{
				ID = replicatorID
			};
			val.Set(data);
			NetworkAPI.InvokeEvent<P>(Name, val, (SNet_ChannelType)2);
		}

		public void Invoke(uint replicatorID, S data, SNet_ChannelType channelType)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			P val = new P
			{
				ID = replicatorID
			};
			val.Set(data);
			NetworkAPI.InvokeEvent<P>(Name, val, channelType);
		}

		public void Invoke(uint replicatorID, S data, SNet_Player target)
		{
			P val = new P
			{
				ID = replicatorID
			};
			val.Set(data);
			NetworkAPI.InvokeEvent<P>(Name, val, target, (SNet_ChannelType)2);
		}

		public void Invoke(uint replicatorID, S data, SNet_Player target, SNet_ChannelType channelType)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			P val = new P
			{
				ID = replicatorID
			};
			val.Set(data);
			NetworkAPI.InvokeEvent<P>(Name, val, target, channelType);
		}
	}
	public interface IStatePayload
	{
		uint ID { get; set; }

		S Get<S>() where S : struct;

		void Set<S>(S stateData) where S : struct;
	}
	public struct StatePayload4Byte : IStatePayload
	{
		public const int Size = 4;

		private uint id;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
		public byte[] PayloadBytes;

		public uint ID
		{
			get
			{
				return id;
			}
			set
			{
				id = value;
			}
		}

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 4);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 4, ref PayloadBytes);
		}
	}
	public struct StatePayload8Byte : IStatePayload
	{
		public const int Size = 8;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 8);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 8, ref PayloadBytes);
		}
	}
	public struct StatePayload16Byte : IStatePayload
	{
		public const int Size = 16;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 16);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 16, ref PayloadBytes);
		}
	}
	public struct StatePayload32Byte : IStatePayload
	{
		public const int Size = 32;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 32);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 32, ref PayloadBytes);
		}
	}
	public struct StatePayload48Byte : IStatePayload
	{
		public const int Size = 48;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 48)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 48);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 48, ref PayloadBytes);
		}
	}
	public struct StatePayload64Byte : IStatePayload
	{
		public const int Size = 64;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 64);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 64, ref PayloadBytes);
		}
	}
	public struct StatePayload80Byte : IStatePayload
	{
		public const int Size = 80;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 80);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 80, ref PayloadBytes);
		}
	}
	public struct StatePayload96Byte : IStatePayload
	{
		public const int Size = 96;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 96);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 96, ref PayloadBytes);
		}
	}
	public struct StatePayload128Byte : IStatePayload
	{
		public const int Size = 128;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 128);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 128, ref PayloadBytes);
		}
	}
	public struct StatePayload196Byte : IStatePayload
	{
		public const int Size = 196;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 196)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 196);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 196, ref PayloadBytes);
		}
	}
	public struct StatePayload256Byte : IStatePayload
	{
		public const int Size = 256;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 256);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 256, ref PayloadBytes);
		}
	}
	public enum LifeTimeType
	{
		Permanent,
		Session
	}
	public sealed class StateReplicator<S> where S : struct
	{
		private readonly Dictionary<eBufferType, S> _RecallStateSnapshots = new Dictionary<eBufferType, S>();

		public static readonly string Name;

		public static readonly string HashName;

		public static readonly string ClientRequestEventName;

		public static readonly string HostSetStateEventName;

		public static readonly string HostSetRecallStateEventName;

		public static readonly int StateSize;

		public static readonly StatePayloads.Size StateSizeType;

		private static readonly IReplicatorEvent<S> _C_RequestEvent;

		private static readonly IReplicatorEvent<S> _H_SetStateEvent;

		private static readonly IReplicatorEvent<S> _H_SetRecallStateEvent;

		private static readonly ReplicatorHandshake _Handshake;

		private static readonly Dictionary<uint, StateReplicator<S>> _Replicators;

		public bool IsValid => ID != 0;

		public bool IsInvalid => ID == 0;

		public uint ID { get; private set; }

		public LifeTimeType LifeTime { get; private set; }

		public IStateReplicatorHolder<S> Holder { get; private set; }

		public S State { get; private set; }

		public bool ClientSendStateAllowed { get; set; } = true;


		public bool CanSendToClient => SNet.IsInLobby && SNet.IsMaster;

		public bool CanSendToHost => SNet.IsInLobby && !SNet.IsMaster && SNet.HasMaster && ClientSendStateAllowed;

		public event Action<S, S, bool> OnStateChanged;

		public void SetState(S state)
		{
			if (!IsInvalid)
			{
				DoSync(state);
			}
		}

		public void SetStateUnsynced(S state)
		{
			if (!IsInvalid)
			{
				State = state;
			}
		}

		public void Unload()
		{
			if (IsValid)
			{
				_Replicators.Remove(ID);
				_RecallStateSnapshots.Clear();
				_Handshake.UpdateDestroyed(ID);
				ID = 0u;
			}
		}

		private void DoSync(S newState)
		{
			if (!IsInvalid)
			{
				if (CanSendToClient)
				{
					_H_SetStateEvent.Invoke(ID, newState);
					Internal_ChangeState(newState, isRecall: false);
				}
				else if (CanSendToHost)
				{
					_C_RequestEvent.Invoke(ID, newState, SNet.Master);
				}
			}
		}

		private void Internal_ChangeState(S state, bool isRecall)
		{
			if (!IsInvalid)
			{
				S state2 = State;
				State = state;
				this.OnStateChanged?.Invoke(state2, state, isRecall);
				Holder?.OnStateChange(state2, state, isRecall);
			}
		}

		private void SendDropInState(SNet_Player target)
		{
			if (!IsInvalid)
			{
				if ((Object)(object)target == (Object)null)
				{
					Logger.Error("SendDropInState::Target was null??");
				}
				else
				{
					_H_SetRecallStateEvent.Invoke(ID, State, target);
				}
			}
		}

		public void ClearAllRecallSnapshot()
		{
			if (!IsInvalid)
			{
				_RecallStateSnapshots.Clear();
			}
		}

		private void SaveSnapshot(eBufferType type)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (!IsInvalid)
			{
				_RecallStateSnapshots[type] = State;
			}
		}

		private void RestoreSnapshot(eBufferType type)
		{
			//IL_0021: 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_0059: Expected O, but got Unknown
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			if (IsInvalid || !CanSendToClient)
			{
				return;
			}
			if (_RecallStateSnapshots.TryGetValue(type, out var value))
			{
				_H_SetRecallStateEvent.Invoke(ID, value);
				Internal_ChangeState(value, isRecall: true);
				return;
			}
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(29, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("RestoreSnapshot");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("::There was no snapshot for ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eBufferType>(type);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("?");
			}
			Logger.Error(val);
		}

		static StateReplicator()
		{
			_Replicators = new Dictionary<uint, StateReplicator<S>>();
			Name = typeof(S).Name;
			StateSize = Marshal.SizeOf(typeof(S));
			StateSizeType = StatePayloads.GetSizeType(StateSize);
			using MD5 mD = MD5.Create();
			byte[] inArray = mD.ComputeHash(Encoding.UTF8.GetBytes(typeof(S).FullName));
			HashName = Convert.ToBase64String(inArray);
			ClientRequestEventName = "SRs" + Name + "-" + HashName;
			HostSetStateEventName = "SRr" + Name + "-" + HashName;
			HostSetRecallStateEventName = "SRre" + Name + "-" + HashName;
			_C_RequestEvent = StatePayloads.CreateEvent<S>(StateSizeType, ClientRequestEventName, ClientRequestEventCallback);
			_H_SetStateEvent = StatePayloads.CreateEvent<S>(StateSizeType, HostSetStateEventName, HostSetStateEventCallback);
			_H_SetRecallStateEvent = StatePayloads.CreateEvent<S>(StateSizeType, HostSetRecallStateEventName, HostSetRecallStateEventCallback);
			_Handshake = ReplicatorHandshake.Create(Name + "-" + HashName);
			_Handshake.OnClientSyncRequested += ClientSyncRequested;
			Inject_SNet_Capture.OnBufferCapture += BufferStored;
			Inject_SNet_Capture.OnBufferRecalled += BufferRecalled;
			LevelEvents.OnLevelCleanup += LevelCleanedUp;
		}

		private static void ClientSyncRequested(SNet_Player requestedPlayer)
		{
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.IsValid)
				{
					value.SendDropInState(requestedPlayer);
				}
			}
		}

		private static void BufferStored(eBufferType type)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.IsValid)
				{
					value.SaveSnapshot(type);
				}
			}
		}

		private static void BufferRecalled(eBufferType type)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.IsValid)
				{
					value.RestoreSnapshot(type);
				}
			}
		}

		private static void LevelCleanedUp()
		{
			UnloadSessionReplicator();
		}

		private StateReplicator()
		{
		}

		public static StateReplicator<S> Create(uint replicatorID, S startState, LifeTimeType lifeTime, IStateReplicatorHolder<S> holder = null)
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			if (replicatorID == 0)
			{
				Logger.Error("Replicator ID 0 is reserved for empty!");
				return null;
			}
			if (_Replicators.ContainsKey(replicatorID))
			{
				Logger.Error("Replicator ID has already assigned!");
				return null;
			}
			StateReplicator<S> stateReplicator = new StateReplicator<S>
			{
				ID = replicatorID,
				LifeTime = lifeTime,
				Holder = holder,
				State = startState
			};
			switch (lifeTime)
			{
			case LifeTimeType.Permanent:
				Logger.Debug("LifeTime is Permanent :: Handshaking is disabled!");
				break;
			case LifeTimeType.Session:
				_Handshake.UpdateCreated(replicatorID);
				break;
			default:
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(22, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("LifeTime is invalid!: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<LifeTimeType>(lifeTime);
				}
				Logger.Error(val);
				return null;
			}
			}
			_Replicators[replicatorID] = stateReplicator;
			return stateReplicator;
		}

		public static void UnloadSessionReplicator()
		{
			List<uint> list = new List<uint>();
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.LifeTime == LifeTimeType.Session)
				{
					list.Add(value.ID);
					value.Unload();
				}
			}
			foreach (uint item in list)
			{
				_Replicators.Remove(item);
			}
			_Handshake.Reset();
		}

		private static void ClientRequestEventCallback(ulong sender, uint replicatorID, S newState)
		{
			if (SNet.IsMaster && _Replicators.TryGetValue(replicatorID, out StateReplicator<S> value))
			{
				value.SetState(newState);
			}
		}

		private static void HostSetStateEventCallback(ulong sender, uint replicatorID, S newState)
		{
			if (SNet.HasMaster && SNet.Master.Lookup == sender && _Replicators.TryGetValue(replicatorID, out StateReplicator<S> value))
			{
				value.Internal_ChangeState(newState, isRecall: false);
			}
		}

		private static void HostSetRecallStateEventCallback(ulong sender, uint replicatorID, S newState)
		{
			if (SNet.HasMaster && SNet.Master.Lookup == sender && _Replicators.TryGetValue(replicatorID, out StateReplicator<S> value))
			{
				value.Internal_ChangeState(newState, isRecall: true);
			}
		}
	}
}
namespace AWO.Networking.CommonReplicator.Inject
{
	[HarmonyPatch(typeof(WardenObjectiveManager), "CheckExpeditionFailed")]
	internal static class Inject_LevelFailCheck
	{
		public static bool LevelFailAllowed = true;

		public static bool LevelFailWhenAnyPlayerDown = false;

		private static void Postfix(ref bool __result)
		{
			if (!LevelFailAllowed)
			{
				__result = false;
			}
			else if (LevelFailWhenAnyPlayerDown && HasAnyDownedPlayer())
			{
				__result = true;
			}
		}

		private static bool HasAnyDownedPlayer()
		{
			bool result = false;
			int count = PlayerManager.PlayerAgentsInLevel.Count;
			if (count <= 0)
			{
				return false;
			}
			for (int i = 0; i < count; i++)
			{
				PlayerAgent val = PlayerManager.PlayerAgentsInLevel[i];
				if (!((Agent)val).Alive)
				{
					result = true;
				}
			}
			return result;
		}
	}
}
namespace AWO.Networking.Inject
{
	[HarmonyPatch(typeof(SNet_Capture))]
	internal static class Inject_SNet_Capture
	{
		public static event Action<eBufferType> OnBufferCapture;

		public static event Action<eBufferType> OnBufferRecalled;

		[HarmonyPatch("TriggerCapture")]
		[HarmonyPrefix]
		private static void Pre_TriggerCapture(SNet_Capture __instance)
		{
			//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_0013: Unknown result type (might be due to invalid IL or missing references)
			eBufferType primedBufferType = __instance.PrimedBufferType;
			Inject_SNet_Capture.OnBufferCapture?.Invoke(primedBufferType);
		}

		[HarmonyPatch("RecallBuffer")]
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		private static void Post_RecallBuffer(SNet_Capture __instance, eBufferType bufferType)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.IsRecalling)
			{
				Inject_SNet_Capture.OnBufferRecalled?.Invoke(bufferType);
			}
		}
	}
}
namespace AWO.Modules.WOE
{
	public static class WardenObjectiveExt
	{
		private static readonly Dictionary<eWardenObjectiveType, Type> _DTOTypes;

		private static readonly List<WOE_ContextBase> _ActiveContexts;

		static WardenObjectiveExt()
		{
			//IL_007b: 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: Expected O, but got Unknown
			//IL_018c: 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_0129: Expected O, but got Unknown
			_DTOTypes = new Dictionary<eWardenObjectiveType, Type>();
			_ActiveContexts = new List<WOE_ContextBase>();
			IEnumerable<Type> enumerable = from x in typeof(WOE_ContextBase).Assembly.GetTypes()
				where !x.IsAbstract
				where x.IsAssignableTo(typeof(WOE_ContextBase))
				select x;
			bool flag = default(bool);
			foreach (Type item in enumerable)
			{
				WOE_ContextBase wOE_ContextBase = (WOE_ContextBase)Activator.CreateInstance(item);
				if (_DTOTypes.TryGetValue(wOE_ContextBase.TargetType, out Type _))
				{
					Logger.Error("Duplicate TargetType Detected!");
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(14, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("With '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(item.Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' and '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(wOE_ContextBase.GetType().Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("'");
					}
					Logger.Error(val);
				}
				else if (!wOE_ContextBase.DataType.IsAssignableTo(typeof(WOE_DataBase)))
				{
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(41, 3, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(item.Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" does not have valid ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("DataType");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (not derived from ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("WOE_DataBase");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(")");
					}
					Logger.Error(val);
				}
				else
				{
					_DTOTypes[wOE_ContextBase.TargetType] = item;
				}
			}
			WOEvents.OnSetup += ObjectiveSetup;
			LevelEvents.OnLevelCleanup += LevelCleanup;
		}

		internal static void Initialize()
		{
		}

		private static void ObjectiveSetup(LG_LayerType layer, int chainIndex)
		{
			//IL_0001: 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_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0083: 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)
			WardenObjectiveDataBlock val = default(WardenObjectiveDataBlock);
			Type value;
			if (!WardenObjectiveManager.TryGetWardenObjectiveDataForLayer(layer, chainIndex, ref val))
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(44, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<LG_LayerType>(layer);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" Layer (CI: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(chainIndex);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(") does not have ObjectiveData!!!");
				}
				Logger.Error(val2);
			}
			else if (_DTOTypes.TryGetValue(val.Type, out value))
			{
				WOE_ContextBase wOE_ContextBase = (WOE_ContextBase)Activator.CreateInstance(value);
				wOE_ContextBase.Setup(layer, chainIndex);
				_ActiveContexts.Add(wOE_ContextBase);
			}
		}

		private static void LevelCleanup()
		{
			foreach (WOE_ContextBase activeContext in _ActiveContexts)
			{
				activeContext.OnLevelCleanup();
			}
			_ActiveContexts.Clear();
		}
	}
	internal abstract class WOE_ContextBase
	{
		public abstract eWardenObjectiveType TargetType { get; }

		public abstract Type DataType { get; }

		protected WOE_DataBase Data { get; private set; }

		protected LG_LayerType Layer { get; private set; }

		protected int ChainIndex { get; private set; }

		public void Setup(LG_LayerType layer, int chainIndex)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Layer = layer;
			ChainIndex = chainIndex;
		}

		public virtual void OnSetup()
		{
		}

		public virtual void OnBuildDone()
		{
		}

		public virtual void OnBuildDoneLate()
		{
		}

		public virtual void OnLevelCleanup()
		{
		}
	}
	internal abstract class WOE_DataBase
	{
		public uint ObjectiveID { get; set; }

		public WardenObjectiveDataBlock GameData { get; set; }
	}
}
namespace AWO.Modules.WOE.Objectives.Uplinks
{
	internal sealed class WOE_UplinkContext : WOE_ContextBase
	{
		public override eWardenObjectiveType TargetType => (eWardenObjectiveType)8;

		public override Type DataType => typeof(WOE_UplinkData);
	}
	internal sealed class WOE_UplinkData : WOE_DataBase
	{
		public UplinkCodeBehaviour[] CodeBehaviours { get; set; } = Array.Empty<UplinkCodeBehaviour>();

	}
	internal sealed class UplinkCodeBehaviour
	{
		public bool ShowCodesOnTerminal { get; set; } = false;


		public bool ShowCodesOnHUD { get; set; } = true;


		public bool ShowCodeToOtherTerminal { get; set; } = true;


		public TerminalZoneSelectionData TerminalZone { get; set; } = new TerminalZoneSelectionData();


		public TerminalOutput[] StartOutputs { get; set; } = Array.Empty<TerminalOutput>();


		public TerminalOutput[] EndOutputs { get; set; } = Array.Empty<TerminalOutput>();


		public WardenObjectiveEventData[] EventsOnStart { get; set; } = Array.Empty<WardenObjectiveEventData>();


		public WardenObjectiveEventData[] EventsOnEnd { get; set; } = Array.Empty<WardenObjectiveEventData>();

	}
}
namespace AWO.Modules.WOE.Objectives.ReactorStartups
{
	internal sealed class WOE_ReactorStartupContext : WOE_ContextBase
	{
		public override eWardenObjectiveType TargetType => (eWardenObjectiveType)1;

		public override Type DataType => typeof(WOE_ReactorStartupData);
	}
	internal enum ReactorWavePuzzleType
	{
		Default,
		CustomLock,
		UseCommand_OnMainTerminal,
		UseCommand_InZone,
		PowerGenerator_InZone
	}
	internal sealed class WOE_ReactorStartupData : WOE_DataBase
	{
		public bool RemoveMainStartupCommand { get; set; } = false;


		public bool RemoveMainVerifyCommand { get; set; } = false;


		public ScriptedWaveData[] WaveDatas { get; set; } = Array.Empty<ScriptedWaveData>();


		public ReactorWavePuzzleData[] WavePuzzles { get; set; } = Array.Empty<ReactorWavePuzzleData>();

	}
	internal enum SettingWarpMode
	{
		Clamped,
		Repeat,
		PingPong
	}
	internal sealed class ScriptedWaveData
	{
		public float[] IntroDuration { get; set; } = Array.Empty<float>();


		public SettingWarpMode IntroDurationWarpMode { get; set; } = SettingWarpMode.Clamped;


		public float[] WaveDuration { get; set; } = Array.Empty<float>();


		public SettingWarpMode WaveDurationWarpMode { get; set; } = SettingWarpMode.Clamped;


		public string[][] WaveInstructions { get; set; } = Array.Empty<string[]>();


		public SettingWarpMode WaveInstructionsWarpMode { get; set; } = SettingWarpMode.Clamped;

	}
	internal sealed class ReactorWavePuzzleData
	{
		public ReactorWavePuzzleType Type { get; set; } = ReactorWavePuzzleType.Default;


		public bool ShowBeacon { get; set; } = false;


		public string BeaconText { get; set; } = "Auxiliary Terminal";


		public Color BeaconColor { get; set; } = Color.magenta;


		public string Command { get; set; } = "REACTOR_CONTINUE";


		public string CommandDescription { get; set; } = "CONTINUE REACTOR STARTUP PROCESS";


		public bool ForceJumpWaveWhenSolved { get; set; } = true;

	}
}
namespace AWO.Modules.WOE.Objectives.GenClusters
{
	internal sealed class WOE_GenClusterContext : WOE_ContextBase
	{
		public override eWardenObjectiveType TargetType => (eWardenObjectiveType)9;

		public override Type DataType => typeof(int);
	}
}
namespace AWO.Modules.WOE.JsonInjects
{
	internal class ObjectiveDataHandler : Il2CppJsonReferenceTypeHandler<WardenObjectiveDataBlock>
	{
		public override void OnRead(in Object result, in JToken jToken)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Invalid comparison between Unknown and I4
			if ((int)jToken.Type == 1)
			{
				JObject val = (JObject)jToken;
				JToken val2 = default(JToken);
				if (val.TryGetValue("woeEnabled", ref val2) && (int)val2.Type == 9 && (bool)val2)
				{
					WardenObjectiveDataBlock val3 = ((Il2CppObjectBase)result).Cast<WardenObjectiveDataBlock>();
				}
			}
		}
	}
}
namespace AWO.Modules.WEE
{
	public static class WardenEventExt
	{
		internal static readonly Dictionary<WEE_Type, BaseEvent> _EventsToTrigger;

		static WardenEventExt()
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			_EventsToTrigger = new Dictionary<WEE_Type, BaseEvent>();
			IEnumerable<Type> enumerable = from x in typeof(BaseEvent).Assembly.GetTypes()
				where !x.IsAbstract
				where x.IsAssignableTo(typeof(BaseEvent))
				select x;
			bool flag = default(bool);
			foreach (Type item in enumerable)
			{
				BaseEvent baseEvent = (BaseEvent)Activator.CreateInstance(item);
				if (_EventsToTrigger.TryGetValue(baseEvent.EventType, out BaseEvent value))
				{
					Logger.Error("Duplicate EventType Detected!");
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(14, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("With '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(value.Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' and '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(baseEvent.Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("'");
					}
					Logger.Error(val);
				}
				else
				{
					baseEvent.Setup();
					_EventsToTrigger[baseEvent.EventType] = baseEvent;
				}
			}
		}

		internal static void Initialize()
		{
			ClassInjector.RegisterTypeInIl2Cpp<ScanPositionReplicator>();
			ClassInjector.RegisterTypeInIl2Cpp<ZoneLightReplicator>();
			JsonInjector.SetConverter<eWardenObjectiveEventType>((Il2CppJsonUnmanagedTypeConverter<eWardenObjectiveEventType>)new EventTypeConverter());
			JsonInjector.AddHandler<WardenObjectiveEventData>((Il2CppJsonReferenceTypeHandler<WardenObjectiveEventData>)(object)new EventDataHandler());
			JsonInjector.AddHandler<WorldEventFromSourceData>((Il2CppJsonReferenceTypeHandler<WorldEventFromSourceData>)(object)new TriggerDataHandler());
			WEE_EnumInjector.Inject();
			Detour_ExecuteEvent.Patch();
		}

		internal static void HandleEvent(WEE_Type type, WardenObjectiveEventData e, float currentDuration)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(36, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("We got Type ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<WEE_Type>(type);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" on WardenEventExt event");
			}
			Logger.Debug(val);
			WEE_EventData wEEData = e.GetWEEData();
			if (wEEData != null)
			{
				CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(Handle(type, wEEData, currentDuration)), (Action)null);
				return;
			}
			BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(71, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("WardenEvent Type is Extension (");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<WEE_Type>(type);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(") But it's not registered to dataholder!");
			}
			Logger.Error(val2);
		}

		private static IEnumerator Handle(WEE_Type type, WEE_EventData e, float currentDuration)
		{
			float delay = Mathf.Max(e.Delay - currentDuration, 0f);
			if (delay > 0f)
			{
				yield return (object)new WaitForSeconds(delay);
			}
			if (WorldEventManager.GetCondition(e.Condition.ConditionIndex) != e.Condition.IsTrue)
			{
				yield break;
			}
			WardenObjectiveManager.DisplayWardenIntel(e.Layer, e.WardenIntel.ToLocalizedText());
			if (e.DialogueID != 0)
			{
				PlayerDialogManager.WantToStartDialog(e.DialogueID, -1, false, false);
			}
			if (e.SoundID != 0)
			{
				WardenObjectiveManager.Current.m_sound.Post(e.SoundID, true);
				string line = e.SoundSubtitle.ToString();
				if (!string.IsNullOrWhiteSpace(line))
				{
					GuiManager.PlayerLayer.ShowMultiLineSubtitle(line);
				}
			}
			if (e.SubObjective.DoUpdate)
			{
				WardenObjectiveManager.UpdateSyncCustomSubObjective(e.SubObjective.CustomSubObjectiveHeader.ToLocalizedText(), e.SubObjective.CustomSubObjective.ToLocalizedText());
			}
			if (e.Fog.DoUpdate)
			{
				EnvironmentStateManager.AttemptStartFogTransition(e.Fog.FogSetting, e.Fog.FogTransitionDuration, e.DimensionIndex);
			}
			if (_EventsToTrigger.TryGetValue(type, out BaseEvent eventInstance))
			{
				eventInstance.Trigger(e);
				yield break;
			}
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(26, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<WEE_Type>(type);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" does not exist in lookup!");
			}
			Logger.Error(val);
		}
	}
	internal static class WEE_EnumInjector
	{
		public const int ExtendedIndex = 10000;

		private static readonly Dictionary<string, object> _EventTypes;

		private static int _CurrentIndex;

		static WEE_EnumInjector()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			_EventTypes = new Dictionary<string, object>();
			_CurrentIndex = 0;
			WEE_Type[] values = Enum.GetValues<WEE_Type>();
			bool flag = default(bool);
			for (int i = 0; i < values.Length; i++)
			{
				WEE_Type wEE_Type = values[i];
				string text = wEE_Type.ToString();
				AddEvent(text);
				BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(22, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Injecting EWOEvent: '");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("'");
				}
				Logger.Debug(val);
			}
		}

		private static void AddEvent(string name)
		{
			_EventTypes[name] = _CurrentIndex + 10000;
			_CurrentIndex++;
		}

		internal static void Inject()
		{
			EnumInjector.InjectEnumValues<eWardenObjectiveEventType>(_EventTypes);
		}
	}
	public sealed class WEE_EventData
	{
		public WEE_Type Type { get; set; }

		public WorldEventConditionPair Condition { get; set; } = new WorldEventConditionPair
		{
			ConditionIndex = -1,
			IsTrue = false
		};


		public eWardenObjectiveEventTrigger Trigger { get; set; } = (eWardenObjectiveEventTrigger)0;


		public uint ChainPuzzle { get; set; } = 0u;


		public bool UseStaticBioscanPoints { get; set; } = false;


		public LG_LayerType Layer { get; set; } = (LG_LayerType)0;


		public eDimensionIndex DimensionIndex { get; set; } = (eDimensionIndex)0;


		public eLocalZoneIndex LocalIndex { get; set; } = (eLocalZoneIndex)0;


		public Vector3 Position { get; set; } = Vector3.zero;


		public float Delay { get; set; } = 0f;


		public float Duration { get; set; } = 0f;


		public LocaleText WardenIntel { get; set; } = LocaleText.Empty;


		public uint SoundID { get; set; } = 0u;


		public LocaleText SoundSubtitle { get; set; } = LocaleText.Empty;


		public uint DialogueID { get; set; } = 0u;


		public int Count { get; set; } = 0;


		public bool Enabled { get; set; } = true;


		public int SpecialNumber { get; set; } = -1;


		public LocaleText SpecialText { get; set; } = LocaleText.Empty;


		public WEE_SubObjectiveData SubObjective { get; set; } = new WEE_SubObjectiveData();


		public WEE_UpdateFogData Fog { get; set; } = new WEE_UpdateFogData();


		public bool CleanUpEnemiesBehind { get; set; } = true;


		public WEE_ReactorEventData Reactor { get; set; } = new WEE_ReactorEventData();


		public WEE_CountdownData Countdown { get; set; } = new WEE_CountdownData();


		public WEE_ZoneLightData SetZoneLight { get; set; } = new WEE_ZoneLightData();


		public WEE_CleanupEnemiesData CleanupEnemies { get; set; } = new WEE_CleanupEnemiesData();


		public WEE_SpawnHibernateData SpawnHibernates { get; set; } = new WEE_SpawnHibernateData();


		public WEE_SpawnScoutData SpawnScouts { get; set; } = new WEE_SpawnScoutData();


		public WEE_AddTerminalCommand AddTerminalCommand { get; set; } = new WEE_AddTerminalCommand();


		public WEE_HideTerminalCommand HideTerminalCommand { get; set; } = new WEE_HideTerminalCommand();


		public WEE_UnhideTerminalCommand UnhideTerminalCommand { get; set; } = new WEE_UnhideTerminalCommand();


		public WEE_NestedEvent NestedEvent { get; set; } = new WEE_NestedEvent();


		public WEE_StartEventLoop StartEventLoop { get; set; } = new WEE_StartEventLoop();


		public WEE_StartEventLoop EventLoop
		{
			get
			{
				return StartEventLoop;
			}
			set
			{
				StartEventLoop = value;
			}
		}

		public WEE_TeleportPlayer TeleportPlayer { get; set; } = new WEE_TeleportPlayer();


		public WEE_InfectPlayer InfectPlayer { get; set; } = new WEE_InfectPlayer();


		public WEE_DamagePlayer DamagePlayer { get; set; } = new WEE_DamagePlayer();


		public WEE_RevivePlayer RevivePlayer { get; set; } = new WEE_RevivePlayer();


		public WEE_AdjustTimer AdjustTimer { get; set; } = new WEE_AdjustTimer();


		public WEE_CountupData Countup { get; set; } = new WEE_CountupData();


		public WEE_ShakeScreen CameraShake { get; set; } = new WEE_ShakeScreen();


		public WEE_StartPortalMachine Portal { get; set; } = new WEE_StartPortalMachine();


		public WEE_SetSuccessScreen SuccessScreen { get; set; } = new WEE_SetSuccessScreen();


		public List<WEE_SubObjectiveData> MultiProgression { get; set; } = new List<WEE_SubObjectiveData>();


		public WEE_PlayWaveDistantRoar WaveRoarSound { get; set; } = new WEE_PlayWaveDistantRoar();


		public WEE_CustomHudText CustomHudText { get; set; } = new WEE_CustomHudText();


		public WEE_SpecialHudTimer SpecialHudTimer { get; set; } = new WEE_SpecialHudTimer();


		public WardenObjectiveEventData CreateDummyEventData()
		{
			//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_0013: 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_002d: 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_0048: Expected O, but got Unknown
			return new WardenObjectiveEventData
			{
				Type = (eWardenObjectiveEventType)Type,
				ChainPuzzle = ChainPuzzle,
				UseStaticBioscanPoints = UseStaticBioscanPoints,
				Trigger = Trigger,
				Condition = Condition
			};
		}
	}
	public sealed class WEE_UpdateFogData
	{
		public bool DoUpdate { get; set; } = false;


		public uint FogSetting { get; set; }

		public float FogTransitionDuration { get; set; }
	}
	public sealed class WEE_SubObjectiveData
	{
		public LG_LayerType Layer = (LG_LayerType)0;

		public bool DoUpdate { get; set; } = false;


		public LocaleText CustomSubObjectiveHeader { get; set; } = LocaleText.Empty;


		public LocaleText CustomSubObjective { get; set; } = LocaleText.Empty;


		public uint Index { get; set; } = 0u;


		public LocaleText OverrideTag { get; set; } = LocaleText.Empty;

	}
	public sealed class WEE_ReactorEventData
	{
		public enum WaveState
		{
			Intro,
			Wave,
			Verify
		}

		public WaveState State { get; set; } = WaveState.Intro;


		public int Wave { get; set; } = 1;


		public float Progress { get; set; } = 0f;

	}
	public sealed class WEE_DoorInteractionData
	{
		public bool LockdownState { get; set; }

		public string LockdownMessage { get; set; }
	}
	public sealed class WEE_CountdownData
	{
		public float Duration { get; set; } = 0f;


		public LocaleText TimerText { get; set; } = LocaleText.Empty;


		public Color TimerColor { get; set; } = Color.red;


		public List<EventsOnTimerProgress> EventsOnProgress { get; set; } = new List<EventsOnTimerProgress>();


		public WardenObjectiveEventData[] EventsOnDone { get; set; } = Array.Empty<WardenObjectiveEventData>();

	}
	public sealed class WEE_CleanupEnemiesData
	{
		public enum CleanUpType
		{
			Kill,
			Despawn
		}

		public CleanUpType Type { get; set; } = CleanUpType.Despawn;


		public int AreaIndex { get; set; } = -1;


		public bool IncludeHibernate { get; set; } = true;


		public bool IncludeAggressive { get; set; } = true;


		public bool IncludeScout { get; set; } = true;


		public uint[] ExcludeEnemyID { get; set; } = Array.Empty<uint>();


		public uint[] IncludeOnlyID { get; set; } = Array.Empty<uint>();


		public void DoClear(AIG_CourseNode node)
		{
			//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_0079: 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_0092: Expected I4, but got Unknown
			//IL_0154: 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_015e: 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_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			if (!SNet.IsMaster || node == null || node.m_enemiesInNode == null)
			{
				return;
			}
			List<EnemyAgent> list = new List<EnemyAgent>();
			list.Clear();
			Enumerator<EnemyAgent> enumerator = node.m_enemiesInNode.GetEnumerator();
			while (enumerator.MoveNext())
			{
				EnemyAgent current = enumerator.Current;
				list.Add(current);
			}
			foreach (EnemyAgent item in list)
			{
				AgentMode mode = ((AgentAI)item.AI).Mode;
				if ((mode - 1) switch
				{
					0 => IncludeAggressive, 
					2 => IncludeScout, 
					3 => IncludeHibernate, 
					_ => true, 
				} && !ExcludeEnemyID.Contains(item.EnemyDataID) && (IncludeOnlyID.Length == 0 || IncludeOnlyID.Contains(item.EnemyDataID)))
				{
					switch (Type)
					{
					case CleanUpType.Despawn:
						((Agent)item).m_replicator.Despawn();
						break;
					case CleanUpType.Kill:
						item.Damage.IsImortal = false;
						item.Damage.BulletDamage(((Dam_SyncedDamageBase)item.Damage).DamageMax, (Agent)null, default(Vector3), default(Vector3), default(Vector3), false, 0, 1f, 1f, 0u);
						break;
					}
				}
			}
		}
	}
	public sealed class WEE_ZoneLightData
	{
		public enum ModifierType : byte
		{
			RevertToOriginal,
			SetZoneLightData
		}

		public ModifierType Type { get; set; } = ModifierType.RevertToOriginal;


		public uint LightDataID { get; set; }

		public float TransitionDuration { get; set; } = 0.5f;


		public int Seed { get; set; } = 0;

	}
	public sealed class WEE_SpawnHibernateData
	{
		public int AreaIndex { get; set; } = -1;


		public uint EnemyID { get; set; } = 0u;


		public uint Count { get; set; } = 1u;


		public Vector3 Position { get; set; } = Vector3.zero;


		public Vector3 Rotation { get; set; } = Vector3.zero;

	}
	public sealed class WEE_SpawnScoutData
	{
		public int AreaIndex { get; set; } = -1;


		public eEnemyGroupType GroupType { get; set; }

		public eEnemyRoleDifficulty Difficulty { get; set; }

		public uint Count { get; set; } = 1u;

	}
	public enum FilterMode
	{
		Exclude,
		Include
	}
	public sealed class WEE_AddTerminalCommand
	{
		public int TerminalIndex { get; set; } = 0;


		public int CommandNumber { get; set; } = 6;


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


		public LocaleText CommandDesc { get; set; } = LocaleText.Empty;


		public TERM_CommandRule SpecialCommandRule { get; set; } = (TERM_CommandRule)0;


		public WardenObjectiveEventData[] CommandEvents { get; set; } = Array.Empty<WardenObjectiveEventData>();


		public TerminalOutput[] PostCommandOutputs { get; set; } = Array.Empty<TerminalOutput>();

	}
	public sealed class WEE_HideTerminalCommand
	{
		public int TerminalIndex { get; set; } = 0;


		public TERM_Command CommandEnum { get; set; } = (TERM_Command)0;


		public int CommandNumber { get; set; } = 0;


		public bool DeleteCommand { get; set; } = false;

	}
	public sealed class WEE_UnhideTerminalCommand
	{
		public int TerminalIndex { get; set; } = 0;


		public TERM_Command CommandEnum { get; set; } = (TERM_Command)0;


		public int CommandNumber { get; set; } = 0;

	}
	public sealed class WEE_NestedEvent
	{
		public enum NestedMode : byte
		{
			ActivateAll,
			RandomAny
		}

		public NestedMode Type { get; set; } = NestedMode.ActivateAll;


		public int MaxRandomEvents { get; set; } = -1;


		public bool AllowRepeatsInRandom { get; set; } = false;


		public WardenObjectiveEventData[] EventsToActivate { get; set; } = Array.Empty<WardenObjectiveEventData>();

	}
	public sealed class WEE_StartEventLoop
	{
		public int LoopIndex { get; set; } = 0;


		public float LoopDelay { get; set; } = 1f;


		public int LoopCount { get; set; } = -1;


		public WardenObjectiveEventData[] EventsToActivate { get; set; } = Array.Empty<WardenObjectiveEventData>();

	}
	public enum SlotIndex : byte
	{
		P0,
		P1,
		P2,
		P3
	}
	public sealed class WEE_TeleportPlayer
	{
		public HashSet<SlotIndex> PlayerFilter { get; set; } = new HashSet<SlotIndex>();


		public bool PlayWarpAnimation { get; set; } = true;


		public bool FlashTeleport { get; set; } = false;


		public bool WarpSentries { get; set; } = true;


		public bool WarpBigPickups { get; set; } = true;


		public bool SendBPUsToHost { get; set; } = false;


		public Vector3 Player0Position { get; set; } = Vector3.zero;


		public int P0LookDir { get; set; } = 0;


		public Vector3 Player1Position { get; set; } = Vector3.zero;


		public int P1LookDir { get; set; } = 0;


		public Vector3 Player2Position { get; set; } = Vector3.zero;


		public int P2LookDir { get; set; } = 0;


		public Vector3 Player3Position { get; set; } = Vector3.zero;


		public int P3LookDir { get; set; } = 0;

	}
	public sealed class WEE_InfectPlayer
	{
		public HashSet<SlotIndex> PlayerFilter { get; set; } = new HashSet<SlotIndex>
		{
			SlotIndex.P0,
			SlotIndex.P1,
			SlotIndex.P2,
			SlotIndex.P3
		};


		public float InfectionAmount { get; set; } = 0f;


		public bool InfectOverTime { get; set; } = false;


		public bool UseZone { get; set; } = false;

	}
	public sealed class WEE_DamagePlayer
	{
		public HashSet<SlotIndex> PlayerFilter { get; set; } = new HashSet<SlotIndex>
		{
			SlotIndex.P0,
			SlotIndex.P1,
			SlotIndex.P2,
			SlotIndex.P3
		};


		public float DamageAmount { get; set; } = 0f;


		public bool DamageOverTime { get; set; } = false;


		public bool UseZone { get; set; } = false;

	}
	public sealed class WEE_RevivePlayer
	{
		public HashSet<SlotIndex> PlayerFilter { get; set; } = new HashSet<SlotIndex>
		{
			SlotIndex.P0,
			SlotIndex.P1,
			SlotIndex.P2,
			SlotIndex.P3
		};

	}
	public sealed class WEE_AdjustTimer
	{
		public float Duration { get; set; } = 0f;


		public float Speed { get; set; } = 0f;


		public bool UpdateText { get; set; } = false;


		public LocaleText CustomText { get; set; } = LocaleText.Empty;


		public Color TimerColor { get; set; } = Color.red;

	}
	public sealed class WEE_CountupData
	{
		public float Duration { get; set; } = 0f;


		public float StartValue { get; set; } = 0f;


		public float Speed { get; set; } = 1f;


		public LocaleText TimerText { get; set; } = LocaleText.Empty;


		public LocaleText CustomText { get; set; } = LocaleText.Empty;


		public Color TimerColor { get; set; } = Color.red;


		public int DecimalPoints { get; set; } = 0;


		public List<EventsOnTimerProgress> EventsOnProgress { get; set; } = new List<EventsOnTimerProgress>();


		public WardenObjectiveEventData[] EventsOnDone { get; set; } = Array.Empty<WardenObjectiveEventData>();

	}
	public struct EventsOnTimerProgress
	{
		public float Progress { get; set; }

		public WardenObjectiveEventData[] Events { get; set; }
	}
	public sealed class WEE_ShakeScreen
	{
		public float Radius { get; set; } = 0f;


		public float Duration { get; set; } = 0f;


		public float Amplitude { get; set; } = 0f;


		public float Frequency { get; set; } = 0f;


		public bool Directional { get; set; } = true;

	}
	public sealed class WEE_StartPortalMachine
	{
		public eDimensionIndex TargetDimension { get; set; } = (eDimensionIndex)1;


		public eLocalZoneIndex TargetZone { get; set; } = (eLocalZoneIndex)0;

	}
	public sealed class WEE_SetSuccessScreen
	{
		public enum ScreenType : byte
		{
			SetSuccessScreen,
			FlashFakeScreen
		}

		public ScreenType Type { get; set; } = ScreenType.SetSuccessScreen;


		public WinScreen CustomSuccessScreen { get; set; } = WinScreen.Empty;


		public eCM_MenuPage FakeEndScreen { get; set; } = (eCM_MenuPage)17;


		public float Duration { get; set; } = 0f;

	}
	public sealed class WEE_PlayWaveDistantRoar
	{
		public enum WaveRoarSound : byte
		{
			Striker,
			Shooter,
			Birther,
			Shadow,
			Tank,
			Flyer,
			Immortal,
			Bullrush,
			Pouncer,
			Striker_Berserk,
			Shooter_Spread
		}

		public enum WaveRoarSize : byte
		{
			Small,
			Medium,
			Big
		}

		public WaveRoarSound RoarSound { get; set; }

		public WaveRoarSize RoarSize { get; set; }

		public bool IsOutside { get; set; }
	}
	public sealed class WEE_CustomHudText
	{
		public LocaleText Title { get; set; } = LocaleText.Empty;


		public LocaleText Body { get; set; } = LocaleText.Empty;

	}
	public sealed class WEE_SpecialHudTimer
	{
		public LocaleText Message { get; set; } = LocaleText.Empty;


		public ePUIMessageStyle Style { get; set; } = (ePUIMessageStyle)0;


		public int Priority { get; set; } = -2;


		public bool ShowTimeInProgressBar { get; set; } = true;


		public float Duration { get; set; } = 0f;


		public List<EventsOnTimerProgress> EventsOnProgress { get; set; } = new List<EventsOnTimerProgress>();


		public WardenObjectiveEventData[] EventsOnDone { get; set; } = Array.Empty<WardenObjectiveEventData>();

	}
	public enum WEE_Type
	{
		CloseSecurityDoor = 10000,
		LockSecurityDoor = 10001,
		SetDoorInteraction = 10002,
		TriggerSecurityDoorAlarm = 10003,
		SolveSecurityDoorAlarm = 10004,
		StartReactor = 10005,
		ModifyReactorWaveState = 10006,
		ForceCompleteReactor = 10007,
		ForceCompleteLevel = 10008,
		ForceFailLevel = 10009,
		Countdown = 10010,
		SetLevelFailCheckEnabled = 10011,
		SetLevelFailWhenAnyPlayerDowned = 10012,
		KillAllPlayers = 10013,
		KillPlayersInZone = 10014,
		SolveSingleObjectiveItem = 10015,
		SetLightDataInZone = 10016,
		AlertEnemiesInZone = 10017,
		CleanupEnemiesInZone = 10018,
		SpawnHibernateInZone = 10019,
		SpawnScoutInZone = 10020,
		SaveCheckpoint = 10021,
		MoveExtractionWorldPosition = 10022,
		SetBlackoutEnabled = 10023,
		AddTerminalCommand = 10024,
		HideTerminalCommand = 10025,
		UnhideTerminalCommand = 10026,
		AddChainPuzzleToSecurityDoor = 10027,
		NestedEvent = 20000,
		StartEventLoop = 20001,
		StopEventLoop = 20002,
		TeleportPlayer = 20003,
		InfectPlayer = 20004,
		DamagePlayer = 20005,
		RevivePlayer = 20006,
		AdjustAWOTimer = 20007,
		Countup = 20008,
		ForceCompleteChainPuzzle = 20009,
		SpawnNavMarker = 20010,
		ShakeScreen = 20011,
		StartPortalMachine = 20012,
		SetSuccessScreen = 20013,
		PlaySubtitles = 20014,
		MultiProgression = 20015,
		PlayWaveRoarSound = 20016,
		CustomHudText = 20017,
		SpecialHudTimer = 20018
	}
}
namespace AWO.Modules.WEE.Events
{
	internal sealed class NestedEvent : BaseEvent
	{
		public override WEE_Type EventType => WEE_Type.NestedEvent;

		protected override void OnSetup()
		{
			LevelEvents.OnLevelBuildDoneLate += PostFactoryDone;
		}

		private void PostFactoryDone()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			int sessionSeed = RundownManager.GetActiveExpeditionData().sessionSeed;
			EntryPoint.SessionSeed = new Random(sessionSeed);
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(12, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("SessionSeed ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(sessionSeed);
			}
			Logger.Info(val);
		}

		protected override void TriggerCommon(WEE_EventData e)
		{
			int maxValue = e.NestedEvent.EventsToActivate.Length;
			List<WardenObjectiveEventData> list;
			if (e.NestedEvent.Type == WEE_NestedEvent.NestedMode.RandomAny)
			{
				list = new List<WardenObjectiveEventData>();
				for (int i = 0; i < e.NestedEvent.MaxRandomEvents && i < e.NestedEvent.EventsToActivate.Length; i++)
				{
					int num;
					do
					{
						num = EntryPoint.SessionSeed.Next(maxValue);
					}
					while (!e.NestedEvent.AllowRepeatsInRandom && list.Contains(e.NestedEvent.EventsToActivate[num]));
					list.Add(e.NestedEvent.EventsToActivate[num]);
				}
			}
			else
			{
				list = new List<WardenObjectiveEventData>(e.NestedEvent.EventsToActivate);
			}
			foreach (WardenObjectiveEventData item in list)
			{
				WorldEventManager.ExecuteEvent(item, 0f);
			}
		}
	}
	internal sealed class StartEventLoop : BaseEvent
	{
		public override WEE_Type EventType => WEE_Type.StartEventLoop;

		protected override void TriggerCommon(WEE_EventData e)
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			if (e.StartEventLoop.LoopDelay < 1f)
			{
				LogError("LoopDelay must be > 1.0 seconds");
				return;
			}
			lock (EntryPoint.ActiveEventLoops)
			{
				bool flag = default(bool);
				if (EntryPoint.ActiveEventLoops.Contains(e.StartEventLoop.LoopIndex))
				{
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(31, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("EventLoop ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(e.StartEventLoop.LoopIndex);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is already active...");
					}
					LogError(val);
					return;
				}
				EntryPoint.ActiveEventLoops.Add(e.StartEventLoop.LoopIndex);
				BepInExDebugLogInterpolatedStringHandler val2 = new BepInExDebugLogInterpolatedStringHandler(26, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Starting EventLoop Index: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(e.StartEventLoop.LoopIndex);
				}
				LogDebug(val2);
				CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DoLoop(e)), (Action)null);
				LevelAPI.OnLevelCleanup += OnLevelCleanup;
			}
		}

		private void OnLevelCleanup()
		{
			Logger.Debug("[StartEventLoop] Cleaning up active EventLoops...");
			EntryPoint.ActiveEventLoops.Clear();
		}

		private static IEnumerator DoLoop(WEE_EventData e)
		{
			WEE_StartEventLoop sel = e.StartEventLoop;
			int repeatNum = 0;
			int repeatMax = sel.LoopCount;
			bool repeatInf = repeatMax == -1;
			int index = sel.LoopIndex;
			int myReloadCount = CheckpointManager.Current.m_stateReplicator.State.reloadCount;
			WaitForSeconds delay = new WaitForSeconds(sel.LoopDelay);
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val;
			for (; repeatNum < repeatMax || repeatInf; repeatNum++)
			{
				lock (EntryPoint.ActiveEventLoops)
				{
					if ((int)GameStateManager.CurrentStateName != 10)
					{
						EntryPoint.ActiveEventLoops.Remove(index);
						yield break;
					}
					if (CheckpointManager.Current.m_stateReplicator.State.reloadCount > myReloadCount)
					{
						EntryPoint.ActiveEventLoops.Remove(index);
						yield break;
					}
					if (!EntryPoint.ActiveEventLoops.Contains(index))
					{
						val = new BepInExDebugLogInterpolatedStringHandler(39, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[StartEventLoop] EventLoop ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(index);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is now done");
						}
						Logger.Debug(val);
						yield break;
					}
				}
				val = new BepInExDebugLogInterpolatedStringHandler(39, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[StartEventLoop] EventLoop ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(index);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" repeating #");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(repeatNum);
				}
				Logger.Debug(val);
				WardenObjectiveEventData[] eventsToActivate = sel.EventsToActivate;
				foreach (WardenObjectiveEventData eventData in eventsToActivate)
				{
					WorldEventManager.ExecuteEvent(eventData, 0f);
				}
				yield return delay;
			}
			val = new BepInExDebugLogInterpolatedStringHandler(39, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[StartEventLoop] EventLoop ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(index);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is now done");
			}
			Logger.Debug(val);
		}
	}
	internal sealed class StopEventLoop : BaseEvent
	{
		public override WEE_Type EventType => WEE_Type.StopEventLoop;

		protected override void TriggerCommon(WEE_EventData e)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			lock (EntryPoint.ActiveEventLoops)
			{
				if (e.Count == -1)
				{
					LogDebug("Stopping all EventLoops...");
					EntryPoint.ActiveEventLoops.Clear();
					return;
				}
				bool flag = default(bool);
				BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(22, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Stopping EventLoop ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(e.Count);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("...");
				}
				LogDebug(val);
				EntryPoint.ActiveEventLoops.Remove(e.Count);
			}
		}
	}
}
namespace AWO.Modules.WEE.Events.World
{
	internal sealed class DamagePlayerEvent : BaseEvent
	{
		public override WEE_Type EventType => WEE_Type.DamagePlayer;

		protected override void TriggerMaster(WEE_EventData e)
		{
			HashSet<int> hashSet = new HashSet<int>(e.DamagePlayer.PlayerFilter.Select((SlotIndex filter) => (int)filter));
			if (!TryGetZone(e, out LG_Zone zone))
			{
				LogError("Cannot find zone!");
				return;
			}
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (!hashSet.Contains(current.PlayerSlotIndex))
				{
					continue;
				}
				AIG_CourseNode courseNode = ((Agent)current).CourseNode;
				if (!((Object)(object)((courseNode != null) ? courseNode.m_zone : null) == (Object)null))
				{
					if (e.DamagePlayer.DamageOverTime && e.Duration > 0f)
					{
						CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DamageOverTime(e, current, zone.ID)), (Action)null);
					}
					else
					{
						ApplyDamage(current, e.DamagePlayer.DamageAmount, e.DamagePlayer.UseZone, zone.ID);
					}
				}
			}
		}

		private static IEnumerator DamageOverTime(WEE_EventData e, PlayerAgent player, int id)
		{
			int reloadCount = CheckpointManager.Current.m_stateReplicator.State.reloadCount;
			float damagePerSecond = e.DamagePlayer.DamageAmount / e.Duration;
			float elapsed = 0f;
			WaitForSeconds delay = new WaitForSeconds(1f);
			while (elapsed <= e.Duration && (int)GameStateManager.CurrentStateName == 10 && CheckpointManager.Current.m_stateReplicator.State.reloadCount <= reloadCount)
			{
				ApplyDamage(player, damagePerSecond, e.DamagePlayer.UseZone, id);
				elapsed += Time.deltaTime;
				yield return delay;
			}
		}

		private static void ApplyDamage(PlayerAgent player, float damage, bool useZone, int id)
		{
			if (!useZone || ((Agent)player).CourseNode.m_zone.ID == id)
			{
				player.Damage.OnIncomingDamage(damage / 4f, 0f, (Agent)null);
			}
		}
	}
	internal sealed class InfectPlayerEvent : BaseEvent
	{
		public override WEE_Type EventType => WEE_Type.InfectPlayer;

		protected override void TriggerMaster(WEE_EventData e)
		{
			HashSet<int> hashSet = new HashSet<int>(e.InfectPlayer.PlayerFilter.Select((SlotIndex filter) => (int)filter));
			if (!TryGetZone(e, out LG_Zone zone))
			{
				LogError("Cannot find zone!");
				return;
			}
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (!hashSet.Contains(current.PlayerSlotIndex) || current.Owner.IsBot)
				{
					continue;
				}
				AIG_CourseNode courseNode = ((Agent)current).CourseNode;
				if (!((Object)(object)((courseNode != null) ? courseNode.m_zone : null) == (Object)null))
				{
					if (e.InfectPlayer.InfectOverTime && e.Duration > 0f)
					{
						CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(InfectOverTime(e, current, zone.ID)), (Action)null);
					}
					else
					{
						ApplyInfection(current, e.InfectPlayer.InfectionAmount, e.InfectPlayer.UseZone, zone.ID);
					}
				}
			}
		}

		private static IEnumerator InfectOverTime(WEE_EventData e, PlayerAgent player, int id)
		{
			int reloadCount = CheckpointManager.Current.m_stateReplicator.State.reloadCount;
			float infectionPerSecond = e.InfectPlayer.InfectionAmount / e.Duration;
			float elapsed = 0f;
			WaitForSeconds delay = new WaitForSeconds(1f);
			while (elapsed <= e.Duration && (int)GameStateManager.CurrentStateName == 10 && CheckpointManager.Current.m_stateReplicator.State.reloadCount <= reloadCount)
			{
				ApplyInfection(player, infectionPerSecond, e.InfectPlayer.UseZone, id);
				elapsed += Time.deltaTime;
				yield return delay;
			}
		}

		private static void ApplyInfection(PlayerAgent player, float infection, bool useZone, int id)
		{
			//IL_0003: 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_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_0028: 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)
			pInfection val = default(pInfection);
			val.amount = infection / 100f;
			val.mode = (pInfectionMode)1;
			val.effect = (pInfectionEffect)0;
			pInfection val2 = val;
			if (!useZone || ((Agent)player).CourseNode.m_zone.ID == id)
			{
				player.Damage.ModifyInfection(val2, true, true);
			}
		}
	}
	internal sealed class KillPlayersInZoneEvent : BaseEvent
	{
		public override WEE_Type EventType => WEE_Type.KillPlayersInZone;

		protected override void TriggerMaster(WEE_EventData e)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGetZone(e, out LG_Zone zone))
			{
				LogError("Cannot find zone!");
				return;
			}
			int iD = zone.ID;
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				AIG_CourseNode courseNode = ((Agent)current).CourseNode;
				if (courseNode != null && !((Object)(object)courseNode.m_zone == (Object)null) && courseNode.m_zone.ID == iD)
				{
					((Dam_SyncedDamageBase)current.Damage).ExplosionDamage(((Dam_SyncedDamageBase)current.Damage).DamageMax, default(Vector3), default(Vector3), 0u);
				}
			}
		}
	}
	internal sealed class PlayWaveDistantRoarEvent : BaseEvent
	{
		public override WEE_Type EventType => WEE_Type.PlayWaveRoarSound;

		protected override void TriggerCommon(WEE_EventData e)
		{
			//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_000c: Expected O, but got Unknown
			//IL_000e: 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_0079: 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_00a5: 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_00d1: 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_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: 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_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			CellSoundPlayer val = new CellSoundPlayer(Vector3.zero);
			val.UpdatePosition(GetSoundPlayerPosition(e.Position, e.SpecialText));
			switch ((byte)e.WaveRoarSound.RoarSound)
			{
			case 0:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.STRIKER);
				break;
			case 1:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.SHOOTER);
				break;
			case 2:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.BIRTHER);
				break;
			case 3:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.SHADOW);
				break;
			case 4:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.TANK);
				break;
			case 5:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.FLYER);
				break;
			case 6:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.IMMORTAL);
				break;
			case 7:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.BULLRUSHER);
				break;
			case 8:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.POUNCER);
				break;
			case 9:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.STRIKER_BERSERK);
				break;
			case 10:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.SHOOTER_SPREAD);
				break;
			}
			switch ((byte)e.WaveRoarSound.RoarSize)
			{
			case 0:
				val.SetSwitch(ROAR_SIZE.GROUP, SWITCH.SMALL);
				break;
			case 1:
				val.SetSwitch(ROAR_SIZE.GROUP, SWITCH.MEDIUM);
				break;
			case 2:
				val.SetSwitch(ROAR_SIZE.GROUP, SWITCH.BIG);
				break;
			}
			val.SetSwitch(ENVIROMENT.GROUP, e.WaveRoarSound.IsOutside ? SWITCH.DESERT : SWITCH.COMPLEX);
			val.Post(EVENTS.PLAY_WAVE_DISTANT_ROAR, true);
			CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(Cleanup(val)), (Action)null);
		}

		private static Vector3 GetSoundPlayerPosition(Vector3 pos, string weObjectFilter)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//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_00a9: 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 (pos != Vector3.zero)
			{
				return pos;
			}
			if (Utility.IsNullOrWhiteSpace(weObjectFilter))
			{
				return Vector3.zero;
			}
			Enumerator<LG_WorldEventObject> enumerator = WorldEventManager.Current.m_worldEventObjects.GetEnumerator();
			while (enumerator.MoveNext())
			{
				LG_WorldEventObject current = enumerator.Current;
				if (((Object)((Component)current).gameObject).name == weObjectFilter)
				{
					return ((Component)current).gameObject.transform.position;
				}
			}
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(65, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PlayWaveDistantRoarEvent] Could not find WorldEventObjectFilter ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(weObjectFilter);
			}
			Logger.Error(val);
			return Vector3.zero;
		}

		private static IEnumerator Cleanup(CellSoundPlayer csPlayer)
		{
			yield return (object)new WaitForSeconds(10f);
			csPlayer.Recycle();
		}
	}
	internal sealed class RevivePlayerEvent : BaseEvent
	{
		public override WEE_Type EventType => WEE_Type.RevivePlayer;

		protected override void TriggerMaster(WEE_EventData e)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			HashSet<int> hashSet = new HashSet<int>(e.RevivePlayer.PlayerFilter.Select((SlotIndex filter) => (int)filter));
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (hashSet.Contains(current.PlayerSlotIndex) && !((Agent)current).Alive)
				{
					AgentReplicatedActions.PlayerReviveAction(current, current, ((Agent)current).Position);
				}
			}
		}
	}
	internal sealed class TeleportPlayerEvent : BaseEvent
	{
		private class TPData
		{
			public SlotIndex SlotIndex { get; set; }

			public Vector3 Position { get; set; }

			public int LookDir { get; set; }

			public eDimensionIndex LastDim { get; set; }

			public Vector3 LastPosition { get; set; }

			public Vector3 LastLookDir { get; set; }

			public List<IWarpableObject> ItemsToWarp { get; set; }

			public TPData(SlotIndex a, Vector3 b, int c, eDimensionIndex d, Vector3 e, Vector3 f, List<IWarpableObject> g)
			{
				//IL_0011: 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)
	

plugins/hirnukuono-EEC_H/ExtraEnemyCustomization.dll

Decompiled 7 hours ago
#define DEBUG
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using AIGraph;
using AK;
using Agents;
using AssetShards;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using CellMenu;
using CullingSystem;
using EEC;
using EEC.API;
using EEC.Configs;
using EEC.Configs.Customizations;
using EEC.CustomAbilities.Bleed;
using EEC.CustomAbilities.Bleed.Handlers;
using EEC.CustomAbilities.Bleed.Inject;
using EEC.CustomAbilities.DrainStamina;
using EEC.CustomAbilities.EMP;
using EEC.CustomAbilities.EMP.Handlers;
using EEC.CustomAbilities.EMP.Inject;
using EEC.CustomAbilities.Explosion;
using EEC.CustomAbilities.Explosion.Handlers;
using EEC.CustomSettings.CustomProjectiles;
using EEC.CustomSettings.CustomScoutWaves;
using EEC.CustomSettings.CustomTentacles;
using EEC.EnemyCustomizations;
using EEC.EnemyCustomizations.Abilities;
using EEC.EnemyCustomizations.Abilities.Handlers;
using EEC.EnemyCustomizations.Abilities.Inject;
using EEC.EnemyCustomizations.Detections;
using EEC.EnemyCustomizations.EnemyAbilities;
using EEC.EnemyCustomizations.EnemyAbilities.Abilities;
using EEC.EnemyCustomizations.EnemyAbilities.Events;
using EEC.EnemyCustomizations.EnemyAbilities.Handlers;
using EEC.EnemyCustomizations.Models;
using EEC.EnemyCustomizations.Models.Handlers;
using EEC.EnemyCustomizations.Properties;
using EEC.EnemyCustomizations.Shared;
using EEC.EnemyCustomizations.Shared.Handlers;
using EEC.EnemyCustomizations.Shooters;
using EEC.EnemyCustomizations.Shooters.Handlers;
using EEC.EnemyCustomizations.Strikers;
using EEC.Events;
using EEC.Managers;
using EEC.Managers.Assets;
using EEC.Managers.Properties;
using EEC.Networking;
using EEC.Networking.Events;
using EEC.Networking.Replicators;
using EEC.Patches.Handlers;
using EEC.Utils;
using EEC.Utils.Integrations;
using EEC.Utils.Json;
using EEC.Utils.Json.Converters;
using EEC.Utils.Json.Elements;
using EEC.Utils.Unity;
using Enemies;
using ExtraEnemyCustomization.EnemyCustomizations.Properties.Inject;
using ExtraEnemyCustomization.Utils.Integrations;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using Gear;
using HarmonyLib;
using IRF;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.InteropTypes.Fields;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using InjectLib.JsonNETInjection.Supports;
using LevelGeneration;
using Localization;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using SemanticVersioning;
using StateMachines;
using TMPro;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Rendering;

[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("ExtraEnemyCustomization")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+gite3cf4af-dirty-master.e3cf4af2ae7be1c49b17fc3a74b48d1151e9a9b5")]
[assembly: AssemblyProduct("ExtraEnemyCustomization")]
[assembly: AssemblyTitle("ExtraEnemyCustomization")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace ExtraEnemyCustomization
{
	[GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "ExtraEnemyCustomization";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "gite3cf4af-dirty-master";

		public const string SemVer = "1.0.0+gite3cf4af-dirty-master";

		public const string GitRevShort = "e3cf4af-dirty";

		public const string GitRevLong = "e3cf4af2ae7be1c49b17fc3a74b48d1151e9a9b5-dirty";

		public const string GitBranch = "master";

		public const string GitTag = "0.8.1";

		public const bool GitIsDirty = true;
	}
}
namespace ExtraEnemyCustomization.Utils.Integrations
{
	public static class InjectLibUtil
	{
		public const string PLUGIN_GUID = "GTFO.InjectLib";

		public static JsonConverter InjectLibConnector { get; private set; }

		public static bool IsLoaded { get; private set; }

		static InjectLibUtil()
		{
			InjectLibConnector = null;
			IsLoaded = false;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("GTFO.InjectLib", out var value))
			{
				return;
			}
			try
			{
				Assembly assembly = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)assembly == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type[] types = assembly.GetTypes();
				Type type = types.First((Type t) => t.Name == "InjectLibConnector");
				if ((object)type == null)
				{
					throw new Exception("Unable to Find InjectLibConnector Class");
				}
				InjectLibConnector = (JsonConverter)Activator.CreateInstance(type);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				Logger.Error($"Exception thrown while reading data from GTFO.AWO: {value2}");
			}
		}
	}
}
namespace ExtraEnemyCustomization.EnemyCustomizations._EnemyEvents
{
	internal interface IEnemySpawn
	{
	}
}
namespace ExtraEnemyCustomization.EnemyCustomizations.Properties.Inject
{
	[HarmonyPatch(typeof(LG_LevelInteractionManager), "DoSetWaveRoarSoundInformation")]
	internal static class Inject_DoSetWaveRoar
	{
		[HarmonyWrapSafe]
		public static bool Prefix(pWaveRoarSettings settings)
		{
			//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_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//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_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_00fe: 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_012a: 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_0156: 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_017c: 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_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			DistantRoarCustom distantRoarCustom = SharedRoarData.Condense(SharedRoarData.Dict.Where<KeyValuePair<uint, SharedRoarData.RoarData>>((KeyValuePair<uint, SharedRoarData.RoarData> entry) => entry.Value.EnemyType == settings.enemyType && entry.Value.IsInWave).ToList());
			if (distantRoarCustom == null)
			{
				return true;
			}
			CellSoundPlayer val = new CellSoundPlayer(Vector3.zero);
			val.UpdatePosition(settings.position);
			bool flag = false;
			CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(Cleanup(val)), (Action)null);
			switch (settings.enemyType)
			{
			case 0:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.STRIKER);
				break;
			case 1:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.SHOOTER);
				break;
			case 2:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.BIRTHER);
				break;
			case 3:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.SHADOW);
				break;
			case 4:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.TANK);
				break;
			case 5:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.FLYER);
				break;
			case 6:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.IMMORTAL);
				break;
			case 7:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.BULLRUSHER);
				break;
			case 8:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.POUNCER);
				break;
			case 9:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.STRIKER_BERSERK);
				break;
			case 10:
				val.SetSwitch(ENEMY_TYPE.GROUP, SWITCH.SHOOTER_SPREAD);
				break;
			case 11:
				return false;
			case 12:
				flag = true;
				break;
			case 13:
				val.Post(distantRoarCustom.SoundID, distantRoarCustom.IsGlobal);
				return false;
			default:
				return true;
			}
			int num = ((distantRoarCustom.RoarSize == RoarSizeOverride.Unchanged) ? ((int)settings.roarSize) : ((int)distantRoarCustom.RoarSize));
			if (flag)
			{
				val.Post((num < 3) ? EVENTS.DISTANT_ROAR_MEDIUM : EVENTS.DISTANT_ROAR_LARGE, distantRoarCustom.IsGlobal);
				return false;
			}
			switch (num)
			{
			case 1:
				val.SetSwitch(ROAR_SIZE.GROUP, SWITCH.SMALL);
				break;
			case 2:
				val.SetSwitch(ROAR_SIZE.GROUP, SWITCH.MEDIUM);
				break;
			case 3:
				val.SetSwitch(ROAR_SIZE.GROUP, SWITCH.BIG);
				break;
			default:
				return true;
			}
			val.SetSwitch(ENVIROMENT.GROUP, distantRoarCustom.IsOutside.GetValue(settings.isOutside) ? SWITCH.DESERT : SWITCH.COMPLEX);
			val.Post(EVENTS.PLAY_WAVE_DISTANT_ROAR, true);
			return false;
		}

		private static IEnumerator Cleanup(CellSoundPlayer csPlayer)
		{
			yield return (object)new WaitForSeconds(10f);
			csPlayer.Recycle();
		}
	}
	[HarmonyPatch]
	internal static class Inject_EnemyGroup
	{
		[HarmonyPatch(typeof(EnemyGroup), "TryGetAKSwitchIDFromEnemyType")]
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		public static bool OverrideSwitchID(ref bool __result, EnemyAgent agent, out uint switchID)
		{
			switchID = 0u;
			if (SharedRoarData.Dict.TryGetValue(((GameDataBlockBase<EnemyDataBlock>)(object)agent.EnemyData).persistentID, out SharedRoarData.RoarData value))
			{
				switchID = value.SwitchID;
				SharedRoarData.Dict[((GameDataBlockBase<EnemyDataBlock>)(object)agent.EnemyData).persistentID].IsInWave = true;
				__result = true;
			}
			return switchID == 0;
		}

		[HarmonyPatch(typeof(EnemyGroup), "GetByteFromEnemyType")]
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		public static bool AppendAKEnemyTypes(ref byte __result, uint enemyType)
		{
			if (enemyType == SWITCH.POUNCER)
			{
				__result = 8;
				return false;
			}
			if (enemyType == SWITCH.STRIKER_BERSERK)
			{
				__result = 9;
				return false;
			}
			if (enemyType == SWITCH.SHOOTER_SPREAD)
			{
				__result = 10;
				return false;
			}
			switch (enemyType)
			{
			case 99900u:
				__result = 11;
				return false;
			case 99901u:
				__result = 12;
				return false;
			case 99902u:
				__result = 13;
				return false;
			default:
				return true;
			}
		}
	}
	internal static class SharedRoarData
	{
		internal class RoarData
		{
			public DistantRoarCustom RoarSettings { get; set; } = new DistantRoarCustom();


			public uint SwitchID { get; set; }

			public byte EnemyType { get; set; }

			public bool IsInWave { get; set; } = false;

		}

		public static Dictionary<uint, RoarData> Dict = new Dictionary<uint, RoarData>();

		public static DistantRoarCustom? Condense(List<KeyValuePair<uint, RoarData>>? filter)
		{
			if (filter == null || !filter.Any())
			{
				return null;
			}
			foreach (KeyValuePair<uint, RoarData> item in filter)
			{
				if (Dict.TryGetValue(item.Key, out RoarData value))
				{
					value.IsInWave = false;
				}
			}
			return filter.OrderByDescending<KeyValuePair<uint, RoarData>, RoarSizeOverride>((KeyValuePair<uint, RoarData> entry) => entry.Value.RoarSettings.RoarSize).FirstOrDefault().Value.RoarSettings;
		}
	}
}
namespace EEC
{
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
	internal sealed class CallConstructorOnLoadAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
	internal sealed class InjectToIl2CppAttribute : Attribute
	{
	}
	public static class Configuration
	{
		public const string SECTION_USER = "1. User-End";

		public const string SECTION_RUNDEVS = "2. Rundown Developer";

		public const string SECTION_LOGGING = "3. Logging";

		public const string SECTION_DEV = "4. DEBUG";

		public const int CONFIG_VERSION = 1;

		private static ConfigEntry<bool> _showMarkerText;

		private static ConfigEntry<bool> _showMarkerDistance;

		private static ConfigEntry<bool> _showExplosionEffect;

		private static ConfigEntry<ShitpostType> _shitpostType;

		private static ConfigEntry<bool> _useLiveEdit;

		private static ConfigEntry<bool> _linkMTFOHotReload;

		private static ConfigEntry<bool> _useDebugLog;

		private static ConfigEntry<bool> _useVerboseLog;

		private static ConfigEntry<AssetCacheManager.OutputType> _assetCacheBehaviour;

		private static ConfigEntry<bool> _dumpConfig;

		private static ConfigEntry<bool> _profiler;

		private static ConfigFile _currentContext;

		public static bool ShowMarkerText { get; private set; }

		public static bool ShowMarkerDistance { get; private set; }

		public static bool ShowExplosionEffect { get; private set; }

		public static ShitpostType ShitpostType { get; private set; }

		public static bool UseLiveEdit { get; private set; }

		public static bool LinkMTFOHotReload { get; private set; }

		public static bool UseDebugLog { get; private set; }

		public static bool UseVerboseLog { get; private set; }

		public static AssetCacheManager.OutputType AssetCacheBehaviour { get; private set; }

		public static bool DumpConfig { get; private set; }

		public static bool Profiler { get; private set; }

		public static bool CanShitpostOf(ShitpostType type)
		{
			switch (ShitpostType)
			{
			case ShitpostType.ForceOff:
				return false;
			case ShitpostType.Enable:
			{
				DateTime now = DateTime.Now;
				return now.Month == 4 && now.Day == 1;
			}
			default:
				return ShitpostType.HasFlag(type);
			}
		}

		public static void CreateAndBindAll()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			string text = Path.Combine(Paths.ConfigPath, "EEC.cfg");
			ConfigFile context = new ConfigFile(text, true);
			ConfigEntry<int> val = BindConfigVersion(context);
			if (val.Value < 1)
			{
				File.Delete(text);
				context = new ConfigFile(text, true);
				BindConfigVersion(context);
			}
			BindAll(context);
		}

		public static void BindAll(ConfigFile context)
		{
			_currentContext = context;
			_showMarkerText = BindUserConfig("Marker Text", "Display Enemy Marker Texts? (if set by rundown devs)", defaultValue: true);
			_showMarkerDistance = BindUserConfig("Marker Distance", "Display Enemy Marker Distance? (if set by rundown devs)", defaultValue: true);
			_showExplosionEffect = BindUserConfig("Explosion Flash", "(Accessibility) Display Light flash effect for explosion abilities?", defaultValue: true);
			_shitpostType = BindUserConfig("Shitposting", "Shitpost mode use comma to enable multiple stuffs", ShitpostType.ForceOff);
			ShowMarkerText = _showMarkerText.Value;
			ShowMarkerDistance = _showMarkerDistance.Value;
			ShowExplosionEffect = _showExplosionEffect.Value;
			ShitpostType = _shitpostType.Value;
			_useLiveEdit = BindRdwDevConfig("Live Edit", "Reload Config when they are edited while in-game", defaultValue: false);
			_linkMTFOHotReload = BindRdwDevConfig("Reload on MTFO HotReload", "Reload Configs when MTFO's HotReload button has pressed?", defaultValue: true);
			UseLiveEdit = _useLiveEdit.Value;
			LinkMTFOHotReload = _linkMTFOHotReload.Value;
			_useDebugLog = BindLoggingConfig("UseDevMessage", "Using Dev Message for Debugging your config?", defaultValue: false);
			_useVerboseLog = BindLoggingConfig("Verbose", "Using Much more detailed Message for Debugging?", defaultValue: false);
			_assetCacheBehaviour = BindLoggingConfig("Cached Asset Result Output", "How does your cached material/texture result be returned?", AssetCacheManager.OutputType.None);
			UseDebugLog = _useDebugLog.Value;
			UseVerboseLog = _useVerboseLog.Value;
			AssetCacheBehaviour = _assetCacheBehaviour.Value;
			_dumpConfig = BindDevConfig("DumpConfig", "Dump Empty Config file?", defaultValue: false);
			_profiler = BindDevConfig("Profiler", "Show Profiler Info for Spawned Event", defaultValue: false);
			DumpConfig = _dumpConfig.Value;
			Profiler = _profiler.Value;
		}

		private static ConfigEntry<int> BindConfigVersion(ConfigFile context)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return context.Bind<int>(new ConfigDefinition("Version", "Config Version"), 1, (ConfigDescription)null);
		}

		private static ConfigEntry<T> BindUserConfig<T>(string name, string description, T defaultValue)
		{
			return BindItem(_currentContext, "1. User-End", name, description, defaultValue);
		}

		private static ConfigEntry<T> BindRdwDevConfig<T>(string name, string description, T defaultValue)
		{
			return BindItem(_currentContext, "2. Rundown Developer", name, description, defaultValue);
		}

		private static ConfigEntry<T> BindLoggingConfig<T>(string name, string description, T defaultValue)
		{
			return BindItem(_currentContext, "3. Logging", name, description, defaultValue);
		}

		private static ConfigEntry<T> BindDevConfig<T>(string name, string description, T defaultValue)
		{
			return BindItem(_currentContext, "4. DEBUG", name, description, defaultValue);
		}

		private static ConfigEntry<T> BindItem<T>(ConfigFile context, string section, string name, string description, T defaultValue)
		{
			//IL_0004: 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_001c: Expected O, but got Unknown
			//IL_001c: Expected O, but got Unknown
			return context.Bind<T>(new ConfigDefinition(section, name), defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[BepInPlugin("GTFO.EECustomization", "EECustom", "1.8.4")]
	[BepInProcess("GTFO.exe")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class EntryPoint : BasePlugin
	{
		public static Harmony HarmonyInstance { get; private set; }

		public static string BasePath { get; private set; }

		public override void Load()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			Configuration.CreateAndBindAll();
			Logger.Initialize();
			ClassInjector.RegisterTypeInIl2Cpp<ShadowCustom.FixEnemySER>();
			ClassInjector.RegisterTypeInIl2Cpp<ShadowCustom.FixShadows>();
			InjectAllIl2CppType();
			CallAllAutoConstructor();
			BasePath = Path.Combine(MTFOUtil.CustomPath, "ExtraEnemyCustomization");
			HarmonyInstance = new Harmony("EEC.Harmony");
			HarmonyInstance.PatchAll();
			NetworkManager.Initialize();
			ConfigManager.Initialize();
			if (Configuration.DumpConfig)
			{
				ConfigManager.DumpDefault();
			}
			AssetEvents.AllAssetLoaded += AllAssetLoaded;
			AssetCacheManager.OutputMethod = Configuration.AssetCacheBehaviour;
		}

		private void AllAssetLoaded()
		{
			SpriteManager.Initialize();
			AssetCacheManager.AssetLoaded();
			ConfigManager.FireAssetLoaded();
			ConfigManager.FirePrefabBuildEventAll(rebuildPrefabs: false);
		}

		public override bool Unload()
		{
			UninjectAllIl2CppType();
			HarmonyInstance.UnpatchSelf();
			ConfigManager.UnloadAllConfig(doClear: true);
			return ((BasePlugin)this).Unload();
		}

		private void InjectAllIl2CppType()
		{
			Logger.Debug("Injecting IL2CPP Types");
			IEnumerable<Type> allHandlers = GetAllHandlers();
			Logger.Debug($" - Count: {allHandlers.Count()}");
			foreach (Type item in allHandlers)
			{
				if (!ClassInjector.IsTypeRegisteredInIl2Cpp(item))
				{
					ClassInjector.RegisterTypeInIl2Cpp(item);
				}
			}
		}

		private void CallAllAutoConstructor()
		{
			Logger.Debug("Calling Necessary Static .ctors");
			IEnumerable<Type> allAutoConstructor = GetAllAutoConstructor();
			Logger.Debug($" - Count: {allAutoConstructor.Count()}");
			foreach (Type item in allAutoConstructor)
			{
				Logger.Debug("calling ctor of: " + item.Name);
				RuntimeHelpers.RunClassConstructor(item.TypeHandle);
			}
		}

		private void UninjectAllIl2CppType()
		{
			Logger.Debug("Uninjecting IL2CPP Types");
			IEnumerable<Type> allHandlers = GetAllHandlers();
			Logger.Debug($" - Count: {allHandlers.Count()}");
			foreach (Type item in allHandlers)
			{
				if (ClassInjector.IsTypeRegisteredInIl2Cpp(item))
				{
				}
			}
		}

		private IEnumerable<Type> GetAllAutoConstructor()
		{
			return from type in ((object)this).GetType().Assembly.GetTypes()
				where type != null && Attribute.IsDefined(type, typeof(CallConstructorOnLoadAttribute))
				select type;
		}

		private IEnumerable<Type> GetAllHandlers()
		{
			return from type in ((object)this).GetType().Assembly.GetTypes()
				where type != null && Attribute.IsDefined(type, typeof(InjectToIl2CppAttribute))
				select type;
		}
	}
	public static class AgentExtension
	{
		public static bool TryCastToEnemyAgent(this Agent agent, out EnemyAgent enemyAgent)
		{
			return TryCast<EnemyAgent>(agent, (AgentType)1, out enemyAgent);
		}

		public static bool TryCastToPlayerAgent(this Agent agent, out PlayerAgent playerAgent)
		{
			return TryCast<PlayerAgent>(agent, (AgentType)0, out playerAgent);
		}

		private static bool TryCast<T>(Agent agent, AgentType type, out T result) where T : Agent
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)agent == (Object)null) && !((Il2CppObjectBase)agent).WasCollected && agent.Type == type)
			{
				T val = ((Il2CppObjectBase)agent).TryCast<T>();
				if (!((Object)(object)val == (Object)null))
				{
					result = val;
					return true;
				}
			}
			result = default(T);
			return false;
		}
	}
	public static class EasingExtension
	{
		public static float Evaluate(this eEasingType easeType, float progress, bool backward = false)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return Easing.GetEasingValue(easeType, progress, backward);
		}

		public static Func<float, float, float, float, float> GetEaseFunction(this eEasingType easeType)
		{
			//IL_0001: 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_005d: Expected I4, but got Unknown
			return (easeType - 1) switch
			{
				0 => Easing.EaseInQuad, 
				1 => Easing.EaseOutQuad, 
				2 => Easing.EaseInOutQuad, 
				3 => Easing.EaseInCubic, 
				4 => Easing.EaseOutCubic, 
				5 => Easing.EaseInOutCubic, 
				6 => Easing.EaseInQuart, 
				7 => Easing.EaseOutQuart, 
				8 => Easing.EaseInOutQuart, 
				9 => Easing.EaseInQuint, 
				10 => Easing.EaseOutQuint, 
				11 => Easing.EaseInOutQuint, 
				12 => Easing.EaseInSine, 
				13 => Easing.EaseOutSine, 
				14 => Easing.EaseInOutSine, 
				15 => Easing.EaseInExpo, 
				16 => Easing.EaseOutExpo, 
				17 => Easing.EaseInOutExpo, 
				18 => Easing.EaseInCirc, 
				19 => Easing.EaseOutCirc, 
				20 => Easing.EaseInOutCirc, 
				_ => Easing.LinearTween, 
			};
		}
	}
	public static class EnemyAgentExtension
	{
		public static void AddOnDeadOnce(this EnemyAgent agent, Action onDead)
		{
			Action onDead2 = onDead;
			bool called = false;
			agent.OnDeadCallback += Action.op_Implicit((Action)delegate
			{
				if (!called)
				{
					onDead2?.Invoke();
					called = true;
				}
			});
		}

		public static T RegisterOrGetProperty<T>(this EnemyAgent agent) where T : class, new()
		{
			return EnemyProperty<T>.RegisterOrGet(agent);
		}

		public static bool TryGetProperty<T>(this EnemyAgent agent, out T property) where T : class, new()
		{
			return EnemyProperty<T>.TryGet(agent, out property);
		}

		public static bool TryGetSpawnData(this EnemyAgent agent, out pEnemySpawnData spawnData)
		{
			return EnemySpawnDataManager.TryGet(((Agent)agent).GlobalID, out spawnData);
		}

		public static bool TryGetEnemyGroup(this EnemyAgent agent, out EnemyGroup group)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (!agent.TryGetSpawnData(out var spawnData))
			{
				group = null;
				return false;
			}
			if (spawnData.groupReplicatorKey == 0)
			{
				group = null;
				return false;
			}
			IReplicator val = default(IReplicator);
			if (!SNet_Replication.TryGetReplicator(spawnData.groupReplicatorKey, ref val))
			{
				group = null;
				return false;
			}
			if (val.ReplicatorSupplier == null)
			{
				group = null;
				return false;
			}
			group = ((Il2CppObjectBase)val.ReplicatorSupplier).TryCast<EnemyGroup>();
			return (Object)(object)group != (Object)null;
		}

		public static AIG_CourseNode GetSpawnedNode(this EnemyAgent agent)
		{
			//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)
			pEnemySpawnData spawnData = ((SNet_DynamicReplicator<pEnemySpawnData>)(object)((Il2CppObjectBase)agent.Sync.Replicator).Cast<EnemyReplicator>()).GetSpawnData();
			AIG_CourseNode result = default(AIG_CourseNode);
			if (!((pCourseNode)(ref spawnData.courseNode)).TryGet(ref result))
			{
				return null;
			}
			return result;
		}
	}
	public static class EnemyDataBlockExtension
	{
		public static bool TryGetBehaviourBlock(this EnemyDataBlock data, out EnemyBehaviorDataBlock behaviour)
		{
			if (data == null)
			{
				behaviour = null;
				return false;
			}
			behaviour = GameDataBlockBase<EnemyBehaviorDataBlock>.GetBlock(data.BehaviorDataId);
			return behaviour != null;
		}

		public static bool TryGetBalancingBlock(this EnemyDataBlock data, out EnemyBalancingDataBlock balancing)
		{
			if (data == null)
			{
				balancing = null;
				return false;
			}
			balancing = GameDataBlockBase<EnemyBalancingDataBlock>.GetBlock(data.BalancingDataId);
			return balancing != null;
		}
	}
	public static class GameObjectExtension
	{
		public static bool TryGetComp<T>(this GameObject obj, out T component)
		{
			component = obj.GetComponent<T>();
			return component != null;
		}

		public static T AddOrGetComponent<T>(this GameObject obj) where T : Component
		{
			if (!obj.TryGetComp<T>(out var component))
			{
				return obj.AddComponent<T>();
			}
			return component;
		}

		public static GameObject FindChild(this GameObject obj, string name, bool includeInactive = false)
		{
			Il2CppArrayBase<Transform> componentsInChildren = obj.GetComponentsInChildren<Transform>(includeInactive);
			foreach (Transform item in componentsInChildren)
			{
				if (((Object)((Component)item).gameObject).name != name)
				{
					continue;
				}
				return ((Component)item).gameObject;
			}
			return null;
		}

		public static GameObject RegexFindChild(this GameObject obj, Regex rx, bool includeInactive = false)
		{
			Il2CppArrayBase<Transform> componentsInChildren = obj.GetComponentsInChildren<Transform>(includeInactive);
			foreach (Transform item in componentsInChildren)
			{
				if (!rx.IsMatch(((Object)item).name))
				{
					continue;
				}
				return ((Component)item).gameObject;
			}
			return null;
		}

		public static GameObject Instantiate(this GameObject obj, Transform toParent, string name)
		{
			//IL_001b: 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)
			GameObject val = Object.Instantiate<GameObject>(obj);
			val.transform.parent = toParent;
			val.transform.localPosition = Vector3.zero;
			val.transform.localRotation = Quaternion.Euler(Vector3.zero);
			((Object)val).name = name;
			return val;
		}
	}
	public static class MonoBehaviourExtension
	{
		public static Coroutine StartCoroutine(this MonoBehaviour self, IEnumerator routine)
		{
			return self.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(routine));
		}
	}
	public static class ProjectileTargetingExtension
	{
		public static bool TryGetOwnerEnemyDataID(this ProjectileBase projectile, out uint id)
		{
			if ((Object)(object)projectile == (Object)null)
			{
				id = 0u;
				return false;
			}
			return ProjectileOwnerManager.TryGetDataID(((Object)((Component)projectile).gameObject).GetInstanceID(), out id);
		}

		public static bool TryGetOwnerEnemyDataID(this ProjectileTargeting projectile, out uint id)
		{
			if ((Object)(object)projectile == (Object)null)
			{
				id = 0u;
				return false;
			}
			return ProjectileOwnerManager.TryGetDataID(((Object)((Component)projectile).gameObject).GetInstanceID(), out id);
		}

		public static bool TryGetOwner(this ProjectileBase projectile, out EnemyAgent agent)
		{
			if ((Object)(object)projectile == (Object)null)
			{
				agent = null;
				return false;
			}
			return ProjectileOwnerManager.TryGet(((Object)((Component)projectile).gameObject).GetInstanceID(), out agent);
		}

		public static bool TryGetOwner(this ProjectileTargeting projectile, out EnemyAgent agent)
		{
			if ((Object)(object)projectile == (Object)null)
			{
				agent = null;
				return false;
			}
			return ProjectileOwnerManager.TryGet(((Object)((Component)projectile).gameObject).GetInstanceID(), out agent);
		}
	}
	public static class StringExtension
	{
		public static bool InvariantEquals(this string str, string strToCompare, bool ignoreCase = false)
		{
			return str.Equals(strToCompare, ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture);
		}

		public static bool InvariantContains(this string str, string strToCompare, bool ignoreCase = false)
		{
			return str.Contains(strToCompare, ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture);
		}

		public static bool InvariantStartsWith(this string str, string strToCompare, bool ignoreCase = false)
		{
			return str.StartsWith(strToCompare, ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture);
		}

		public static bool InvariantEndsWith(this string str, string strToCompare, bool ignoreCase = false)
		{
			return str.EndsWith(strToCompare, ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture);
		}

		public static bool EqualsAnyIgnoreCase(this string input, params string[] args)
		{
			return input.EqualsAny(ignoreCase: true, args);
		}

		public static bool EqualsAny(this string input, bool ignoreCase, params string[] args)
		{
			StringComparison comparisonType = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
			foreach (string value in args)
			{
				if (input.Equals(value, comparisonType))
				{
					return true;
				}
			}
			return false;
		}

		public static bool ContainsAnyIgnoreCase(this string input, params string[] args)
		{
			return input.ContainsAny(ignoreCase: true, args);
		}

		public static bool ContainsAny(this string input, bool ignoreCase, params string[] args)
		{
			StringComparison comparisonType = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
			foreach (string value in args)
			{
				if (input.Contains(value, comparisonType))
				{
					return true;
				}
			}
			return false;
		}
	}
	public static class Logger
	{
		public static ManualLogSource LogInstance { get; private set; }

		public static bool UsingDevMessage { get; private set; }

		public static bool UsingVerbose { get; private set; }

		public static bool DevLogAllowed => UsingDevMessage;

		public static bool VerboseLogAllowed => UsingDevMessage && UsingVerbose;

		internal static void Initialize()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			LogInstance = new ManualLogSource("EEC");
			Logger.Sources.Add((ILogSource)(object)LogInstance);
			UsingDevMessage = Configuration.UseDebugLog;
			UsingVerbose = Configuration.UseVerboseLog;
		}

		public static void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		public static void Log(string str)
		{
			ManualLogSource logInstance = LogInstance;
			if (logInstance != null)
			{
				logInstance.Log((LogLevel)8, (object)str);
			}
		}

		public static void Warning(string format, params object[] args)
		{
			Warning(string.Format(format, args));
		}

		public static void Warning(string str)
		{
			ManualLogSource logInstance = LogInstance;
			if (logInstance != null)
			{
				logInstance.Log((LogLevel)4, (object)str);
			}
		}

		public static void Error(string format, params object[] args)
		{
			Error(string.Format(format, args));
		}

		public static void Error(string str)
		{
			ManualLogSource logInstance = LogInstance;
			if (logInstance != null)
			{
				logInstance.Log((LogLevel)2, (object)str);
			}
		}

		public static void Debug(string format, params object[] args)
		{
			Debug(string.Format(format, args));
		}

		public static void Debug(string str)
		{
			if (UsingDevMessage)
			{
				ManualLogSource logInstance = LogInstance;
				if (logInstance != null)
				{
					logInstance.LogDebug((object)str);
				}
			}
		}

		public static void Verbose(string format, params object[] args)
		{
			Verbose(string.Format(format, args));
		}

		public static void Verbose(string str)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			if (!UsingDevMessage || !UsingVerbose)
			{
				return;
			}
			ManualLogSource logInstance = LogInstance;
			if (logInstance != null)
			{
				bool flag = default(bool);
				BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(10, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(str);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (Verbose)");
				}
				logInstance.LogDebug(val);
			}
		}

		[Conditional("DEBUG")]
		public static void Dev(string format, params object[] args)
		{
			Dev(string.Format(format, args));
		}

		[Conditional("DEBUG")]
		public static void Dev(string str)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			ManualLogSource logInstance = LogInstance;
			if (logInstance != null)
			{
				LogLevel val = (LogLevel)8;
				LogLevel val2 = val;
				bool flag = default(bool);
				BepInExLogInterpolatedStringHandler val3 = new BepInExLogInterpolatedStringHandler(6, 1, val, ref flag);
				if (flag)
				{
					val3.AppendLiteral("[DEV] ");
					val3.AppendFormatted<string>(str);
				}
				logInstance.Log(val2, val3);
			}
		}
	}
}
namespace EEC.Utils
{
	public static class EnemyAnimUtil
	{
		private static readonly Dictionary<EnemyAnimType, int[]> _animHashsLookup;

		private static bool _initialized;

		static EnemyAnimUtil()
		{
			_initialized = false;
			_animHashsLookup = new Dictionary<EnemyAnimType, int[]>(Enum.GetValues(typeof(EnemyAnimType)).Length);
		}

		internal static void Initialize()
		{
			if (!_initialized)
			{
				CacheLookup();
				_initialized = true;
			}
		}

		private static void CacheLookup()
		{
			Type typeFromHandle = typeof(EnemyLocomotion);
			foreach (EnemyAnimType value in Enum.GetValues(typeof(EnemyAnimType)))
			{
				switch (value)
				{
				case EnemyAnimType.Heartbeats:
					_animHashsLookup.Add(value, Il2CppArrayBase<int>.op_Implicit((Il2CppArrayBase<int>)(object)EnemyLocomotion.s_hashHearbeats));
					Logger.Verbose($"{value},  {string.Join(" / ", (IEnumerable<int>)EnemyLocomotion.s_hashHearbeats)}");
					continue;
				case EnemyAnimType.None:
					continue;
				}
				string text = "s_hash" + Enum.GetName(typeof(EnemyAnimType), value);
				PropertyInfo property = typeFromHandle.GetProperty(text, BindingFlags.Static | BindingFlags.Public);
				if (property == null)
				{
					Logger.Warning(text + " does not exist!");
				}
				else if (property.PropertyType == typeof(int))
				{
					_animHashsLookup.Add(value, new int[1] { (int)property.GetValue(null) });
					Logger.Verbose($"{value},  {property.GetValue(null)}");
				}
				else if (property.PropertyType == typeof(Il2CppStructArray<int>))
				{
					int[] array = Il2CppArrayBase<int>.op_Implicit((Il2CppArrayBase<int>)(object)(Il2CppStructArray<int>)property.GetValue(null));
					_animHashsLookup.Add(value, array);
					Logger.Verbose($"{value},  {string.Join(" / ", array)}");
				}
				else
				{
					Logger.Error($"{value} is not a valid hash property!");
				}
			}
		}

		public static void DoAnimationLocal(EnemyAgent agent, EnemyAnimType type, float crossfadeTime, bool pauseAI)
		{
			if (!_initialized)
			{
				Logger.Error("EnemyAnimUtil.DoAnimation was called too fast before it got cached!");
			}
			else
			{
				if (type == EnemyAnimType.None)
				{
					return;
				}
				if (!_animHashsLookup.TryGetValue(type, out int[] value))
				{
					Logger.Error($"Cannot find AnimationHash with: {type}");
					return;
				}
				int num = ((value.Length > 1) ? Rand.IndexOf(value) : 0);
				agent.Locomotion.m_animator.applyRootMotion = true;
				agent.Locomotion.m_animator.CrossFadeInFixedTime(value[num], crossfadeTime);
				if (pauseAI && ((AgentAI)agent.AI).m_navMeshAgent.isOnNavMesh)
				{
					((AgentAI)agent.AI).m_navMeshAgent.isStopped = true;
				}
			}
		}

		public static void DoAnimation(EnemyAgent agent, EnemyAnimType type, float crossfadeTime, bool pauseAI)
		{
			if (!_initialized)
			{
				Logger.Error("EnemyAnimUtil.DoAnimation was called too fast before it got cached!");
			}
			else if (type != 0)
			{
				if (!_animHashsLookup.TryGetValue(type, out int[] value))
				{
					Logger.Error($"Cannot find AnimationHash with: {type}");
					return;
				}
				int num = ((value.Length > 1) ? Rand.IndexOf(value) : 0);
				NetworkManager.EnemyAnim.Send(new EnemyAnimEvent.Packet
				{
					enemyID = ((Agent)agent).GlobalID,
					crossfadeTime = crossfadeTime,
					pauseAI = pauseAI,
					animHash = value[num]
				});
			}
		}
	}
	public enum EnemyAnimType : byte
	{
		None,
		MoveOnGround,
		Forward,
		Right,
		ClimbLadder,
		GiveBirth,
		HitLights_Fwd,
		HitLights_Bwd,
		HitLights_Rt,
		HitLights_Lt,
		HitHeavys_Fwd,
		HitHeavys_Bwd,
		HitHeavys_Rt,
		HitHeavys_Lt,
		Screams,
		ScreamTurns,
		HibernationIn,
		Heartbeats,
		HibernationWakeups,
		HibernationWakeupTurns,
		AbilityFires,
		AbilityUse,
		AbilityUseOut,
		MeleeWalkSequences,
		MeleeSequences,
		Melee180Sequences,
		JumpStart,
		JumpLand
	}
	public static class EnemyProperty<T> where T : class, new()
	{
		private static readonly Dictionary<ushort, T> _properties;

		public static IEnumerable<T> Properties => _properties.Values;

		static EnemyProperty()
		{
			_properties = new Dictionary<ushort, T>();
			EnemyEvents.Despawn += EnemyDespawn;
			LevelEvents.LevelCleanup += OnLevelCleanup;
		}

		private static void EnemyDespawn(EnemyAgent agent)
		{
			_properties.Remove(((Agent)agent).GlobalID);
		}

		private static void OnLevelCleanup()
		{
			_properties.Clear();
		}

		public static T RegisterOrGet(EnemyAgent agent)
		{
			T val = RegisterEnemy(agent);
			if (val != null)
			{
				return val;
			}
			return Get(agent);
		}

		public static T RegisterEnemy(EnemyAgent agent)
		{
			ushort globalID = ((Agent)agent).GlobalID;
			if (_properties.ContainsKey(globalID))
			{
				return null;
			}
			T val = new T();
			_properties.Add(globalID, val);
			return val;
		}

		public static T Get(EnemyAgent agent)
		{
			return Get(((Agent)agent).GlobalID);
		}

		public static T Get(ushort id)
		{
			if (_properties.ContainsKey(id))
			{
				return _properties[id];
			}
			return null;
		}

		public static bool TryGet(EnemyAgent agent, out T property)
		{
			return TryGet(((Agent)agent).GlobalID, out property);
		}

		public static bool TryGet(ushort id, out T property)
		{
			return _properties.TryGetValue(id, out property);
		}
	}
	[Obsolete("Will be moved to ExplosionManager")]
	public static class ExplosionUtil
	{
		public static void MakeExplosion(Vector3 position, float damage, float enemyMulti, float minRange, float maxRange)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			ExplosionData data = default(ExplosionData);
			data.position = position;
			data.damage = damage;
			data.enemyMulti = enemyMulti;
			data.minRange = minRange;
			data.maxRange = maxRange;
			data.lightColor = ExplosionManager.FlashColor;
			ExplosionManager.DoExplosion(data);
		}
	}
	public static class PlayerData
	{
		public static float MaxHealth { get; internal set; } = 25f;


		public static float MaxInfection { get; internal set; } = 1f;

	}
	public static class Rand
	{
		public const int InclusiveDoublePrecision = 10000;

		public const double InclusiveDoubleConversion = 0.0001;

		private static readonly Random _rand = new Random();

		public static Random CreateInstance()
		{
			return new Random(_rand.Next());
		}

		public static T ItemOf<T>(T[] array)
		{
			return array[IndexOf(array)];
		}

		public static int IndexOf(Array array)
		{
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			if (array.Length == 0)
			{
				throw new ArgumentException("Array Length was zero!", "array");
			}
			return _rand.Next(0, array.Length);
		}

		public static int Index(int length)
		{
			return _rand.Next(0, length);
		}

		public static int Range(int min, int max)
		{
			return _rand.Next(min, max);
		}

		public static float Range(float min, float max)
		{
			return NextFloat() * (max - min) + min;
		}

		public static int RangeInclusive(int min, int max)
		{
			return _rand.Next(min, max + 1);
		}

		public static float RangeInclusive(float min, float max)
		{
			return NextFloatInclusive() * (max - min) + min;
		}

		public static float NextFloatInclusive()
		{
			return Math.Clamp((float)NextDoubleInclusive(), 0f, 1f);
		}

		public static double NextDoubleInclusive()
		{
			int num = _rand.Next(0, 10001);
			return Math.Clamp((double)num * 0.0001, 0.0, 1.0);
		}

		public static float NextFloat()
		{
			return (float)_rand.NextDouble();
		}

		public static bool CanDoBy(float chance01)
		{
			return NextFloat() <= chance01;
		}

		public static int NextInt()
		{
			return _rand.Next();
		}
	}
	public static class RegexUtil
	{
		private static readonly Regex _vectorRegex = new Regex("-?[0-9.]+");

		public static bool TryParseVectorString(string input, out float[] vectorArray)
		{
			try
			{
				MatchCollection matchCollection = _vectorRegex.Matches(input);
				int count = matchCollection.Count;
				if (count < 1)
				{
					throw new Exception();
				}
				vectorArray = new float[count];
				for (int i = 0; i < count; i++)
				{
					Match match = matchCollection[i];
					vectorArray[i] = float.Parse(match.Value, CultureInfo.InvariantCulture);
				}
				return true;
			}
			catch
			{
				vectorArray = null;
				return false;
			}
		}
	}
}
namespace EEC.Utils.Unity
{
	[CallConstructorOnLoad]
	public static class InLevelCoroutine
	{
		[InjectToIl2Cpp]
		private sealed class InLevelCoroutineHandler : MonoBehaviour
		{
		}

		private static InLevelCoroutineHandler _handler;

		static InLevelCoroutine()
		{
			AssetEvents.AllAssetLoaded += AssetEvents_AllAssetLoaded;
			LevelEvents.LevelCleanup += LevelEvents_LevelCleanup;
			SNetEvents.PrepareRecall += SNetEvents_PrepareRecall;
		}

		private static void AssetEvents_AllAssetLoaded()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			if ((Object)(object)_handler == (Object)null)
			{
				GameObject val = new GameObject();
				Object.DontDestroyOnLoad((Object)(object)val);
				_handler = val.AddComponent<InLevelCoroutineHandler>();
			}
		}

		private static void SNetEvents_PrepareRecall(eBufferType _)
		{
			StopAll();
		}

		private static void LevelEvents_LevelCleanup()
		{
			StopAll();
		}

		public static Coroutine Start(IEnumerator coroutine)
		{
			if ((Object)(object)_handler != (Object)null && GameStateManager.IsInExpedition)
			{
				return ((MonoBehaviour)_handler).StartCoroutine(CollectionExtensions.WrapToIl2Cpp(coroutine));
			}
			return null;
		}

		public static void Stop(Coroutine coroutine)
		{
			if ((Object)(object)_handler != (Object)null && GameStateManager.IsInExpedition)
			{
				((MonoBehaviour)_handler).StopCoroutine(coroutine);
			}
		}

		public static void StopAll()
		{
			if ((Object)(object)_handler != (Object)null)
			{
				((MonoBehaviour)_handler).StopAllCoroutines();
			}
		}
	}
	public struct LazyTimer
	{
		private float _lastTickTime;

		private float _durationInv;

		public float PassedTime { get; private set; }

		public float Duration { get; private set; }

		public bool Done => Progress >= 1f;

		public float Progress => Mathf.Clamp01(ProgressUnclamped);

		public float ProgressUnclamped
		{
			get
			{
				if (Duration != 0f)
				{
					return PassedTime * _durationInv;
				}
				return 1f;
			}
		}

		public LazyTimer(float duration)
		{
			PassedTime = 0f;
			Duration = duration;
			_durationInv = 1f / duration;
			_lastTickTime = GetTime();
		}

		public void Reset(float newDuration = -1f)
		{
			PassedTime = 0f;
			if (newDuration >= 0f)
			{
				Duration = newDuration;
				_durationInv = 1f / newDuration;
			}
			_lastTickTime = GetTime();
		}

		public void Tick()
		{
			float time = GetTime();
			float num = time - _lastTickTime;
			_lastTickTime = time;
			PassedTime += num;
		}

		public bool TickAndCheckDone()
		{
			Tick();
			return Done;
		}

		private static float GetTime()
		{
			//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_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Invalid comparison between Unknown and I4
			eGameStateName currentStateName = GameStateManager.CurrentStateName;
			if ((int)currentStateName == 10)
			{
				return Clock.ExpeditionProgressionTime;
			}
			return Clock.Time;
		}
	}
	public struct Timer
	{
		private float _durationInv;

		public float PassedTime { get; private set; }

		public float Duration { get; private set; }

		public bool Done => Progress >= 1f;

		public float Progress => Mathf.Clamp01(ProgressUnclamped);

		public float ProgressUnclamped
		{
			get
			{
				if (Duration != 0f)
				{
					return PassedTime * _durationInv;
				}
				return 1f;
			}
		}

		public Timer(float duration)
		{
			PassedTime = 0f;
			Duration = duration;
			_durationInv = 1f / duration;
		}

		public void Reset(float newDuration = -1f)
		{
			PassedTime = 0f;
			if (newDuration >= 0f)
			{
				Duration = newDuration;
				_durationInv = 1f / newDuration;
			}
		}

		public void Tick()
		{
			PassedTime += Time.deltaTime;
		}

		public void Tick(float deltaTime)
		{
			PassedTime += deltaTime;
		}

		public bool TickAndCheckDone()
		{
			Tick();
			return Done;
		}

		public bool TickAndCheckDone(float deltaTime)
		{
			Tick(deltaTime);
			return Done;
		}
	}
	public struct DoubleTimer
	{
		private double _durationInv;

		public double PassedTime { get; private set; }

		public double Duration { get; private set; }

		public bool Done => Progress >= 1.0;

		public double Progress => Math.Clamp(0.0, 1.0, ProgressUnclamped);

		public double ProgressUnclamped
		{
			get
			{
				if (Duration != 0.0)
				{
					return PassedTime * _durationInv;
				}
				return 1.0;
			}
		}

		public DoubleTimer(double duration)
		{
			PassedTime = 0.0;
			Duration = duration;
			_durationInv = 1.0 / duration;
		}

		public void Reset(double newDuration = -1.0)
		{
			PassedTime = 0.0;
			if (newDuration >= 0.0)
			{
				Duration = newDuration;
				_durationInv = 1.0 / newDuration;
			}
		}

		public void Tick()
		{
			PassedTime += Time.deltaTime;
		}

		public bool TickAndCheckDone()
		{
			Tick();
			return Done;
		}
	}
	public static class WaitFor
	{
		public static readonly WaitForEndOfFrame EndOfFrame = new WaitForEndOfFrame();

		public static readonly WaitForFixedUpdate FixedUpdate = new WaitForFixedUpdate();

		public static readonly WaitForSecondsCollection Seconds = new WaitForSecondsCollection();

		public static readonly WaitForSecondsRealtimeCollection SecondsRealtime = new WaitForSecondsRealtimeCollection();
	}
	public sealed class WaitForSecondsCollection : WaitForCollection<WaitForSeconds>
	{
		protected override WaitForSeconds CreateInstance(float time)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			return new WaitForSeconds(time);
		}
	}
	public sealed class WaitForSecondsRealtimeCollection : WaitForCollection<WaitForSecondsRealtime>
	{
		protected override WaitForSecondsRealtime CreateInstance(float time)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			return new WaitForSecondsRealtime(time);
		}
	}
	public abstract class WaitForCollection<T>
	{
		private readonly Dictionary<int, T> _lookup = new Dictionary<int, T>(100);

		private T _temp;

		public T this[float time]
		{
			get
			{
				int key = ((!(time <= 0f)) ? Mathf.RoundToInt(time * 1000f) : 0);
				if (_lookup.TryGetValue(key, out _temp))
				{
					return _temp;
				}
				_temp = CreateInstance(time);
				_lookup[key] = _temp;
				return _temp;
			}
		}

		protected abstract T CreateInstance(float time);
	}
}
namespace EEC.Utils.Json
{
	public static class JSON
	{
		private static readonly JsonSerializerOptions _setting;

		static JSON()
		{
			_setting = new JsonSerializerOptions
			{
				ReadCommentHandling = JsonCommentHandling.Skip,
				IncludeFields = false,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true,
				IgnoreReadOnlyProperties = true
			};
			_setting.Converters.Add(new ColorConverter());
			_setting.Converters.Add(new LocalizedTextConverter());
			_setting.Converters.Add(new JsonStringEnumConverter());
			_setting.Converters.Add(new Vector2Converter());
			_setting.Converters.Add(new Vector3Converter());
			if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized)
			{
				_setting.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter);
				Logger.Log("PartialData Support Found!");
			}
			if (InjectLibUtil.IsLoaded)
			{
				_setting.Converters.Add(InjectLibUtil.InjectLibConnector);
				Logger.Log("InjectLib found!");
			}
		}

		public static T Deserialize<T>(string json)
		{
			return JsonSerializer.Deserialize<T>(json, _setting);
		}

		public static object Deserialize(Type type, string json)
		{
			return JsonSerializer.Deserialize(json, type, _setting);
		}

		public static string Serialize(object value, Type type)
		{
			return JsonSerializer.Serialize(value, type, _setting);
		}
	}
}
namespace EEC.Utils.Json.Elements
{
	[JsonConverter(typeof(AgentModeTargetConverter))]
	public struct AgentModeTarget
	{
		public static readonly AgentModeTarget All = new AgentModeTarget(AgentModeType.Off | AgentModeType.Hibernate | AgentModeType.Agressive | AgentModeType.Scout | AgentModeType.Patrolling);

		public static readonly AgentModeTarget Scout = new AgentModeTarget(AgentModeType.Scout);

		public static readonly AgentModeTarget Hibernate = new AgentModeTarget(AgentModeType.Hibernate);

		public static readonly AgentModeTarget Agressive = new AgentModeTarget(AgentModeType.Agressive);

		public static readonly AgentModeTarget None = new AgentModeTarget(AgentModeType.None);

		public AgentModeType Mode;

		public AgentModeTarget(AgentModeType modes)
		{
			Mode = modes;
		}

		public bool IsMatch(EnemyAgent agent)
		{
			//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_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected I4, but got Unknown
			if ((Object)(object)agent == (Object)null)
			{
				return false;
			}
			AgentMode mode = ((AgentAI)agent.AI).Mode;
			return (int)mode switch
			{
				0 => Mode.HasFlag(AgentModeType.Off), 
				4 => Mode.HasFlag(AgentModeType.Hibernate), 
				1 => Mode.HasFlag(AgentModeType.Agressive), 
				3 => Mode.HasFlag(AgentModeType.Scout), 
				2 => Mode.HasFlag(AgentModeType.Patrolling), 
				_ => false, 
			};
		}
	}
	[Flags]
	public enum AgentModeType
	{
		None = 0,
		Off = 1,
		Hibernate = 2,
		Agressive = 4,
		Scout = 8,
		Patrolling = 0x10
	}
	public sealed class AgentModeTargetConverter : JsonConverter<AgentModeTarget>
	{
		private static readonly char[] _separators = new char[2] { ',', '|' };

		public override AgentModeTarget Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			switch (reader.TokenType)
			{
			case JsonTokenType.String:
			{
				string @string = reader.GetString();
				string[] array = @string.Split(_separators, StringSplitOptions.RemoveEmptyEntries);
				if (array.Length == 0)
				{
					throw new JsonException("There are no entries in " + @string + "! Are you sure it's in right format?");
				}
				AgentModeType agentModeType = AgentModeType.None;
				string[] array2 = array;
				foreach (string text in array2)
				{
					switch (text.ToLowerInvariant().Trim())
					{
					case "off":
					case "dead":
						agentModeType |= AgentModeType.Off;
						break;
					case "agressive":
					case "combat":
						agentModeType |= AgentModeType.Agressive;
						break;
					case "hibernate":
					case "hibernation":
					case "hibernating":
					case "sleeping":
						agentModeType |= AgentModeType.Hibernate;
						break;
					case "scout":
					case "scoutpatrolling":
						agentModeType |= AgentModeType.Scout;
						break;
					case "patrolling":
						agentModeType |= AgentModeType.Patrolling;
						break;
					}
				}
				return new AgentModeTarget(agentModeType);
			}
			case JsonTokenType.Number:
				Logger.Warning("Found flag number value in AgentModeTarget! : consider changing it to string.");
				return new AgentModeTarget((AgentModeType)reader.GetInt32());
			default:
				throw new JsonException($"Token type: {reader.TokenType} in AgentModeTarget is not supported!");
			}
		}

		public override void Write(Utf8JsonWriter writer, AgentModeTarget value, JsonSerializerOptions options)
		{
			writer.WriteNumberValue((int)value.Mode);
		}
	}
	[JsonConverter(typeof(BoolBaseConverter))]
	public struct BoolBase
	{
		public static readonly BoolBase False = new BoolBase(BoolMode.False);

		public static readonly BoolBase True = new BoolBase(BoolMode.True);

		public static readonly BoolBase Unchanged = new BoolBase(BoolMode.Unchanged);

		public BoolMode Mode;

		public BoolBase(bool mode)
		{
			Mode = (mode ? BoolMode.True : BoolMode.False);
		}

		public BoolBase(BoolMode mode)
		{
			Mode = mode;
		}

		public bool GetValue(bool originalValue)
		{
			switch (Mode)
			{
			case BoolMode.Unchanged:
				return originalValue;
			case BoolMode.True:
				return true;
			case BoolMode.False:
				return false;
			default:
				Logger.Error($"BoolBase.GetValue; Got Unknown Mode: {Mode}!\n{Environment.StackTrace}");
				return originalValue;
			}
		}
	}
	public enum BoolMode
	{
		False,
		True,
		Unchanged
	}
	public sealed class BoolBaseConverter : JsonConverter<BoolBase>
	{
		public override bool HandleNull => false;

		public override bool CanConvert(Type objectType)
		{
			return objectType == typeof(BoolBase);
		}

		public override BoolBase Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			switch (reader.TokenType)
			{
			case JsonTokenType.String:
			{
				string text = reader.GetString().Trim();
				if (text.EqualsAnyIgnoreCase("Unchanged", "Ignore", "Keep", "Original", "KeepOriginal"))
				{
					return BoolBase.Unchanged;
				}
				if (bool.TryParse(text, out var result))
				{
					return new BoolBase(result);
				}
				throw new JsonException("Cannot parse BoolBase string: " + text + "! Are you sure it's in right format?");
			}
			case JsonTokenType.True:
				return BoolBase.True;
			case JsonTokenType.False:
				return BoolBase.False;
			default:
				throw new JsonException($"BoolBaseJson type: {reader.TokenType} is not implemented!");
			}
		}

		public override void Write(Utf8JsonWriter writer, BoolBase value, JsonSerializerOptions options)
		{
			switch (value.Mode)
			{
			case BoolMode.True:
				writer.WriteBooleanValue(value: true);
				break;
			case BoolMode.False:
				writer.WriteBooleanValue(value: false);
				break;
			case BoolMode.Unchanged:
				writer.WriteStringValue("Unchanged");
				break;
			}
			writer.WriteCommentValue("BoolBase");
		}
	}
	public sealed class CurveWrapper : Collection<CurveKeyFrame>
	{
		public const int KEYFRAME_FRAMECOUNT = 20;

		public const float KEYFRAME_PROGRESS_INV = 0.05f;

		public static readonly CurveWrapper Empty = new CurveWrapper();

		private static readonly List<Keyframe> _keys = new List<Keyframe>();

		public bool HasSetting => base.Count >= 2;

		public bool TryBuildCurve(out AnimationCurve curve)
		{
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Expected O, but got Unknown
			//IL_012f: 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_0175: Unknown result type (might be due to invalid IL or missing references)
			if (base.Count < 2)
			{
				curve = null;
				return false;
			}
			CurveKeyFrame[] array = this.OrderBy((CurveKeyFrame x) => x.Time).ToArray();
			_keys.Clear();
			for (int i = 0; i < base.Count - 1; i++)
			{
				CurveKeyFrame curveKeyFrame = array[i];
				CurveKeyFrame curveKeyFrame2 = array[i + 1];
				if (curveKeyFrame.Time > 1f || curveKeyFrame.Time < 0f)
				{
					Logger.Error($"CurveWrapper Time '{curveKeyFrame.Time}' was invalid!, must be range of 0.0 ~ 1.0");
					curve = null;
					return false;
				}
				float num = curveKeyFrame2.Time - curveKeyFrame.Time;
				float num2 = curveKeyFrame2.Value - curveKeyFrame.Value;
				float num3 = num2 / num;
				for (int j = 0; j < 20; j++)
				{
					float num4 = 0.05f * (float)j;
					float time = curveKeyFrame.Time + num * num4;
					float value = curveKeyFrame.Value + num2 * curveKeyFrame.OutEaseType.Evaluate(num4);
					List<Keyframe> keys = _keys;
					Keyframe item = default(Keyframe);
					((Keyframe)(ref item)).time = time;
					((Keyframe)(ref item)).value = value;
					((Keyframe)(ref item)).inTangent = num3;
					((Keyframe)(ref item)).outTangent = num3;
					keys.Add(item);
				}
			}
			curve = new AnimationCurve(_keys.ToArray());
			return true;
		}
	}
	public struct CurveKeyFrame
	{
		public float Time { get; set; }

		public float Value { get; set; }

		public eEasingType OutEaseType { get; set; }
	}
	[JsonConverter(typeof(EventWrapperConverter))]
	public sealed class EventWrapper : IDisposable
	{
		private string _json;

		private WardenObjectiveEventData _cached = null;

		public EventWrapper(string json)
		{
			_json = json;
		}

		public void Cache()
		{
			_cached = InjectLibJSON.Deserialize<WardenObjectiveEventData>(_json, Array.Empty<JsonConverter>());
			_json = string.Empty;
		}

		public WardenObjectiveEventData ToEvent()
		{
			if (_cached == null)
			{
				Cache();
			}
			return _cached;
		}

		public void Dispose()
		{
			_json = null;
			_cached = null;
		}
	}
	internal sealed class EventWrapperConverter : JsonConverter<EventWrapper>
	{
		public override bool HandleNull => false;

		public override EventWrapper Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			if (reader.TokenType == JsonTokenType.StartObject)
			{
				using (JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader))
				{
					return new EventWrapper(jsonDocument.RootElement.ToString());
				}
			}
			throw new JsonException($"{reader.TokenType} is not supported for EventWrapperValue!");
		}

		public override void Write(Utf8JsonWriter writer, EventWrapper value, JsonSerializerOptions options)
		{
		}
	}
	[JsonConverter(typeof(ValueBaseConverter))]
	public struct ValueBase
	{
		public static readonly ValueBase Unchanged = new ValueBase(1f, ValueMode.Rel, fromDefault: true);

		public static readonly ValueBase Zero = new ValueBase(0f, ValueMode.Abs, fromDefault: false);

		public float Value;

		public ValueMode Mode;

		public bool FromDefault;

		public ValueBase(float value = 1f, ValueMode mode = ValueMode.Rel, bool fromDefault = true)
		{
			Value = value;
			Mode = mode;
			FromDefault = fromDefault;
		}

		public float GetAbsValue(float maxValue, float currentValue)
		{
			if (Mode == ValueMode.Rel)
			{
				if (FromDefault)
				{
					return currentValue * Value;
				}
				return maxValue * Value;
			}
			return Value;
		}

		public float GetAbsValue(float baseValue)
		{
			if (Mode == ValueMode.Rel)
			{
				return baseValue * Value;
			}
			return Value;
		}

		public int GetAbsValue(int maxValue, int currentValue)
		{
			return (int)Math.Round(GetAbsValue((float)maxValue, (float)currentValue));
		}

		public int GetAbsValue(int baseValue)
		{
			return (int)Math.Round(GetAbsValue((float)baseValue));
		}

		public override string ToString()
		{
			return $"[Mode: {Mode}, Value: {Value}]";
		}
	}
	public enum ValueMode
	{
		Rel,
		Abs
	}
	public sealed class ValueBaseConverter : JsonConverter<ValueBase>
	{
		public override bool HandleNull => false;

		public override bool CanConvert(Type objectType)
		{
			return objectType == typeof(ValueBase);
		}

		public override ValueBase Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			switch (reader.TokenType)
			{
			case JsonTokenType.Number:
				return new ValueBase(reader.GetSingle(), ValueMode.Abs);
			case JsonTokenType.StartObject:
			{
				ValueBase result3 = default(ValueBase);
				while (reader.Read())
				{
					if (reader.TokenType == JsonTokenType.EndObject)
					{
						return result3;
					}
					if (reader.TokenType != JsonTokenType.PropertyName)
					{
						throw new JsonException("Expected PropertyName token");
					}
					string @string = reader.GetString();
					reader.Read();
					switch (@string.ToLowerInvariant())
					{
					case "value":
						result3.Value = reader.GetSingle();
						break;
					case "mode":
					{
						if (Enum.TryParse<ValueMode>(reader.GetString(), out var result4))
						{
							result3.Mode = result4;
						}
						break;
					}
					case "fromdefault":
						result3.FromDefault = reader.GetBoolean();
						break;
					}
				}
				throw new JsonException("Expected EndObject token");
			}
			case JsonTokenType.String:
			{
				string text = reader.GetString().Trim();
				bool fromDefault = false;
				if (text.EndsWith("of default", StringComparison.OrdinalIgnoreCase))
				{
					fromDefault = true;
					string text2 = text;
					text = text2.Substring(0, text2.Length - 10).TrimEnd();
				}
				if (text.InvariantEndsWith("%"))
				{
					string text2 = text;
					if (float.TryParse(text2.Substring(0, text2.Length - 1).TrimEnd(), NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var result))
					{
						return new ValueBase(result / 100f, ValueMode.Rel, fromDefault);
					}
				}
				else
				{
					if (text.EqualsAnyIgnoreCase("Unchanged", "Ignore", "Keep", "Original", "KeepOriginal"))
					{
						return new ValueBase(1f, ValueMode.Rel, fromDefault: false);
					}
					if (float.TryParse(text, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var result2))
					{
						return new ValueBase(result2, ValueMode.Abs);
					}
				}
				throw new JsonException("Cannot parse ValueBase string: " + text + "! Are you sure it's in right format?");
			}
			default:
				throw new JsonException($"ValueBaseJson type: {reader.TokenType} is not implemented!");
			}
		}

		public override void Write(Utf8JsonWriter writer, ValueBase value, JsonSerializerOptions options)
		{
			switch (value.Mode)
			{
			case ValueMode.Rel:
			{
				if (Mathf.Approximately(value.Value, 1f))
				{
					writer.WriteStringValue("Unchanged");
					break;
				}
				string format = (value.FromDefault ? "{0}% of default" : "{0}%");
				writer.WriteStringValue(string.Format(format, value.Value * 100f));
				break;
			}
			case ValueMode.Abs:
				writer.WriteStringValue(value.Value.ToString());
				break;
			}
			writer.WriteCommentValue("ValueBase");
		}
	}
}
namespace EEC.Utils.Json.Converters
{
	public sealed class ColorConverter : JsonConverter<Color>
	{
		public override bool HandleNull => false;

		public override bool CanConvert(Type objectType)
		{
			return objectType == typeof(Color);
		}

		public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			//IL_0003: 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_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_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: 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)
			Color color = default(Color);
			float result = 1f;
			switch (reader.TokenType)
			{
			case JsonTokenType.StartObject:
				while (reader.Read())
				{
					if (reader.TokenType == JsonTokenType.EndObject)
					{
						return color * result;
					}
					if (reader.TokenType != JsonTokenType.PropertyName)
					{
						throw new JsonException("Expected PropertyName token");
					}
					string @string = reader.GetString();
					reader.Read();
					switch (@string.ToLowerInvariant())
					{
					case "r":
						color.r = reader.GetSingle();
						break;
					case "g":
						color.g = reader.GetSingle();
						break;
					case "b":
						color.b = reader.GetSingle();
						break;
					case "a":
						color.a = reader.GetSingle();
						break;
					case "multiplier":
						result = reader.GetSingle();
						break;
					}
				}
				throw new JsonException("Expected EndObject token");
			case JsonTokenType.String:
			{
				string text = reader.GetString().Trim();
				string[] array = text.Split("*");
				string text2;
				switch (array.Length)
				{
				case 1:
					result = 1f;
					text2 = array[0].Trim();
					break;
				case 2:
					if (!float.TryParse(array[1].Trim(), NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out result))
					{
						throw new JsonException("Color multiplier is not valid number! (*): " + text);
					}
					text2 = array[0].Trim();
					break;
				default:
					throw new JsonException("Color format has more than two Mutiplier (*): " + text);
				}
				if (ColorUtility.TryParseHtmlString(text2, ref color))
				{
					return color * result;
				}
				if (TryParseColor(text, out color))
				{
					return color * result;
				}
				throw new JsonException("Color format is not right: " + text);
			}
			default:
				throw new JsonException($"ColorJson type: {reader.TokenType} is not implemented!");
			}
		}

		private static bool TryParseColor(string input, out Color color)
		{
			//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_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_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)
			if (!RegexUtil.TryParseVectorString(input, out float[] vectorArray))
			{
				color = Color.white;
				return false;
			}
			if (vectorArray.Length < 3)
			{
				color = Color.white;
				return false;
			}
			float num = 1f;
			if (vectorArray.Length > 3)
			{
				num = vectorArray[3];
			}
			color = new Color(vectorArray[0], vectorArray[1], vectorArray[2], num);
			return true;
		}

		public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			writer.WriteStringValue("#" + ColorUtility.ToHtmlStringRGBA(value));
		}
	}
	public sealed class LocalizedTextConverter : JsonConverter<LocalizedText>
	{
		public override bool HandleNull => false;

		public override LocalizedText Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			//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_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//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_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			switch (reader.TokenType)
			{
			case JsonTokenType.String:
			{
				string @string = reader.GetString();
				if (MTFOPartialDataUtil.TryGetId(@string, out var id))
				{
					return new LocalizedText
					{
						Id = id,
						UntranslatedText = null
					};
				}
				return new LocalizedText
				{
					Id = 0u,
					UntranslatedText = @string
				};
			}
			case JsonTokenType.Number:
				return new LocalizedText
				{
					Id = reader.GetUInt32(),
					UntranslatedText = null
				};
			default:
				throw new JsonException($"LocalizedTextJson type: {reader.TokenType} is not implemented!");
			}
		}

		public override void Write(Utf8JsonWriter writer, LocalizedText value, JsonSerializerOptions options)
		{
			JsonSerializer.Serialize<LocalizedText>(writer, value, options);
		}
	}
	public sealed class Vector2Converter : JsonConverter<Vector2>
	{
		public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			//IL_0003: 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_003a: 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_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			Vector2 vector = default(Vector2);
			switch (reader.TokenType)
			{
			case JsonTokenType.StartObject:
				while (reader.Read())
				{
					if (reader.TokenType == JsonTokenType.EndObject)
					{
						return vector;
					}
					if (reader.TokenType != JsonTokenType.PropertyName)
					{
						throw new JsonException("Expected PropertyName token");
					}
					string @string = reader.GetString();
					reader.Read();
					string text2 = @string.ToLowerInvariant();
					string text3 = text2;
					if (!(text3 == "x"))
					{
						if (text3 == "y")
						{
							vector.y = reader.GetSingle();
						}
					}
					else
					{
						vector.x = reader.GetSingle();
					}
				}
				throw new JsonException("Expected EndObject token");
			case JsonTokenType.String:
			{
				string text = reader.GetString().Trim();
				if (TryParseVector2(text, out vector))
				{
					return vector;
				}
				throw new JsonException("Vector2 format is not right: " + text);
			}
			default:
				throw new JsonException($"Vector2Json type: {reader.TokenType} is not implemented!");
			}
		}

		private static bool TryParseVector2(string input, out Vector2 vector)
		{
			//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_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			if (!RegexUtil.TryParseVectorString(input, out float[] vectorArray))
			{
				vector = Vector2.zero;
				return false;
			}
			if (vectorArray.Length < 2)
			{
				vector = Vector2.zero;
				return false;
			}
			vector = new Vector2(vectorArray[0], vectorArray[1]);
			return true;
		}

		public override void Write(Utf8JsonWriter writer, Vector2 value, JsonSerializerOptions options)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			writer.WriteStringValue($"({value.x} {value.y})");
		}
	}
	public sealed class Vector3Converter : JsonConverter<Vector3>
	{
		public override bool HandleNull => false;

		public override Vector3 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			//IL_0003: 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_003a: 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_010a: 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)
			Vector3 vector = default(Vector3);
			switch (reader.TokenType)
			{
			case JsonTokenType.StartObject:
				while (reader.Read())
				{
					if (reader.TokenType == JsonTokenType.EndObject)
					{
						return vector;
					}
					if (reader.TokenType != JsonTokenType.PropertyName)
					{
						throw new JsonException("Expected PropertyName token");
					}
					string @string = reader.GetString();
					reader.Read();
					switch (@string.ToLowerInvariant())
					{
					case "x":
						vector.x = reader.GetSingle();
						break;
					case "y":
						vector.y = reader.GetSingle();
						break;
					case "z":
						vector.z = reader.GetSingle();
						break;
					}
				}
				throw new JsonException("Expected EndObject token");
			case JsonTokenType.String:
			{
				string text = reader.GetString().Trim();
				if (TryParseVector3(text, out vector))
				{
					return vector;
				}
				throw new JsonException("Vector3 format is not right: " + text);
			}
			default:
				throw new JsonException($"Vector3Json type: {reader.TokenType} is not implemented!");
			}
		}

		private static bool TryParseVector3(string input, out Vector3 vector)
		{
			//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_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_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)
			if (!RegexUtil.TryParseVectorString(input, out float[] vectorArray))
			{
				vector = Vector3.zero;
				return false;
			}
			if (vectorArray.Length < 3)
			{
				vector = Vector3.zero;
				return false;
			}
			vector = new Vector3(vectorArray[0], vectorArray[1], vectorArray[2]);
			return true;
		}

		public override void Write(Utf8JsonWriter writer, Vector3 value, JsonSerializerOptions options)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			writer.WriteStringValue($"({value.x} {value.y} {value.z})");
		}
	}
}
namespace EEC.Utils.Integrations
{
	public static class MTFOPartialDataUtil
	{
		public delegate bool TryGetDelegate(string guid, out uint id);

		public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks";

		private static readonly TryGetDelegate _tryGetIDDelegate;

		public static JsonConverter PersistentIDConverter { get; private set; }

		public static JsonConverter LocalizedTextConverter { get; private set; }

		public static bool IsLoaded { get; private set; }

		public static bool Initialized { get; private set; }

		public static string PartialDataPath { get; private set; }

		public static string ConfigPath { get; private set; }

		static MTFOPartialDataUtil()
		{
			PersistentIDConverter = null;
			LocalizedTextConverter = null;
			IsLoaded = false;
			Initialized = false;
			PartialDataPath = string.Empty;
			ConfigPath = string.Empty;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value))
			{
				return;
			}
			try
			{
				Assembly assembly = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)assembly == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type[] types = assembly.GetTypes();
				Type type = types.First((Type t) => t.Name == "PersistentIDConverter");
				if ((object)type == null)
				{
					throw new Exception("Unable to Find PersistentIDConverter Class");
				}
				Type type2 = types.First((Type t) => t.Name == "PartialDataManager");
				if ((object)type2 == null)
				{
					throw new Exception("Unable to Find PartialDataManager Class");
				}
				PropertyInfo property = type2.GetProperty("Initialized", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo property2 = type2.GetProperty("PartialDataPath", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo property3 = type2.GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public);
				if ((object)property == null)
				{
					throw new Exception("Unable to Find Property: Initialized");
				}
				if ((object)property2 == null)
				{
					throw new Exception("Unable to Find Property: PartialDataPath");
				}
				if ((object)property3 == null)
				{
					throw new Exception("Unable to Find Field: ConfigPath");
				}
				Initialized = (bool)property.GetValue(null);
				PartialDataPath = (string)property2.GetValue(null);
				ConfigPath = (string)property3.GetValue(null);
				Type type3 = types.First((Type t) => t.Name == "PersistentIDManager");
				if ((object)type3 == null)
				{
					throw new Exception("Unable to Find PersistentIDManager Class");
				}
				MethodInfo method = type3.GetMethod("TryGetId", BindingFlags.Static | BindingFlags.Public);
				_tryGetIDDelegate = (TryGetDelegate)method.CreateDelegate(typeof(TryGetDelegate));
				PersistentIDConverter = (JsonConverter)Activator.CreateInstance(type);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				Logger.Error($"Exception thrown while reading data from MTFO_Extension_PartialData:\n{value2}");
			}
		}

		public static bool TryGetId(string guid, out uint id)
		{
			if (!IsLoaded)
			{
				id = 0u;
				return false;
			}
			if (!Initialized)
			{
				id = 0u;
				return false;
			}
			if (_tryGetIDDelegate == null)
			{
				id = 0u;
				return false;
			}
			return _tryGetIDDelegate(guid, out id);
		}
	}
	public static class MTFOUtil
	{
		public const string PLUGIN_GUID = "com.dak.MTFO";

		public const BindingFlags PUBLIC_STATIC = BindingFlags.Static | BindingFlags.Public;

		public static readonly Version MTFO_FORBID;

		public static readonly Version MTFO_V5;

		public static string GameDataPath { get; private set; }

		public static string CustomPath { get; private set; }

		public static bool HasCustomContent { get; private set; }

		public static bool IsLoaded { get; private set; }

		public static bool HasHotReload { get; private set; }

		public static FieldInfo HotReloaderField { get; private set; }

		public static event Action HotReloaded;

		static MTFOUtil()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			MTFO_FORBID = new Version("4.2.0", false);
			MTFO_V5 = new Version("4.3.5", false);
			GameDataPath = string.Empty;
			CustomPath = string.Empty;
			HasCustomContent = false;
			IsLoaded = false;
			HasHotReload = false;
			HotReloaderField = null;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var value))
			{
				return;
			}
			Version version = value.Metadata.Version;
			if (version >= MTFO_V5)
			{
				InitMTFO_V5(value);
				return;
			}
			if (version > MTFO_FORBID)
			{
				InitMTFO_V4(value);
				return;
			}
			throw new Exception("You are using unsupported version of MTFO!");
		}

		private static void InitMTFO_V4(PluginInfo info)
		{
			try
			{
				Assembly assembly = ((info == null) ? null : info.Instance?.GetType()?.Assembly) ?? null;
				if ((object)assembly == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type[] types = assembly.GetTypes();
				Type type = types.First((Type t) => t.Name == "ConfigManager");
				if ((object)type == null)
				{
					throw new Exception("Unable to Find ConfigManager Class");
				}
				FieldInfo field = type.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo field2 = type.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo field3 = type.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public);
				if ((object)field == null)
				{
					throw new Exception("Unable to Find Field: GameDataPath");
				}
				if ((object)field2 == null)
				{
					throw new Exception("Unable to Find Field: CustomPath");
				}
				if ((object)field3 == null)
				{
					throw new Exception("Unable to Find Field: HasCustomContent");
				}
				GameDataPath = (string)field.GetValue(null);
				CustomPath = (string)field2.GetValue(null);
				HasCustomContent = (bool)field3.GetValue(null);
				IsLoaded = true;
			}
			catch (Exception value)
			{
				Logger.Error($"Exception thrown while reading path from DataDumper (MTFO V{info.Metadata.Version}): \n{value}");
			}
		}

		private static void InitMTFO_V5(PluginInfo info)
		{
			try
			{
				Assembly assembly = ((info == null) ? null : info.Instance?.GetType()?.Assembly) ?? null;
				if ((object)assembly == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type[] types = assembly.GetTypes();
				Type type = types.First((Type t) => t.Name == "ConfigManager");
				if ((object)type == null)
				{
					throw new Exception("Unable to Find ConfigManager Class");
				}
				FieldInfo field = type.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo field2 = type.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo field3 = type.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo property = type.GetProperty("IsHotReloadEnabled", BindingFlags.Static | BindingFlags.Public);
				if ((object)field == null)
				{
					throw new Exception("Unable to Find Field: GameDataPath");
				}
				if ((object)field2 == null)
				{
					throw new Exception("Unable to Find Field: CustomPath");
				}
				if ((object)field3 == null)
				{
					throw new Exception("Unable to Find Field: HasCustomContent");
				}
				if ((object)field3 == null)
				{
					throw new Exception("Unable to Find Field: HasCustomContent");
				}
				if ((object)property == null)
				{
					throw new Exception("Unable to Find Property: IsHotReloadEnabled");
				}
				GameDataPath = (string)field.GetValue(null);
				CustomPath = (string)field2.GetValue(null);
				HasCustomContent = (bool)field3.GetValue(null);
				HasHotReload = (bool)property.GetValue(null);
				if (HasHotReload)
				{
					Type type2 = types.First((Type t) => t.Name == "HotReloader");
					if ((object)type2 == null)
					{
						throw new Exception("Unable to Find HotReloader Class");
					}
					FieldInfo field4 = type2.GetField("Current", BindingFlags.Static | BindingFlags.Public);
					if ((object)field4 == null)
					{
						throw new Exception("Unable to Find Field: Current");
					}
					HotReloaderField = field4;
				}
				IsLoaded = true;
			}
			catch (Exception value)
			{
				Logger.Error($"Exception thrown while reading metadata from MTFO (V{info.Metadata.Version}): \n{value}");
			}
		}

		internal static void OnHotReloaded(int _)
		{
			MTFOUtil.HotReloaded?.Invoke();
		}
	}
}
namespace EEC.Utils.Integrations.Inject
{
	[HarmonyPatch(typeof(CM_PageRundown_New), "OnEnable")]
	internal static class Inject_CM_PageRundown_New
	{
		private static bool _isInjected;

		[HarmonyWrapSafe]
		internal static void Postfix()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			if (_isInjected)
			{
				return;
			}
			object obj = MTFOUtil.HotReloaderField?.GetValue(null) ?? null;
			if (obj != null)
			{
				FieldInfo field = obj.GetType().GetField("button", BindingFlags.Instance | BindingFlags.NonPublic);
				if ((object)field != null)
				{
					CM_Item val = (CM_Item)field.GetValue(obj);
					val.OnBtnPressCallback += Action<int>.op_Implicit((Action<int>)MTFOUtil.OnHotReloaded);
					_isInjected = true;
				}
			}
		}
	}
}
namespace EEC.Patches
{
	[CallConstructorOnLoad]
	public static class PatchManager
	{
		static PatchManager()
		{
			ConfigManager.EnemyPrefabBuilt += PrefabBuilt;
		}

		private static void PrefabBuilt(EnemyAgent agent, EnemyDataBlock enemyData)
		{
			if (ConfigManager.Global.UsingFlyerStuckCheck && enemyData.TryGetBehaviourBlock(out EnemyBehaviorDataBlock behaviour) && behaviour.IsFlyer)
			{
				FlyerStuckHandler flyerStuckHandler = ((Component)agent).gameObject.AddComponent<FlyerStuckHandler>();
				flyerStuckHandler.Agent.Value = agent;
				Logger.Debug($"Added Flyer Check to {((GameDataBlockBase<EnemyDataBlock>)(object)enemyData).persistentID}");
			}
		}
	}
}
namespace EEC.Patches.Inject
{
	[HarmonyPatch(typeof(Dam_SyncedDamageBase))]
	internal static class Inject_Patch_HealerEnemies
	{
		[HarmonyPatch("TentacleAttackDamage")]
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		internal static bool Pre_TentacleDamage(float dam, Dam_SyncedDamageBase __instance)
		{
			return DoHealer(dam, __instance);
		}

		[HarmonyPatch("MeleeDamage")]
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		internal static bool Pre_PunchDamage(float dam, Dam_SyncedDamageBase __instance)
		{
			return DoHealer(dam, __instance);
		}

		[HarmonyPatch("ExplosionDamage")]
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		internal static bool Pre_ExplosionDamage(float dam, Dam_SyncedDamageBase __instance)
		{
			return DoHealer(dam, __instance);
		}

		[HarmonyPatch("ShooterProjectileDamage")]
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		internal static bool Pre_ShooterProjectileDamage(float dam, Dam_SyncedDamageBase __instance)
		{
			return DoHealer(dam, __instance);
		}

		private static bool DoHealer(float dam, Dam_SyncedDamageBase damBase)
		{
			if (dam >= 0f)
			{
				return true;
			}
			if (SNet.IsMaster)
			{
				float num = Math.Abs(dam);
				damBase.SendSetHealth(Math.Min(damBase.Health + num, damBase.HealthMax));
			}
			return false;
		}
	}
}
namespace EEC.Patches.Handlers
{
	[InjectToIl2Cpp]
	internal sealed class FlyerStuckHandler : MonoBehaviour
	{
		public Il2CppReferenceField<EnemyAgent> Agent;

		public float UpdateInterval = float.MaxValue;

		public int RetryCount = int.MaxValue;

		private EnemyAgent _agent;

		private Vector3 _firstPosition;

		private Vector2 _lastGoalXZ;

		private Timer _timer;

		private int _tryCount = -1;

		private bool _shouldCheck = true;

		private void Start()
		{
			if (!SNet.IsMaster)
			{
				((Behaviour)this).enabled = false;
				return;
			}
			_agent = Il2CppReferenceField<EnemyAgent>.op_Implicit(Agent);
			if ((Object)(object)_agent == (Object)null)
			{
				((Behaviour)this).enabled = false;
				return;
			}
			if (!_agent.EnemyBehaviorData.IsFlyer)
			{
				((Behaviour)this).enabled = false;
				return;
			}
			UpdateInterval = ConfigManager.Global.FlyerStuck_Interval;
			RetryCount = ConfigManager.Global.FlyerStuck_Retry;
		}

		private void FixedUpdate()
		{
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: 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_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_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Invalid comparison between Unknown and I4
			//IL_0196: 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_0083: 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_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)
			if (_shouldCheck)
			{
				if ((int)((AgentAI)_agent.AI).Mode != 1 || !_timer.TickAndCheckDone())
				{
					return;
				}
				_timer.Reset(UpdateInterval);
				if (_tryCount == -1)
				{
					_firstPosition = _agent.Position;
					_tryCount = 0;
				}
				else if (Vector3.Distance(_firstPosition, _agent.Position) < 0.1f)
				{
					_tryCount++;
					if (_tryCount >= RetryCount)
					{
						Logger.Debug("Flyer was stuck in Place!");
						((Agent)_agent).m_replicator.Despawn();
					}
				}
				else
				{
					_shouldCheck = false;
				}
				return;
			}
			Vector3 navmeshAgentGoal = _agent.AI.NavmeshAgentGoal;
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(navmeshAgentGoal.x, navmeshAgentGoal.z);
			Vector2 val2 = val - _lastGoalXZ;
			float sqrMagnitude = ((Vector2)(ref val2)).sqrMagnitude;
			if (sqrMagnitude < 0.1f)
			{
				EB_States val3 = (EB_States)((MachineState<EB_StateBase>)(object)((StateMachine<EB_StateBase>)(object)_agent.AI.m_behaviour).CurrentState).ENUM_ID;
				if ((int)val3 == 5)
				{
					_tryCount = -1;
					_shouldCheck = true;
				}
			}
			else
			{
				_tryCount = -1;
				_shouldCheck = false;
			}
			_lastGoalXZ = val;
		}

		private void OnDestroy()
		{
			Agent = null;
		}
	}
	[Flags]
	public enum ShitpostType
	{
		ForceOff = -1,
		Enable = 0,
		Dinnerbone = 1
	}
}
namespace EEC.Patches.Handlers.Yes.Yes.Yes.Yes
{
	[CallConstructorOnLoad]
	public static class Shitpost2022
	{
		static Shitpost2022()
		{
			if (Configuration.CanShitpostOf(ShitpostType.Dinnerbone))
			{
				EnemyEvents.Spawned += EnemyEvents_Spawned;
			}
		}

		private static void EnemyEvents_Spawned(EnemyAgent agent)
		{
			//IL_00ed: 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)
			NavMarker marker = GuiManager.NavMarkerLayer.PlaceCustomMarker((NavMarkerOption)16, agent.ModelRef.m_markerTagAlign, "<alpha=#44>Dinnerbone", 0f, false);
			marker.SetVisualStates((NavMarkerOption)0, (NavMarkerOption)0, (NavMarkerOption)0, (NavMarkerOption)0);
			marker.m_titleSubObj.SetEnabled(false);
			marker.SetPinEnabled(false);
			((MonoBehaviour)(object)agent.AI).StartCoroutine(UpdateMarker(agent, marker));
			agent.AddOnDeadOnce(delegate
			{
				GuiManager.NavMarkerLayer.RemoveMarker(marker);
			});
			Transform boneTransform = agent.Anim.GetBoneTransform((HumanBodyBones)0);
			if ((Object)(object)boneTransform != (Object)null)
			{
				BoneOffsetHandler boneOffsetHandler = ((Component)boneTransform).gameObject.AddComponent<BoneOffsetHandler>();
				boneOffsetHandler.Animator = Il2CppReferenceField<Animator>.op_Implicit(agent.Anim);
				boneOffsetHandler.RotationOffset = Il2CppValueField<Vector3>.op_Implicit(new Vector3(0f, 180f, 0f));
			}
			else
			{
				agent.MainModelTransform.Rotate(Vector3.forward, 180f);
			}
		}

		private static IEnumerator UpdateMarker(EnemyAgent agent, NavMarker marker)
		{
			WaitForSeconds yielder = WaitFor.Seconds[0.25f];
			bool enabled = false;
			yield return yielder;
			while (((Agent)agent).Alive)
			{
				if ((int)marker.m_currentState == 2)
				{
					Vector3 val = agent.Position - ((Component)CameraManager.GetCurrentCamera()).transform.position;
					float distanceSqr = ((Vector3)(ref val)).sqrMagnitude;
					if (!enabled && distanceSqr <= 64f)
					{
						marker.m_titleSubObj.SetEnabled(true);
						enabled = true;
					}
					else if (enabled && distanceSqr > 64f)
					{
						marker.m_titleSubObj.SetEnabled(false);
						enabled = false;
					}
				}
				else if (enabled)
				{
					marker.m_titleSubObj.SetEnabled(false);
					enabled = false;
				}
				yield return yielder;
			}
		}
	}
}
namespace EEC.Networking
{
	public static class NetworkManager
	{
		public const ulong LOWEST_STEAMID64 = 76561197960265729uL;

		public static EnemyAgentModeReplicator EnemyAgentModeState { get; private set; } = new EnemyAgentModeReplicator();


		public static EnemyHealthInfoReplicator EnemyHealthState { get; private set; } = new EnemyHealthInfoReplicator();


		public static EnemyAnimEvent EnemyAnim { get; private set; } = new EnemyAnimEvent();


		internal static void Initialize()
		{
			EnemyEvents.Spawned += EnemySpawned;
			EnemyEvents.Despawn += EnemyDespawn;
			EnemyAgentModeState.Initialize();
			EnemyHealthState.Initialize();
			EnemyAnim.Setup();
		}

		private static void EnemySpawned(EnemyAgent agent)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			EnemyAgent agent2 = agent;
			if (agent2.TryGetSpawnData(out var spawnData))
			{
				EnemyAgentModeReplicator.State state = default(EnemyAgentModeReplicator.State);
				state.mode = spawnData.mode;
				EnemyAgentModeReplicator.State startState = state;
				EnemyAgentModeState.Register(((Agent)agent2).GlobalID, startState, delegate(EnemyAgentModeReplicator.State newState)
				{
					//IL_0008: Unknown result type (might be due to invalid IL or missing references)
					ConfigManager.FireAgentModeChangedEvent(agent2, newState.mode);
				});
			}
			EnemyHealthInfoReplicator.State state2 = default(EnemyHealthInfoReplicator.State);
			state2.maxHealth = ((Dam_SyncedDamageBase)agent2.Damage).HealthMax;
			state2.health = ((Dam_SyncedDamageBase)agent2.Damage).Health;
			EnemyHealthInfoReplicator.State startState2 = state2;
			EnemyHealthState.Register(((Agent)agent2).GlobalID, startState2, delegate(EnemyHealthInfoReplicator.State newState)
			{
				EnemyDamageEvents.OnHealthUpdated(agent2, newState.maxHealth, newState.health);
			});
			((MonoBehaviour)(object)agent2.AI).StartCoroutine(CheckHealth(agent2));
		}

		private static IEnumerator CheckHealth(EnemyAgent agent)
		{
			WaitForFixedUpdate fixedUpdateYielder = WaitFor.FixedUpdate;
			float health = ((Dam_SyncedDamageBase)agent.Damage).Health;
			while (true)
			{
				if (SNet.IsMaster)
				{
					float newHealth = ((Dam_SyncedDamageBase)agent.Damage).Health;
					if (!Mathf.Approximately(health, newHealth))
					{
						EnemyHealthState.UpdateInfo(agent);
						health = newHealth;
					}
				}
				yield return fixedUpdateYielder;
			}
		}

		private static void EnemyDespawn(EnemyAgent agent)
		{
			EnemyAgentModeState.Deregister(((Agent)agent).GlobalID);
		}
	}
	public delegate void SNetRecallEvent(eBufferType bufferType);
	public delegate void SNetPlayerEvent(SNet_Player player);
	public delegate void SNetPlayerEventWithReason(SNet_Player player, SNet_PlayerEventReason reason);
	public static class SNetEvents
	{
		public static event SNetPlayerEvent AgentSpawned;

		public static event SNetRecallEvent PrepareRecall;

		public static event SNetRecallEvent RecallComplete;

		internal static void OnAgentSpawned(SNet_Player player)
		{
			SNetEvents.AgentSpawned?.Invoke(player);
		}

		internal static void OnPrepareRecall(eBufferType bufferType)
		{
			//IL_000c: Unknown result type (might be due t

plugins/hirnukuono-LGTuner/LGTuner.dll

Decompiled 7 hours ago
using System;
using System.CodeDom.Compiler;
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.Json;
using System.Text.Json.Serialization;
using AIGraph;
using AssetShards;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CullingSystem;
using Expedition;
using FluffyUnderware.DevTools.Extensions;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LGTuner.Configs;
using LGTuner.Manager;
using LGTuner.Utils;
using LGTuner.hirnugeos;
using LevelGeneration;
using LevelGeneration.Core;
using LogUtils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;
using XXHashing;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("LGTuner")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+git8f77ed4-dirty-master.8f77ed4ad58a391ea6fcf250c7111074c5e3cce3")]
[assembly: AssemblyProduct("LGTuner")]
[assembly: AssemblyTitle("LGTuner")]
[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 LGTuner
{
	public static class BuilderInfo
	{
		private static readonly List<Complex> _extraComplexResourceToLoad = new List<Complex>();

		public static IEnumerable<Complex> ExtraComplexResourceToLoad => _extraComplexResourceToLoad;

		public static ComplexResourceSetDataBlock ComplexResourceSet { get; private set; }

		public static int GridSize { get; private set; }

		public static int GridCenter { get; private set; }

		public static int GridZeroOffset { get; private set; }

		public static float AltitudeOffset { get; private set; }

		public static LayoutConfig MainLayer { get; private set; }

		public static LayoutConfig SecondaryLayer { get; private set; }

		public static LayoutConfig ThirdLayer { get; private set; }

		public static LayoutConfig[] DimensionLayer { get; private set; } = Array.Empty<LayoutConfig>();


		internal static void OnResourceSetSelected()
		{
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			ComplexResourceSet = Builder.ComplexResourceSetBlock;
			GridSize = ComplexResourceSet.LevelGenConfig.GridSize;
			GridCenter = GridSize / 2;
			GridZeroOffset = -GridCenter;
			AltitudeOffset = ComplexResourceSet.LevelGenConfig.AltitudeOffset;
			MainLayer = null;
			SecondaryLayer = null;
			ThirdLayer = null;
			DimensionLayer = new LayoutConfig[Enum.GetValues(typeof(eDimensionIndex)).Length];
			_extraComplexResourceToLoad.Clear();
			ExpeditionInTierData activeExpedition = RundownManager.ActiveExpedition;
			if (ConfigManager.TryGetConfig(activeExpedition.LevelLayoutData, out var config))
			{
				MainLayer = config;
			}
			if (activeExpedition.SecondaryLayerEnabled && ConfigManager.TryGetConfig(activeExpedition.SecondaryLayout, out var config2))
			{
				SecondaryLayer = config2;
			}
			if (activeExpedition.ThirdLayerEnabled && ConfigManager.TryGetConfig(activeExpedition.ThirdLayout, out var config3))
			{
				ThirdLayer = config3;
			}
			Enumerator<Dimension> enumerator = Builder.CurrentFloor.m_dimensions.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Dimension current = enumerator.Current;
				if (!current.IsMainDimension && !current.DimensionData.IsStaticDimension)
				{
					LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(current.DimensionData.LevelLayoutData);
					if (block != null && ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out var config4))
					{
						Logger.Info("loysimme dimension ja levellayoutin");
						config4.Reset(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)current.Grid).m_sizeX);
						DimensionLayer[current.DimensionIndex] = config4;
					}
				}
			}
			MainLayer?.Reset(GridSize);
			SecondaryLayer?.Reset(GridSize);
			ThirdLayer?.Reset(GridSize);
			AddExtraShard(MainLayer);
			AddExtraShard(SecondaryLayer);
			AddExtraShard(ThirdLayer);
			Array.ForEach(DimensionLayer, delegate(LayoutConfig x)
			{
				AddExtraShard(x);
			});
		}

		private static void AddExtraShard(LayoutConfig layerConfig)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (layerConfig == null)
			{
				return;
			}
			Complex[] extraComplexResourceToLoad = layerConfig.ExtraComplexResourceToLoad;
			foreach (Complex item in extraComplexResourceToLoad)
			{
				if (!_extraComplexResourceToLoad.Contains(item))
				{
					_extraComplexResourceToLoad.Add(item);
				}
			}
		}

		public static bool TryGetConfig(LG_Zone zone, out LayoutConfig config)
		{
			//IL_0001: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected I4, but got Unknown
			//IL_0116: 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)
			Dimension val = default(Dimension);
			if (!Dimension.GetDimension(zone.DimensionIndex, ref val))
			{
				Logger.Info("dimension getter failed");
				config = null;
				return false;
			}
			if (val.IsMainDimension)
			{
				LG_LayerType type = zone.Layer.m_type;
				switch ((int)type)
				{
				case 0:
					config = MainLayer;
					return MainLayer != null;
				case 1:
					config = SecondaryLayer;
					return SecondaryLayer != null;
				case 2:
					config = ThirdLayer;
					return ThirdLayer != null;
				}
			}
			else if (!val.DimensionData.IsStaticDimension)
			{
				Enumerator<Dimension> enumerator = Builder.CurrentFloor.m_dimensions.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Dimension current = enumerator.Current;
					if (!current.IsMainDimension && !current.DimensionData.IsStaticDimension)
					{
						LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(current.DimensionData.LevelLayoutData);
						if (block != null && ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out var config2))
						{
							Logger.Info("found a dimension + levellayout");
							config2.Reset(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)current.Grid).m_sizeX);
							DimensionLayer[current.DimensionIndex] = config2;
						}
					}
				}
				config = DimensionLayer[zone.DimensionIndex];
				return config != null;
			}
			config = null;
			return false;
		}

		public static GameObject GetRandomPlug(uint seed, int plugHeight, SubComplex subcomplex, bool withGate)
		{
			//IL_002d: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			ComplexResourceSetDataBlock complexResourceSet = ComplexResourceSet;
			return (GameObject)(plugHeight switch
			{
				0 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_straightPlugsWithGates : complexResourceSet.m_straightPlugsNoGates, subcomplex), 
				1 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_singleDropPlugsWithGates : complexResourceSet.m_singleDropPlugsNoGates, subcomplex), 
				2 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_doubleDropPlugsWithGates : complexResourceSet.m_doubleDropPlugsNoGates, subcomplex), 
				_ => null, 
			});
		}

		public static uint GetLayoutIdOfZone(LG_Zone zone)
		{
			//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_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected I4, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			Dimension dimension = zone.Dimension;
			if (dimension.IsMainDimension)
			{
				LG_LayerType type = zone.Layer.m_type;
				ExpeditionInTierData activeExpedition = RundownManager.ActiveExpedition;
				return (int)type switch
				{
					0 => activeExpedition.LevelLayoutData, 
					1 => activeExpedition.SecondaryLayout, 
					2 => activeExpedition.ThirdLayout, 
					_ => throw new NotSupportedException($"LayerType: {type} is not supported!"), 
				};
			}
			return dimension.DimensionData.LevelLayoutData;
		}
	}
	[BepInPlugin("LGTuner", "LGTuner", "1.1.2")]
	[BepInProcess("GTFO.exe")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class EntryPoint : BasePlugin
	{
		public static GameObject hirnuigo;

		public static GameObject hirnuhubgo;

		public static GameObject hirnudeadendgo;

		public static GameObject hirnuhubgengo;

		public static GameObject hirnuhubreactorgo;

		public static GameObject hirnuhubelevatorgo;

		public static GameObject hirnuiareatestgo;

		public static LG_PrefabSpawner hirnulamp;

		public static GameObject hirnulampfixture;

		public static GameObject hirnureactorterminal;

		public static GameObject hirnucargocage;

		public static Material hirnufloormaterial;

		public static Material hirnuwallmaterial;

		public Harmony HarmonyInstance { get; private set; }

		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			HarmonyInstance = new Harmony("LGTuner");
			HarmonyInstance.PatchAll();
			LG_Factory.OnFactoryBuildDone += Action.op_Implicit((Action)Hirnu_materials.OnFactoryBuildDone);
			ConfigManager.Init();
		}
	}
	public static class LGExtensions
	{
		public static bool IsSame(this LG_GridPosition position, LG_GridPosition other)
		{
			//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_000e: 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)
			if (position.x == other.x)
			{
				return position.z == other.z;
			}
			return false;
		}

		public static LG_GridPosition ToNormalGrid(this LG_Tile tile, int gridSize)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return tile.m_shape.m_gridPosition.GetNormal(gridSize);
		}

		public static LG_GridPosition GetNormal(this LG_GridPosition position, int gridSize)
		{
			//IL_003a: 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_0051: 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_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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)
			LG_GridPosition result;
			if (gridSize < 0)
			{
				result = default(LG_GridPosition);
				result.x = position.x + BuilderInfo.GridZeroOffset;
				result.z = position.z + BuilderInfo.GridZeroOffset;
				return result;
			}
			int num = gridSize / 2;
			result = default(LG_GridPosition);
			result.x = position.x - num;
			result.z = position.z - num;
			return result;
		}

		public static Vector3 GetPositionNormal(this LG_Grid grid, int x, int z, int gridSize)
		{
			//IL_0024: 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)
			if (gridSize < 0)
			{
				return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetPosition(x - BuilderInfo.GridZeroOffset, z - BuilderInfo.GridZeroOffset);
			}
			int num = gridSize / 2;
			return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetPosition(x + num, z + num);
		}

		public static int GetGridSize(this Dimension dimension)
		{
			return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)dimension.Grid).m_sizeX;
		}

		public static bool TryGetDimension(this LG_Floor floor, int dimensionIndex, out Dimension dimension)
		{
			if (Enum.IsDefined(typeof(eDimensionIndex), dimensionIndex))
			{
				return floor.GetDimension((eDimensionIndex)dimensionIndex, ref dimension);
			}
			dimension = null;
			return false;
		}

		public static bool TryGetDimension(this LG_Floor floor, eDimensionIndex dimensionIndex, out Dimension dimension)
		{
			//IL_000a: 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)
			if (Enum.IsDefined(typeof(eDimensionIndex), dimensionIndex))
			{
				return floor.GetDimension(dimensionIndex, ref dimension);
			}
			dimension = null;
			return false;
		}
	}
	public static class RandomExtensions
	{
		public static uint NextUint(this Random random)
		{
			int num = random.Next(1073741824);
			uint num2 = (uint)random.Next(4);
			return (uint)(num << 2) | num2;
		}

		public static float NextFloat(this Random random)
		{
			return Mathf.Clamp01((float)random.NextDouble());
		}

		public static int ToSeed(this uint seed)
		{
			return (int)seed;
		}
	}
	internal static class Logger
	{
		private static readonly ManualLogSource _logger;

		static Logger()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			_logger = new ManualLogSource("LGTuner");
			Logger.Sources.Add((ILogSource)(object)_logger);
		}

		private static string Format(object msg)
		{
			return msg.ToString();
		}

		public static void Info(object data)
		{
			_logger.LogMessage((object)Format(data));
		}

		public static void Verbose(object data)
		{
		}

		public static void Debug(object data)
		{
			_logger.LogDebug((object)Format(data));
		}

		public static void Error(object data)
		{
			_logger.LogError((object)Format(data));
		}
	}
	public enum DirectionType
	{
		Unknown,
		Forward,
		Backward,
		Left,
		Right
	}
	public enum RotateType
	{
		None,
		Flip,
		MoveTo_Left,
		MoveTo_Right,
		Towards_Random,
		Towards_Forward,
		Towards_Backward,
		Towards_Left,
		Towards_Right
	}
	public struct LG_PlugInfo
	{
		public static readonly Quaternion NoRotation = Quaternion.AngleAxis(0f, Vector3.up);

		public static readonly Quaternion RightRotation = Quaternion.AngleAxis(90f, Vector3.up);

		public static readonly Quaternion BackwardRotation = Quaternion.AngleAxis(180f, Vector3.up);

		public static readonly Quaternion LeftRotation = Quaternion.AngleAxis(270f, Vector3.up);

		public static readonly Vector3 FrontPlugPosition = Vector3.forward * 32f;

		public static readonly Vector3 BackPlugPosition = Vector3.back * 32f;

		public static readonly Vector3 LeftPlugPosition = Vector3.left * 32f;

		public static readonly Vector3 RightPlugPosition = Vector3.right * 32f;

		public bool IsValid { get; private set; }

		public DirectionType StartDirection { get; private set; }

		public int Count { get; private set; }

		public bool HasFront { get; private set; }

		public bool HasBack { get; private set; }

		public bool HasLeft { get; private set; }

		public bool HasRight { get; private set; }

		public bool TryGetNewRotation(uint seed, RotateType rotate, out Quaternion rotation)
		{
			//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_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)
			DirectionType newDirection = GetNewDirection(seed, StartDirection, rotate);
			if (Count >= 4)
			{
				rotation = GetRotationOfDirection(newDirection);
				return true;
			}
			Logger.Info($"You are rotating {Count} side Geomorph, this could lead to level gen crash!");
			rotation = GetRotationOfDirection(newDirection);
			return true;
		}

		public bool HasPlug(DirectionType direction)
		{
			if (!IsValid)
			{
				return false;
			}
			if (Count >= 4)
			{
				return true;
			}
			return direction switch
			{
				DirectionType.Forward => HasFront, 
				DirectionType.Backward => HasBack, 
				DirectionType.Left => HasLeft, 
				DirectionType.Right => HasRight, 
				_ => false, 
			};
		}

		public static LG_PlugInfo BuildPlugInfo(GameObject geoObject, Quaternion rotation)
		{
			//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_0065: 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_007e: Expected I4, but got Unknown
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)geoObject.GetComponent<LG_Geomorph>() == (Object)null)
			{
				return default(LG_PlugInfo);
			}
			Il2CppArrayBase<LG_Plug> componentsInChildren = geoObject.GetComponentsInChildren<LG_Plug>();
			if (componentsInChildren == null)
			{
				return default(LG_PlugInfo);
			}
			if (componentsInChildren.Length < 1)
			{
				return default(LG_PlugInfo);
			}
			LG_PlugInfo result = default(LG_PlugInfo);
			foreach (LG_Plug item in componentsInChildren)
			{
				LG_PlugDir dir = item.m_dir;
				switch (dir - 2)
				{
				case 0:
					result.HasBack = true;
					result.Count++;
					break;
				case 2:
					result.HasFront = true;
					result.Count++;
					break;
				case 3:
					result.HasLeft = true;
					result.Count++;
					break;
				case 1:
					result.HasRight = true;
					result.Count++;
					break;
				}
			}
			result.IsValid = result.Count > 0;
			float num = Mathf.Round(((Quaternion)(ref rotation)).eulerAngles.y);
			Logger.Verbose($"angle: {num}");
			num = Mathf.Repeat(num, 360f);
			result.StartDirection = Mathf.RoundToInt(num / 90f) switch
			{
				0 => DirectionType.Forward, 
				1 => DirectionType.Right, 
				2 => DirectionType.Backward, 
				3 => DirectionType.Left, 
				_ => DirectionType.Unknown, 
			};
			return result;
		}

		public static DirectionType GetNewDirection(uint seed, DirectionType direction, RotateType rotate)
		{
			if (direction == DirectionType.Unknown)
			{
				return DirectionType.Unknown;
			}
			if (rotate == RotateType.Towards_Random)
			{
				rotate = new Random(seed.ToSeed()).Next(4) switch
				{
					0 => RotateType.Towards_Forward, 
					1 => RotateType.Towards_Backward, 
					2 => RotateType.Towards_Left, 
					3 => RotateType.Towards_Right, 
					_ => throw new IndexOutOfRangeException("Towards_Random: nextIndex was out of range?!"), 
				};
			}
			return rotate switch
			{
				RotateType.None => direction, 
				RotateType.Flip => direction switch
				{
					DirectionType.Forward => DirectionType.Backward, 
					DirectionType.Backward => DirectionType.Forward, 
					DirectionType.Left => DirectionType.Right, 
					DirectionType.Right => DirectionType.Left, 
					_ => throw new ArgumentOutOfRangeException("direction"), 
				}, 
				RotateType.MoveTo_Left => direction switch
				{
					DirectionType.Forward => DirectionType.Left, 
					DirectionType.Backward => DirectionType.Right, 
					DirectionType.Left => DirectionType.Backward, 
					DirectionType.Right => DirectionType.Forward, 
					_ => throw new ArgumentOutOfRangeException("direction"), 
				}, 
				RotateType.MoveTo_Right => direction switch
				{
					DirectionType.Forward => DirectionType.Right, 
					DirectionType.Backward => DirectionType.Left, 
					DirectionType.Left => DirectionType.Forward, 
					DirectionType.Right => DirectionType.Backward, 
					_ => throw new ArgumentOutOfRangeException("direction"), 
				}, 
				RotateType.Towards_Forward => DirectionType.Forward, 
				RotateType.Towards_Backward => DirectionType.Backward, 
				RotateType.Towards_Left => DirectionType.Left, 
				RotateType.Towards_Right => DirectionType.Right, 
				_ => throw new ArgumentOutOfRangeException("direction"), 
			};
		}

		public static Quaternion GetRotationOfDirection(DirectionType direction)
		{
			//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)
			//IL_0027: 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_0032: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			return (Quaternion)(direction switch
			{
				DirectionType.Forward => NoRotation, 
				DirectionType.Backward => BackwardRotation, 
				DirectionType.Left => LeftRotation, 
				DirectionType.Right => RightRotation, 
				_ => throw new ArgumentOutOfRangeException("direction"), 
			});
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "LGTuner";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "git8f77ed4-dirty-master";

		public const string SemVer = "1.0.0+git8f77ed4-dirty-master";

		public const string GitRevShort = "8f77ed4-dirty";

		public const string GitRevLong = "8f77ed4ad58a391ea6fcf250c7111074c5e3cce3-dirty";

		public const string GitBranch = "master";

		public const string GitTag = null;

		public const bool GitIsDirty = true;
	}
}
namespace LGTuner.Utils
{
	internal static class JSON
	{
		private static readonly JsonSerializerOptions _setting;

		static JSON()
		{
			_setting = new JsonSerializerOptions
			{
				ReadCommentHandling = JsonCommentHandling.Skip,
				IncludeFields = false,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true,
				IgnoreReadOnlyProperties = true
			};
			_setting.Converters.Add(new JsonStringEnumConverter());
			if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized)
			{
				_setting.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter);
				Logger.Info("PartialData Support Found!");
			}
		}

		public static T Deserialize<T>(string json)
		{
			return JsonSerializer.Deserialize<T>(json, _setting);
		}

		public static object Deserialize(Type type, string json)
		{
			return JsonSerializer.Deserialize(json, type, _setting);
		}

		public static string Serialize(object value, Type type)
		{
			return JsonSerializer.Serialize(value, type, _setting);
		}
	}
	public static class MTFOPartialDataUtil
	{
		public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks";

		public static JsonConverter PersistentIDConverter { get; private set; }

		public static bool IsLoaded { get; private set; }

		public static bool Initialized { get; private set; }

		public static string PartialDataPath { get; private set; }

		public static string ConfigPath { get; private set; }

		static MTFOPartialDataUtil()
		{
			PersistentIDConverter = null;
			IsLoaded = false;
			Initialized = false;
			PartialDataPath = string.Empty;
			ConfigPath = string.Empty;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type[] types = obj.GetTypes();
				Type type = types.First((Type t) => t.Name == "PersistentIDConverter");
				if ((object)type == null)
				{
					throw new Exception("Unable to Find PersistentIDConverter Class");
				}
				Type obj2 = types.First((Type t) => t.Name == "PartialDataManager") ?? throw new Exception("Unable to Find PartialDataManager Class");
				PropertyInfo property = obj2.GetProperty("Initialized", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo property2 = obj2.GetProperty("PartialDataPath", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo? property3 = obj2.GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public);
				if ((object)property == null)
				{
					throw new Exception("Unable to Find Property: Initialized");
				}
				if ((object)property2 == null)
				{
					throw new Exception("Unable to Find Property: PartialDataPath");
				}
				if ((object)property3 == null)
				{
					throw new Exception("Unable to Find Field: ConfigPath");
				}
				Initialized = (bool)property.GetValue(null);
				PartialDataPath = (string)property2.GetValue(null);
				ConfigPath = (string)property3.GetValue(null);
				PersistentIDConverter = (JsonConverter)Activator.CreateInstance(type);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				Logger.Error($"Exception thrown while reading data from MTFO_Extension_PartialData:\n{value2}");
			}
		}
	}
	public static class MTFOUtil
	{
		public const string PLUGIN_GUID = "com.dak.MTFO";

		public const BindingFlags PUBLIC_STATIC = BindingFlags.Static | BindingFlags.Public;

		public static string GameDataPath { get; private set; }

		public static string CustomPath { get; private set; }

		public static bool HasCustomContent { get; private set; }

		public static bool IsLoaded { get; private set; }

		static MTFOUtil()
		{
			GameDataPath = string.Empty;
			CustomPath = string.Empty;
			HasCustomContent = false;
			IsLoaded = false;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type obj2 = obj.GetTypes().First((Type t) => t.Name == "ConfigManager") ?? throw new Exception("Unable to Find ConfigManager Class");
				FieldInfo field = obj2.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo field2 = obj2.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo? field3 = obj2.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public);
				if ((object)field == null)
				{
					throw new Exception("Unable to Find Field: GameDataPath");
				}
				if ((object)field2 == null)
				{
					throw new Exception("Unable to Find Field: CustomPath");
				}
				if ((object)field3 == null)
				{
					throw new Exception("Unable to Find Field: HasCustomContent");
				}
				GameDataPath = (string)field.GetValue(null);
				CustomPath = (string)field2.GetValue(null);
				HasCustomContent = (bool)field3.GetValue(null);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				Logger.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}");
			}
		}
	}
}
namespace LGTuner.Manager
{
	public static class ConfigManager
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static LiveEditEventHandler <0>__LiveEdit_FileChanged;
		}

		private static readonly List<LayoutConfig> _layouts = new List<LayoutConfig>();

		private static readonly Dictionary<uint, LayoutConfig> _lookup = new Dictionary<uint, LayoutConfig>();

		private static readonly Dictionary<string, LayoutConfig> _fileNameLookup = new Dictionary<string, LayoutConfig>();

		public static IEnumerable<LayoutConfig> Layouts => _layouts;

		public static void Init()
		{
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Expected O, but got Unknown
			if (!MTFOUtil.HasCustomContent)
			{
				return;
			}
			string text = Path.Combine(MTFOUtil.CustomPath, "LGTuner");
			FileInfo[] files = Directory.CreateDirectory(text).GetFiles();
			foreach (FileInfo fileInfo in files)
			{
				string extension = fileInfo.Extension;
				bool flag = extension.Equals(".json", StringComparison.InvariantCultureIgnoreCase);
				bool flag2 = extension.Equals(".jsonc", StringComparison.InvariantCultureIgnoreCase);
				if (flag || flag2)
				{
					LayoutConfig layoutConfig = JSON.Deserialize<LayoutConfig>(File.ReadAllText(fileInfo.FullName));
					if (_lookup.ContainsKey(layoutConfig.LevelLayoutID))
					{
						Logger.Error($"Duplicated ID found!: {fileInfo.Name}, {layoutConfig.LevelLayoutID}");
					}
					else
					{
						_layouts.Add(layoutConfig);
						_lookup.Add(layoutConfig.LevelLayoutID, layoutConfig);
						_fileNameLookup.Add(fileInfo.Name.ToLowerInvariant(), layoutConfig);
					}
				}
			}
			LiveEditListener obj = LiveEdit.CreateListener(text, "*.*", true);
			object obj2 = <>O.<0>__LiveEdit_FileChanged;
			if (obj2 == null)
			{
				LiveEditEventHandler val = LiveEdit_FileChanged;
				<>O.<0>__LiveEdit_FileChanged = val;
				obj2 = (object)val;
			}
			obj.FileChanged += (LiveEditEventHandler)obj2;
			obj.StartListen();
		}

		private static void LiveEdit_FileChanged(LiveEditEventArgs e)
		{
			string key = Path.GetFileName(e.FullPath).ToLowerInvariant();
			string extension = Path.GetExtension(e.FullPath);
			if (!extension.Equals(".json", StringComparison.InvariantCulture) && !extension.Equals(".jsonc", StringComparison.InvariantCulture))
			{
				return;
			}
			Logger.Error($"File Edited: '{key}' '{e.FullPath}'");
			try
			{
				LayoutConfig data = _fileNameLookup[key];
				uint oldID = data.LevelLayoutID;
				LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string json)
				{
					try
					{
						LayoutConfig layoutConfig = JSON.Deserialize<LayoutConfig>(json);
						layoutConfig.LevelLayoutID = oldID;
						_fileNameLookup.Remove(key);
						_lookup.Remove(oldID);
						_layouts.Remove(data);
						_layouts.Add(layoutConfig);
						_lookup.Add(oldID, layoutConfig);
						_fileNameLookup.Add(key, layoutConfig);
					}
					catch (Exception value2)
					{
						Logger.Error($"Error while reading LGTuner Config: {value2}");
					}
				});
			}
			catch (Exception value)
			{
				Logger.Error($"Error while reading LGTuner Config: {value}");
			}
		}

		private static void DumpLevel()
		{
		}

		private static void DumpLayerToConfig()
		{
		}

		public static bool TryGetConfig(uint layoutID, out LayoutConfig config)
		{
			return _lookup.TryGetValue(layoutID, out config);
		}
	}
}
namespace LGTuner.Inject
{
	[HarmonyPatch(typeof(LG_Floor), "CreateDimension")]
	internal static class Inject_CreateDimension
	{
		[HarmonyPrefix]
		private static bool Prefix(LG_Floor __instance, uint seed, eDimensionIndex dimensionIndex, bool arenaDimension, DimensionData dimensionData, Vector3 position, ref int __result, int gridSize = 10, float cellSize = 64f)
		{
			//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_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//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_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			//IL_0387: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_040d: 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_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_052c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0443: 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)
			SubComplex subComplex = Builder.LayerBuildDatas[0].m_zoneBuildDatas[0].SubComplex;
			if ((Object)(object)EntryPoint.hirnuhubelevatorgo != (Object)null)
			{
				EntryPoint.hirnuhubelevatorgo.SetActive(false);
			}
			if (dimensionData.IsStaticDimension)
			{
				return true;
			}
			LayoutConfig config = null;
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(dimensionData.LevelLayoutData);
			ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out config);
			if (config == null)
			{
				return true;
			}
			if (config.TileOverrides.Length == 0)
			{
				return true;
			}
			gridSize = 10;
			cellSize = 64f;
			GameObject val = null;
			XXHashSequence val2 = default(XXHashSequence);
			((XXHashSequence)(ref val2))..ctor(seed, true);
			Vector3 val3 = position - new Vector3(cellSize, 0f, cellSize) * (float)gridSize * 0.5f;
			LG_TileShape val4 = __instance.CreateTileShape((LG_TileShapeType)1, cellSize, ref val3);
			LG_Grid val5 = CellGridBase<LG_Grid, LG_Tile, LG_Cell>.Create(cellSize, val3);
			((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)val5).SetupCells(gridSize, gridSize);
			((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)val5).InititalizeCells();
			int count = __instance.m_dimensions.Count;
			Dimension val6 = new Dimension(val5, dimensionIndex, count, dimensionData, position, arenaDimension);
			DebugLog.LogPrefix((Object)(object)__instance, $"Created Dimension (Index: {dimensionIndex}, gridSize: {gridSize}, cellSize: {cellSize}).");
			val = val6.ResourceData.GetCustomGeomorph(dimensionData.DimensionGeomorph);
			if (block != null && config.TileOverrides[0].X == 0 && config.TileOverrides[0].Z == 0 && !string.IsNullOrEmpty(config.TileOverrides[0].Geomorph))
			{
				bool flag = false;
				if (config.TileOverrides[0].Geomorph == "hirnugeos_elevator")
				{
					Hirnu_hub_elevator.OnFactoryBuildStart(subComplex, dimensionData.IsOutside);
					val = EntryPoint.hirnuhubelevatorgo;
					EntryPoint.hirnuhubelevatorgo.SetActive(false);
					flag = true;
					Logger.Info($" - dim {dimensionIndex} elevator overriden! {((Object)EntryPoint.hirnuhubelevatorgo).name}");
				}
				if (!flag)
				{
					Object loadedAsset = AssetAPI.GetLoadedAsset(config.TileOverrides[0].Geomorph);
					val = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).Cast<GameObject>() : null);
					Logger.Info($" - dim {dimensionIndex} elevator overriden! {((Object)val).name}");
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				DebugLog.LogPrefixError((Object)(object)__instance, $"<b><color=red>NULL ERROR</color></b> Could not get the Dimension Geomorph prefab for dimension {dimensionIndex}, are you using a resource set in the DimensionDataBlock that contains the Dimension Geomorph prefab under the \"Custom Geomorphs_Objective_1x1\" header?");
				__result = count;
				return false;
			}
			LG_FloorTransition val7 = __instance.CreateFloorTransition(((XXHashSequence)(ref val2)).NextSubSeed(), val6, position, Quaternion.identity, val, val6.DimensionData.IsStaticDimension);
			if ((Object)(object)val7 == (Object)null)
			{
				DebugLog.LogPrefixError((Object)(object)__instance, $"<b><color=red>NULL ERROR</color></b> The LG_FloorTransition of dimension {dimensionIndex} was null! Does the dimension prefab have a LG_FloorTransition component on its root?");
				__result = count;
				return false;
			}
			LG_Dimension val8 = ((Component)val7).GetComponent<LG_Dimension>();
			if ((Object)(object)val8 == (Object)null)
			{
				val8 = ((Component)val7).gameObject.AddComponent<LG_Dimension>();
				DebugLog.LogPrefixError((Object)(object)__instance, $"<b><color=red>NULL ERROR</color></b> The dimension {dimensionIndex} had no {typeof(LG_Dimension).Name} component, so added one automatically!");
			}
			val6.DimensionLevel = val8;
			if (val7.m_spawnPoints != null && ((Il2CppArrayBase<Transform>)(object)val7.m_spawnPoints).Length != 0)
			{
				val8.AddSpawnPoints(val7.m_spawnPoints);
			}
			val4.m_gridPosition = new LG_GridPosition(gridSize / 2, gridSize / 2);
			val4.m_type = val7.m_shapeType;
			AIG_GeomorphNodeVolume component = ((Component)val7).GetComponent<AIG_GeomorphNodeVolume>();
			if ((Object)(object)component == (Object)null)
			{
				DebugLog.LogPrefixError((Object)(object)__instance, $"<b><color=red>NULL ERROR</color></b> The Dimension Geomorph for {dimensionIndex} did not have a {typeof(AIG_GeomorphNodeVolume).Name} component on it!");
				__result = count;
				return false;
			}
			((LG_Geomorph)val7).m_nodeVolume = (AIG_NodeVolume)(object)component;
			((AIG_NodeVolume)component).ConstructVoxelNodeVolume();
			((LG_Geomorph)val7).ScanChildrenAreas();
			val6.m_startTile = LG_Tile.Create(val5, val4);
			val6.m_startTile.m_geoRoot = (LG_Geomorph)(object)val7;
			val6.m_startTile.m_geoRoot.m_tile = val6.m_startTile;
			((Component)val7).transform.SetParent(((Component)val6.DimensionRootTemp).transform);
			((LG_Geomorph)val7).m_tile = val6.m_startTile;
			val6.m_startTransition = val7;
			val6.Tiles.Add(val6.m_startTile);
			__instance.m_dimensions.Add(val6);
			__instance.m_indexToDimensionMap[dimensionIndex] = val6;
			__result = count;
			return false;
		}
	}
	[HarmonyPatch(typeof(LG_SetupFloor), "Build")]
	internal static class Inject_SetupFloor
	{
		private static LayoutConfig _configContext;

		[HarmonyPrefix]
		private static bool Prefix(LG_SetupFloor __instance, ref bool __result)
		{
			//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)
			//IL_00b7: 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_01a3: 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_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Expected O, but got Unknown
			LayoutConfig config = null;
			Debug.Log(Object.op_Implicit(Deb.LG("LG_SetupFloor.Build", 0f)));
			GameObject val = null;
			uint num = 0u;
			if (Builder.LayerBuildDatas[0].m_zoneBuildDatas != null && Builder.LayerBuildDatas[0].m_zoneBuildDatas.Count > 0)
			{
				_ = Builder.LayerBuildDatas[0].m_zoneBuildDatas[0].SubComplex;
				num = (uint)Builder.LayerBuildDatas[0].m_zoneBuildDatas[0].SubSeed;
			}
			XXHashSeed seed = __instance.m_rnd.Seed;
			XXHashSequence val2 = default(XXHashSequence);
			((XXHashSequence)(ref val2))..ctor(((XXHashSeed)(ref seed)).SubSeed(num), true);
			ConfigManager.TryGetConfig(RundownManager.ActiveExpedition.LevelLayoutData, out config);
			if (config == null)
			{
				return true;
			}
			LG_GridPosition val3 = default(LG_GridPosition);
			val3.x = 0;
			val3.z = 0;
			if (config.TileOverrides.Length == 0)
			{
				return true;
			}
			if (config.TileOverrides[0].X != 0 || config.TileOverrides[0].Z != 0)
			{
				return true;
			}
			if (!string.IsNullOrEmpty(config.TileOverrides[0].Geomorph))
			{
				bool flag = false;
				if (config.TileOverrides[0].Geomorph == "hirnugeos_elevator")
				{
					Hirnu_hub_elevator.OnFactoryBuildStart((SubComplex)4, IsOutside: false);
					val = EntryPoint.hirnuhubelevatorgo;
					flag = true;
					Logger.Info(" - elevator overriden! " + ((Object)EntryPoint.hirnuhubelevatorgo).name);
				}
				if (!flag)
				{
					Object loadedAsset = AssetAPI.GetLoadedAsset(config.TileOverrides[0].Geomorph);
					val = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).Cast<GameObject>() : null);
					if ((Object)(object)val == (Object)null)
					{
						Logger.Info("LGTuner failed to override elevator!");
						return true;
					}
					Logger.Info(" - elevator overriden! " + ((Object)val).name);
				}
				LG_FloorTransition val4 = GOUtil.SpawnChildAndGetComp<LG_FloorTransition>(val, __instance.m_position, __instance.m_rotation);
				((LG_Geomorph)val4).m_geoPrefab = val;
				((LG_Geomorph)val4).SetupAreas(((XXHashSequence)(ref val2)).NextSubSeed());
				((LG_Geomorph)val4).SetPlaced();
				__instance.m_floor.Setup(((XXHashSequence)(ref val2)).NextSubSeed(), (LG_FloorType)0, Builder.ComplexResourceSetBlock.LevelGenConfig.TransitionDirection, val4);
				for (int i = 0; i < __instance.m_floor.m_dimensions.Count; i++)
				{
					__instance.m_floor.InjectJobs(__instance.m_floor.m_dimensions[i].DimensionIndex);
				}
				LG_Factory.InjectJob((LG_FactoryJob)new LG_BuildFloorJob(__instance.m_floor), (BatchName)7);
				__result = true;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(LG_BuildPlugBaseJob), "SpawnPlug")]
	internal static class Inject_BuildPlug
	{
		private static void Prefix(LG_Plug plug, ref GameObject prefab)
		{
			//IL_0023: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: 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_012a: Expected I4, but got Unknown
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			Logger.Info($"found plug for zone: {((LG_ZoneExpander)plug).m_linksFrom.m_zone.LocalIndex}{((Object)((LG_ZoneExpander)plug).m_linksFrom).name}->{((LG_ZoneExpander)plug).m_linksTo.m_zone.LocalIndex}{((Object)((LG_ZoneExpander)plug).m_linksTo).name}");
			if (!BuilderInfo.TryGetConfig(((LG_ZoneExpander)plug).m_linksFrom.m_zone, out var config))
			{
				return;
			}
			LG_GridPosition normal = ((LG_ZoneExpander)plug).m_linksFrom.m_geomorph.m_tile.m_shape.m_gridPosition.GetNormal(config.GridSize);
			if (!config.TryGetTileData(normal, out var overrideData))
			{
				return;
			}
			ZoneOverrideData zoneData = overrideData.ZoneData;
			if (zoneData != null && zoneData.OverridePlugs && TryGetPlugPrefab(overrideData.ZoneData.GetNextPlug(), out var prefab2))
			{
				Logger.Info(" - Prefab Replaced by Zone OverridePlugs! " + ((Object)prefab2).name);
				prefab = prefab2;
			}
			LG_PlugDir dir = plug.m_dir;
			GameObject prefab3;
			switch (dir - 2)
			{
			case 0:
				if (TryGetPlugPrefab(overrideData.BackwardPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by BackwardPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			case 2:
				if (TryGetPlugPrefab(overrideData.ForwardPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by ForwardPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			case 3:
				if (TryGetPlugPrefab(overrideData.LeftPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by LeftPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			case 1:
				if (TryGetPlugPrefab(overrideData.RightPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by RightPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			}
			if (overrideData.OverridePlugWithNoGateChance)
			{
				Random random = new Random(((LG_ZoneExpander)plug).m_linksFrom.AreaSeed.ToSeed());
				bool withGate = ((LG_ZoneExpander)plug).m_isZoneSource || (!(overrideData.PlugWithNoGateChance >= 1f) && (overrideData.PlugWithNoGateChance <= 0f || random.NextFloat() >= overrideData.PlugWithNoGateChance));
				int dropHeight = GetDropHeight(plug);
				GameObject randomPlug = BuilderInfo.GetRandomPlug(random.NextUint(), dropHeight, GetSubComplexOfPlug(plug), withGate);
				if ((Object)(object)randomPlug == (Object)null)
				{
					Logger.Error($"Plug was null! - Height: {dropHeight}");
				}
				else
				{
					prefab = randomPlug;
				}
			}
		}

		private static SubComplex GetSubComplexOfPlug(LG_Plug plug)
		{
			//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_0013: 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_001b: Unknown result type (might be due to invalid IL or missing references)
			SubComplex result = ((LG_ZoneExpander)plug).m_subComplex;
			if (((LG_ZoneExpander)plug).m_subComplex != ((LG_ZoneExpander)plug.m_pariedWith).m_subComplex)
			{
				result = (SubComplex)8;
			}
			return result;
		}

		private static bool TryGetPlugPrefab(string prefabPath, out GameObject prefab)
		{
			if (string.IsNullOrEmpty(prefabPath))
			{
				prefab = null;
				return false;
			}
			prefab = ((Il2CppObjectBase)AssetAPI.GetLoadedAsset(prefabPath)).Cast<GameObject>();
			return (Object)(object)prefab != (Object)null;
		}

		private static int GetDropHeight(LG_Plug plug)
		{
			//IL_0006: 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)
			return Mathf.RoundToInt(Mathf.Abs(((Component)plug).transform.position.y - ((Component)plug.m_pariedWith).transform.position.y) / BuilderInfo.AltitudeOffset);
		}
	}
	[HarmonyPatch(typeof(LG_BuildPlugJob), "Build")]
	internal class Inject_BuildPlugJob
	{
		[HarmonyWrapSafe]
		private static bool Prefix(LG_BuildPlugJob __instance)
		{
			//IL_0022: 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_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Invalid comparison between Unknown and I4
			//IL_00b6: 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_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_00f5: Expected I4, but got Unknown
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = null;
			LG_Plug plug = __instance.m_plug;
			Logger.Info($"buildplugjob plug in complex {((LG_ZoneExpander)plug).m_subComplex} plug status {((LG_ZoneExpander)plug).ExpanderStatus} plug direction {plug.m_dir} ..");
			if ((int)((LG_ZoneExpander)plug).ExpanderStatus == 1)
			{
				return true;
			}
			if (((LG_ZoneExpander)plug).m_isZoneSource)
			{
				return true;
			}
			if (!BuilderInfo.TryGetConfig(((LG_ZoneExpander)plug).m_linksFrom.m_zone, out var config))
			{
				return true;
			}
			LG_GridPosition normal = ((LG_ZoneExpander)plug).m_linksFrom.m_geomorph.m_tile.m_shape.m_gridPosition.GetNormal(config.GridSize);
			if (!config.TryGetTileData(normal, out var overrideData))
			{
				return true;
			}
			LG_PlugDir dir = plug.m_dir;
			GameObject prefab;
			switch (dir - 2)
			{
			case 0:
				if (TryGetPlugPrefab(overrideData.BackwardPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by BackwardPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			case 2:
				if (TryGetPlugPrefab(overrideData.ForwardPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by ForwardPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			case 3:
				if (TryGetPlugPrefab(overrideData.LeftPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by LeftPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			case 1:
				if (TryGetPlugPrefab(overrideData.RightPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by RightPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			}
			if ((Object)(object)val != (Object)null)
			{
				Logger.Info($"we shall replace a cap going {plug.m_dir}");
				Vector3 position = ((Component)plug).transform.position;
				Quaternion rotation = ((Component)plug).transform.rotation;
				GameObject val2 = Object.Instantiate<GameObject>(val, position, rotation);
				val2.transform.SetParent(((Component)plug).transform, true);
				LG_Factory.FindAndBuildSelectorsAndSpawners(val2, RandomExtensions.NextSubSeed(__instance.m_rnd.Random), false);
				__instance.ProcessDivider(plug, val2, false, RandomExtensions.NextSubSeed(__instance.m_rnd.Random));
				((LG_ZoneExpander)plug).m_wasProcessed = true;
			}
			return true;
		}

		private static bool TryGetPlugPrefab(string prefabPath, out GameObject prefab)
		{
			if (string.IsNullOrEmpty(prefabPath))
			{
				prefab = null;
				return false;
			}
			prefab = ((Il2CppObjectBase)AssetAPI.GetLoadedAsset(prefabPath)).Cast<GameObject>();
			return (Object)(object)prefab != (Object)null;
		}
	}
	[HarmonyPatch(typeof(LG_LevelBuilder), "PlaceRoot")]
	internal static class Inject_BuildGeomorph
	{
		private static LayoutConfig _configContext;

		private static RotateType _nextRotateType;

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("BuildFloor")]
		private static void Post_BuildFloor()
		{
			BuilderInfo.OnResourceSetSelected();
		}

		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch("PlaceRoot")]
		private static void Pre_PlaceRoot(LG_Tile tile, ref GameObject tilePrefab, ref bool forceAlignToVector, ref Vector3 alignVector, LG_Zone zone)
		{
			//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_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_004b: 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_0099: 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_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_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			_configContext = null;
			_nextRotateType = RotateType.None;
			forceAlignToVector = alignVector != Vector3.zero;
			int gridSize = zone.Dimension.GetGridSize();
			LG_GridPosition val = tile.ToNormalGrid(gridSize);
			Logger.Info($"tile info: {val.x} {val.z} {((Object)tilePrefab).name} for {zone.LocalIndex} : {zone.DimensionIndex}");
			if (!BuilderInfo.TryGetConfig(zone, out _configContext))
			{
				return;
			}
			if (!_configContext.TryGetTileData(val, out var overrideData))
			{
				overrideData = _configContext.PopulateTileOverrideForZone(zone, val);
				if (overrideData == null)
				{
					return;
				}
			}
			if (!string.IsNullOrEmpty(overrideData.Geomorph))
			{
				if (overrideData.X == 0 && overrideData.Z == 0)
				{
					return;
				}
				bool flag = false;
				if (overrideData.Geomorph == "hirnugeos_i")
				{
					Hirnu_materials.OnFactoryBuildStart();
					Hirnu_i.OnFactoryBuildStart(zone.m_settings.m_zoneData.SubComplex, zone);
					tilePrefab = EntryPoint.hirnuigo;
					Logger.Info(" - tile overriden! " + ((Object)EntryPoint.hirnuigo).name);
					flag = true;
				}
				if (overrideData.Geomorph == "hirnugeos_hub")
				{
					Hirnu_materials.OnFactoryBuildStart();
					Hirnu_hub.OnFactoryBuildStart(zone.m_settings.m_zoneData.SubComplex, zone);
					tilePrefab = EntryPoint.hirnuhubgo;
					Logger.Info(" - tile overriden! " + ((Object)EntryPoint.hirnuhubgo).name);
					flag = true;
				}
				if (overrideData.Geomorph == "hirnugeos_deadend")
				{
					Hirnu_materials.OnFactoryBuildStart();
					Hirnu_deadend.OnFactoryBuildStart(zone.m_settings.m_zoneData.SubComplex, zone);
					tilePrefab = EntryPoint.hirnudeadendgo;
					Logger.Info(" - tile overriden! " + ((Object)EntryPoint.hirnudeadendgo).name);
					flag = true;
				}
				if (overrideData.Geomorph == "hirnugeos_hub_gencluster")
				{
					Hirnu_materials.OnFactoryBuildStart();
					Hirnu_hub_gencluster.OnFactoryBuildStart(zone.m_settings.m_zoneData.SubComplex, zone);
					tilePrefab = EntryPoint.hirnuhubgengo;
					Logger.Info(" - tile overriden! " + ((Object)EntryPoint.hirnuhubgengo).name);
					flag = true;
				}
				if (overrideData.Geomorph == "hirnugeos_hub_reactor")
				{
					Hirnu_materials.OnFactoryBuildStart();
					Hirnu_hub_reactor.OnFactoryBuildStart(zone.m_settings.m_zoneData.SubComplex, zone);
					tilePrefab = EntryPoint.hirnuhubreactorgo;
					Logger.Info(" - tile overriden! " + ((Object)EntryPoint.hirnuhubreactorgo).name);
					flag = true;
				}
				if (overrideData.Geomorph == "hirnugeos_i_areatest")
				{
					Hirnu_materials.OnFactoryBuildStart();
					Hirnu_i_areatest.OnFactoryBuildStart(zone.m_settings.m_zoneData.SubComplex, zone);
					tilePrefab = EntryPoint.hirnuiareatestgo;
					Logger.Info(" - tile overriden! " + ((Object)EntryPoint.hirnuiareatestgo).name);
					flag = true;
				}
				if (!flag)
				{
					Object loadedAsset = AssetAPI.GetLoadedAsset(overrideData.Geomorph);
					GameObject val2 = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).Cast<GameObject>() : null);
					if ((Object)(object)val2 != (Object)null)
					{
						Logger.Info(" - tile overriden! " + ((Object)val2).name);
						tilePrefab = val2;
					}
				}
			}
			if (overrideData.Rotation != 0)
			{
				_nextRotateType = overrideData.Rotation;
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("GetTilePosition")]
		private static void Post_GetTilePosition(LG_Tile tile, LG_Floor floor, int dimensionIndex, ref Vector3 __result)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			if (_configContext != null && floor.TryGetDimension(dimensionIndex, out var dimension))
			{
				int gridSize = _configContext.GridSize;
				LG_GridPosition val = tile.ToNormalGrid(gridSize);
				if (_configContext.TryGetTileData(val, out var overrideData) && overrideData.OverrideAltitude)
				{
					Vector3 positionNormal = dimension.Grid.GetPositionNormal(val.x, val.z, gridSize);
					positionNormal += new Vector3(0f, (float)overrideData.Altitude * BuilderInfo.AltitudeOffset, 0f);
					__result = positionNormal;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("PlaceRoot")]
		private static void Post_PlaceRoot(LG_Tile tile, LG_Zone zone, LG_Geomorph __result)
		{
			//IL_00bc: 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_00c7: 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_00a2: Unknown result type (might be due to invalid IL or missing references)
			Hirnu_i.OnFactoryBuildDone();
			Hirnu_hub.OnFactoryBuildDone();
			Hirnu_deadend.OnFactoryBuildDone();
			Hirnu_hub_gencluster.OnFactoryBuildDone();
			Hirnu_hub_reactor.OnFactoryBuildDone();
			Hirnu_hub_elevator.OnFactoryBuildDone();
			Hirnu_i_areatest.OnFactoryBuildDone();
			if (_configContext == null)
			{
				return;
			}
			if (_nextRotateType != 0)
			{
				GameObject gameObject = ((Component)__result).gameObject;
				LG_PlugInfo lG_PlugInfo = LG_PlugInfo.BuildPlugInfo(gameObject, gameObject.transform.rotation);
				Logger.Info($" - TRYING ROTATION! PLUG COUNT: {lG_PlugInfo.Count}");
				if (lG_PlugInfo.TryGetNewRotation(zone.m_subSeed, _nextRotateType, out var rotation))
				{
					Logger.Info(" - Done!");
					gameObject.transform.rotation = rotation;
				}
				__result.SetPlaced();
			}
			int gridSize = _configContext.GridSize;
			LG_GridPosition normalGridPosition = tile.ToNormalGrid(gridSize);
			if (!_configContext.TryGetTileData(normalGridPosition, out var overrideData) || !overrideData.OverrideAreaSeeds)
			{
				return;
			}
			if (overrideData.AreaSeeds.Length == ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length)
			{
				int length = ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length;
				for (int i = 0; i < length; i++)
				{
					uint num = overrideData.AreaSeeds[i];
					if (num != 0)
					{
						((Il2CppArrayBase<LG_Area>)(object)__result.m_areas)[i].AreaSeed = num;
						Logger.Info($" - new area seed: {((Il2CppArrayBase<LG_Area>)(object)__result.m_areas)[i].m_navInfo}, {num}");
					}
				}
			}
			else
			{
				Logger.Error($" - Area count and AreaSeeds item count mismatched! (CFG: {overrideData.AreaSeeds.Length} != AREA: {((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length}) Area seed will not be applied!");
			}
		}
	}
	[HarmonyPatch(typeof(LG_LoadComplexDataSetResourcesJob), "Build")]
	internal static class Inject_LoadComplexShard
	{
		private static int _waitingShared;

		private static void Prefix(LG_LoadComplexDataSetResourcesJob __instance)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected I4, but got Unknown
			//IL_0032: 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_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_0040: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.m_loadingStarted)
			{
				return;
			}
			foreach (Complex item in BuilderInfo.ExtraComplexResourceToLoad)
			{
				AssetBundleName val = (AssetBundleName)((int)item switch
				{
					0 => 2, 
					1 => 4, 
					2 => 3, 
					_ => 0, 
				});
				if ((int)val != 0)
				{
					AssetShardManager.LoadAllShardsForBundleAsync(val, Action.op_Implicit((Action)Loaded), 1, (LoadSceneMode)1);
					_waitingShared++;
				}
			}
		}

		private static void Loaded()
		{
			_waitingShared--;
		}

		[HarmonyWrapSafe]
		private static void Postfix(LG_LoadComplexDataSetResourcesJob __instance, ref bool __result)
		{
			if (_waitingShared >= 1)
			{
				__result = false;
			}
		}
	}
}
namespace LGTuner.hirnugeos
{
	public class Hirnu_materials : MonoBehaviour
	{
		public static void OnFactoryBuildDone()
		{
			//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_004c: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Invalid comparison between Unknown and I4
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Invalid comparison between Unknown and I4
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Invalid comparison between Unknown and I4
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			//IL_036a: Invalid comparison between Unknown and I4
			//IL_036c: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Invalid comparison between Unknown and I4
			EntryPoint.hirnufloormaterial = null;
			EntryPoint.hirnuwallmaterial = null;
			List<GameObject> list = new List<GameObject>();
			list.Clear();
			SubComplex subComplex = Builder.LayerBuildDatas[0].m_zoneBuildDatas[0].SubComplex;
			Debug.Log(Object.op_Implicit($"hirnugeos - building materials for {subComplex}"));
			if ((int)subComplex == 0 || (int)subComplex == 1)
			{
				GameObject obj = ((Il2CppObjectBase)AssetAPI.GetLoadedAsset("Assets/AssetPrefabs/Complex/Mining/Geomorphs/geo_32x32_elevator_shaft_dig_site_03.prefab")).Cast<GameObject>();
				Debug.Log(Object.op_Implicit("hirnugeos - materials digsite going"));
				foreach (LG_PrefabSpawner componentsInChild in obj.GetComponentsInChildren<LG_PrefabSpawner>(true))
				{
					if ((Object)(object)EntryPoint.hirnufloormaterial != (Object)null && (Object)(object)EntryPoint.hirnuwallmaterial != (Object)null)
					{
						Debug.Log(Object.op_Implicit("hirnugeos - materials breaking"));
					}
					if ((Object)(object)EntryPoint.hirnufloormaterial != (Object)null && (Object)(object)EntryPoint.hirnuwallmaterial != (Object)null)
					{
						break;
					}
					if (!((Object)componentsInChild.m_prefab).name.Contains("BuildingPart_StorageGround_Gravel_2x2_a"))
					{
						continue;
					}
					foreach (MeshRenderer componentsInChild2 in componentsInChild.m_prefab.GetComponentsInChildren<MeshRenderer>())
					{
						if (((Object)((Component)componentsInChild2).gameObject).name.Contains("g_BuildingPart"))
						{
							EntryPoint.hirnufloormaterial = Object.Instantiate<Material>(((Renderer)componentsInChild2).material);
							EntryPoint.hirnuwallmaterial = Object.Instantiate<Material>(((Renderer)componentsInChild2).material);
						}
					}
				}
			}
			Debug.Log(Object.op_Implicit("hirnugeos - materials digsite done"));
			if ((int)subComplex == 4 || (int)subComplex == 3)
			{
				foreach (LG_PrefabSpawner componentsInChild3 in ((Il2CppObjectBase)AssetAPI.GetLoadedAsset("Assets/AssetPrefabs/Complex/Tech/Geomorphs/geo_64x64_Lab_dead_end_HSU.prefab")).Cast<GameObject>().GetComponentsInChildren<LG_PrefabSpawner>(true))
				{
					if ((Object)(object)EntryPoint.hirnufloormaterial != (Object)null)
					{
						break;
					}
					if (!((Object)componentsInChild3.m_prefab).name.Contains("BuildingPart_Lab_Floor_4x4_a"))
					{
						continue;
					}
					foreach (MeshRenderer componentsInChild4 in componentsInChild3.m_prefab.GetComponentsInChildren<MeshRenderer>())
					{
						if (((Object)((Component)componentsInChild4).gameObject).name.Contains("g_BuildingPart"))
						{
							EntryPoint.hirnufloormaterial = Object.Instantiate<Material>(((Renderer)componentsInChild4).material);
						}
					}
				}
				foreach (LG_PrefabSpawner componentsInChild5 in ((Il2CppObjectBase)AssetAPI.GetLoadedAsset("Assets/AssetPrefabs/Complex/Tech/Geomorphs/geo_64x64_tech_node_transition_07_LF.prefab")).Cast<GameObject>().GetComponentsInChildren<LG_PrefabSpawner>(true))
				{
					if ((Object)(object)EntryPoint.hirnufloormaterial != (Object)null && (Object)(object)EntryPoint.hirnuwallmaterial != (Object)null)
					{
						Debug.Log(Object.op_Implicit("hirnugeos - materials breaking"));
					}
					if ((Object)(object)EntryPoint.hirnufloormaterial != (Object)null && (Object)(object)EntryPoint.hirnuwallmaterial != (Object)null)
					{
						break;
					}
					if (!((Object)componentsInChild5.m_prefab).name.Contains("BuildingPart_DataCenter_6x6_Roof_c"))
					{
						continue;
					}
					foreach (MeshRenderer componentsInChild6 in componentsInChild5.m_prefab.GetComponentsInChildren<MeshRenderer>())
					{
						if (((Object)((Component)componentsInChild6).gameObject).name.Contains("g_BuildingPart"))
						{
							EntryPoint.hirnuwallmaterial = Object.Instantiate<Material>(((Renderer)componentsInChild6).material);
						}
					}
				}
			}
			if ((int)subComplex == 6 || (int)subComplex == 11)
			{
				foreach (LG_PrefabSpawner componentsInChild7 in ((Il2CppObjectBase)AssetAPI.GetLoadedAsset("Assets/AssetPrefabs/Complex/Service/Geomorphs/Maintenance/geo_64x64_service_floodways_hub_AW_01.prefab")).Cast<GameObject>().GetComponentsInChildren<LG_PrefabSpawner>(true))
				{
					if ((Object)(object)EntryPoint.hirnufloormaterial != (Object)null && (Object)(object)EntryPoint.hirnuwallmaterial != (Object)null)
					{
						Debug.Log(Object.op_Implicit("hirnugeos - materials breaking"));
					}
					if ((Object)(object)EntryPoint.hirnufloormaterial != (Object)null && (Object)(object)EntryPoint.hirnuwallmaterial != (Object)null)
					{
						break;
					}
					if (!((Object)componentsInChild7.m_prefab).name.Contains("edgeup"))
					{
						continue;
					}
					foreach (MeshRenderer componentsInChild8 in componentsInChild7.m_prefab.GetComponentsInChildren<MeshRenderer>())
					{
						if (((Object)((Component)componentsInChild8).gameObject).name.Contains("g_Service"))
						{
							EntryPoint.hirnufloormaterial = Object.Instantiate<Material>(((Renderer)componentsInChild8).material);
							EntryPoint.hirnuwallmaterial = Object.Instantiate<Material>(((Renderer)componentsInChild8).material);
						}
					}
				}
			}
			Debug.Log(Object.op_Implicit($"hirnugeos - materials done {(Object)(object)EntryPoint.hirnufloormaterial == (Object)null} {(Object)(object)EntryPoint.hirnuwallmaterial == (Object)null}"));
			foreach (GameObject item in list)
			{
				item.SetActive(false);
			}
			foreach (LG_Geomorph item2 in Object.FindObjectsOfType<LG_Geomorph>())
			{
				foreach (MeshRenderer componentsInChild9 in ((Component)item2).GetComponentsInChildren<MeshRenderer>())
				{
					if (((Object)((Component)componentsInChild9).gameObject).name.Contains("hirnu_floor"))
					{
						((Renderer)componentsInChild9).SetMaterial(EntryPoint.hirnufloormaterial);
					}
					if (((Object)((Component)componentsInChild9).gameObject).name.Contains("hirnu_wall"))
					{
						((Renderer)componentsInChild9).SetMaterial(EntryPoint.hirnuwallmaterial);
					}
				}
			}
		}

		public static void OnFactoryBuildStart()
		{
			//IL_00b4: 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)
			if (!((Object)(object)EntryPoint.hirnulamp == (Object)null))
			{
				return;
			}
			foreach (LG_PrefabSpawner componentsInChild in ((Il2CppObjectBase)AssetAPI.GetLoadedAsset("Assets/AssetPrefabs/Complex/Tech/Geomorphs/geo_32x32_elevator_shaft_lab_03.prefab")).Cast<GameObject>().GetComponentsInChildren<LG_PrefabSpawner>())
			{
				if (((Object)componentsInChild.m_prefab).name == "prop_generic_light_regular_wall_fluorescent_02")
				{
					EntryPoint.hirnulamp = Object.Instantiate<LG_PrefabSpawner>(componentsInChild);
					EntryPoint.hirnulampfixture = Object.Instantiate<GameObject>(EntryPoint.hirnulamp.m_prefab);
				}
				if ((Object)(object)EntryPoint.hirnulamp != (Object)null)
				{
					break;
				}
			}
			EntryPoint.hirnulamp.m_prefab = EntryPoint.hirnulampfixture;
			((Component)EntryPoint.hirnulamp).transform.position = new Vector3(0f, -50f, 0f);
			EntryPoint.hirnulampfixture.transform.position = new Vector3(0f, -50f, 0f);
		}
	}
	public class Hirnu_hub_elevator : MonoBehaviour
	{
		public static LG_PrefabSpawner hirnulamp;

		public static GameObject hirnulampfixture;

		public static void OnFactoryBuildDone()
		{
			if ((Object)(object)EntryPoint.hirnuhubelevatorgo != (Object)null)
			{
				EntryPoint.hirnuhubelevatorgo.SetActive(false);
			}
		}

		public static void OnFactoryBuildStart(SubComplex subcomplex, bool IsOutside)
		{
			//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)
			//IL_002c: Expected O, but got Unknown
			//IL_0044: 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_00ca: Expected O, but got Unknown
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: 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_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0314: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_049a: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_04da: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_051a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0539: Unknown result type (might be due to invalid IL or missing references)
			//IL_059d: Unknown result type (might be due to invalid IL or missing references)
			//IL_05bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0618: Unknown result type (might be due to invalid IL or missing references)
			//IL_062c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0631: Unknown result type (might be due to invalid IL or missing references)
			//IL_0642: Unknown result type (might be due to invalid IL or missing references)
			//IL_0657: Unknown result type (might be due to invalid IL or missing references)
			//IL_066a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0675: Unknown result type (might be due to invalid IL or missing references)
			//IL_067a: Unknown result type (might be due to invalid IL or missing references)
			//IL_068b: 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_06aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_06bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_06dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0708: Unknown result type (might be due to invalid IL or missing references)
			//IL_0712: Unknown result type (might be due to invalid IL or missing references)
			//IL_0727: Unknown result type (might be due to invalid IL or missing references)
			//IL_073a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0745: Unknown result type (might be due to invalid IL or missing references)
			//IL_074a: Unknown result type (might be due to invalid IL or missing references)
			//IL_075b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0770: Unknown result type (might be due to invalid IL or missing references)
			//IL_077a: Unknown result type (might be due to invalid IL or missing references)
			//IL_078f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0801: Unknown result type (might be due to invalid IL or missing references)
			//IL_0808: Expected O, but got Unknown
			//IL_0830: Unknown result type (might be due to invalid IL or missing references)
			//IL_084b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0852: Expected O, but got Unknown
			//IL_0869: Unknown result type (might be due to invalid IL or missing references)
			//IL_086e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0880: Unknown result type (might be due to invalid IL or missing references)
			//IL_0895: Unknown result type (might be due to invalid IL or missing references)
			//IL_0abb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ada: Unknown result type (might be due to invalid IL or missing references)
			//IL_0af8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b3c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b5c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b7c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b86: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b8d: Expected O, but got Unknown
			//IL_0b8d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b94: Expected O, but got Unknown
			//IL_0b94: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b9b: Expected O, but got Unknown
			//IL_0b9b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ba2: Expected O, but got Unknown
			//IL_0bdc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bfc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c4f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c6e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c89: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cae: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cb3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cc5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cda: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ce4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cf9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d4b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d6b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a11: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a30: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a4e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0946: Unknown result type (might be due to invalid IL or missing references)
			//IL_0965: Unknown result type (might be due to invalid IL or missing references)
			//IL_0983: Unknown result type (might be due to invalid IL or missing references)
			//IL_0dbe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ddd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0df8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e1d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e22: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e34: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e49: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e53: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e68: Unknown result type (might be due to invalid IL or missing references)
			//IL_0eba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0eda: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f2d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f4c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f67: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f8c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f91: Unknown result type (might be due to invalid IL or missing references)
			//IL_0fa3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0fb8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0fc2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0fd7: Unknown result type (might be due to invalid IL or missing references)
			//IL_1029: Unknown result type (might be due to invalid IL or missing references)
			//IL_1049: Unknown result type (might be due to invalid IL or missing references)
			//IL_109c: Unknown result type (might be due to invalid IL or missing references)
			//IL_10bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_10d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_10fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_1100: Unknown result type (might be due to invalid IL or missing references)
			//IL_1112: Unknown result type (might be due to invalid IL or missing references)
			//IL_1127: Unknown result type (might be due to invalid IL or missing references)
			//IL_1131: Unknown result type (might be due to invalid IL or missing references)
			//IL_1146: Unknown result type (might be due to invalid IL or missing references)
			//IL_1163: Unknown result type (might be due to invalid IL or missing references)
			//IL_116a: Expected O, but got Unknown
			//IL_1193: Unknown result type (might be due to invalid IL or missing references)
			//IL_119d: Unknown result type (might be due to invalid IL or missing references)
			//IL_11a4: Expected O, but got Unknown
			//IL_11cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_11ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_11f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_11fe: Expected O, but got Unknown
			//IL_1227: Unknown result type (might be due to invalid IL or missing references)
			//IL_1247: Unknown result type (might be due to invalid IL or missing references)
			//IL_1251: Unknown result type (might be due to invalid IL or missing references)
			//IL_1258: Expected O, but got Unknown
			//IL_1281: Unknown result type (might be due to invalid IL or missing references)
			//IL_12a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_12fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_1319: Unknown result type (might be due to invalid IL or missing references)
			//IL_1333: Unknown result type (might be due to invalid IL or missing references)
			//IL_13aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_13c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_13e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_145a: Unknown result type (might be due to invalid IL or missing references)
			//IL_1479: Unknown result type (might be due to invalid IL or missing references)
			//IL_1493: Unknown result type (might be due to invalid IL or missing references)
			//IL_1570: Unknown result type (might be due to invalid IL or missing references)
			//IL_1577: Expected O, but got Unknown
			//IL_159f: Unknown result type (might be due to invalid IL or missing references)
			//IL_15be: Unknown result type (might be due to invalid IL or missing references)
			//IL_15dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_15f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_1614: Unknown result type (might be due to invalid IL or missing references)
			//IL_150a: Unknown result type (might be due to invalid IL or missing references)
			//IL_1529: Unknown result type (might be due to invalid IL or missing references)
			//IL_1543: Unknown result type (might be due to invalid IL or missing references)
			//IL_1671: Unknown result type (might be due to invalid IL or missing references)
			//IL_1678: Expected O, but got Unknown
			//IL_1694: Unknown result type (might be due to invalid IL or missing references)
			//IL_16b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_16e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_170b: Unknown result type (might be due to invalid IL or missing references)
			//IL_1736: Unknown result type (might be due to invalid IL or missing references)
			//IL_173b: Unknown result type (might be due to invalid IL or missing references)
			//IL_174d: Unknown result type (might be due to invalid IL or missing references)
			//IL_1762: Unknown result type (might be due to invalid IL or missing references)
			//IL_176c: Unknown result type (might be due to invalid IL or missing references)
			//IL_1781: Unknown result type (might be due to invalid IL or missing references)
			subcomplex = Builder.LayerBuildDatas[0].m_zoneBuildDatas[0].SubComplex;
			Hirnu_materials.OnFactoryBuildStart();
			EntryPoint.hirnuhubelevatorgo = new GameObject();
			Debug.Log(Object.op_Implicit($"LGTuner - hirnugeos - building hub-elevator-tile, subcomplex {subcomplex}"));
			EntryPoint.hirnuhubelevatorgo.SetActive(true);
			((Object)EntryPoint.hirnuhubelevatorgo).hideFlags = (HideFlags)61;
			EntryPoint.hirnuhubelevatorgo.layer = LayerManager.LAYER_DEFAULT;
			((Object)EntryPoint.hirnuhubelevatorgo).name = "hirnu_tile_hub_elevator";
			LG_FloorTransition val = EntryPoint.hirnuhubelevatorgo.AddComponent<LG_FloorTransition>();
			val.m_shapeType = (LG_TileShapeType)1;
			val.m_transitionType = (LG_FloorTransitionType)2;
			ElevatorShaftLanding val2 = EntryPoint.hirnuhubelevatorgo.AddComponent<ElevatorShaftLanding>();
			EntryPoint.hirnuhubelevatorgo.AddComponent<AIG_VoxelNodeVolume>();
			GameObject val3 = new GameObject("Area A");
			val3.transform.parent = EntryPoint.hirnuhubelevatorgo.transform;
			((Object)val3).name = "hirnu_tile_hub_elevator_a";
			GameObject val4 = new GameObject("AreaAIGraphSource");
			val4.transform.parent = val3.transform;
			Transform transform = val4.transform;
			transform.localPosition += new Vector3(-5f, 2f, 0f);
			LG_AreaAIGraphSource val5 = val4.AddComponent<LG_AreaAIGraphSource>();
			val5.m_position = new Vector3(0f, 2f, 0f);
			LG_Area val6 = val3.AddComponent<LG_Area>();
			val6.m_size = (LG_AreaSize)2;
			val6.m_geomorph = (LG_Geomorph)(object)val;
			((LG_Geomorph)val).m_areas = Il2CppReferenceArray<LG_Area>.op_Implicit((LG_Area[])(object)new LG_Area[1] { val6 });
			GameObject val7 = ComponentExt.AddChildGameObject((Component)(object)val3.transform, "ExpeditionExitScanAlign");
			val7.transform.localPosition = new Vector3(0.32f, 0.4f, 15.27f);
			foreach (Transform componentsInChild in ((Il2CppObjectBase)AssetAPI.GetLoadedAsset("Assets/AssetPrefabs/Complex/Tech/Geomorphs/geo_32x32_elevator_shaft_lab_03.prefab")).Cast<GameObject>().GetComponentsInChildren<Transform>())
			{
				if (((Object)componentsInChild).name == "ElevatorCargoAlign")
				{
					EntryPoint.hirnucargocage = Object.Instantiate<GameObject>(((Component)componentsInChild).gameObject);
				}
			}
			GameObject val8 = Object.Instantiate<GameObject>(EntryPoint.hirnucargocage);
			val8.transform.parent = val3.transform;
			val8.transform.position = new Vector3(0f, 0f, 0f);
			val8.transform.localPosition = new Vector3(0f, 0f, 14f);
			val2.m_cargoCageAlign = val8.transform;
			val2.m_securityScanAlign = val7.transform;
			GameObject val9 = ComponentExt.AddChildGameObject((Component)(object)val3.transform, "spawn");
			val9.transform.localPosition = new Vector3(-3.136f, 1.338f, 13.661f);
			GameObject val10 = ComponentExt.AddChildGameObject((Component)(object)val3.transform, "spawn (2)");
			val10.transform.localPosition = new Vector3(-1.542f, 1.135f, 13.099f);
			GameObject val11 = ComponentExt.AddChildGameObject((Component)(object)val3.transform, "spawn (3)");
			val11.transform.localPosition = new Vector3(1.284f, 1.135f, 13.099f);
			GameObject val12 = ComponentExt.AddChildGameObject((Component)(object)val3.transform, "spawn (4)");
			val12.transform.localPosition = new Vector3(2.89f, 1.405f, 12.08f);
			val.m_spawnPoints = new Il2CppReferenceArray<Transform>((Transform[])(object)new Transform[4] { val9.transform, val10.transform, val11.transform, val12.transform });
			GameObject val13 = new GameObject("Gate");
			val13.transform.parent = val3.transform;
			val13.transform.localPosition = new Vector3(0f, 0f, 32f);
			val13.transform.localEulerAngles = new Vector3(0f, 0f, 0f);
			GameObject obj = ComponentExt.AddChildGameObject((Component)(object)val13.transform, "plug");
			GameObject val14 = ComponentExt.AddChildGameObject((Component)(object)obj.transform, "crossing");
			ComponentExt.AddChildGameObject((Component)(object)obj.transform, "behind");
			GameObject val15 = ComponentExt.AddChildGameObject((Component)(object)val14.transform, "FreeNode 1");
			GameObject val16 = ComponentExt.AddChildGameObject((Component)(object)val14.transform, "FreeNode 2");
			GameObject val17 = ComponentExt.AddChildGameObject((Component)(object)val14.transform, "FreeNode 3");
			GameObject val18 = ComponentExt.AddChildGameObject((Component)(object)val14.transform, "FreeNode 4");
			GameObject val19 = ComponentExt.AddChildGameObject((Component)(object)val14.transform, "FreeNode 5");
			GameObject obj2 = ComponentExt.AddChildGameObject((Component)(object)val14.transform, "FreeNode 6");
			val15.transform.localPosition = new Vector3(-1.528f, 1.16f, 32f);
			val16.transform.localPosition = new Vector3(-0.905f, 0.168f, 32f);
			val17.transform.localPosition = new Vector3(-0.185f, 0.168f, 32f);
			val18.transform.localPosition = new Vector3(0.487f, 0.168f, 32f);
			val19.transform.localPosition = new Vector3(1.242f, 0.168f, 32f);
			obj2.transform.localPosition = new Vector3(1.974f, 0.168f, 32f);
			AIG_FreeNode val20 = val15.AddComponent<AIG_FreeNode>();
			AIG_FreeNode val21 = val16.AddComponent<AIG_FreeNode>();
			AIG_FreeNode val22 = val17.AddComponent<AIG_FreeNode>();
			AIG_FreeNode val23 = val18.AddComponent<AIG_FreeNode>();
			AIG_FreeNode val24 = val19.AddComponent<AIG_FreeNode>();
			AIG_FreeNode val25 = obj2.AddComponent<AIG_FreeNode>();
			GameObject obj3 = ComponentExt.AddChildGameObject((Component)(object)val14.transform, "PortalHelper");
			obj3.transform.localPosition = new Vector3(0f, 0f, 32f);
			obj3.transform.localScale = new Vector3(16f, 8f, 1f);
			obj3.AddComponent<C_PortalHelper>();
			LG_PlugCustom val26 = val13.AddComponent<LG_PlugCustom>();
			val13.AddComponent<AIG_PlugSocket>();
			AIG_DoorInsert val27 = val13.AddComponent<AIG_DoorInsert>();
			Il2CppReferenceArray<AIG_FreeNode> nodes = new Il2CppReferenceArray<AIG_FreeNode>((AIG_FreeNode[])(object)new AIG_FreeNode[6] { val20, val21, val22, val23, val24, val25 });
			val27.m_nodes = nodes;
			((LG_ZoneExpander)val26).m_subComplex = subcomplex;
			((LG_ZoneExpander)val26).m_linksFrom = val6;
			GameObject val28 = new GameObject("Gate X");
			val28.transform.parent = val3.transform;
			val28.transform.localPosition = new Vector3(0f, 0f, 32f);
			LG_Plug val29 = val28.AddComponent<LG_Plug>();
			((LG_ZoneExpander)val29).m_subComplex = subcomplex;
			GameObject val30 = new GameObject("Gate 2");
			val30.transform.parent = val3.transform;
			val30.transform.localPosition = new Vector3(-32f, 0f, 0f);
			val30.transform.localEulerAngles = new Vector3(0f, 270.0002f, 0f);
			LG_Plug val31 = val30.AddComponent<LG_Plug>();
			((LG_ZoneExpander)val31).m_subComplex = subcomplex;
			GameObject val32 = new GameObject("Gate 3");
			val32.transform.parent = val3.transform;
			val32.transform.localPosition = new Vector3(32f, 0f, 0f);
			val32.transform.localEulerAngles = new Vector3(0f, 89.9999f, 0f);
			LG_Plug val33 = val32.AddComponent<LG_Plug>();
			((LG_ZoneExpander)val33).m_subComplex = subcomplex;
			GameObject val34 = new GameObject("Gate 4");
			val34.transform.parent = val3.transform;
			val34.transform.localPosition = new Vector3(0f, 0f, -32f);
			val34.transform.localEulerAngles = new Vector3(0f, 180f, 0f);
			LG_Plug val35 = val34.AddComponent<LG_Plug>();
			((LG_Geomorph)val).m_plugs = new List<LG_Plug>();
			((LG_Geomorph)val).m_plugs.Add((LG_Plug)(object)val26);
			((LG_Geomorph)val).m_plugs.Add(val31);
			((LG_Geomorph)val).m_plugs.Add(val33);
			((LG_Geomorph)val).m_plugs.Add(val35);
			((LG_Geomorph)val).m_plugs.Add(val29);
			val6.m_groupSource = val5;
			val6.m_geomorph = (LG_Geomorph)(object)val;
			GameObject val36 = new GameObject("EnvProps");
			val36.transform.parent = val3.transform;
			val36.transform.localPosition = new Vector3(0f, 0f, 0f);
			MarkerGroupDataBlock block = GameDataBlockBase<MarkerGroupDataBlock>.GetBlock("Tech_DataCenter");
			GameObject val37 = new GameObject("Markers");
			val37.transform.parent = val3.transform;
			GameObject val38 = new GameObject("Fallback 1");
			val38.transform.parent = val37.transform;
			val38.transform.localPosition = new Vector3(0f, 0f, 22f);
			val38.AddComponent<TechDataCenterMarkerProducer>().m_markerDataBlockID = 63u;
			for (int i = -31; i < 32; i += 2)
			{
				for (int j = -31; j < 32; j += 2)
				{
					if ((i >= -24 || j <= -8 || j >= 8) && (i <= 24 || j <= -8 || j >= 8) && (j >= -24 || i <= -8 || i >= 8) && (j <= 24 || i <= -8 || i >= 8))
					{
						GameObject obj4 = GameObject.CreatePrimitive((PrimitiveType)5);
						((Object)obj4.gameObject).name = "hirnu_floor";
						obj4.transform.parent = val36.transform;
						obj4.transform.localPosition = new Vector3((float)i, -0.05f, (float)j);
						obj4.transform.localEulerAngles = new Vector3(90f, 0f, 0f);
						obj4.transform.localScale = new Vector3(2f, 2f, 2f);
					}
				}
			}
			for (int k = -31; k < 32; k += 2)
			{
				for (int l = -31; l < 32; l += 2)
				{
					if (k <= -16 || k >= 16 || l <= -16 || l >= 16)
					{
						GameObject obj5 = GameObject.CreatePrimitive((PrimitiveType)5);
						((Object)obj5.gameObject).name = "hirnu_wall";
						obj5.transform.parent = val36.transform;
						obj5.transform.localPosition = new Vector3((float)k, 8f, (float)l);
						obj5.transform.localEulerAngles = new Vector3(270f, 0f, 0f);
						obj5.transform.localScale = new Vector3(2f, 2f, 2f);
					}
				}
			}
			GameObject obj6 = GameObject.CreatePrimitive((PrimitiveType)5);
			GameObject val39 = GameObject.CreatePrimitive((PrimitiveType)5);
			((Object)obj6.gameObject).name = "hirnu_wall";
			obj6.transform.parent = val14.transform;
			obj6.transform.localPosition = new Vector3(-8f, 4f, 32f);
			obj6.transform.localScale = new Vector3(1f, 8f, 1f);
			obj6.transform.localEulerAngles = new Vector3(0f, 270f, 0f);
			((Object)val39.gameObject).name = "hirnu_wall";
			val39.transform.parent = val14.transform;
			val39.transform.localPosition = new Vector3(8f, 4f, 32f);
			val39.transform.localScale = new Vector3(1f, 8f, 1f);
			val39.transform.localEulerAngles = new Vector3(0f, 90f, 0f);
			GameObject val40 = new GameObject();
			GameObject val41 = new GameObject();
			GameObject val42 = new GameObject();
			GameObject val43 = new GameObject();
			((Object)val40.gameObject).name = "hirnu_wall_sw1";
			val40.transform.SetParent(val36.transform);
			val40.transform.localPosition = new Vector3(-20f, 4f, -20f);
			val40.transform.localEulerAngles = new Vector3(0f, 225f, 0f);
			for (float num = -14.97f; num < 17f; num += 3.394f)
			{
				GameObject obj7 = GameObject.CreatePrimitive((PrimitiveType)5);
				((Object)obj7.transform).name = "hirnu_wall";
				obj7.transform.parent = val40.transform;
				obj7.transform.localEulerAngles = new Vector3(0f, 0f, 0f);
				obj7.transform.localScale = new Vector3(3.394f, 8.2f, 3.394f);
				obj7.transform.localPosition = new Vector3(num, 0f, 0f);
			}
			GameObject val44 = new GameObject("Sign 1");
			val44.transform.parent = val37.transform;
			val44.transform.localPosition = new Vector3(-20f, 5f, -20f);
			val44.transform.localEulerAngles = new Vector3(0f, 45f, 0f);
			TechDataCenterMarkerProducer obj8 = val44.AddComponent<TechDataCenterMarkerProducer>();
			obj8.m_markerDataBlockID = 9u;
			((LG_MarkerProducer)obj8).m_allowFunction = true;
			((Object)val41).name = "hirnu_wall_nw1";
			val41.transform.SetParent(val36.transform);
			val41.transform.localPosition = new Vector3(-20f, 4f, 20f);
			val41.transform.localEulerAngles = new Vector3(0f, 315f, 0f);
			for (float num2 = -14.97f; num2 < 17f; num2 += 3.394f)
			{
				GameObject obj9 = GameObject.CreatePrimitive((PrimitiveType)5);
				((Object)obj9.gameObject).name = "hirnu_wall";
				obj9.transform.parent = val41.transform;
				obj9.transform.localEulerAngles = new Vector3(0f, 0f, 0f);
				obj9.transform.localScale = new Vector3(3.394f, 8.2f, 3.394f);
				obj9.transform.localPosition = new Vector3(num2, 0f, 0f);
			}
			GameObject val45 = new GameObject("Sign 2");
			val45.transform.parent = val37.transform;
			val45.transform.localPosition = new Vector3(-20f, 5f, 20f);
			val45.transform.localEulerAngles = new Vector3(0f, 135f, 0f);
			TechDataCenterMarkerProducer obj10 = val45.AddComponent<TechDataCenterMarkerProducer>();
			obj10.m_markerDataBlockID = 9u;
			((LG_MarkerProducer)obj10).m_allowFunction = true;
			((Object)val42).name = "hirnu_wall_ne1";
			val42.transform.SetParent(val36.transform);
			val42.transform.localPosition = new Vector3(20f, 4f, 20f);
			val42.transform.localEulerAngles = new Vector3(0f, 45f, 0f);
			for (float num3 = -14.97f; num3 < 17f; num3 += 3.394f)
			{
				GameObject obj11 = GameObject.CreatePrimitive((PrimitiveType)5);
				((Object)obj11.gameObject).name = "hirnu_wall";
				obj11.transform.parent = val42.transform;
				obj11.transform.localEulerAngles = new Vector3(0f, 0f, 0f);
				obj11.transform.localScale = new Vector3(3.394f, 8.2f, 3.394f);
				obj11.transform.localPosition = new Vector3(num3, 0f, 0f);
			}
			GameObject val46 = new GameObject("Sign 3");
			val46.transform.parent = val37.transform;
			val46.transform.localPosition = new Vector3(20f, 5f, 20f);
			val46.transform.localEulerAngles = new Vector3(0f, 225f, 0f);
			TechDataCenterMarkerProducer obj12 = val46.AddComponent<TechDataCenterMarkerProducer>();
			obj12.m_markerDataBlockID = 9u;
			((LG_MarkerProducer)obj12).m_allowFunction = true;
			((Object)val43).name = "hirnu_wall_se1";
			val43.transform.SetParent(val36.t

plugins/Inas07-EOSExt_Reactor/Inas07.EOSExt.Reactor.dll

Decompiled 7 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Json.Serialization;
using AIGraph;
using AK;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using ChainedPuzzles;
using EOSExt.Reactor.Component;
using EOSExt.Reactor.Definition;
using EOSExt.Reactor.Managers;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.BaseClasses.CustomTerminalDefinition;
using ExtraObjectiveSetup.ExtendedWardenEvents;
using ExtraObjectiveSetup.Instances;
using ExtraObjectiveSetup.Utils;
using GTFO.API;
using GTFO.API.Extensions;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Localization;
using Microsoft.CodeAnalysis;
using SNetwork;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("Inas07.EOSExt.Reactor")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+f482d476223f2755edf5596e77619b51d0c530e4")]
[assembly: AssemblyProduct("Inas07.EOSExt.Reactor")]
[assembly: AssemblyTitle("Inas07.EOSExt.Reactor")]
[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 EOSExt.Reactor
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Inas.EOSExt.Reactor", "EOSExt.Reactor", "1.0.7")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas";

		public const string PLUGIN_NAME = "EOSExt.Reactor";

		public const string VERSION = "1.0.7";

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			m_Harmony = new Harmony("EOSExt.Reactor");
			m_Harmony.PatchAll();
			SetupManagers();
			SetupExtraWardenEventDefinitions();
			ClassInjector.RegisterTypeInIl2Cpp<OverrideReactorComp>();
			EOSLogger.Log("ExtraObjectiveSetup.Reactor loaded.");
		}

		private void SetupManagers()
		{
			((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).Init();
			((InstanceDefinitionManager<ReactorStartupOverride>)ReactorStartupOverrideManager.Current).Init();
		}

		private void SetupExtraWardenEventDefinitions()
		{
			EOSWardenEventManager.Current.AddEventDefinition(WardenEvents.EventType.ReactorStartup.ToString(), 150u, (Action<WardenObjectiveEventData>)WardenEvents.ReactorStartup);
			EOSWardenEventManager.Current.AddEventDefinition(WardenEvents.EventType.CompleteCurrentVerify.ToString(), 151u, (Action<WardenObjectiveEventData>)WardenEvents.CompleteCurrentVerify);
		}
	}
}
namespace EOSExt.Reactor.Patches
{
	[HarmonyPatch]
	internal class CommandInterpreter_ReactorVerify
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReactorVerify")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_ReactorVerify(LG_ComputerTerminalCommandInterpreter __instance, string param1)
		{
			LG_WardenObjective_Reactor connectedReactor = __instance.m_terminal.ConnectedReactor;
			if ((Object)(object)connectedReactor == (Object)null)
			{
				EOSLogger.Error("ReactorVerify: connected reactor is null - bug detected");
				return true;
			}
			if (connectedReactor.m_isWardenObjective)
			{
				return true;
			}
			if (connectedReactor.ReadyForVerification && param1 == connectedReactor.CurrentStateOverrideCode)
			{
				__instance.m_terminal.ChangeState((TERM_State)7);
			}
			else
			{
				__instance.AddOutput("", true);
				__instance.AddOutput((TerminalLineType)3, Text.Get(2195342028u), 4f, (TerminalSoundType)0, (TerminalSoundType)0);
				__instance.AddOutput("", true);
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal class OnTerminalStartupSequenceVerify
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnTerminalStartupSequenceVerify")]
		private static void Post_ExecuteEventsOnEndOnClientSide(LG_WardenObjective_Reactor __instance)
		{
			if (!SNet.IsMaster)
			{
				WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)3, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
			}
		}
	}
	[HarmonyPatch]
	internal class Reactor_OnBuildDone
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnBuildDone")]
		private static void Post_LG_WardenObjective_Reactor_OnBuildDone(LG_WardenObjective_Reactor __instance)
		{
			//IL_00f2: 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_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: 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_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Invalid comparison between Unknown and I4
			uint num = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).Register(__instance);
			if (__instance.m_isWardenObjective)
			{
				ReactorStartupOverride definition = ((InstanceDefinitionManager<ReactorStartupOverride>)ReactorStartupOverrideManager.Current).GetDefinition(__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex, num);
				if (definition == null)
				{
					return;
				}
				WardenObjectiveDataBlock val = default(WardenObjectiveDataBlock);
				if (!WardenObjectiveManager.TryGetWardenObjectiveDataForLayer(__instance.SpawnNode.LayerType, __instance.WardenObjectiveChainIndex, ref val) || val == null)
				{
					EOSLogger.Error("Failed to get WardenObjectiveData for this reactor");
					return;
				}
				if ((int)val.Type != 1)
				{
					EOSLogger.Error($"Reactor Instance {(((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(__instance), num)} is not setup as vanilla ReactorStartup, cannot override");
					return;
				}
				definition.ObjectiveDB = val;
				ReactorStartupOverrideManager.Current.Build(__instance, definition);
			}
			else
			{
				ReactorShutdownDefinition definition2 = ((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).GetDefinition(__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex, num);
				if (definition2 != null)
				{
					ReactorShutdownObjectiveManager.Current.Build(__instance, definition2);
					EOSLogger.Debug($"Reactor Shutdown Instance {(((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(__instance), num)}: custom setup complete");
				}
			}
			if ((Object)(object)__instance.m_terminal != (Object)null)
			{
				TerminalInstanceManager.Current.RegisterReactorTerminal(__instance);
			}
		}
	}
	[HarmonyPatch]
	internal class Reactor_OnStateChange
	{
		private static void Startup_OnStateChange(LG_WardenObjective_Reactor reactor, pReactorState oldState, pReactorState newState, bool isDropinState)
		{
			//IL_0020: 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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			if (isDropinState)
			{
				return;
			}
			uint zoneInstanceIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetZoneInstanceIndex(reactor);
			ReactorStartupOverride definition = ((InstanceDefinitionManager<ReactorStartupOverride>)ReactorStartupOverrideManager.Current).GetDefinition(reactor.SpawnNode.m_dimension.DimensionIndex, reactor.OriginLayer, reactor.SpawnNode.m_zone.LocalIndex, zoneInstanceIndex);
			if (definition != null && (int)oldState.status == 0 && (Object)(object)reactor.m_chainedPuzzleToStartSequence != (Object)null)
			{
				definition.EventsOnActive.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
		}

		private static void Shutdown_OnStateChange(LG_WardenObjective_Reactor reactor, pReactorState oldState, pReactorState newState, bool isDropinState, ReactorShutdownDefinition def)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//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_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_001f: Expected I4, but got Unknown
			eReactorStatus status = newState.status;
			switch (status - 6)
			{
			case 0:
				GuiManager.PlayerLayer.m_wardenIntel.ShowSubObjectiveMessage("", Text.Get(1080u), false, 200f, 8f, (Action)null);
				reactor.m_progressUpdateEnabled = true;
				reactor.m_currentDuration = 15f;
				reactor.m_lightCollection.SetMode(false);
				reactor.m_sound.Stop();
				def.EventsOnActive.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
				break;
			case 1:
				GuiManager.PlayerLayer.m_wardenIntel.ShowSubObjectiveMessage("", Text.Get(1081u), false, 200f, 8f, (Action)null);
				reactor.m_progressUpdateEnabled = false;
				reactor.ReadyForVerification = true;
				break;
			case 2:
				reactor.m_progressUpdateEnabled = false;
				if ((Object)(object)def.ChainedPuzzleOnVerificationInstance != (Object)null)
				{
					GuiManager.PlayerLayer.m_wardenIntel.ShowSubObjectiveMessage("", Text.Get(1082u), false, 200f, 8f, (Action)null);
					def.ChainedPuzzleOnVerificationInstance.AttemptInteract((eChainedPuzzleInteraction)0);
				}
				def.EventsOnShutdownPuzzleStarts.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
				break;
			case 3:
				reactor.m_progressUpdateEnabled = false;
				reactor.m_objectiveCompleteTimer = Clock.Time + 5f;
				def.EventsOnComplete.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
				break;
			}
		}

		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateChange")]
		private static bool Pre_LG_WardenObjective_Reactor_OnStateChange(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState, bool isDropinState)
		{
			//IL_0020: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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_0017: 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_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)
			//IL_005b: 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_00ad: 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_00c5: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.m_isWardenObjective)
			{
				if (ReactorInstanceManager.Current.IsStartupReactor(__instance))
				{
					Startup_OnStateChange(__instance, oldState, newState, isDropinState);
				}
				return true;
			}
			if (oldState.stateCount != newState.stateCount)
			{
				__instance.OnStateCountUpdate(newState.stateCount);
			}
			if (oldState.stateProgress != newState.stateProgress)
			{
				__instance.OnStateProgressUpdate(newState.stateProgress);
			}
			if (oldState.status == newState.status)
			{
				return false;
			}
			__instance.ReadyForVerification = false;
			if (ReactorInstanceManager.Current.IsShutdownReactor(__instance))
			{
				uint zoneInstanceIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetZoneInstanceIndex(__instance);
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(__instance);
				ReactorShutdownDefinition definition = ((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).GetDefinition(globalZoneIndex, zoneInstanceIndex);
				if (definition == null)
				{
					EOSLogger.Error("Reactor_OnStateChange: found built custom reactor but its definition is missing, what happened?");
					return false;
				}
				Shutdown_OnStateChange(__instance, oldState, newState, isDropinState, definition);
				__instance.m_currentState = newState;
				return false;
			}
			EOSLogger.Error("Reactor_OnStateChange: found built custom reactor but it's not a shutdown reactor, what happened?");
			return false;
		}
	}
	[HarmonyPatch]
	internal class Reactor_OnStateCountUpdate
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateCountUpdate")]
		private static bool Pre_LG_WardenObjective_Reactor_OnStateCountUpdate(LG_WardenObjective_Reactor __instance, int count)
		{
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: 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_0141: 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_015c: Expected O, but got Unknown
			//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_00ae: 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_00d5: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Expected O, but got Unknown
			if (__instance.m_isWardenObjective)
			{
				return true;
			}
			uint zoneInstanceIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetZoneInstanceIndex(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(__instance);
			if (ReactorInstanceManager.Current.IsStartupReactor(__instance))
			{
				return true;
			}
			if (ReactorInstanceManager.Current.IsShutdownReactor(__instance))
			{
				ReactorShutdownDefinition definition = ((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).GetDefinition(globalZoneIndex, zoneInstanceIndex);
				if (definition == null)
				{
					EOSLogger.Error("Reactor_OnStateCountUpdate: found built custom reactor but its definition is missing, what happened?");
					return true;
				}
				__instance.m_currentWaveCount = count;
				if (definition.PutVerificationCodeOnTerminal)
				{
					LG_ComputerTerminal instance = ((InstanceManager<LG_ComputerTerminal>)(object)TerminalInstanceManager.Current).GetInstance(((GlobalZoneIndex)definition.VerificationCodeTerminal).GlobalZoneIndexTuple(), definition.VerificationCodeTerminal.InstanceIndex);
					__instance.m_currentWaveData = new ReactorWaveData
					{
						HasVerificationTerminal = (definition.PutVerificationCodeOnTerminal && (Object)(object)instance != (Object)null),
						VerificationTerminalSerial = (((Object)(object)instance != (Object)null) ? instance.ItemKey : string.Empty),
						Warmup = 1f,
						WarmupFail = 1f,
						Wave = 1f,
						Verify = 1f,
						VerifyFail = 1f
					};
				}
				else
				{
					__instance.m_currentWaveData = new ReactorWaveData
					{
						HasVerificationTerminal = false,
						VerificationTerminalSerial = string.Empty,
						Warmup = 1f,
						WarmupFail = 1f,
						Wave = 1f,
						Verify = 1f,
						VerifyFail = 1f
					};
				}
				if (__instance.m_overrideCodes != null && !string.IsNullOrEmpty(((Il2CppArrayBase<string>)(object)__instance.m_overrideCodes)[0]))
				{
					__instance.CurrentStateOverrideCode = ((Il2CppArrayBase<string>)(object)__instance.m_overrideCodes)[0];
				}
				else
				{
					EOSLogger.Error("Reactor_OnStateCountUpdate: code is not built?");
				}
				return false;
			}
			EOSLogger.Error("Reactor_OnStateCountUpdate: found built custom reactor but it's neither a startup nor shutdown reactor, what happen?");
			return true;
		}
	}
	[HarmonyPatch]
	internal class Reactor_Update
	{
		private static bool _checked;

		private static TextDataBlock shutdownVerification_GUIText;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "Update")]
		private static bool Pre_LG_WardenObjective_Reactor_Update(LG_WardenObjective_Reactor __instance)
		{
			//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_0014: Invalid comparison between Unknown and I4
			if (__instance.m_isWardenObjective || (int)__instance.m_currentState.status != 7)
			{
				return true;
			}
			if (!_checked)
			{
				shutdownVerification_GUIText = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.ExtraObjectiveSetup_ReactorShutdown.SecurityVerificationRequired");
				_checked = true;
			}
			string empty = string.Empty;
			empty = ((!__instance.m_currentWaveData.HasVerificationTerminal) ? string.Format(Text.Get(1107u), "<color=orange>" + __instance.CurrentStateOverrideCode + "</color>") : string.Format((shutdownVerification_GUIText != null) ? Text.Get(((GameDataBlockBase<TextDataBlock>)(object)shutdownVerification_GUIText).persistentID) : "SECURITY VERIFICATION REQUIRED. USE COMMAND <color=orange>REACTOR_VERIFY</color> AND FIND CODE ON <color=orange>{0}</color>.", __instance.m_currentWaveData.VerificationTerminalSerial));
			__instance.SetGUIMessage(true, empty, (ePUIMessageStyle)3, false, "", "");
			return false;
		}
	}
	[HarmonyPatch]
	internal class Reactor_CommandInterpreter
	{
		private static bool Handle_ReactorShutdown(LG_ComputerTerminalCommandInterpreter __instance)
		{
			LG_WardenObjective_Reactor connectedReactor = __instance.m_terminal.ConnectedReactor;
			uint zoneInstanceIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetZoneInstanceIndex(connectedReactor);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(connectedReactor);
			ReactorShutdownDefinition definition = ((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (definition == null)
			{
				EOSLogger.Error("ReactorVerify: found built custom reactor shutdown but its definition is missing, what happened?");
				return true;
			}
			__instance.AddOutput((TerminalLineType)3, Text.Get(3436726297u), 4f, (TerminalSoundType)0, (TerminalSoundType)0);
			if ((Object)(object)definition.ChainedPuzzleToActiveInstance != (Object)null)
			{
				__instance.AddOutput(Text.Get(2277987284u), true);
				if (SNet.IsMaster)
				{
					definition.ChainedPuzzleToActiveInstance.AttemptInteract((eChainedPuzzleInteraction)0);
				}
			}
			else
			{
				connectedReactor.AttemptInteract((eReactorInteraction)6, 0f);
			}
			return false;
		}

		private static bool Handle_ReactorStartup_SpecialCommand(LG_ComputerTerminalCommandInterpreter __instance, TERM_Command cmd)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			LG_WardenObjective_Reactor connectedReactor = __instance.m_terminal.ConnectedReactor;
			if (__instance.m_terminal.CommandIsHidden(cmd))
			{
				return true;
			}
			_ = __instance.m_terminal.ItemKey;
			OverrideReactorComp component = ((Component)connectedReactor).gameObject.GetComponent<OverrideReactorComp>();
			if ((Object)(object)component == (Object)null)
			{
				return true;
			}
			if (!connectedReactor.ReadyForVerification)
			{
				__instance.AddOutput("", true);
				__instance.AddOutput((TerminalLineType)3, ReactorStartupOverrideManager.NotReadyForVerificationOutputText, 4f, (TerminalSoundType)0, (TerminalSoundType)0);
				__instance.AddOutput("", true);
				return false;
			}
			if (component.IsCorrectTerminal(__instance.m_terminal))
			{
				EOSLogger.Log("Reactor Verify Correct!");
				if (SNet.IsMaster)
				{
					if (connectedReactor.m_currentWaveCount == connectedReactor.m_waveCountMax)
					{
						connectedReactor.AttemptInteract((eReactorInteraction)5, 0f);
					}
					else
					{
						connectedReactor.AttemptInteract((eReactorInteraction)3, 0f);
					}
				}
				else
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(connectedReactor.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)3, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
				}
				__instance.AddOutput(ReactorStartupOverrideManager.CorrectTerminalOutputText, true);
			}
			else
			{
				EOSLogger.Log("Reactor Verify Incorrect!");
				__instance.AddOutput("", true);
				__instance.AddOutput((TerminalLineType)3, ReactorStartupOverrideManager.IncorrectTerminalOutputText, 4f, (TerminalSoundType)0, (TerminalSoundType)0);
				__instance.AddOutput("", true);
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReceiveCommand")]
		private static bool Pre_ReceiveCommand(LG_ComputerTerminalCommandInterpreter __instance, TERM_Command cmd, string inputLine, string param1, string param2)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Invalid comparison between Unknown and I4
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			LG_WardenObjective_Reactor connectedReactor = __instance.m_terminal.ConnectedReactor;
			if ((Object)(object)connectedReactor == (Object)null)
			{
				return true;
			}
			if ((int)cmd == 23 && !connectedReactor.m_isWardenObjective)
			{
				return Handle_ReactorShutdown(__instance);
			}
			if ((int)cmd == 42)
			{
				return Handle_ReactorStartup_SpecialCommand(__instance, cmd);
			}
			return true;
		}
	}
}
namespace EOSExt.Reactor.Patches.Shutdown
{
	[HarmonyPatch]
	internal class Reactor_OnReactorShutdownVerifyChaosDone
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "OnReactorShutdownVerifyChaosDone")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_OnReactorShutdownVerifyChaosDone(LG_ComputerTerminalCommandInterpreter __instance)
		{
			LG_WardenObjective_Reactor connectedReactor = __instance.m_terminal.ConnectedReactor;
			if ((Object)(object)connectedReactor == (Object)null || connectedReactor.m_isWardenObjective)
			{
				return true;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(connectedReactor);
			uint zoneInstanceIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetZoneInstanceIndex(connectedReactor);
			ReactorShutdownDefinition definition = ((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (definition == null)
			{
				EOSLogger.Error("OnReactorShutdownVerifyChaosDone: found built custom reactor shutdown but its definition is missing, what happened?");
				return false;
			}
			connectedReactor.AttemptInteract((eReactorInteraction)(((Object)(object)definition.ChainedPuzzleOnVerificationInstance != (Object)null) ? 8 : 9), 0f);
			return false;
		}
	}
}
namespace EOSExt.Reactor.Managers
{
	public sealed class ReactorInstanceManager : InstanceManager<LG_WardenObjective_Reactor>
	{
		private HashSet<IntPtr> startupReactor = new HashSet<IntPtr>();

		private HashSet<IntPtr> shutdownReactor = new HashSet<IntPtr>();

		public static ReactorInstanceManager Current { get; private set; }

		public override (eDimensionIndex, LG_LayerType, eLocalZoneIndex) GetGlobalZoneIndex(LG_WardenObjective_Reactor instance)
		{
			//IL_000b: 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_0026: Unknown result type (might be due to invalid IL or missing references)
			return (instance.SpawnNode.m_dimension.DimensionIndex, instance.SpawnNode.LayerType, instance.SpawnNode.m_zone.LocalIndex);
		}

		public void MarkAsStartupReactor(LG_WardenObjective_Reactor reactor)
		{
			if (shutdownReactor.Contains(((Il2CppObjectBase)reactor).Pointer))
			{
				throw new ArgumentException("Invalid: cannot mark a reactor both as startup and shutdown reactor");
			}
			startupReactor.Add(((Il2CppObjectBase)reactor).Pointer);
		}

		public void MarkAsShutdownReactor(LG_WardenObjective_Reactor reactor)
		{
			if (startupReactor.Contains(((Il2CppObjectBase)reactor).Pointer))
			{
				throw new ArgumentException("Invalid: cannot mark a reactor both as startup and shutdown reactor");
			}
			shutdownReactor.Add(((Il2CppObjectBase)reactor).Pointer);
		}

		public bool IsStartupReactor(LG_WardenObjective_Reactor reactor)
		{
			return startupReactor.Contains(((Il2CppObjectBase)reactor).Pointer);
		}

		public bool IsShutdownReactor(LG_WardenObjective_Reactor reactor)
		{
			return shutdownReactor.Contains(((Il2CppObjectBase)reactor).Pointer);
		}

		private void Clear()
		{
			//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_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)
			foreach (IntPtr item in startupReactor)
			{
				LG_WardenObjective_Reactor val = new LG_WardenObjective_Reactor(item);
				if ((int)val != 0)
				{
					CellSoundPlayer sound = val.m_sound;
					if (sound != null)
					{
						sound.Recycle();
					}
				}
			}
			foreach (IntPtr item2 in shutdownReactor)
			{
				LG_WardenObjective_Reactor val2 = new LG_WardenObjective_Reactor(item2);
				if ((int)val2 != 0)
				{
					CellSoundPlayer sound2 = val2.m_sound;
					if (sound2 != null)
					{
						sound2.Recycle();
					}
				}
			}
			startupReactor.Clear();
			shutdownReactor.Clear();
		}

		public void SetupReactorTerminal(LG_WardenObjective_Reactor reactor, TerminalDefinition reactorTerminalData)
		{
			reactor.SpawnNode.m_zone.TerminalsSpawnedInZone.Add(reactor.m_terminal);
			if (reactorTerminalData != null)
			{
				reactorTerminalData.LocalLogFiles?.ForEach(delegate(TerminalLogFileData log)
				{
					reactor.m_terminal.AddLocalLog(log, true);
				});
				reactorTerminalData.UniqueCommands?.ForEach(delegate(CustomCommand cmd)
				{
					EOSTerminalUtils.AddUniqueCommand(reactor.m_terminal, cmd);
				});
				EOSTerminalUtils.BuildPassword(reactor.m_terminal, reactorTerminalData.PasswordData);
			}
		}

		public static LG_WardenObjective_Reactor FindVanillaReactor(LG_LayerType layer, int count)
		{
			//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_0066: 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)
			if (count < 0)
			{
				EOSLogger.Error($"FindVanillaReactor: Count should be non-negative, but got {count}!");
				return null;
			}
			LG_WardenObjective_Reactor val = null;
			int num = count;
			Enumerator<LayerChainIndex, iWardenObjectiveItem> enumerator = WardenObjectiveManager.Current.m_wardenObjectiveItem.GetEnumerator();
			while (enumerator.MoveNext())
			{
				KeyValuePair<LayerChainIndex, iWardenObjectiveItem> current = enumerator.Current;
				if (current.Key.Layer != layer)
				{
					continue;
				}
				iWardenObjectiveItem value = current.Value;
				val = ((value != null) ? ((Il2CppObjectBase)value).TryCast<LG_WardenObjective_Reactor>() : null);
				if (!((Object)(object)val == (Object)null))
				{
					if (num <= 0)
					{
						break;
					}
					val = null;
					num--;
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				EOSLogger.Error($"FindVanillaReactor: reactor not found with index(Count) {num} in {layer}!");
			}
			return val;
		}

		private ReactorInstanceManager()
		{
			LevelAPI.OnLevelCleanup += Clear;
		}

		static ReactorInstanceManager()
		{
			Current = new ReactorInstanceManager();
		}
	}
	internal class ReactorStartupOverrideManager : InstanceDefinitionManager<ReactorStartupOverride>
	{
		private List<ReactorStartupOverride> builtOverride = new List<ReactorStartupOverride>();

		public static uint SpecialCmdVerifyTextID { get; private set; }

		public static uint MainTerminalTextID { get; private set; }

		public static uint CooldownCommandDescTextID { get; private set; }

		public static uint InfiniteWaveVerifyTextID { get; private set; }

		public static uint NotReadyForVerificationOutputTextID { get; private set; }

		public static uint IncorrectTerminalOutputTextID { get; private set; }

		public static uint CorrectTerminalOutputTextID { get; private set; }

		public static string CoolDownCommandDesc
		{
			get
			{
				if (CooldownCommandDescTextID == 0)
				{
					return "Confirm Reactor Startup Cooling Protocol";
				}
				return Text.Get(CooldownCommandDescTextID);
			}
		}

		public static string MainTerminalText
		{
			get
			{
				if (MainTerminalTextID == 0)
				{
					return "Main Terminal";
				}
				return Text.Get(MainTerminalTextID);
			}
		}

		public static string SpecialCmdVerifyText
		{
			get
			{
				if (SpecialCmdVerifyTextID == 0)
				{
					return "REACTOR COOLING REQUIRED ({0}/{1})\nMANUAL OVERRIDE REQUIRED. USE COMMAND <color=orange>REACTOR_COOLDOWN</color> AT {2}";
				}
				return Text.Get(SpecialCmdVerifyTextID);
			}
		}

		public static string InfiniteWaveVerifyText
		{
			get
			{
				if (InfiniteWaveVerifyTextID == 0)
				{
					return "VERIFICATION ({0}/{1}).";
				}
				return Text.Get(InfiniteWaveVerifyTextID);
			}
		}

		public static string NotReadyForVerificationOutputText
		{
			get
			{
				if (NotReadyForVerificationOutputTextID == 0)
				{
					return "<color=red>Reactor intensive test in progress, cannot initate cooldown</color>";
				}
				return Text.Get(NotReadyForVerificationOutputTextID);
			}
		}

		public static string CorrectTerminalOutputText
		{
			get
			{
				if (CorrectTerminalOutputTextID == 0)
				{
					return "<color=red>Reactor stage cooldown completed</color>";
				}
				return Text.Get(CorrectTerminalOutputTextID);
			}
		}

		public static string IncorrectTerminalOutputText
		{
			get
			{
				if (IncorrectTerminalOutputTextID == 0)
				{
					return "<color=red>Incorrect terminal, cannot initate cooldown</color>";
				}
				return Text.Get(IncorrectTerminalOutputTextID);
			}
		}

		public static ReactorStartupOverrideManager Current { get; private set; }

		protected override string DEFINITION_NAME => "ReactorStartup";

		public static void FetchOverrideTextDB()
		{
			SpecialCmdVerifyTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownVerification");
			MainTerminalTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownMainTerminalName");
			CooldownCommandDescTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.CommandDesc");
			InfiniteWaveVerifyTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.Verification.InfiniteWave");
			NotReadyForVerificationOutputTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.Not_ReadyForVerification_Output");
			IncorrectTerminalOutputTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.IncorrectTerminal_Output");
			CorrectTerminalOutputTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.CorrectTerminal_Output");
		}

		protected override void AddDefinitions(InstanceDefinitionsForLevel<ReactorStartupOverride> definitions)
		{
			definitions.Definitions.ForEach(delegate(ReactorStartupOverride def)
			{
				def.Overrides.Sort((WaveOverride o1, WaveOverride o2) => o1.WaveIndex.CompareTo(o2.WaveIndex));
			});
			base.AddDefinitions(definitions);
		}

		internal void Build(LG_WardenObjective_Reactor reactor, ReactorStartupOverride def)
		{
			if (!reactor.m_isWardenObjective)
			{
				EOSLogger.Error($"ReactorStartup: Reactor Override for reactor {((GlobalZoneIndex)def).GlobalZoneIndexTuple()}, Instance_{((BaseInstanceDefinition)def).InstanceIndex} is not setup by vanilla, won't override");
				return;
			}
			OverrideReactorComp overrideReactorComp = ((Component)reactor).gameObject.AddComponent<OverrideReactorComp>();
			overrideReactorComp.ChainedReactor = reactor;
			overrideReactorComp.overrideData = def;
			overrideReactorComp.UsingLightEffect = false;
			overrideReactorComp.Init();
			ReactorInstanceManager.Current.MarkAsStartupReactor(reactor);
			ReactorInstanceManager.Current.SetupReactorTerminal(reactor, def.ReactorTerminal);
			def.ChainedPuzzleToActiveInstance = reactor.m_chainedPuzzleToStartSequence;
			_ = (Object)(object)def.ChainedPuzzleToActiveInstance != (Object)null;
			builtOverride.Add(def);
			EOSLogger.Debug($"ReactorStartup: {((GlobalZoneIndex)def).GlobalZoneIndexTuple()}, Instance_{((BaseInstanceDefinition)def).InstanceIndex}, override completed");
		}

		private void OnLevelCleanup()
		{
			builtOverride.ForEach(delegate(ReactorStartupOverride def)
			{
				def.ChainedPuzzleToActiveInstance = null;
			});
			builtOverride.Clear();
		}

		private ReactorStartupOverrideManager()
		{
			LevelAPI.OnLevelCleanup += OnLevelCleanup;
			LevelAPI.OnBuildStart += OnLevelCleanup;
		}

		static ReactorStartupOverrideManager()
		{
			SpecialCmdVerifyTextID = 0u;
			MainTerminalTextID = 0u;
			CooldownCommandDescTextID = 0u;
			InfiniteWaveVerifyTextID = 0u;
			NotReadyForVerificationOutputTextID = 0u;
			IncorrectTerminalOutputTextID = 0u;
			CorrectTerminalOutputTextID = 0u;
			Current = new ReactorStartupOverrideManager();
			EventAPI.OnExpeditionStarted += FetchOverrideTextDB;
		}
	}
	internal class ReactorShutdownObjectiveManager : InstanceDefinitionManager<ReactorShutdownDefinition>
	{
		private List<ReactorShutdownDefinition> builtShutdownPuzzles = new List<ReactorShutdownDefinition>();

		public static ReactorShutdownObjectiveManager Current { get; private set; }

		protected override string DEFINITION_NAME => "ReactorShutdown";

		private void GenericObjectiveSetup(LG_WardenObjective_Reactor reactor, TerminalDefinition reactorTerminalData)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			reactor.m_serialNumber = SerialGenerator.GetUniqueSerialNo();
			reactor.m_itemKey = "REACTOR_" + reactor.m_serialNumber;
			reactor.m_terminalItem = GOUtil.GetInterfaceFromComp<iTerminalItem>(reactor.m_terminalItemComp);
			reactor.m_terminalItem.Setup(reactor.m_itemKey, (AIG_CourseNode)null);
			reactor.m_terminalItem.FloorItemStatus = EnumUtil.GetRandomValue<eFloorInventoryObjectStatus>();
			reactor.m_overrideCodes = Il2CppStringArray.op_Implicit(new string[1] { SerialGenerator.GetCodeWord() });
			reactor.m_terminalItem.OnWantDetailedInfo = Func<List<string>, List<string>>.op_Implicit((Func<List<string>, List<string>>)delegate(List<string> defaultDetails)
			{
				List<string> list = new List<string> { "----------------------------------------------------------------", "MAIN POWER REACTOR" };
				Enumerator<string> enumerator = defaultDetails.GetEnumerator();
				while (enumerator.MoveNext())
				{
					string current = enumerator.Current;
					list.Add(current);
				}
				list.Add("----------------------------------------------------------------");
				return ListExtensions.ToIl2Cpp<string>(list);
			});
			reactor.m_terminal = GOUtil.SpawnChildAndGetComp<LG_ComputerTerminal>(reactor.m_terminalPrefab, reactor.m_terminalAlign);
			reactor.m_terminal.Setup((TerminalStartStateData)null, (TerminalPlacementData)null);
			reactor.m_terminal.ConnectedReactor = reactor;
			ReactorInstanceManager.Current.SetupReactorTerminal(reactor, reactorTerminalData);
		}

		private void OnLateBuildJob(LG_WardenObjective_Reactor reactor, BaseReactorDefinition reactorDefinition)
		{
			//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)
			//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_0044: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			reactor.m_stateReplicator = SNet_StateReplicator<pReactorState, pReactorInteraction>.Create(new iSNet_StateReplicatorProvider<pReactorState, pReactorInteraction>(((Il2CppObjectBase)reactor).Pointer), (eSNetReplicatorLifeTime)1, default(pReactorState), (SNet_ChannelType)2);
			GenericObjectiveSetup(reactor, reactorDefinition.ReactorTerminal);
			reactor.m_sound = new CellSoundPlayer(reactor.m_terminalAlign.position);
			reactor.m_sound.Post(EVENTS.REACTOR_POWER_LEVEL_1_LOOP, true);
			reactor.m_sound.SetRTPCValue(GAME_PARAMETERS.REACTOR_POWER, 100f);
			reactor.m_terminal.m_command.SetupReactorCommands(false, true);
		}

		internal void Build(LG_WardenObjective_Reactor reactor, ReactorShutdownDefinition def)
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: 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_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Expected O, but got Unknown
			//IL_019d: Expected O, but got Unknown
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			if (reactor.m_isWardenObjective)
			{
				EOSLogger.Error($"ReactorShutdown: Reactor definition for reactor {((GlobalZoneIndex)def).GlobalZoneIndexTuple()}, Instance_{((BaseInstanceDefinition)def).InstanceIndex} is already setup by vanilla, won't build.");
				return;
			}
			OnLateBuildJob(reactor, def);
			reactor.m_lightCollection = LG_LightCollection.Create(reactor.m_reactorArea.m_courseNode, reactor.m_terminalAlign.position, (LG_LightCollectionSorting)1, float.MaxValue);
			reactor.m_lightCollection.SetMode(true);
			if (def.PutVerificationCodeOnTerminal)
			{
				LG_ComputerTerminal instance = ((InstanceManager<LG_ComputerTerminal>)(object)TerminalInstanceManager.Current).GetInstance(((GlobalZoneIndex)def.VerificationCodeTerminal).GlobalZoneIndexTuple(), def.VerificationCodeTerminal.InstanceIndex);
				if ((Object)(object)instance == (Object)null)
				{
					EOSLogger.Error($"ReactorShutdown: PutVerificationCodeOnTerminal is specified but could NOT find terminal {def.VerificationCodeTerminal}, will show verification code upon shutdown initiation");
				}
				else
				{
					string fileName = "reactor_ver" + SerialGenerator.GetCodeWordPrefix() + ".log";
					TerminalLogFileData val = new TerminalLogFileData
					{
						FileName = fileName,
						FileContent = new LocalizedText
						{
							UntranslatedText = string.Format(Text.Get(182408469u), ((Il2CppArrayBase<string>)(object)reactor.m_overrideCodes)[0].ToUpperInvariant()),
							Id = 0u
						}
					};
					instance.AddLocalLog(val, true);
					instance.m_command.ClearOutputQueueAndScreenBuffer();
					instance.m_command.AddInitialTerminalOutput();
				}
			}
			if (reactor.SpawnNode != null && reactor.m_terminalItem != null)
			{
				reactor.m_terminalItem.SpawnNode = reactor.SpawnNode;
				reactor.m_terminalItem.FloorItemLocation = reactor.SpawnNode.m_zone.NavInfo.GetFormattedText((LG_NavInfoFormat)7);
			}
			if (def.ChainedPuzzleToActive != 0)
			{
				ChainedPuzzleDataBlock block = GameDataBlockBase<ChainedPuzzleDataBlock>.GetBlock(def.ChainedPuzzleToActive);
				if (block == null)
				{
					EOSLogger.Error("ReactorShutdown: ChainedPuzzleToActive is specified but could not find its ChainedPuzzleDatablock definition!");
				}
				else
				{
					_ = ((Component)reactor).transform.position;
					def.ChainedPuzzleToActiveInstance = ChainedPuzzleManager.CreatePuzzleInstance(block, reactor.SpawnNode.m_area, reactor.m_chainedPuzzleAlign.position, ((Component)reactor).transform);
					ChainedPuzzleInstance chainedPuzzleToActiveInstance = def.ChainedPuzzleToActiveInstance;
					chainedPuzzleToActiveInstance.OnPuzzleSolved += Action.op_Implicit((Action)delegate
					{
						if (SNet.IsMaster)
						{
							reactor.AttemptInteract((eReactorInteraction)6, 0f);
						}
					});
				}
			}
			else
			{
				EOSLogger.Debug("ReactorShutdown: Reactor has no ChainedPuzzleToActive, will start shutdown sequence on shutdown command initiation.");
			}
			if (def.ChainedPuzzleOnVerification != 0)
			{
				ChainedPuzzleDataBlock block2 = GameDataBlockBase<ChainedPuzzleDataBlock>.GetBlock(def.ChainedPuzzleOnVerification);
				if (block2 == null)
				{
					EOSLogger.Error("ReactorShutdown: ChainedPuzzleOnVerification is specified but could not find its ChainedPuzzleDatablock definition! Will complete shutdown on verification");
				}
				_ = ((Component)reactor).transform.position;
				def.ChainedPuzzleOnVerificationInstance = ChainedPuzzleManager.CreatePuzzleInstance(block2, reactor.SpawnNode.m_area, reactor.m_chainedPuzzleAlign.position, ((Component)reactor).transform);
				ChainedPuzzleInstance chainedPuzzleOnVerificationInstance = def.ChainedPuzzleOnVerificationInstance;
				chainedPuzzleOnVerificationInstance.OnPuzzleSolved += Action.op_Implicit((Action)delegate
				{
					if (SNet.IsMaster)
					{
						reactor.AttemptInteract((eReactorInteraction)9, 0f);
					}
				});
			}
			else
			{
				EOSLogger.Debug("ReactorShutdown: ChainedPuzzleOnVerification unspecified, will complete shutdown on verification.");
			}
			LG_ComputerTerminal terminal = reactor.m_terminal;
			iLG_SpawnedInNodeHandler val2 = ((terminal != null) ? ((Component)terminal).GetComponent<iLG_SpawnedInNodeHandler>() : null);
			if (val2 != null)
			{
				val2.SpawnNode = reactor.SpawnNode;
			}
			reactor.SetLightsEnabled(reactor.m_lightsWhenOff, false);
			reactor.SetLightsEnabled(reactor.m_lightsWhenOn, true);
			builtShutdownPuzzles.Add(def);
			ReactorInstanceManager.Current.MarkAsShutdownReactor(reactor);
			EOSLogger.Debug($"ReactorShutdown: {((GlobalZoneIndex)def).GlobalZoneIndexTuple()}, Instance_{((BaseInstanceDefinition)def).InstanceIndex}, custom setup completed");
		}

		private void OnLevelCleanup()
		{
			builtShutdownPuzzles.ForEach(delegate(ReactorShutdownDefinition def)
			{
				ChainedPuzzleInstance chainedPuzzleOnVerificationInstance = (def.ChainedPuzzleToActiveInstance = null);
				def.ChainedPuzzleOnVerificationInstance = chainedPuzzleOnVerificationInstance;
			});
			builtShutdownPuzzles.Clear();
		}

		private ReactorShutdownObjectiveManager()
		{
			LevelAPI.OnLevelCleanup += OnLevelCleanup;
			LevelAPI.OnBuildStart += OnLevelCleanup;
		}

		static ReactorShutdownObjectiveManager()
		{
			Current = new ReactorShutdownObjectiveManager();
		}
	}
}
namespace EOSExt.Reactor.Definition
{
	public enum EOSReactorVerificationType
	{
		NORMAL,
		BY_SPECIAL_COMMAND,
		BY_WARDEN_EVENT
	}
	public class WaveOverride
	{
		public int WaveIndex { get; set; } = -1;


		public EOSReactorVerificationType VerificationType { get; set; }

		public bool HideVerificationTimer { get; set; }

		public bool ChangeVerifyZone { get; set; }

		public BaseInstanceDefinition VerifyZone { get; set; } = new BaseInstanceDefinition();


		public bool UseCustomVerifyText { get; set; }

		public LocalizedText VerifySequenceText { get; set; }

		[JsonIgnore]
		public LG_ComputerTerminal VerifyTerminal { get; set; }
	}
	public class ReactorStartupOverride : BaseReactorDefinition
	{
		public bool StartupOnDrop { get; set; }

		[JsonIgnore]
		public WardenObjectiveDataBlock ObjectiveDB { get; set; }

		public List<WaveOverride> Overrides { get; set; } = new List<WaveOverride>
		{
			new WaveOverride()
		};

	}
	internal class WardenEvents
	{
		public enum EventType
		{
			ReactorStartup = 150,
			CompleteCurrentVerify
		}

		internal static void ReactorStartup(WardenObjectiveEventData e)
		{
			//IL_0009: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Invalid comparison between Unknown and I4
			//IL_005e: 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_00cc: 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_010c: Unknown result type (might be due to invalid IL or missing references)
			if (!SNet.IsMaster)
			{
				return;
			}
			LG_WardenObjective_Reactor val = ReactorInstanceManager.FindVanillaReactor(e.Layer, e.Count);
			WardenObjectiveDataBlock val2 = default(WardenObjectiveDataBlock);
			if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(e.Layer, ref val2) || val2 == null)
			{
				EOSLogger.Error("CompleteCurrentReactorWave: Cannot get WardenObjectiveDataBlock");
				return;
			}
			if ((int)val2.Type != 1)
			{
				EOSLogger.Error($"CompleteCurrentReactorWave: {e.Layer} is not ReactorStartup. CompleteCurrentReactorWave is invalid.");
				return;
			}
			if ((Object)(object)val == (Object)null)
			{
				EOSLogger.Error($"ReactorStartup: Cannot find reactor in {e.Layer}.");
				return;
			}
			if ((int)val.m_currentState.status == 0)
			{
				if (SNet.IsMaster)
				{
					val.AttemptInteract((eReactorInteraction)0, 0f);
				}
				val.m_terminal.TrySyncSetCommandHidden((TERM_Command)21);
			}
			EOSLogger.Debug($"ReactorStartup: Current reactor wave for {e.Layer} completed");
		}

		internal static void CompleteCurrentVerify(WardenObjectiveEventData e)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			//IL_0068: 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_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			WardenObjectiveDataBlock val = default(WardenObjectiveDataBlock);
			if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(e.Layer, ref val) || val == null)
			{
				EOSLogger.Error("CompleteCurrentReactorWave: Cannot get WardenObjectiveDataBlock");
				return;
			}
			if ((int)val.Type != 1)
			{
				EOSLogger.Error($"CompleteCurrentReactorWave: {e.Layer} is not ReactorStartup. CompleteCurrentReactorWave is invalid.");
				return;
			}
			LG_WardenObjective_Reactor val2 = ReactorInstanceManager.FindVanillaReactor(e.Layer, e.Count);
			if ((Object)(object)val2 == (Object)null)
			{
				EOSLogger.Error($"CompleteCurrentReactorWave: Cannot find reactor in {e.Layer}.");
				return;
			}
			if (SNet.IsMaster)
			{
				if (val2.m_currentWaveCount == val2.m_waveCountMax)
				{
					val2.AttemptInteract((eReactorInteraction)5, 0f);
				}
				else
				{
					val2.AttemptInteract((eReactorInteraction)3, 0f);
				}
			}
			else
			{
				WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(val2.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)3, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
			}
			EOSLogger.Debug($"CompleteCurrentReactorWave: Current reactor verify for {e.Layer} completed");
		}
	}
	public class BaseReactorDefinition : BaseInstanceDefinition
	{
		[JsonPropertyOrder(-9)]
		public TerminalDefinition ReactorTerminal { get; set; } = new TerminalDefinition();


		[JsonPropertyOrder(-9)]
		public List<WardenObjectiveEventData> EventsOnActive { get; set; } = new List<WardenObjectiveEventData>();


		[JsonIgnore]
		public ChainedPuzzleInstance ChainedPuzzleToActiveInstance { get; set; }
	}
	public class ReactorShutdownDefinition : BaseReactorDefinition
	{
		[JsonPropertyOrder(-9)]
		public uint ChainedPuzzleToActive { get; set; }

		public bool PutVerificationCodeOnTerminal { get; set; }

		public BaseInstanceDefinition VerificationCodeTerminal { get; set; } = new BaseInstanceDefinition();


		public uint ChainedPuzzleOnVerification { get; set; }

		[JsonIgnore]
		public ChainedPuzzleInstance ChainedPuzzleOnVerificationInstance { get; set; }

		public List<WardenObjectiveEventData> EventsOnShutdownPuzzleStarts { get; set; } = new List<WardenObjectiveEventData>();


		public List<WardenObjectiveEventData> EventsOnComplete { get; set; } = new List<WardenObjectiveEventData>();

	}
}
namespace EOSExt.Reactor.Component
{
	public class OverrideReactorComp : MonoBehaviour
	{
		private static Color LowTemperature;

		private static Color HighTemperature;

		private LG_Light[] _lights;

		private float _updateTimer;

		private List<WaveOverride> WaveData = new List<WaveOverride>();

		public LG_WardenObjective_Reactor ChainedReactor { get; internal set; }

		public ReactorStartupOverride overrideData { get; internal set; }

		public bool UsingLightEffect { get; set; } = true;


		public WardenObjectiveDataBlock ObjectiveData => overrideData?.ObjectiveDB;

		public void Init()
		{
			if ((Object)(object)ChainedReactor == (Object)null || overrideData == null)
			{
				EOSLogger.Error("ReactorOverride not properly initialized!");
				return;
			}
			foreach (WaveOverride @override in overrideData.Overrides)
			{
				int waveIndex = @override.WaveIndex;
				for (int i = ((WaveData.Count > 0) ? WaveData.Last().WaveIndex : (-1)) + 1; i < waveIndex; i++)
				{
					WaveData.Add(new WaveOverride
					{
						WaveIndex = i
					});
				}
				WaveData.Add(@override);
			}
			for (int j = ((WaveData.Count > 0) ? WaveData.Last().WaveIndex : (-1)) + 1; j < ChainedReactor.m_waveCountMax; j++)
			{
				WaveData.Add(new WaveOverride
				{
					WaveIndex = j
				});
			}
			if (WaveData.Count != ObjectiveData.ReactorWaves.Count)
			{
				EOSLogger.Error($"WaveData.Count({WaveData.Count}) != ObjectiveData.ReactorWaves.Count({ObjectiveData.ReactorWaves.Count})");
			}
			LevelAPI.OnEnterLevel += OnEnterLevel;
		}

		private void OnEnterLevel()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			LG_WardenObjective_Reactor chainedReactor = ChainedReactor;
			LG_ComputerTerminal terminal = ChainedReactor.m_terminal;
			if ((int)ObjectiveData.Type != 1)
			{
				EOSLogger.Error("Only Reactor Startup is supported");
				((Behaviour)this).enabled = false;
				return;
			}
			if (UsingLightEffect)
			{
				_lights = ((IEnumerable<LG_Light>)chainedReactor.SpawnNode.m_lightsInNode).Where((LG_Light x) => (int)x.m_category == 3).ToArray();
				chainedReactor.m_lightCollection.RemoveLights(Il2CppReferenceArray<LG_Light>.op_Implicit(_lights));
			}
			if (overrideData.StartupOnDrop && SNet.IsMaster)
			{
				chainedReactor.AttemptInteract((eReactorInteraction)0, 0f);
				terminal.TrySyncSetCommandHidden((TERM_Command)21);
			}
			SetupVerifyZoneOverrides();
			SetupWaves();
		}

		private void SetupVerifyZoneOverrides()
		{
			//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_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_03db: Unknown result type (might be due to invalid IL or missing references)
			//IL_03dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0411: Unknown result type (might be due to invalid IL or missing references)
			//IL_041d: Expected O, but got Unknown
			//IL_041f: Expected O, but got Unknown
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = default(LG_Zone);
			foreach (WaveOverride waveDatum in WaveData)
			{
				if (!waveDatum.ChangeVerifyZone)
				{
					continue;
				}
				if (waveDatum.VerificationType == EOSReactorVerificationType.BY_WARDEN_EVENT)
				{
					EOSLogger.Error($"VerifyZoneOverrides: Wave_{waveDatum.WaveIndex} - Verification Type is {2}, which doesn't work with VerifyZoneOverride");
					continue;
				}
				BaseInstanceDefinition verifyZone = waveDatum.VerifyZone;
				if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(((GlobalZoneIndex)verifyZone).DimensionIndex, ((GlobalZoneIndex)verifyZone).LayerType, ((GlobalZoneIndex)verifyZone).LocalIndex, ref val) || (Object)(object)val == (Object)null)
				{
					EOSLogger.Error($"VerifyZoneOverrides: Wave_{waveDatum.WaveIndex} - Cannot find target zone {((GlobalZoneIndex)verifyZone).GlobalZoneIndexTuple()}.");
					continue;
				}
				if (val.TerminalsSpawnedInZone == null || val.TerminalsSpawnedInZone.Count <= 0)
				{
					EOSLogger.Error($"VerifyZoneOverrides: No spawned terminal found in target zone {((GlobalZoneIndex)verifyZone).GlobalZoneIndexTuple()}.");
					continue;
				}
				LG_ComputerTerminal val2 = null;
				if (verifyZone.InstanceIndex >= 0)
				{
					val2 = ((InstanceManager<LG_ComputerTerminal>)(object)TerminalInstanceManager.Current).GetInstance(((GlobalZoneIndex)verifyZone).GlobalZoneIndexTuple(), verifyZone.InstanceIndex);
				}
				else
				{
					List<LG_ComputerTerminal> instancesInZone = ((InstanceManager<LG_ComputerTerminal>)(object)TerminalInstanceManager.Current).GetInstancesInZone(((GlobalZoneIndex)verifyZone).GlobalZoneIndexTuple());
					int index = Builder.SessionSeedRandom.Range(0, instancesInZone.Count, "NO_TAG");
					val2 = instancesInZone[index];
				}
				if ((Object)(object)val2 == (Object)null)
				{
					EOSLogger.Error($"VerifyZoneOverride: cannot find target terminal with Terminal Instance Index: {waveDatum}");
				}
				waveDatum.VerifyTerminal = val2;
				ReactorWaveData waveData = ObjectiveData.ReactorWaves[waveDatum.WaveIndex];
				TerminalLogFileData val3 = null;
				if (waveData.VerifyInOtherZone)
				{
					List<LG_ComputerTerminal> list = EOSTerminalUtils.FindTerminal(ChainedReactor.SpawnNode.m_dimension.DimensionIndex, ChainedReactor.SpawnNode.LayerType, waveData.ZoneForVerification, (Predicate<LG_ComputerTerminal>)((LG_ComputerTerminal x) => x.ItemKey == waveData.VerificationTerminalSerial));
					if (list == null || list.Count < 1)
					{
						EOSLogger.Error($"Wave_{waveDatum.WaveIndex}: cannot find vanilla verification terminal in {(ChainedReactor.SpawnNode.m_dimension.DimensionIndex, ChainedReactor.SpawnNode.LayerType, waveData.ZoneForVerification)}, unable to override");
						continue;
					}
					LG_ComputerTerminal val4 = list[0];
					if ((Object)(object)val4 == (Object)null)
					{
						EOSLogger.Error($"VerifyZoneOverrides: Wave_{waveDatum.WaveIndex} - Cannot find log terminal");
						continue;
					}
					string text = waveData.VerificationTerminalFileName.ToUpperInvariant();
					val3 = EOSTerminalUtils.GetLocalLog(val4, text);
					if (val3 == null)
					{
						EOSLogger.Error("VerifyZoneOverrides: Cannot find vanilla-generated reactor verify log on terminal...");
						continue;
					}
					val4.RemoveLocalLog(text);
					EOSTerminalUtils.ResetInitialOutput(val4);
				}
				else
				{
					waveData.VerificationTerminalFileName = "reactor_ver" + SerialGenerator.GetCodeWordPrefix() + ".log";
					val3 = new TerminalLogFileData
					{
						FileName = waveData.VerificationTerminalFileName,
						FileContent = new LocalizedText
						{
							UntranslatedText = string.Format(Text.Get(182408469u), ((Il2CppArrayBase<string>)(object)ChainedReactor.m_overrideCodes)[waveDatum.WaveIndex].ToUpper()),
							Id = 0u
						}
					};
					EOSLogger.Debug($"VerifyZoneOverrides: Wave_{waveDatum.WaveIndex} - Log generated.");
				}
				waveData.HasVerificationTerminal = true;
				waveData.VerificationTerminalSerial = val2.ItemKey;
				val2.AddLocalLog(val3, true);
				EOSTerminalUtils.ResetInitialOutput(val2);
				EOSLogger.Debug($"VerifyZoneOverrides: Wave_{waveDatum.WaveIndex} verification overriden");
			}
		}

		private void SetupWaves()
		{
			//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_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_00c7: 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_00d0: Unknown result type (might be due to invalid IL or missing references)
			LG_WardenObjective_Reactor chainedReactor = ChainedReactor;
			eDimensionIndex dimensionIndex = chainedReactor.SpawnNode.m_dimension.DimensionIndex;
			LG_LayerType layerType = chainedReactor.SpawnNode.LayerType;
			int num = 0;
			for (int i = 0; i < WaveData.Count; i++)
			{
				ReactorWaveData reactorWave = ObjectiveData.ReactorWaves[i];
				WaveOverride waveOverride = WaveData[i];
				switch (waveOverride.VerificationType)
				{
				case EOSReactorVerificationType.BY_SPECIAL_COMMAND:
					if (!reactorWave.HasVerificationTerminal)
					{
						waveOverride.VerifyTerminal = ChainedReactor.m_terminal;
						AddVerifyCommand(ChainedReactor.m_terminal);
					}
					else
					{
						LG_ComputerTerminal val = waveOverride.VerifyTerminal;
						if ((Object)(object)val == (Object)null)
						{
							val = EOSTerminalUtils.FindTerminal(dimensionIndex, layerType, reactorWave.ZoneForVerification, (Predicate<LG_ComputerTerminal>)((LG_ComputerTerminal terminal) => terminal.ItemKey.Equals(reactorWave.VerificationTerminalSerial, StringComparison.InvariantCultureIgnoreCase)))?[0];
							if ((Object)(object)val == (Object)null)
							{
								EOSLogger.Error($"SetupWaves: cannot find verify terminal for Wave_{i}, skipped");
								break;
							}
							waveOverride.VerifyTerminal = val;
						}
						val.ConnectedReactor = chainedReactor;
						val.RemoveLocalLog(reactorWave.VerificationTerminalFileName.ToUpperInvariant());
						AddVerifyCommand(val);
						EOSTerminalUtils.ResetInitialOutput(val);
					}
					num++;
					EOSLogger.Debug($"WaveOverride: Setup as Wave Verification {1} for Wave_{i}");
					break;
				default:
					EOSLogger.Error($"Unimplemented Verification Type {waveOverride.VerificationType}");
					break;
				case EOSReactorVerificationType.NORMAL:
				case EOSReactorVerificationType.BY_WARDEN_EVENT:
					break;
				}
			}
			if (num == ObjectiveData.ReactorWaves.Count)
			{
				ChainedReactor.m_terminal.TrySyncSetCommandHidden((TERM_Command)22);
			}
		}

		private void AddVerifyCommand(LG_ComputerTerminal terminal)
		{
			//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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			LG_ComputerTerminalCommandInterpreter command = terminal.m_command;
			if (command.HasRegisteredCommand((TERM_Command)42))
			{
				EOSLogger.Debug("TERM_Command.UniqueCommand5 already registered. If this terminal is specified as objective terminal for 2 waves and the number of commands in 'UniqueCommands' on this terminal isn't more than 4, simply ignore this message.");
				return;
			}
			command.AddCommand((TERM_Command)42, "REACTOR_COOLDOWN", new LocalizedText
			{
				UntranslatedText = ReactorStartupOverrideManager.CoolDownCommandDesc,
				Id = 0u
			}, (TERM_CommandRule)0);
			terminal.TrySyncSetCommandRule((TERM_Command)42, (TERM_CommandRule)0);
		}

		public bool IsCorrectTerminal(LG_ComputerTerminal terminal)
		{
			int num = ChainedReactor.m_currentWaveCount - 1;
			if (num >= 0)
			{
				EOSLogger.Debug($"Index: {num}");
				EOSLogger.Debug("Comp Terminal Key1: " + terminal.ItemKey);
				EOSLogger.Debug("Comp Terminal Key2: " + (((Object)(object)WaveData[num].VerifyTerminal != (Object)null) ? WaveData[num].VerifyTerminal.ItemKey : "empty"));
				if (WaveData[num].VerifyTerminal.ItemKey != null && WaveData[num].VerifyTerminal.ItemKey.Equals(terminal.ItemKey, StringComparison.InvariantCultureIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		public void SetIdle()
		{
			//IL_0011: 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_003b: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)ChainedReactor == (Object)null))
			{
				pReactorState val = default(pReactorState);
				val.status = (eReactorStatus)0;
				val.stateCount = 0;
				val.stateProgress = 0f;
				val.verifyFailed = false;
				pReactorState state = val;
				ChainedReactor.m_stateReplicator.State = state;
			}
		}

		private void OnDestroy()
		{
			LevelAPI.OnEnterLevel -= OnEnterLevel;
			ChainedReactor = null;
			overrideData = null;
		}

		private void LateUpdate()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//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_001a: 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_0024: Unknown result type (might be due to invalid IL or missing references)
			if ((int)GameStateManager.CurrentStateName == 10)
			{
				eReactorStatus status = ChainedReactor.m_currentState.status;
				if (UsingLightEffect)
				{
					UpdateLight(status, ChainedReactor.m_currentWaveProgress);
				}
				UpdateGUIText(status);
			}
		}

		private void UpdateGUIText(eReactorStatus status)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Invalid comparison between Unknown and I4
			int num = ChainedReactor.m_currentWaveCount - 1;
			if (num < 0 || num >= ChainedReactor.m_waveCountMax)
			{
				return;
			}
			WaveOverride waveOverride = WaveData[num];
			string format = string.Empty;
			if (waveOverride.UseCustomVerifyText)
			{
				format = ((waveOverride.VerifySequenceText.Id != 0) ? Text.Get(waveOverride.VerifySequenceText.Id) : waveOverride.VerifySequenceText.UntranslatedText);
			}
			if ((int)status != 4)
			{
				return;
			}
			switch (waveOverride.VerificationType)
			{
			case EOSReactorVerificationType.NORMAL:
				if (ChainedReactor.m_currentWaveData.HasVerificationTerminal)
				{
					if (!waveOverride.UseCustomVerifyText)
					{
						format = Text.Get(1103u);
					}
					ChainedReactor.SetGUIMessage(true, string.Format(format, ChainedReactor.m_currentWaveCount, ChainedReactor.m_waveCountMax, "<color=orange>" + ChainedReactor.m_currentWaveData.VerificationTerminalSerial + "</color>"), (ePUIMessageStyle)3, !waveOverride.HideVerificationTimer, "<size=125%>" + Text.Get(1104u), "</size>");
				}
				else
				{
					if (!waveOverride.UseCustomVerifyText)
					{
						format = Text.Get(1105u);
					}
					ChainedReactor.SetGUIMessage(true, string.Format(format, ChainedReactor.m_currentWaveCount, ChainedReactor.m_waveCountMax, "<color=orange>" + ChainedReactor.CurrentStateOverrideCode + "</color>"), (ePUIMessageStyle)3, !waveOverride.HideVerificationTimer, "<size=125%>" + Text.Get(1104u), "</size>");
				}
				break;
			case EOSReactorVerificationType.BY_SPECIAL_COMMAND:
			{
				string text = (ChainedReactor.m_currentWaveData.HasVerificationTerminal ? ChainedReactor.m_currentWaveData.VerificationTerminalSerial : ReactorStartupOverrideManager.MainTerminalText);
				if (!waveOverride.UseCustomVerifyText)
				{
					format = ReactorStartupOverrideManager.SpecialCmdVerifyText;
				}
				ChainedReactor.SetGUIMessage(true, string.Format(format, ChainedReactor.m_currentWaveCount, ChainedReactor.m_waveCountMax, "<color=orange>" + text + "</color>"), (ePUIMessageStyle)3, !waveOverride.HideVerificationTimer, "<size=125%>" + Text.Get(1104u), "</size>");
				break;
			}
			case EOSReactorVerificationType.BY_WARDEN_EVENT:
				if (!waveOverride.UseCustomVerifyText)
				{
					format = ReactorStartupOverrideManager.InfiniteWaveVerifyText;
				}
				ChainedReactor.SetGUIMessage(true, string.Format(format, ChainedReactor.m_currentWaveCount, ChainedReactor.m_waveCountMax), (ePUIMessageStyle)3, !waveOverride.HideVerificationTimer, "<size=125%>" + Text.Get(1104u), "</size>");
				break;
			}
		}

		private void UpdateLight(eReactorStatus status, float progress)
		{
			//IL_001f: 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: Expected I4, but got Unknown
			//IL_003d: 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_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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)
			if (!(_updateTimer > Clock.Time))
			{
				_updateTimer = Clock.Time + 0.15f;
				switch (status - 1)
				{
				case 0:
					SetLightColor(Color.black);
					break;
				case 1:
					SetLightColor(Color.Lerp(LowTemperature, HighTemperature, progress));
					break;
				case 2:
					SetLightColor(Color.Lerp(HighTemperature, LowTemperature, progress));
					break;
				case 3:
					SetLightColor(LowTemperature);
					break;
				case 4:
					SetLightColor(LowTemperature);
					break;
				}
			}
		}

		private void SetLightColor(Color color)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if (UsingLightEffect && _lights != null)
			{
				for (int i = 0; i < _lights.Length; i++)
				{
					_lights[i].ChangeColor(color);
				}
			}
		}

		static OverrideReactorComp()
		{
			//IL_0005: 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_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_002d: Unknown result type (might be due to invalid IL or missing references)
			LowTemperature = ColorExt.Hex("#23E4F2") * 2.5f;
			HighTemperature = ColorExt.Hex("#F63838") * 12f;
		}
	}
}

plugins/Inas07-ExtraChainedPuzzleCustomization/ScanPosOverride.dll

Decompiled 7 hours 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 System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using AIGraph;
using Agents;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using ChainedPuzzles;
using GTFO.API;
using GTFO.API.Extensions;
using GTFO.API.Utilities;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Text;
using LevelGeneration;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using ScanPosOverride.Component;
using ScanPosOverride.JSON;
using ScanPosOverride.Managers;
using ScanPosOverride.PuzzleOverrideData;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ScanPosOverride")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ScanPosOverride")]
[assembly: AssemblyTitle("ScanPosOverride")]
[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 ScanPosOverride
{
	internal static class SPOLogger
	{
		private static readonly ManualLogSource logger = Logger.CreateLogSource("ScanPosOverride");

		public static void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		public static void Log(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)8, (object)str);
			}
		}

		public static void Warning(string format, params object[] args)
		{
			Warning(string.Format(format, args));
		}

		public static void Warning(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)4, (object)str);
			}
		}

		public static void Error(string format, params object[] args)
		{
			Error(string.Format(format, args));
		}

		public static void Error(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)2, (object)str);
			}
		}

		public static void Debug(string format, params object[] args)
		{
			Debug(string.Format(format, args));
		}

		public static void Debug(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)32, (object)str);
			}
		}

		public static void Log(BepInExDebugLogInterpolatedStringHandler logHandler)
		{
			logger.LogDebug(logHandler);
		}
	}
	[BepInPlugin("ScanPositionOverride", "ScanPositionOverride", "1.6.7")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal sealed class Plugin : BasePlugin
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static LiveEditEventHandler <0>__LiveEdit_FileChanged;
		}

		private static Dictionary<uint, Dictionary<uint, PuzzleOverride>> PuzzleOverrides = new Dictionary<uint, Dictionary<uint, PuzzleOverride>>();

		public static readonly string OVERRIDE_SCAN_POS_PATH = Path.Combine(MTFOPathAPI.CustomPath, "ScanPositionOverrides");

		private static LiveEditListener listener = null;

		private static Harmony m_Harmony = null;

		public override void Load()
		{
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Expected O, but got Unknown
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Expected O, but got Unknown
			SPOLogger.Error(OVERRIDE_SCAN_POS_PATH);
			if (!Directory.Exists(OVERRIDE_SCAN_POS_PATH))
			{
				Directory.CreateDirectory(OVERRIDE_SCAN_POS_PATH);
				StreamWriter streamWriter = File.CreateText(Path.Combine(OVERRIDE_SCAN_POS_PATH, "Template.json"));
				streamWriter.WriteLine(Json.Serialize(new PuzzleOverrideJsonFile()));
				streamWriter.Flush();
				streamWriter.Close();
				return;
			}
			foreach (string item in Directory.EnumerateFiles(OVERRIDE_SCAN_POS_PATH, "*.json", SearchOption.AllDirectories))
			{
				Json.Load<PuzzleOverrideJsonFile>(item, out var config);
				if (PuzzleOverrides.ContainsKey(config.MainLevelLayout))
				{
					SPOLogger.Warning("Duplicate MainLevelLayout {0}, won't load.", config.MainLevelLayout);
					continue;
				}
				Dictionary<uint, PuzzleOverride> dictionary = new Dictionary<uint, PuzzleOverride>();
				foreach (PuzzleOverride puzzle in config.Puzzles)
				{
					if (dictionary.ContainsKey(puzzle.Index))
					{
						SPOLogger.Error("Duplicate Puzzle Override found. MainLevelLayout {0}, Index {1}.", config.MainLevelLayout, puzzle.Index);
						continue;
					}
					puzzle.EventsOnBioscanProgress.RemoveAll((BioscanProgressEvent e) => e.Progress <= 0f);
					puzzle.EventsOnBioscanProgress.Sort((BioscanProgressEvent e1, BioscanProgressEvent e2) => Mathf.RoundToInt(e1.Progress - e2.Progress));
					dictionary.Add(puzzle.Index, puzzle);
				}
				PuzzleOverrides.Add(config.MainLevelLayout, dictionary);
			}
			listener = LiveEdit.CreateListener(OVERRIDE_SCAN_POS_PATH, "*.json", true);
			LiveEditListener obj = listener;
			object obj2 = <>O.<0>__LiveEdit_FileChanged;
			if (obj2 == null)
			{
				LiveEditEventHandler val = LiveEdit_FileChanged;
				<>O.<0>__LiveEdit_FileChanged = val;
				obj2 = (object)val;
			}
			obj.FileChanged += (LiveEditEventHandler)obj2;
			m_Harmony = new Harmony("ScanPosOverride.Patches");
			m_Harmony.PatchAll();
		}

		private static void LiveEdit_FileChanged(LiveEditEventArgs e)
		{
			SPOLogger.Warning("LiveEdit File Changed: " + e.FullPath + ".");
			LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content)
			{
				PuzzleOverrideJsonFile puzzleOverrideJsonFile = Json.Deserialize<PuzzleOverrideJsonFile>(content);
				if (!PuzzleOverrides.ContainsKey(puzzleOverrideJsonFile.MainLevelLayout))
				{
					SPOLogger.Warning("MainLevelLayout not found, which is now not supported. Will not replace.");
				}
				else
				{
					Dictionary<uint, PuzzleOverride> dictionary = PuzzleOverrides[puzzleOverrideJsonFile.MainLevelLayout];
					dictionary.Clear();
					foreach (PuzzleOverride puzzle in puzzleOverrideJsonFile.Puzzles)
					{
						if (dictionary.ContainsKey(puzzle.Index))
						{
							SPOLogger.Error("Duplicate Puzzle Override found. MainLevelLayout {0}, Index {1}.", puzzleOverrideJsonFile.MainLevelLayout, puzzle.Index);
						}
						else
						{
							puzzle.EventsOnBioscanProgress.Sort((BioscanProgressEvent e1, BioscanProgressEvent e2) => Mathf.RoundToInt(e1.Progress - e2.Progress));
							dictionary.Add(puzzle.Index, puzzle);
						}
					}
					SPOLogger.Warning("Replaced Override Puzzle with MainLevelLayout {0}", puzzleOverrideJsonFile.MainLevelLayout);
				}
			});
		}

		internal static PuzzleOverride GetOverride(uint mainLevelLayout, uint puzzleIndex)
		{
			if (!PuzzleOverrides.ContainsKey(mainLevelLayout))
			{
				return null;
			}
			Dictionary<uint, PuzzleOverride> dictionary = PuzzleOverrides[mainLevelLayout];
			if (!dictionary.ContainsKey(puzzleIndex))
			{
				return null;
			}
			return dictionary[puzzleIndex];
		}
	}
	public static class Utils
	{
	}
}
namespace ScanPosOverride.PuzzleOverrideData
{
	internal sealed class PuzzleOverrideJsonFile
	{
		public uint MainLevelLayout { get; set; }

		public List<PuzzleOverride> Puzzles { get; set; } = new List<PuzzleOverride>
		{
			new PuzzleOverride()
		};

	}
	public class BioscanProgressEvent
	{
		public float Progress { get; set; } = -1f;


		public List<WardenObjectiveEventData> Events { get; set; } = new List<WardenObjectiveEventData>();

	}
	public class ClusterProgressEvent
	{
		public int Count { get; set; } = -1;


		public List<WardenObjectiveEventData> Events { get; set; } = new List<WardenObjectiveEventData>();

	}
	public class PuzzleOverride
	{
		public uint Index { get; set; }

		public Vec3 Position { get; set; } = new Vec3();


		public Vec3 Rotation { get; set; } = new Vec3();


		public bool HideSpline { get; set; }

		public Vec3 PrevPosOverride { get; set; } = new Vec3();


		public uint PrevPosOverrideIndex { get; set; }

		public bool ConcurrentCluster { get; set; }

		public float TMoveSpeedMulti { get; set; } = -1f;


		public List<BioscanProgressEvent> EventsOnBioscanProgress { get; set; } = new List<BioscanProgressEvent>
		{
			new BioscanProgressEvent()
		};


		public List<ClusterProgressEvent> EventsOnClusterProgress { get; set; } = new List<ClusterProgressEvent>
		{
			new ClusterProgressEvent()
		};


		public List<Vec3> TPositions { get; set; } = new List<Vec3>
		{
			new Vec3()
		};


		public List<int> RequiredItemsIndices { get; set; } = new List<int> { 0 };


		public List<WardenObjectiveEventData> EventsOnPuzzleSolved { get; set; } = new List<WardenObjectiveEventData>();

	}
	public class Vec3
	{
		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public Vector3 ToVector3()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(x, y, z);
		}

		public Quaternion ToQuaternion()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return Quaternion.Euler(x, y, z);
		}
	}
}
namespace ScanPosOverride.Patches
{
	[HarmonyPatch]
	internal static class Patch_CP_BasicMovable_TryGetNextIndex
	{
	}
	[HarmonyPatch]
	internal static class Patch_CP_Bioscan_Core_OnSyncStateChange
	{
		private static Dictionary<IntPtr, int> EOPIndex;

		static Patch_CP_Bioscan_Core_OnSyncStateChange()
		{
			EOPIndex = new Dictionary<IntPtr, int>();
			LevelAPI.OnBuildStart += EOPIndex.Clear;
			LevelAPI.OnLevelCleanup += EOPIndex.Clear;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Bioscan_Core), "OnSyncStateChange")]
		private static void Post_OnSyncStateChanged_CheckEOPAndEventsOnPuzzleSolved(CP_Bioscan_Core __instance, float progress, eBioscanStatus status, List<PlayerAgent> playersInScan, bool isDropinState)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Invalid comparison between Unknown and I4
			uint bioscanCoreOverrideIndex = PuzzleOverrideManager.Current.GetBioscanCoreOverrideIndex(__instance);
			PuzzleOverride def = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, bioscanCoreOverrideIndex);
			if (def != null)
			{
				if (def.EventsOnBioscanProgress.Count > 0)
				{
					CheckBioscanEventsOnProgress();
				}
				if ((int)status == 4 && !isDropinState && def.EventsOnPuzzleSolved.Count > 0)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(def.EventsOnPuzzleSolved), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
				}
			}
			void CheckBioscanEventsOnProgress()
			{
				if (!EOPIndex.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
				{
					EOPIndex[((Il2CppObjectBase)__instance).Pointer] = 0;
				}
				int i = EOPIndex[((Il2CppObjectBase)__instance).Pointer];
				if (isDropinState)
				{
					for (; i < def.EventsOnBioscanProgress.Count && !(def.EventsOnBioscanProgress[i].Progress > progress); i++)
					{
					}
				}
				else if (i < def.EventsOnBioscanProgress.Count && def.EventsOnBioscanProgress[i].Progress < progress)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(def.EventsOnBioscanProgress[i].Events), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
					EOPIndex[((Il2CppObjectBase)__instance).Pointer] = i + 1;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Bioscan_Core), "OnSyncStateChange")]
		private static void Post_OnSyncStateChanged_CheckReqItemAndConcurrentCluster(CP_Bioscan_Core __instance, float progress, eBioscanStatus status, List<PlayerAgent> playersInScan, bool isDropinState)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Invalid comparison between Unknown and I4
			//IL_002f: 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_0077: Invalid comparison between Unknown and I4
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Invalid comparison between Unknown and I4
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Invalid comparison between Unknown and I4
			//IL_018f: 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_01a3: 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_01d8: Invalid comparison between Unknown and I4
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0335: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			bool flag = PlayerScannerManager.Current.IsConcurrentCluster(__instance);
			if (flag && __instance.m_reqItemsEnabled)
			{
				SPOLogger.Warning($"OnSyncStateChange: status - {status}, playersInScan - {playersInScan.Count}, progress: {progress}");
			}
			if ((int)status != 3)
			{
				if (flag)
				{
					if ((int)status == 4)
					{
						CP_Cluster_Core val = ((Il2CppObjectBase)__instance.Owner).TryCast<CP_Cluster_Core>();
						if ((Object)(object)val == (Object)null)
						{
							SPOLogger.Error("Cannot find parent cluster core! The concurrent cluster may fail!");
						}
						else
						{
							PlayerScannerManager.Current.CompleteConcurrentCluster(val, __instance);
						}
					}
					else
					{
						PlayerScannerManager.Current.CCShouldProgress(__instance, IsThisScanShouldProgress: false);
					}
				}
				if (__instance.m_reqItemsEnabled)
				{
					__instance.m_graphics.SetColorMode((eChainedPuzzleGraphicsColorMode)((!__instance.m_hasAlarm) ? 1 : 4));
				}
			}
			else
			{
				if (!__instance.IsMovable && !flag && !__instance.m_reqItemsEnabled)
				{
					return;
				}
				CP_PlayerScanner cacheScanner = PlayerScannerManager.Current.GetCacheScanner(__instance);
				if ((Object)(object)cacheScanner == (Object)null)
				{
					return;
				}
				int count = playersInScan.Count;
				List<PlayerAgent> playerAgentsInLevel = PlayerManager.PlayerAgentsInLevel;
				float num = 0f;
				float[] cacheOriginalScanSpeed = PlayerScannerManager.Current.GetCacheOriginalScanSpeed(__instance);
				if ((int)__instance.m_playerScanner.ScanPlayersRequired == 0)
				{
					num = ((count <= 0) ? 0f : cacheOriginalScanSpeed[count - 1]);
				}
				else if (((int)cacheScanner.m_playerRequirement == 1 && count == playerAgentsInLevel.Count) || ((int)cacheScanner.m_playerRequirement == 2 && count == 1))
				{
					num = cacheOriginalScanSpeed[0];
				}
				bool flag2 = num > 0f;
				if (flag2 && cacheScanner.m_reqItemsEnabled)
				{
					for (int i = 0; i < ((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems).Length; i++)
					{
						Vector3 val2 = Vector3.zero;
						if ((int)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickupItemStatus == 0)
						{
							val2 = ((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].transform.position;
						}
						else if ((int)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickupItemStatus == 1)
						{
							if ((Object)(object)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickedUpByPlayer != (Object)null)
							{
								val2 = ((Agent)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickedUpByPlayer).Position;
							}
							else
							{
								Debug.LogError(Object.op_Implicit("Playerscanner is looking for an item that has ePickupItemStatus.PickedUp but null player, how come!?"));
							}
						}
						Vector3 val3 = ((Component)cacheScanner).transform.position - val2;
						if (((Vector3)(ref val3)).sqrMagnitude >= cacheScanner.m_scanRadiusSqr)
						{
							flag2 = false;
							break;
						}
					}
				}
				if (flag)
				{
					if (flag2)
					{
						flag2 = PlayerScannerManager.Current.CCShouldProgress(__instance, IsThisScanShouldProgress: true);
					}
					else
					{
						PlayerScannerManager.Current.CCShouldProgress(__instance, IsThisScanShouldProgress: false);
					}
				}
				if (flag2)
				{
					if (flag)
					{
						CP_Cluster_Core parent = ((Il2CppObjectBase)__instance.Owner).Cast<CP_Cluster_Core>();
						PlayerScannerManager.Current.RestoreCCScanSpeed(parent);
					}
					if (__instance.IsMovable)
					{
						__instance.m_movingComp.ResumeMovement();
					}
					if (cacheScanner.m_reqItemsEnabled)
					{
						if ((int)cacheScanner.m_playerRequirement == 0)
						{
							((Il2CppArrayBase<float>)(object)cacheScanner.m_scanSpeeds)[0] = ((count > 0) ? cacheOriginalScanSpeed[count - 1] : 0f);
						}
						__instance.m_graphics.SetColorMode((eChainedPuzzleGraphicsColorMode)(__instance.m_hasAlarm ? 5 : 2));
					}
					return;
				}
				if (flag)
				{
					CP_Cluster_Core parent2 = ((Il2CppObjectBase)__instance.Owner).Cast<CP_Cluster_Core>();
					PlayerScannerManager.Current.ZeroCCScanSpeed(parent2);
				}
				if (__instance.IsMovable)
				{
					__instance.m_movingComp.PauseMovement();
				}
				if (cacheScanner.m_reqItemsEnabled)
				{
					if ((int)cacheScanner.m_playerRequirement == 0)
					{
						PlayerScannerManager.Current.GetCacheOriginalScanSpeed(__instance);
						((Il2CppArrayBase<float>)(object)cacheScanner.m_scanSpeeds)[0] = 0f;
					}
					__instance.m_graphics.SetColorMode((eChainedPuzzleGraphicsColorMode)((!__instance.m_hasAlarm) ? 1 : 4));
				}
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_CP_Bioscan_Core_Setup
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(CP_Bioscan_Core), "Setup")]
		private static void Pre_CP_Bioscan_Core_Setup(CP_Bioscan_Core __instance, int puzzleIndex, iChainedPuzzleOwner owner, ref Vector3 prevPuzzlePos, ref bool revealWithHoloPath, ref bool onlyShowHUDWhenPlayerIsClose)
		{
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: 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_0389: Unknown result type (might be due to invalid IL or missing references)
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a5: 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_00a9: 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_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: 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_00b2: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: 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_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: 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_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_047c: Unknown result type (might be due to invalid IL or missing references)
			//IL_049f: Unknown result type (might be due to invalid IL or missing references)
			ChainedPuzzleInstance val = ((Il2CppObjectBase)owner).TryCast<ChainedPuzzleInstance>();
			uint num = PuzzleOverrideManager.Current.Register(__instance);
			PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, num);
			if ((Object)(object)val != (Object)null)
			{
				bool flag = false;
				if (@override != null)
				{
					if (@override.PrevPosOverride.ToVector3() != Vector3.zero)
					{
						prevPuzzlePos = @override.PrevPosOverride.ToVector3();
						flag = true;
					}
					else if (@override.PrevPosOverrideIndex != 0)
					{
						CP_Bioscan_Core bioscanCore = PuzzleOverrideManager.Current.GetBioscanCore(@override.PrevPosOverrideIndex);
						? val2;
						if (bioscanCore == null)
						{
							CP_Cluster_Core clusterCore = PuzzleOverrideManager.Current.GetClusterCore(@override.PrevPosOverrideIndex);
							val2 = ((clusterCore != null) ? ((Component)clusterCore).transform.position : Vector3.zero);
						}
						else
						{
							val2 = bioscanCore.m_position;
						}
						Vector3 val3 = (Vector3)val2;
						if (val3 == Vector3.zero)
						{
							SPOLogger.Error($"PuzzleOverrideIndex: {num} - trying to use 'PrevPosOverrideIndex' ({@override.PrevPosOverrideIndex}) but the puzzle is not found.");
							SPOLogger.Error($"The puzzle is probably yet registered. NOTE: 'PrevPosOverrideIndex' could only be a integer that is less than PuzzleOverrideIndex({num})");
							flag = false;
						}
						else
						{
							prevPuzzlePos = val3;
							flag = true;
						}
					}
				}
				if (!flag && puzzleIndex != 0)
				{
					CP_Bioscan_Core val4 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Bioscan_Core>();
					if ((Object)(object)val4 != (Object)null)
					{
						prevPuzzlePos = ((Component)val4).transform.position;
					}
					else
					{
						CP_Cluster_Core val5 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Cluster_Core>();
						if ((Object)(object)val5 == (Object)null)
						{
							SPOLogger.Error($"Cannot cast m_chainedPuzzleCores[{puzzleIndex - 1}] to neither CP_Bioscan_Core or CP_Cluster_Core! WTF???");
						}
						else
						{
							prevPuzzlePos = ((Component)val5).transform.position;
						}
					}
				}
			}
			else
			{
				CP_Cluster_Core val6 = ((Il2CppObjectBase)owner).Cast<CP_Cluster_Core>();
				if (@override != null && @override.PrevPosOverride.ToVector3() != Vector3.zero)
				{
					prevPuzzlePos = @override.PrevPosOverride.ToVector3();
				}
				else if (@override != null && @override.PrevPosOverrideIndex != 0)
				{
					CP_Bioscan_Core bioscanCore2 = PuzzleOverrideManager.Current.GetBioscanCore(@override.PrevPosOverrideIndex);
					? val7;
					if (bioscanCore2 == null)
					{
						CP_Cluster_Core clusterCore2 = PuzzleOverrideManager.Current.GetClusterCore(@override.PrevPosOverrideIndex);
						val7 = ((clusterCore2 != null) ? ((Component)clusterCore2).transform.position : Vector3.zero);
					}
					else
					{
						val7 = bioscanCore2.m_position;
					}
					Vector3 val8 = (Vector3)val7;
					if (val8 == Vector3.zero)
					{
						SPOLogger.Error($"PuzzleOverrideIndex: {num} - trying to use 'PrevPosOverrideIndex' ({@override.PrevPosOverrideIndex}) but the puzzle is not found.");
						SPOLogger.Error($"The puzzle is probably yet registered. NOTE: 'PrevPosOverrideIndex' could only be a integer that is less than PuzzleOverrideIndex({num})");
						prevPuzzlePos = ((Component)val6).transform.position;
					}
					else
					{
						prevPuzzlePos = val8;
					}
				}
				else
				{
					prevPuzzlePos = ((Component)val6).transform.position;
				}
				val = ((Il2CppObjectBase)val6.m_owner).Cast<ChainedPuzzleInstance>();
				if (val.Data.OnlyShowHUDWhenPlayerIsClose)
				{
					onlyShowHUDWhenPlayerIsClose = true;
				}
			}
			if (@override != null)
			{
				if (@override.Position.ToVector3() != Vector3.zero || @override.Rotation.ToVector3() != Vector3.zero)
				{
					((Component)__instance).transform.SetPositionAndRotation(@override.Position.ToVector3(), @override.Rotation.ToQuaternion());
				}
				if (@override.HideSpline || ((Object)(object)__instance.m_movingComp != (Object)null && __instance.m_movingComp.IsMoveConfigured))
				{
					revealWithHoloPath = false;
				}
				if (@override.RequiredItemsIndices != null && @override.RequiredItemsIndices.Count > 0)
				{
					PuzzleReqItemManager.Current.QueueForAddingReqItems(__instance, @override.RequiredItemsIndices);
				}
				SPOLogger.Warning("Overriding CP_Bioscan_Core." + (((Object)(object)val == (Object)null) ? "" : $"Zone {val.m_sourceArea.m_zone.Alias}, Layer {val.m_sourceArea.m_zone.Layer.m_type}, Dim {val.m_sourceArea.m_zone.DimensionIndex}"));
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_ChainedPuzzleInstance_SetupMovement
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(ChainedPuzzleInstance), "SetupMovement")]
		private static bool Pre_SetupMovement(ChainedPuzzleInstance __instance, GameObject gameObject)
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			iChainedPuzzleMovable movingComp = gameObject.GetComponent<iChainedPuzzleMovable>();
			if (movingComp == null || !movingComp.UsingStaticBioscanPoints)
			{
				return true;
			}
			CP_BasicMovable val = ((Il2CppObjectBase)movingComp).Cast<CP_BasicMovable>();
			CP_Bioscan_Core core = ((Il2CppObjectBase)gameObject.GetComponent<iChainedPuzzleCore>()).Cast<CP_Bioscan_Core>();
			uint bioscanCoreOverrideIndex = PuzzleOverrideManager.Current.GetBioscanCoreOverrideIndex(core);
			if (bioscanCoreOverrideIndex == 0)
			{
				SPOLogger.Error("Did not find registered movable override for this movable scan.");
				return true;
			}
			PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, bioscanCoreOverrideIndex);
			if (@override == null || @override.TPositions.Count < 1)
			{
				SPOLogger.Error("No Override for this T-Scan, falling back to vanilla impl.");
				return true;
			}
			@override.TPositions.ForEach(delegate(Vec3 pos)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				movingComp.ScanPositions.Add(pos.ToVector3());
			});
			gameObject.transform.position = @override.TPositions[0].ToVector3();
			val.m_amountOfPositions = @override.TPositions.Count;
			if (@override.TMoveSpeedMulti > 0f)
			{
				val.m_movementSpeed *= @override.TMoveSpeedMulti;
			}
			SPOLogger.Warning("Overriding T-Scan pos!");
			return false;
		}
	}
	[HarmonyPatch]
	internal class Patch_CarryItemPickup_Core_Setup
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CarryItemPickup_Core), "Setup")]
		private static void Post_CarryItemPickup_Core_Setup(CarryItemPickup_Core __instance)
		{
			PuzzleReqItemManager.Current.Register(__instance);
		}
	}
	[HarmonyPatch]
	internal static class Patch_CP_Cluster_Core_OnSyncStateChange
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Cluster_Core), "OnSyncStateChange")]
		private static void Post_CheckEventsOnPuzzleSolved(CP_Cluster_Core __instance, eClusterStatus newStatus, bool isDropinState)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			if ((int)newStatus == 3)
			{
				uint clusterCoreOverrideIndex = PuzzleOverrideManager.Current.GetClusterCoreOverrideIndex(__instance);
				PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, clusterCoreOverrideIndex);
				if (@override != null && @override.EventsOnPuzzleSolved.Count > 0 && !isDropinState)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(@override.EventsOnPuzzleSolved), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
				}
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_CP_Cluster_Core_Setup
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(CP_Cluster_Core), "Setup")]
		private static void Pre_CP_Cluster_Core_Setup(CP_Cluster_Core __instance, int puzzleIndex, iChainedPuzzleOwner owner, ref Vector3 prevPuzzlePos, ref bool revealWithHoloPath)
		{
			//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_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_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: 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_0096: 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_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			uint num = PuzzleOverrideManager.Current.Register(__instance);
			PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, num);
			ChainedPuzzleInstance val = ((Il2CppObjectBase)owner).Cast<ChainedPuzzleInstance>();
			bool flag = false;
			if (@override != null)
			{
				if (@override.PrevPosOverride.ToVector3() != Vector3.zero)
				{
					prevPuzzlePos = @override.PrevPosOverride.ToVector3();
					flag = true;
				}
				else if (@override.PrevPosOverrideIndex != 0)
				{
					CP_Bioscan_Core bioscanCore = PuzzleOverrideManager.Current.GetBioscanCore(@override.PrevPosOverrideIndex);
					? val2;
					if (bioscanCore == null)
					{
						CP_Cluster_Core clusterCore = PuzzleOverrideManager.Current.GetClusterCore(@override.PrevPosOverrideIndex);
						val2 = ((clusterCore != null) ? ((Component)clusterCore).transform.position : Vector3.zero);
					}
					else
					{
						val2 = bioscanCore.m_position;
					}
					Vector3 val3 = (Vector3)val2;
					if (val3 == Vector3.zero)
					{
						SPOLogger.Error($"PuzzleOverrideIndex: {num} - trying to use 'PrevPosOverrideIndex' ({@override.PrevPosOverrideIndex}) but the puzzle is not found.");
						SPOLogger.Error($"The puzzle is probably yet registered. NOTE: 'PrevPosOverrideIndex' could only be a integer that is less than PuzzleOverrideIndex({num})");
						flag = false;
					}
					else
					{
						prevPuzzlePos = val3;
						flag = true;
					}
				}
			}
			if (!flag && puzzleIndex != 0)
			{
				CP_Bioscan_Core val4 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Bioscan_Core>();
				if ((Object)(object)val4 != (Object)null)
				{
					prevPuzzlePos = ((Component)val4).transform.position;
				}
				else
				{
					CP_Cluster_Core val5 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Cluster_Core>();
					if ((Object)(object)val5 == (Object)null)
					{
						SPOLogger.Error($"Cannot cast m_chainedPuzzleCores[{puzzleIndex - 1}] to neither CP_Bioscan_Core or CP_Cluster_Core! WTF???");
					}
					else
					{
						prevPuzzlePos = ((Component)val5).transform.position;
					}
				}
			}
			if (@override != null)
			{
				if (@override.Position.ToVector3() != Vector3.zero || @override.Rotation.ToVector3() != Vector3.zero)
				{
					((Component)__instance).transform.SetPositionAndRotation(@override.Position.ToVector3(), @override.Rotation.ToQuaternion());
				}
				if (@override.RequiredItemsIndices != null && @override.RequiredItemsIndices.Count > 0)
				{
					PuzzleReqItemManager.Current.QueueForAddingReqItems(__instance, @override.RequiredItemsIndices);
				}
				if (@override.HideSpline)
				{
					revealWithHoloPath = false;
				}
				SPOLogger.Warning("Overriding CP_Cluster_Core!");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Cluster_Core), "Setup")]
		private static void Post_CP_Cluster_Core_Setup(CP_Cluster_Core __instance)
		{
			ChainedPuzzleInstance val = ((Il2CppObjectBase)__instance.m_owner).Cast<ChainedPuzzleInstance>();
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores)
			{
				if (item.IsMovable && PuzzleOverrideManager.Current.GetBioscanCoreOverrideIndex(((Il2CppObjectBase)item).Pointer) != 0)
				{
					val.SetupMovement(((Component)((Il2CppObjectBase)item).Cast<CP_Bioscan_Core>()).gameObject, val.m_sourceArea);
				}
			}
			uint clusterCoreOverrideIndex = PuzzleOverrideManager.Current.GetClusterCoreOverrideIndex(__instance);
			if (clusterCoreOverrideIndex == 0)
			{
				return;
			}
			PuzzleOverride def = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, clusterCoreOverrideIndex);
			if (def == null)
			{
				return;
			}
			if (def.ConcurrentCluster)
			{
				if (2 <= ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Count && ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Count <= 4)
				{
					CP_Cluster_Hud val2 = ((Il2CppObjectBase)__instance.m_hud).Cast<CP_Cluster_Hud>();
					ConcurrentClusterHud concurrentClusterHud = ((Component)val2).gameObject.AddComponent<ConcurrentClusterHud>();
					concurrentClusterHud.parent = __instance;
					concurrentClusterHud.parentHud = ((Il2CppObjectBase)val2.m_hud).Cast<CP_Bioscan_Hud>();
					concurrentClusterHud.def = def;
					if (concurrentClusterHud.Setup())
					{
						PlayerScannerManager.Current.RegisterConcurrentCluster(__instance);
						SPOLogger.Warning("Setting up CP_Cluster_Core as Concurrent Cluster!");
					}
					else
					{
						SPOLogger.Warning("Concurrent Cluster: failed to setup");
					}
				}
				else
				{
					SPOLogger.Error("Trying to setup concurrent cluster, " + $"but the cluster scan has {((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Count}, which is senseless or is impossible for 4 players to complete");
				}
			}
			if (def.EventsOnClusterProgress.Count <= 0)
			{
				return;
			}
			foreach (iChainedPuzzleCore item2 in (Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores)
			{
				item2.OnPuzzleDone += Action<int>.op_Implicit((Action<int>)CheckEventsOnClusterProgress);
			}
			void CheckEventsOnClusterProgress(int puzzleIndex)
			{
				int num = 0;
				for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Length; i++)
				{
					if (((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores)[i].IsFinished())
					{
						num++;
					}
				}
				foreach (ClusterProgressEvent item3 in def.EventsOnClusterProgress)
				{
					if (item3.Count == num)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(item3.Events), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
					}
				}
			}
		}
	}
	[HarmonyPatch]
	internal class Patches_CP_Cluster_Hud_ReqItems
	{
		private static Dictionary<IntPtr, List<bool>> childrenReqItemEnabled { get; }

		private static Dictionary<IntPtr, List<string[]>> clustersChildrenReqItemNames { get; }

		private static Dictionary<IntPtr, List<Il2CppStructArray<bool>>> clustersChildrenReqItemsStatus { get; }

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Bioscan_Core), "AddRequiredItems")]
		private static void Post_CP_Bioscan_Core_AddRequiredItems(CP_Bioscan_Core __instance, Il2CppReferenceArray<iWardenObjectiveItem> requiredItems)
		{
			CP_Cluster_Core val = ((Il2CppObjectBase)__instance.Owner).TryCast<CP_Cluster_Core>();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			if (__instance.m_hud == null)
			{
				SPOLogger.Error("CP_Cluster_Hud_ReqItems: replacement Cluster_hud is null.");
				return;
			}
			CP_Cluster_Hud val2 = ((Il2CppObjectBase)__instance.m_hud).Cast<CP_Cluster_Hud>();
			string[] array = new string[((Il2CppArrayBase<iWardenObjectiveItem>)(object)requiredItems).Count];
			for (int i = 0; i < __instance.m_reqItems.Count; i++)
			{
				if (__instance.m_reqItems[i] != null)
				{
					array[i] = __instance.m_reqItems[i].PublicName;
				}
				else
				{
					SPOLogger.Error("Post_CP_Bioscan_Core_AddRequiredItems: CP_Bioscan_Core " + ((Object)__instance).name + " has a missing m_reqItem! " + i);
				}
			}
			List<bool> list;
			List<string[]> list2;
			if (childrenReqItemEnabled.ContainsKey(((Il2CppObjectBase)val2).Pointer))
			{
				list = childrenReqItemEnabled[((Il2CppObjectBase)val2).Pointer];
				list2 = clustersChildrenReqItemNames[((Il2CppObjectBase)val2).Pointer];
			}
			else
			{
				list = Enumerable.Repeat(element: false, val.NRofPuzzles()).ToList();
				list2 = Enumerable.Repeat(new string[0], val.NRofPuzzles()).ToList();
				childrenReqItemEnabled.Add(((Il2CppObjectBase)val2).Pointer, list);
				clustersChildrenReqItemNames.Add(((Il2CppObjectBase)val2).Pointer, list2);
			}
			list[__instance.m_puzzleIndex] = __instance.m_reqItemsEnabled;
			list2[__instance.m_puzzleIndex] = array;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(CP_Cluster_Hud), "SetRequiredItemData")]
		private static bool Pre_CP_Cluster_Hud_SetRequiredItemData(CP_Cluster_Hud __instance, int puzzleIndex, Il2CppStructArray<bool> reqItemStatus)
		{
			List<Il2CppStructArray<bool>> list;
			if (!clustersChildrenReqItemsStatus.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
			{
				list = Enumerable.Repeat<Il2CppStructArray<bool>>(null, __instance.m_clusterSize).ToList();
				clustersChildrenReqItemsStatus.Add(((Il2CppObjectBase)__instance).Pointer, list);
			}
			else
			{
				list = clustersChildrenReqItemsStatus[((Il2CppObjectBase)__instance).Pointer];
			}
			list[puzzleIndex] = reqItemStatus;
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Cluster_Hud), "UpdateDataFor")]
		private static void Post_CP_Cluster_Hud_UpdateDataFor(CP_Cluster_Hud __instance, int index)
		{
			if (clustersChildrenReqItemsStatus.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
			{
				if (!childrenReqItemEnabled.ContainsKey(((Il2CppObjectBase)__instance).Pointer) || !clustersChildrenReqItemNames.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
				{
					SPOLogger.Error("CP_Cluster_Hud_UpdateDataFor: Found registered reqItemStatus but ReqItemEnabled or ReqItemNames is missing!");
					return;
				}
				Il2CppStructArray<bool> val = clustersChildrenReqItemsStatus[((Il2CppObjectBase)__instance).Pointer][index];
				__instance.m_hud.SetupRequiredItems(childrenReqItemEnabled[((Il2CppObjectBase)__instance).Pointer][index], Il2CppStringArray.op_Implicit(clustersChildrenReqItemNames[((Il2CppObjectBase)__instance).Pointer][index]));
				__instance.m_hud.SetRequiredItemData(__instance.m_puzzleIndex, val);
			}
		}

		private static void Clear()
		{
			clustersChildrenReqItemsStatus.Clear();
			clustersChildrenReqItemNames.Clear();
			childrenReqItemEnabled.Clear();
		}

		static Patches_CP_Cluster_Hud_ReqItems()
		{
			childrenReqItemEnabled = new Dictionary<IntPtr, List<bool>>();
			clustersChildrenReqItemNames = new Dictionary<IntPtr, List<string[]>>();
			clustersChildrenReqItemsStatus = new Dictionary<IntPtr, List<Il2CppStructArray<bool>>>();
			LevelAPI.OnLevelCleanup += Clear;
		}
	}
}
namespace ScanPosOverride.Managers
{
	public class PlayerScannerManager
	{
		private static readonly float[] ZERO_SCAN_SPEED;

		private Mutex CCStateMutex;

		private Dictionary<IntPtr, CP_PlayerScanner> ChildScanners = new Dictionary<IntPtr, CP_PlayerScanner>();

		public static PlayerScannerManager Current { get; }

		private Dictionary<IntPtr, List<CP_PlayerScanner>> CCCores { get; } = new Dictionary<IntPtr, List<CP_PlayerScanner>>();


		private Dictionary<IntPtr, HashSet<IntPtr>> CCChildren { get; } = new Dictionary<IntPtr, HashSet<IntPtr>>();


		private Dictionary<IntPtr, HashSet<IntPtr>> CCChildrenState { get; } = new Dictionary<IntPtr, HashSet<IntPtr>>();


		private Dictionary<IntPtr, float[]> OriginalClusterScanSpeeds { get; } = new Dictionary<IntPtr, float[]>();


		private Dictionary<IntPtr, float[]> OriginalScanSpeed { get; } = new Dictionary<IntPtr, float[]>();


		internal bool RegisterConcurrentCluster(CP_Cluster_Core core)
		{
			if (CCCores.ContainsKey(((Il2CppObjectBase)core).Pointer))
			{
				return false;
			}
			List<CP_PlayerScanner> list = Enumerable.Repeat<CP_PlayerScanner>(null, core.m_amountOfPuzzles).ToList();
			HashSet<IntPtr> hashSet = new HashSet<IntPtr>();
			for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)core.m_childCores).Count; i++)
			{
				if ((Object)(object)list[i] != (Object)null)
				{
					SPOLogger.Error("SetupConcurrentClusterScanners: Duplicate child scanner for child scan. ??");
					continue;
				}
				iChainedPuzzleCore val = ((Il2CppArrayBase<iChainedPuzzleCore>)(object)core.m_childCores)[i];
				CP_Bioscan_Core val2 = ((Il2CppObjectBase)val).TryCast<CP_Bioscan_Core>();
				if ((Object)(object)val2 == (Object)null)
				{
					SPOLogger.Error("SetupConcurrentClusterScanners: Failed to cast child to CP_Bioscan_Core");
					continue;
				}
				CP_PlayerScanner val3 = ((Il2CppObjectBase)val2.PlayerScanner).TryCast<CP_PlayerScanner>();
				if ((Object)(object)val3 == (Object)null)
				{
					SPOLogger.Error("SetupConcurrentClusterScanners: Failed to cast CP_Bioscan_Core.PlayerScanner to CP_PlayerScanner");
					continue;
				}
				list[i] = val3;
				ChildScanners.Add(((Il2CppObjectBase)val).Pointer, val3);
				hashSet.Add(((Il2CppObjectBase)val2).Pointer);
				if (!OriginalClusterScanSpeeds.ContainsKey(((Il2CppObjectBase)core).Pointer))
				{
					Il2CppStructArray<float> scanSpeeds = val3.m_scanSpeeds;
					float[] array = new float[((Il2CppArrayBase<float>)(object)scanSpeeds).Length];
					Array.Copy(Il2CppArrayBase<float>.op_Implicit((Il2CppArrayBase<float>)(object)scanSpeeds), array, ((Il2CppArrayBase<float>)(object)scanSpeeds).Length);
					OriginalClusterScanSpeeds.Add(((Il2CppObjectBase)core).Pointer, array);
				}
			}
			CCCores.Add(((Il2CppObjectBase)core).Pointer, list);
			CCChildren.Add(((Il2CppObjectBase)core).Pointer, hashSet);
			CCChildrenState.Add(((Il2CppObjectBase)core).Pointer, new HashSet<IntPtr>());
			return true;
		}

		internal bool IsConcurrentCluster(CP_Cluster_Core core)
		{
			return CCCores.ContainsKey(((Il2CppObjectBase)core).Pointer);
		}

		internal bool IsConcurrentCluster(CP_Bioscan_Core core)
		{
			return CCCores.ContainsKey(((Il2CppObjectBase)core.Owner).Pointer);
		}

		internal void ZeroCCScanSpeed(CP_Cluster_Core parent)
		{
			if (!CCCores.ContainsKey(((Il2CppObjectBase)parent).Pointer))
			{
				return;
			}
			foreach (CP_PlayerScanner item in CCCores[((Il2CppObjectBase)parent).Pointer])
			{
				bool flag = true;
				for (int i = 0; i < 4; i++)
				{
					flag = flag && ((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] == 0f;
					((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] = 0f;
				}
				if (flag)
				{
					break;
				}
			}
		}

		internal void RestoreCCScanSpeed(CP_Cluster_Core parent)
		{
			if (!CCCores.ContainsKey(((Il2CppObjectBase)parent).Pointer) || !OriginalClusterScanSpeeds.ContainsKey(((Il2CppObjectBase)parent).Pointer))
			{
				return;
			}
			float[] array = OriginalClusterScanSpeeds[((Il2CppObjectBase)parent).Pointer];
			foreach (CP_PlayerScanner item in CCCores[((Il2CppObjectBase)parent).Pointer])
			{
				bool flag = false;
				for (int i = 0; i < 4; i++)
				{
					flag = flag || ((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] != 0f;
					((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] = array[i];
				}
				if (flag)
				{
					break;
				}
			}
		}

		internal float[] GetCacheOriginalScanSpeed(CP_Bioscan_Core core)
		{
			if (IsConcurrentCluster(core))
			{
				if (!CCCores.ContainsKey(((Il2CppObjectBase)core.Owner).Pointer))
				{
					return ZERO_SCAN_SPEED;
				}
				return OriginalClusterScanSpeeds[((Il2CppObjectBase)core.Owner).Pointer];
			}
			if (OriginalScanSpeed.ContainsKey(((Il2CppObjectBase)core).Pointer))
			{
				return OriginalScanSpeed[((Il2CppObjectBase)core).Pointer];
			}
			CP_PlayerScanner cacheScanner = GetCacheScanner(core);
			if ((Object)(object)cacheScanner == (Object)null)
			{
				SPOLogger.Error("GetCacheOriginalScanSpeed: cannot get scanner for this CP_Bioscan_Core");
				return ZERO_SCAN_SPEED;
			}
			float[] array = new float[4];
			Array.Copy(Il2CppArrayBase<float>.op_Implicit((Il2CppArrayBase<float>)(object)cacheScanner.m_scanSpeeds), array, array.Length);
			OriginalScanSpeed.Add(((Il2CppObjectBase)core).Pointer, array);
			return array;
		}

		public CP_PlayerScanner GetCacheScanner(CP_Bioscan_Core core)
		{
			if (ChildScanners.ContainsKey(((Il2CppObjectBase)core).Pointer))
			{
				return ChildScanners[((Il2CppObjectBase)core).Pointer];
			}
			CP_PlayerScanner val = ((Il2CppObjectBase)core.PlayerScanner).TryCast<CP_PlayerScanner>();
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			ChildScanners.Add(((Il2CppObjectBase)core).Pointer, val);
			return val;
		}

		internal bool CCShouldProgress(CP_Bioscan_Core child, bool IsThisScanShouldProgress)
		{
			if (CCStateMutex == null)
			{
				CCStateMutex = new Mutex();
			}
			if (CCStateMutex.WaitOne(2000))
			{
				if (!CCCores.ContainsKey(((Il2CppObjectBase)child.Owner).Pointer))
				{
					SPOLogger.Error("ConcurrentClusterShouldProgress: failed to find cluster parent!");
					CCStateMutex.ReleaseMutex();
					return false;
				}
				CP_Cluster_Core val = ((Il2CppObjectBase)child.Owner).Cast<CP_Cluster_Core>();
				if (!CCChildrenState.ContainsKey(((Il2CppObjectBase)val).Pointer))
				{
					SPOLogger.Error("ConcurrentClusterShouldProgress: ConcurrentClusterChildScanState initialization error!");
					CCStateMutex.ReleaseMutex();
					return false;
				}
				HashSet<IntPtr> hashSet = CCChildrenState[((Il2CppObjectBase)val).Pointer];
				bool result;
				if (IsThisScanShouldProgress)
				{
					hashSet.Add(((Il2CppObjectBase)child).Pointer);
					result = hashSet.Count == val.m_amountOfPuzzles;
				}
				else
				{
					hashSet.Remove(((Il2CppObjectBase)child).Pointer);
					result = false;
				}
				CCStateMutex.ReleaseMutex();
				return result;
			}
			SPOLogger.Debug("ConcurrentCluster: Failed to acquire scan mutex.");
			return false;
		}

		internal void CompleteConcurrentCluster(CP_Cluster_Core parent, CP_Bioscan_Core child)
		{
			if (CCChildren.ContainsKey(((Il2CppObjectBase)parent).Pointer))
			{
				HashSet<IntPtr> hashSet = CCChildren[((Il2CppObjectBase)parent).Pointer];
				hashSet.Remove(((Il2CppObjectBase)child).Pointer);
				if (hashSet.Count < 1)
				{
					CCChildren.Remove(((Il2CppObjectBase)parent).Pointer);
				}
			}
		}

		public List<CP_PlayerScanner> GetCCChildrenScanner(CP_Cluster_Core parent)
		{
			if (!CCCores.ContainsKey(((Il2CppObjectBase)parent).Pointer))
			{
				return null;
			}
			return CCCores[((Il2CppObjectBase)parent).Pointer];
		}

		public void Clear()
		{
			CCCores.Clear();
			CCChildren.Clear();
			CCChildrenState.Clear();
			OriginalClusterScanSpeeds.Clear();
			ChildScanners.Clear();
			OriginalScanSpeed.Clear();
			if (CCStateMutex != null)
			{
				CCStateMutex.Dispose();
			}
			CCStateMutex = null;
		}

		static PlayerScannerManager()
		{
			ZERO_SCAN_SPEED = new float[4];
			Current = new PlayerScannerManager();
			LevelAPI.OnLevelCleanup += Current.Clear;
		}

		private PlayerScannerManager()
		{
		}
	}
	public class PuzzleReqItemManager
	{
		public static readonly PuzzleReqItemManager Current;

		private Dictionary<int, CarryItemPickup_Core> BigPickupItemsInLevel = new Dictionary<int, CarryItemPickup_Core>();

		private int itemIndexCounter = 1;

		private List<(CP_Bioscan_Core, List<int>)> bioscanCoresToAddReqItems = new List<(CP_Bioscan_Core, List<int>)>();

		private List<(CP_Cluster_Core, List<int>)> clusterCoresToAddReqItems = new List<(CP_Cluster_Core, List<int>)>();

		private Dictionary<IntPtr, CP_Bioscan_Core> movableScansWithReqItems = new Dictionary<IntPtr, CP_Bioscan_Core>();

		internal int Register(CarryItemPickup_Core item)
		{
			int num = itemIndexCounter;
			itemIndexCounter++;
			BigPickupItemsInLevel.Add(num, item);
			return num;
		}

		internal void QueueForAddingReqItems(CP_Bioscan_Core core, List<int> itemsIndices)
		{
			bioscanCoresToAddReqItems.Add((core, itemsIndices));
		}

		internal void QueueForAddingReqItems(CP_Cluster_Core core, List<int> itemsIndices)
		{
			clusterCoresToAddReqItems.Add((core, itemsIndices));
		}

		internal CP_Bioscan_Core GetMovableCoreWithReqItem(CP_PlayerScanner scanner)
		{
			if (!movableScansWithReqItems.ContainsKey(((Il2CppObjectBase)scanner).Pointer))
			{
				return null;
			}
			return movableScansWithReqItems[((Il2CppObjectBase)scanner).Pointer];
		}

		public CarryItemPickup_Core GetBigPickupItem(int bigPickupInLevelIndex)
		{
			if (!BigPickupItemsInLevel.ContainsKey(bigPickupInLevelIndex))
			{
				return null;
			}
			return BigPickupItemsInLevel[bigPickupInLevelIndex];
		}

		public bool AddReqItems(CP_Bioscan_Core puzzle, int itemIndex)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			if ((Object)(object)puzzle == (Object)null || itemIndex == 0L)
			{
				return false;
			}
			if (!BigPickupItemsInLevel.ContainsKey(itemIndex))
			{
				SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}");
				return false;
			}
			CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex];
			puzzle.AddRequiredItems(Il2CppReferenceArray<iWardenObjectiveItem>.op_Implicit((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
			{
				new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer)
			}));
			return true;
		}

		public bool AddReqItems(CP_Cluster_Core puzzle, int itemIndex)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			if ((Object)(object)puzzle == (Object)null || itemIndex == 0L)
			{
				return false;
			}
			if (!BigPickupItemsInLevel.ContainsKey(itemIndex))
			{
				SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}");
				return false;
			}
			CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex];
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)puzzle.m_childCores)
			{
				item.AddRequiredItems(Il2CppReferenceArray<iWardenObjectiveItem>.op_Implicit((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
				{
					new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer)
				}));
			}
			return true;
		}

		public bool AddReqItems(CP_Bioscan_Core puzzle, List<int> itemsIndices)
		{
			if ((Object)(object)puzzle == (Object)null || itemsIndices == null || itemsIndices.Count < 1)
			{
				return false;
			}
			bool flag = false;
			foreach (int item in itemsIndices.ToHashSet())
			{
				flag |= AddReqItems(puzzle, item);
			}
			if (puzzle.IsMovable && flag)
			{
				movableScansWithReqItems.Add(((Il2CppObjectBase)puzzle.m_playerScanner).Pointer, puzzle);
			}
			return flag;
		}

		public void RemoveReqItem(CP_Bioscan_Core puzzle, int itemIndex)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			if (!((Object)(object)puzzle == (Object)null))
			{
				if (!BigPickupItemsInLevel.ContainsKey(itemIndex) && itemIndex != 0L)
				{
					SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}");
				}
				else
				{
					CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex];
					puzzle.RemoveRequiredItems((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
					{
						new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer)
					});
				}
			}
		}

		public void RemoveReqItem(CP_Cluster_Core puzzle, int itemIndex)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			if ((Object)(object)puzzle == (Object)null)
			{
				return;
			}
			if (!BigPickupItemsInLevel.ContainsKey(itemIndex) && itemIndex != 0L)
			{
				SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}");
				return;
			}
			CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex];
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)puzzle.m_childCores)
			{
				item.RemoveRequiredItems((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
				{
					new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer)
				});
			}
		}

		private void AddQueuedReqItems()
		{
			foreach (var (puzzle, itemsIndices) in bioscanCoresToAddReqItems)
			{
				AddReqItems(puzzle, itemsIndices);
			}
			foreach (var (val, itemsIndices2) in clusterCoresToAddReqItems)
			{
				foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_childCores)
				{
					CP_Bioscan_Core val2 = ((Il2CppObjectBase)item).TryCast<CP_Bioscan_Core>();
					if ((Object)(object)val2 == (Object)null)
					{
						SPOLogger.Error("Failed to cast child core to CP_Bioscan_Core");
					}
					else
					{
						AddReqItems(val2, itemsIndices2);
					}
				}
			}
		}

		public void OutputLevelBigPickupInfo()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_010a: 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)
			StringBuilder val = new StringBuilder();
			val.AppendLine();
			List<CarryItemPickup_Core> list = new List<CarryItemPickup_Core>(BigPickupItemsInLevel.Values);
			list.Sort(delegate(CarryItemPickup_Core b1, CarryItemPickup_Core b2)
			{
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: 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_002c: 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_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_0051: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: 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)
				AIG_CourseNode spawnNode = b1.SpawnNode;
				AIG_CourseNode spawnNode2 = b2.SpawnNode;
				if (spawnNode.m_dimension.DimensionIndex != spawnNode2.m_dimension.DimensionIndex)
				{
					if (spawnNode.m_dimension.DimensionIndex > spawnNode2.m_dimension.DimensionIndex)
					{
						return 1;
					}
					return -1;
				}
				if (spawnNode.LayerType != spawnNode2.LayerType)
				{
					if (spawnNode.LayerType >= spawnNode2.LayerType)
					{
						return 1;
					}
					return -1;
				}
				return (spawnNode.m_zone.LocalIndex != spawnNode2.m_zone.LocalIndex) ? ((spawnNode.m_zone.LocalIndex >= spawnNode2.m_zone.LocalIndex) ? 1 : (-1)) : 0;
			});
			Dictionary<CarryItemPickup_Core, int> dictionary = new Dictionary<CarryItemPickup_Core, int>();
			foreach (int key in BigPickupItemsInLevel.Keys)
			{
				dictionary.Add(BigPickupItemsInLevel[key], key);
			}
			foreach (CarryItemPickup_Core item in list)
			{
				val.AppendLine("Item Name: " + ((Item)item).ItemDataBlock.publicName);
				val.AppendLine($"Zone {item.SpawnNode.m_zone.Alias}, {item.SpawnNode.LayerType}, Dim {item.SpawnNode.m_dimension.DimensionIndex}");
				val.AppendLine($"Item Index: {dictionary[item]}");
				val.AppendLine();
			}
			SPOLogger.Debug(((Object)val).ToString());
		}

		internal void OnEnterLevel()
		{
			AddQueuedReqItems();
			OutputLevelBigPickupInfo();
		}

		public void Clear()
		{
			BigPickupItemsInLevel.Clear();
			itemIndexCounter = 1;
			bioscanCoresToAddReqItems.Clear();
			clusterCoresToAddReqItems.Clear();
			movableScansWithReqItems.Clear();
		}

		static PuzzleReqItemManager()
		{
			Current = new PuzzleReqItemManager();
			LevelAPI.OnLevelCleanup += Current.Clear;
			LevelAPI.OnEnterLevel += Current.OnEnterLevel;
		}

		private PuzzleReqItemManager()
		{
		}
	}
	public class PuzzleOverrideManager
	{
		public static readonly PuzzleOverrideManager Current;

		private uint puzzleOverrideIndex = 1u;

		public static uint MainLevelLayout => RundownManager.ActiveExpedition.LevelLayoutData;

		private Dictionary<IntPtr, uint> bioscanIndex { get; } = new Dictionary<IntPtr, uint>();


		private Dictionary<IntPtr, uint> clusterIndex { get; } = new Dictionary<IntPtr, uint>();


		private Dictionary<uint, CP_Bioscan_Core> index2Bioscan { get; } = new Dictionary<uint, CP_Bioscan_Core>();


		private Dictionary<uint, CP_Cluster_Core> index2Cluster { get; } = new Dictionary<uint, CP_Cluster_Core>();


		public uint Register(CP_Bioscan_Core __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return 0u;
			}
			uint num = puzzleOverrideIndex;
			puzzleOverrideIndex++;
			if (!bioscanIndex.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
			{
				bioscanIndex.Add(((Il2CppObjectBase)__instance).Pointer, num);
				index2Bioscan.Add(num, __instance);
				return num;
			}
			return GetBioscanCoreOverrideIndex(__instance);
		}

		public uint Register(CP_Cluster_Core __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return 0u;
			}
			uint num = puzzleOverrideIndex;
			puzzleOverrideIndex++;
			if (!clusterIndex.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
			{
				clusterIndex.Add(((Il2CppObjectBase)__instance).Pointer, num);
				index2Cluster.Add(num, __instance);
				return num;
			}
			return GetClusterCoreOverrideIndex(__instance);
		}

		public void OutputLevelPuzzleInfo()
		{
			//IL_00bd: 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_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_045d: Unknown result type (might be due to invalid IL or missing references)
			List<ChainedPuzzleInstance> list = new List<ChainedPuzzleInstance>();
			Enumerator<ChainedPuzzleInstance> enumerator = ChainedPuzzleManager.Current.m_instances.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ChainedPuzzleInstance current = enumerator.Current;
				list.Add(current);
			}
			list.Sort(delegate(ChainedPuzzleInstance c1, ChainedPuzzleInstance c2)
			{
				//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_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_0027: 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_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_0056: 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)
				LG_Zone zone2 = c1.m_sourceArea.m_zone;
				LG_Zone zone3 = c2.m_sourceArea.m_zone;
				if (zone2.DimensionIndex != zone3.DimensionIndex)
				{
					if (zone2.DimensionIndex >= zone3.DimensionIndex)
					{
						return 1;
					}
					return -1;
				}
				if (zone2.Layer.m_type != zone3.Layer.m_type)
				{
					if (zone2.Layer.m_type >= zone3.Layer.m_type)
					{
						return 1;
					}
					return -1;
				}
				return (zone2.LocalIndex >= zone3.LocalIndex) ? 1 : (-1);
			});
			StringBuilder stringBuilder = new StringBuilder();
			foreach (ChainedPuzzleInstance item in list)
			{
				LG_Zone zone = item.m_sourceArea.m_zone;
				StringBuilder stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder3 = stringBuilder2;
				StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(15, 3, stringBuilder2);
				handler.AppendLiteral("\nZone ");
				handler.AppendFormatted(zone.Alias);
				handler.AppendLiteral(", ");
				handler.AppendFormatted<LG_LayerType>(zone.m_layer.m_type);
				handler.AppendLiteral(", Dim ");
				handler.AppendFormatted<eDimensionIndex>(zone.DimensionIndex);
				handler.AppendLiteral("\n");
				stringBuilder3.Append(ref handler);
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder4 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(14, 1, stringBuilder2);
				handler.AppendLiteral("Alarm name: ");
				handler.AppendFormatted(item.Data.PublicAlarmName);
				handler.AppendLiteral(":\n");
				stringBuilder4.Append(ref handler);
				for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)item.m_chainedPuzzleCores).Count; i++)
				{
					iChainedPuzzleCore val = ((Il2CppArrayBase<iChainedPuzzleCore>)(object)item.m_chainedPuzzleCores)[i];
					if (bioscanIndex.ContainsKey(((Il2CppObjectBase)val).Pointer))
					{
						uint value = bioscanIndex[((Il2CppObjectBase)val).Pointer];
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder5 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2);
						handler.AppendLiteral("puzzle index: ");
						handler.AppendFormatted(i);
						handler.AppendLiteral("\n");
						stringBuilder5.Append(ref handler);
						stringBuilder.Append("type: CP_Bioscan_Core\n");
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder6 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(22, 1, stringBuilder2);
						handler.AppendLiteral("PuzzleOverrideIndex: ");
						handler.AppendFormatted(value);
						handler.AppendLiteral("\n");
						stringBuilder6.Append(ref handler);
						CP_Bioscan_Core val2 = ((Il2CppObjectBase)val).Cast<CP_Bioscan_Core>();
						CP_PlayerScanner val3 = ((Il2CppObjectBase)val2.PlayerScanner).Cast<CP_PlayerScanner>();
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder7 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(11, 1, stringBuilder2);
						handler.AppendLiteral("Position: ");
						handler.AppendFormatted<Vector3>(val2.m_position);
						handler.AppendLiteral("\n");
						stringBuilder7.Append(ref handler);
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder8 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(9, 1, stringBuilder2);
						handler.AppendLiteral("Radius: ");
						handler.AppendFormatted(val3.Radius);
						handler.AppendLiteral("\n");
						stringBuilder8.Append(ref handler);
					}
					else if (clusterIndex.ContainsKey(((Il2CppObjectBase)val).Pointer))
					{
						uint value2 = clusterIndex[((Il2CppObjectBase)val).Pointer];
						CP_Cluster_Core val4 = ((Il2CppObjectBase)val).Cast<CP_Cluster_Core>();
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder9 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2);
						handler.AppendLiteral("puzzle index: ");
						handler.AppendFormatted(i);
						handler.AppendLiteral("\n");
						stringBuilder9.Append(ref handler);
						stringBuilder.Append("type: CP_Cluster_Core\n");
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder10 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(22, 1, stringBuilder2);
						handler.AppendLiteral("PuzzleOverrideIndex: ");
						handler.AppendFormatted(value2);
						handler.AppendLiteral("\n");
						stringBuilder10.Append(ref handler);
						stringBuilder.Append("=== Clustered puzzles info: ===\n");
						for (int j = 0; j < val4.m_amountOfPuzzles; j++)
						{
							iChainedPuzzleCore val5 = ((Il2CppArrayBase<iChainedPuzzleCore>)(object)val4.m_childCores)[j];
							if (!bioscanIndex.ContainsKey(((Il2CppObjectBase)val5).Pointer))
							{
								SPOLogger.Error("Unregistered clustered iChainedPuzzleCore found...");
								continue;
							}
							uint value3 = bioscanIndex[((Il2CppObjectBase)val5).Pointer];
							stringBuilder2 = stringBuilder;
							StringBuilder stringBuilder11 = stringBuilder2;
							handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2);
							handler.AppendLiteral("puzzle index: ");
							handler.AppendFormatted(j);
							handler.AppendLiteral("\n");
							stringBuilder11.Append(ref handler);
							stringBuilder.Append("type: CP_Bioscan_Core\n");
							stringBuilder2 = stringBuilder;
							StringBuilder stringBuilder12 = stringBuilder2;
							handler = new StringBuilder.AppendInterpolatedStringHandler(22, 1, stringBuilder2);
							handler.AppendLiteral("PuzzleOverrideIndex: ");
							handler.AppendFormatted(value3);
							handler.AppendLiteral("\n");
							stringBuilder12.Append(ref handler);
							CP_Bioscan_Core val6 = ((Il2CppObjectBase)val5).Cast<CP_Bioscan_Core>();
							CP_PlayerScanner val7 = ((Il2CppObjectBase)val6.PlayerScanner).Cast<CP_PlayerScanner>();
							stringBuilder2 = stringBuilder;
							StringBuilder stringBuilder13 = stringBuilder2;
							handler = new StringBuilder.AppendInterpolatedStringHandler(11, 1, stringBuilder2);
							handler.AppendLiteral("Position: ");
							handler.AppendFormatted<Vector3>(val6.m_position);
							handler.AppendLiteral("\n");
							stringBuilder13.Append(ref handler);
							stringBuilder2 = stringBuilder;
							StringBuilder stringBuilder14 = stringBuilder2;
							handler = new StringBuilder.AppendInterpolatedStringHandler(9, 1, stringBuilder2);
							handler.AppendLiteral("Radius: ");
							handler.AppendFormatted(val7.Radius);
							handler.AppendLiteral("\n");
							stringBuilder14.Append(ref handler);
						}
						stringBuilder.Append("=== Clustered puzzles END ===\n");
					}
					else
					{
						SPOLogger.Error("Unregistered iChainedPuzzleCore found...");
					}
				}
				stringBuilder.Append('\n');
			}
			SPOLogger.Debug(stringBuilder.ToString());
		}

		public uint GetBioscanCoreOverrideIndex(CP_Bioscan_Core core)
		{
			if (bioscanIndex.ContainsKey(((Il2CppObjectBase)core).Pointer))
			{
				return bioscanIndex[((Il2CppObjectBase)core).Pointer];
			}
			return 0u;
		}

		public uint GetClusterCoreOverrideIndex(CP_Cluster_Core core)
		{
			if (clusterIndex.ContainsKey(((Il2CppObjectBase)core).Pointer))
			{
				return clusterIndex[((Il2CppObjectBase)core).Pointer];
			}
			return 0u;
		}

		public uint GetBioscanCoreOverrideIndex(IntPtr pointer)
		{
			if (bioscanIndex.ContainsKey(pointer))
			{
				return bioscanIndex[pointer];
			}
			return 0u;
		}

		public uint GetClusterCoreOverrideIndex(IntPtr pointer)
		{
			if (clusterIndex.ContainsKey(pointer))
			{
				return clusterIndex[pointer];
			}
			return 0u;
		}

		public CP_Bioscan_Core GetBioscanCore(uint puzzleOverrideIndex)
		{
			if (!index2Bioscan.ContainsKey(puzzleOverrideIndex))
			{
				return null;
			}
			return index2Bioscan[puzzleOverrideIndex];
		}

		public CP_Cluster_Core GetClusterCore(uint puzzleOverrideIndex)
		{
			if (!index2Cluster.ContainsKey(puzzleOverrideIndex))
			{
				return null;
			}
			return index2Cluster[puzzleOverrideIndex];
		}

		public void Clear()
		{
			puzzleOverrideIndex = 1u;
			bioscanIndex.Clear();
			clusterIndex.Clear();
			index2Bioscan.Clear();
			index2Cluster.Clear();
		}

		private PuzzleOverrideManager()
		{
		}

		static PuzzleOverrideManager()
		{
			Current = new PuzzleOverrideManager();
			LevelAPI.OnEnterLevel += Current.OutputLevelPuzzleInfo;
			LevelAPI.OnBuildStart += Current.Clear;
			LevelAPI.OnLevelCleanup += Current.Clear;
		}

		public iChainedPuzzleOwner ChainedPuzzleInstanceOwner(CP_Bioscan_Core bioscanCore)
		{
			if ((Object)(object)bioscanCore == (Object)null)
			{
				return null;
			}
			iChainedPuzzleOwner owner = bioscanCore.Owner;
			if ((Object)(object)((Il2CppObjectBase)owner).TryCast<ChainedPuzzleInstance>() != (Object)null)
			{
				return owner;
			}
			CP_Cluster_Core val = ((Il2CppObjectBase)owner).TryCast<CP_Cluster_Core>();
			if ((Object)(object)val != (Object)null)
			{
				return val.m_owner;
			}
			SPOLogger.Error("Failed to find CP_BioScan_Core owner (instance of ChainedPuzzleInstance).");
			return null;
		}
	}
}
namespace ScanPosOverride.JSON
{
	public static class InjectLibUtil
	{
		public const string PLUGIN_GUID = "GTFO.InjectLib";

		public static JsonConverter InjectLibConnector { get; private set; }

		public static bool IsLoaded { get; private set; }

		static InjectLibUtil()
		{
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("GTFO.InjectLib", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				InjectLibConnector = (JsonConverter)Activator.CreateInstance(obj.GetTypes().First((Type t) => t.Name == "InjectLibConnector") ?? throw new Exception("Unable to Find InjectLibConnector Class"));
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				SPOLogger.Error($"Exception thrown while reading data from GTFO.AWO: {value2}");
			}
		}
	}
	internal class LocalizedTextConverter : JsonConverter<LocalizedText>
	{
		public override bool HandleNull => false;

		public override LocalizedText Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			//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_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			switch (reader.TokenType)
			{
			case JsonTokenType.String:
			{
				string @string = reader.GetString();
				return new LocalizedText
				{
					Id = 0u,
					UntranslatedText = @string
				};
			}
			case JsonTokenType.Number:
				return new LocalizedText
				{
					Id = reader.GetUInt32(),
					UntranslatedText = null
				};
			default:
				throw new JsonException($"LocalizedTextJson type: {reader.TokenType} is not implemented!");
			}
		}

		public override void Write(Utf8JsonWriter writer, LocalizedText value, JsonSerializerOptions options)
		{
			JsonSerializer.Serialize<LocalizedText>(writer, value, options);
		}
	}
	public sealed class MyVector3Converter : JsonConverter<Vector3>
	{
		public override bool HandleNull => false;

		public override Vector3 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			//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_0114: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			Vector3 vector = Vector3.zero;
			switch (reader.TokenType)
			{
			case JsonTokenType.StartObject:
			{
				int currentDepth = reader.CurrentDepth;
				while (reader.Read())
				{
					if (reader.TokenType == JsonTokenType.EndObject && reader.CurrentDepth == currentDepth)
					{
						SPOLogger.Warning($"Parsed Vector3 : {vector}");
						return vector;
					}
					if (reader.TokenType != JsonTokenType.PropertyName)
					{
						throw new JsonException("Expected PropertyName token");
					}
					string? @string = reader.GetString();
					reader.Read();
					switch (@string.ToLowerInvariant())
					{
					case "x":
						vector.x = reader.GetSingle();
						break;
					case "y":
						vector.y = reader.GetSingle();
						break;
					case "z":
						vector.z = reader.GetSingle();
						break;
					}
				}
				throw new JsonException("Expected EndObject token");
			}
			case JsonTokenType.String:
			{
				string text = reader.GetString().Trim();
				if (TryParseVector3(text, out vector))
				{
					return vector;
				}
				throw new JsonException("Vector3 format is not right: " + text);
			}
			default:
				throw new JsonException($"Vector3Json type: {reader.TokenType} is not implemented!");
			}
		}

		private static bool TryParseVector3(string input, out Vector3 vector)
		{
			//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_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_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)
			float[] array = default(float[]);
			if (!RegexUtils.TryParseVectorString(input, ref array))
			{
				vector = Vector3.zero;
				return false;
			}
			if (array.Length < 3)
			{
				vector = Vector3.zero;
				return false;
			}
			vector = new Vector3(array[0], array[1], array[2]);
			return true;
		}

		public override void Write(Utf8JsonWriter writer, Vector3 value, JsonSerializerOptions options)
		{
			//IL_0018: 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_004a: Unknown result type (might be due to invalid IL or missing references)
			writer.WriteStringValue($"({value.x} {value.y} {value.z})");
		}
	}
	internal static class Json
	{
		private static readonly JsonSerializerOptions _setting;

		static Json()
		{
			_setting = new JsonSerializerOptions
			{
				ReadCommentHandling = JsonCommentHandling.Skip,
				IncludeFields = false,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true,
				IgnoreReadOnlyProperties = true
			};
			_setting.Converters.Add(new JsonStringEnumConverter());
			_setting.Converters.Add(new MyVector3Converter());
			if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized)
			{
				_setting.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter);
				_setting.Converters.Add(MTFOPartialDataUtil.LocalizedTextConverter);
				SPOLogger.Log("PartialData Support Found!");
			}
			else
			{
				_setting.Converters.Add(new LocalizedTextConverter());
			}
			if (InjectLibUtil.IsLoaded)
			{
				_setting.Converters.Add(InjectLibUtil.InjectLibConnector);
				SPOLogger.Log("InjectLib (AWO) support found!");
			}
		}

		public static T Deserialize<T>(string json)
		{
			return JsonSerializer.Deserialize<T>(json, _setting);
		}

		public static object Deserialize(Type type, string json)
		{
			return JsonSerializer.Deserialize(json, type, _setting);
		}

		public static string Serialize<T>(T value)
		{
			return JsonSerializer.Serialize(value, _setting);
		}

		public static void Load<T>(string file, out T config) where T : new()
		{
			if (file.Length < ".json".Length)
			{
				config = default(T);
				return;
			}
			if (file.Substring(file.Length - ".json".Length) != ".json")
			{
				file += ".json";
			}
			file = File.ReadAllText(Path.Combine(Plugin.OVERRIDE_SCAN_POS_PATH, file));
			config = Deserialize<T>(file);
		}
	}
	public static class MTFOPartialDataUtil
	{
		public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks";

		public static JsonConverter PersistentIDConverter { get; private set; }

		public static JsonConverter LocalizedTextConverter { get; private set; }

		public static bool IsLoaded { get; private set; }

		public static bool Initialized { get; private set; }

		public static string PartialDataPath { get; private set; }

		public static string ConfigPath { get; private set; }

		static MTFOPartialDataUtil()
		{
			PersistentIDConverter = null;
			LocalizedTextConverter = null;
			IsLoaded = false;
			Initialized = false;
			PartialDataPath = string.Empty;
			ConfigPath = string.Empty;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type[] types = obj.GetTypes();
				Type type = types.First((Type t) => t.Name == "PersistentIDConverter");
				if ((object)type == null)
				{
					throw new Exception("Unable to Find PersistentIDConverter Class");
				}
				Type type2 = types.First((Type t) => t.Name == "PartialDataManager");
				if ((object)type2 == null)
				{
					throw new Exception("Unable to Find PartialDataManager Class");
				}
				Type type3 = types.First((Type t) => t.Name == "LocalizedTextConverter") ?? throw new Exception("Unable to Find LocalizedTextConverter Class");
				PropertyInfo property = type2.GetProperty("Initialized", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo property2 = type2.GetProperty("PartialDataPath", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo? property3 = type2.GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public);
				if ((object)property == null)
				{
					throw new Exception("Unable to Find Property: Initialized");
				}
				if ((object)property2 == null)
				{
					throw new Exception("Unable to Find Property: PartialDataPath");
				}
				if ((object)property3 == null)
				{
					throw new Exception("Unable to Find Field: ConfigPath");
				}
				Initialized = (bool)property.GetValue(null);
				PartialDataPath = (string)property2.GetValue(null);
				ConfigPath = (string)property3.GetValue(null);
				PersistentIDConverter = (JsonConverter)Activator.CreateInstance(type);
				LocalizedTextConverter = (JsonConverter)Activator.CreateInstance(type3);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				SPOLogger.Error($"Exception thrown while reading data from MTFO_Extension_PartialData:\n{value2}");
			}
		}
	}
	public static class MTFOUtil
	{
		public const string PLUGIN_GUID = "com.dak.MTFO";

		public const BindingFlags PUBLIC_STATIC = BindingFlags.Static | BindingFlags.Public;

		public static string GameDataPath { get; private set; }

		public static string CustomPath { get; private set; }

		public static bool HasCustomContent { get; private set; }

		public static bool IsLoaded { get; private set; }

		static MTFOUtil()
		{
			GameDataPath = string.Empty;
			CustomPath = string.Empty;
			HasCustomContent = false;
			IsLoaded = false;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type obj2 = obj.GetTypes().First((Type t) => t.Name == "ConfigManager") ?? throw new Exception("Unable to Find ConfigManager Class");
				FieldInfo field = obj2.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo field2 = obj2.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo? field3 = obj2.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public);
				if ((object)field == null)
				{
					throw new Exception("Unable to Find Field: GameDataPath");
				}
				if ((object)field2 == null)
				{
					throw new Exception("Unable to Find Field: CustomPath");
				}
				if ((object)field3 == null)
				{
					throw new Exception("Unable to Find Field: HasCustomContent");
				}
				GameDataPath = (string)field.GetValue(null);
				CustomPath = (string)field2.GetValue(null);
				HasCustomContent = (bool)field3.GetValue(null);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				SPOLogger.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}");
			}
		}
	}
}
namespace ScanPosOverride.Component
{
	internal class ConcurrentClusterHud : MonoBehaviour
	{
		public enum PlayerCountRequirement
		{
			INVALID,
			ANY,
			SOLO,
			DUO
		}

		private StringBuilder displayText = new StringBuilder();

		private bool m_isValid;

		private List<CP_Bioscan_Core> children;

		private float childRadius = -1f;

		private int[] playerInScanCount;

		private readonly string[] ROMAN = new string[4] { "I", "II", "III", "IV" };

		internal CP_Cluster_Core parent { get; set; }

		internal CP_Bioscan_Hud parentHud { get; set; }

		internal PuzzleOverride def { get; set; }

		public PlayerCountRequirement playerCountReq { get; private set; }

		private PlayerCountRequirement ReqPlayerCount(iChainedPuzzleCore child)
		{
			//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_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected I4, but got Unknown
			CP_PlayerScanner obj = ((Il2CppObjectBase)((Il2CppObjectBase)child).Cast<CP_Bioscan_Core>().m_playerScanner).Cast<CP_PlayerScanner>();
			PlayerRequirement playerRequirement = obj.m_playerRequirement;
			Il2CppStructArray<float> scanSpeeds = obj.m_scanSpeeds;
			switch ((int)playerRequirement)
			{
			case 2:
				if (!(((Il2CppArrayBase<float>)(object)scanSpeeds)[0] > 0f))
				{
					return PlayerCountRequirement.INVALID;
				}
				return PlayerCountRequirement.SOLO;
			case 0:
			{
				int i;
				for (i = 0; i < ((Il2CppArrayBase<float>)(object)scanSpeeds).Count && ((Il2CppArrayBase<float>)(object)scanSpeeds)[i] == 0f; i++)
				{
				}
				if (i >= 2)
				{
					return PlayerCountRequirement.INVALID;
				}
				if (i == 1)
				{
					return PlayerCountRequirement.DUO;
				}
				if (!(((Il2CppArrayBase<float>)(object)scanSpeeds)[i + 1] > 0f))
				{
					return PlayerCountRequirement.SOLO;
				}
				return PlayerCountRequirement.ANY;
			}
			default:
				return PlayerCountRequirement.INVALID;
			}
		}

		internal bool Setup()
		{
			if (((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count < 2 || ((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count > 4)
			{
				SPOLogger.Error($"ConcurrentClusterHud: got cluster scan with {((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count} children, which is invalid for concurrent cluster");
				return false;
			}
			playerCountReq = ReqPlayerCount(((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores)[0]);
			if (playerCountReq == PlayerCountRequirement.INVALID)
			{
				SPOLogger.Error($"ConcurrentCluster setup: playerRequirement is {1}, which is invalid for concurrent cluster");
				return false;
			}
			switch (((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count)
			{
			case 2:
				switch (playerCountReq)
				{
				case PlayerCountRequirement.ANY:
				case PlayerCountRequirement.SOLO:
					m_isValid = true;
					break;
				case PlayerCountRequirement.DUO:
					m_isValid = true;
					break;
				}
				break;
			case 4:
			{
				PlayerCountRequirement playerCountRequirement = playerCountReq;
				if ((uint)(playerCountRequirement - 1) <= 1u)
				{
					m_isValid = true;
				}
				break;
			}
			case 3:
			{
				PlayerCountRequirement playerCountRequirement = playerCountReq;
				if ((uint)(playerCountRequirement - 1) <= 1u)
				{
					m_isValid = true;
				}
				break;
			}
			}
			if (!m_isValid)
			{
				SPOLogger.Error($"ConcurrentCluster setup: Something went wrong! PlayerCountRequirement: {playerCountReq}, children num: {((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count}");
				return false;
			}
			playerInScanCount = new int[((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count];
			Array.Fill(playerInScanCount, 0);
			children = ((IEnumerable<iChainedPuzzleCore>)parent.m_childCores).ToList().ConvertAll((iChainedPuzzleCore c) => ((Il2CppObjectBase)c).Cast<CP_Bioscan_Core>());
			childRadius = ((Il2CppObjectBase)((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores)[0]).Cast<CP_Bioscan_Core>().m_playerScanner).Cast<CP_PlayerScanner>().Radius;
			return true;
		}

		private void LateUpdate()
		{
			//IL_032b: 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_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			if (!m_isValid || !parentHud.m_visible || !parentHud.m_isClosestToPlayer)
			{
				return;
			}
			displayText.Clear();
			displayText.AppendLine().Append("<color=white>");
			for (int i = 0; i < children.Count; i++)
			{
				int num = 0;
				CP_Bioscan_Core val = children[i];
				Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Vector3 val2 = ((Agent)enumerator.Current).Position - ((Component)val).transform.position;
					if (((Vector3)(ref val2)).magnitude < childRadius)
					{
						num++;
					}
				}
				playerInScanCount[i] = num;
				string value = string.Empty;
				string value2 = string.Empty;
				switch (playerCountReq)
				{
				case PlayerCountRequirement.ANY:
					switch (num)
					{
					case 0:
						value = " ";
						break;
					case 1:
						value = "A";
						break;
					case 2:
						value = "A,B";
						break;
					case 3:
						value = "A,B,C";
						break;
					case 4:
						value = "A,B,C,D";
						break;
					}
					value2 = ((num > 0) ? "white" : "orange");
					break;
				case PlayerCountRequirement.SOLO:
					switch (num)
					{
					case 0:
						value = " ";
						value2 = "orange";
						break;
					case 1:
						value = "A";
						value2 = "white";
						break;
					case 2:
						value = "A,<color=red>B</color>";
						value2 = "orange";
						break;
					case 3:
						value = "A,<color=red>B</color>,<color=red>C</color>";
						value2 = "orange";
						break;
					case 4:
						value = "A,<color=red>B</color>,<color=red>C</color>,<color=red>D</color>";
						value2 = "orange";
						break;
					}
					break;
				case PlayerCountRequirement.DUO:
					switch (num)
					{
					case 0:
						value = " , ";
						value2 = "orange";
						break;
					case 1:
						value = "A, ";
						value2 = "orange";
						break;
					case 2:
						value = "A,B";
						value2 = "white";
						break;
					case 3:
						value = "A,B,<color=red>C</color>";
						value2 = "orange";
						break;
					case 4:
						value = "A,B,<color=red>C</color>,<color=red>D</color>";
						value2 = "orange";
						break;
					}
					break;
				}
				StringBuilder stringBuilder = displayText;
				StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(8, 1, stringBuilder);
				handler.AppendLiteral("<color=");
				handler.AppendFormatted(value2);
				handler.AppendLiteral(">");
				StringBuilder stringBuilder2 = stringBuilder.Append(ref handler).Append(ROMAN[i]).Append(": ")
					.Append("[")
					.Append(value)
					.Append("]");
				StringBuilder.AppendInterpolatedStringHandler handler2 = new StringBuilder.AppendInterpolatedStringHandler(9, 1, stringBuilder2);
				handler2.AppendLiteral("</color=");
				handler2.AppendFormatted(value2);
				handler2.AppendLiteral(">");
				stringBuilder2.Append(ref handler2);
				if (i != children.Count - 1)
				{
					displayText.Append(" | ");
				}
			}
			displayText.Append("</color=white>");
			parentHud.m_msgCharBuffer.Add(displayText.ToString());
			GuiManager.InteractionLayer.SetMessage(parentHud.m_msgCharBuffer, parentHud.m_msgStyle, 0);
		}

		private void OnDestroy()
		{
			parent = null;
			parentHud = null;
			def = null;
			children.Clear();
			children = null;
			m_isValid = false;
			playerInScanCount = null;
			displayText = null;
		}

		static ConcurrentClusterHud()
		{
			ClassInjector.RegisterTypeInIl2Cpp<ConcurrentClusterHud>();
		}
	}
}

plugins/Inas07-ExtraObjectiveSetup/FloLib.dll

Decompiled 7 hours ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using AIGraph;
using AK;
using Agents;
using AssetShards;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using BepInEx.Unity.IL2CPP.Utils;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using FloLib.Attributes;
using FloLib.Events;
using FloLib.Infos;
using FloLib.Infos.Comps;
using FloLib.Infos.Inject;
using FloLib.Networks;
using FloLib.Networks.Inject;
using FloLib.Networks.PayloadStructs;
using FloLib.Utils;
using FloLib.Utils.Comps;
using FloLib.Utils.Extensions;
using GTFO.API;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.InteropTypes.Fields;
using Il2CppInterop.Runtime.Runtime;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("FloLib")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+gitd7090d7-dirty-master")]
[assembly: AssemblyProduct("FloLib")]
[assembly: AssemblyTitle("FloLib")]
[assembly: TargetPlatform("Windows7.0")]
[assembly: SupportedOSPlatform("Windows7.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.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.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = 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 FloLib
{
	public static class Automation
	{
		private const BindingFlags ALL = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenStartGame;

		private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenStartupAssetLoaded;

		private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenEnemyAssetLoaded;

		private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenSharedAssetLoaded;

		private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenAllAssetsLoaded;

		static Automation()
		{
			_InvokeWhenStartGame = new Queue<(MethodInfo, object[])>();
			_InvokeWhenStartupAssetLoaded = new Queue<(MethodInfo, object[])>();
			_InvokeWhenEnemyAssetLoaded = new Queue<(MethodInfo, object[])>();
			_InvokeWhenSharedAssetLoaded = new Queue<(MethodInfo, object[])>();
			_InvokeWhenAllAssetsLoaded = new Queue<(MethodInfo, object[])>();
			StartGameEvent.OnGameLoaded += delegate
			{
				(MethodInfo, object[]) result5;
				while (_InvokeWhenStartGame.TryDequeue(out result5))
				{
					RunMethod(result5.Item1, result5.Item2);
				}
			};
			AssetEvent.OnStartupAssetLoaded += delegate
			{
				(MethodInfo, object[]) result4;
				while (_InvokeWhenStartupAssetLoaded.TryDequeue(out result4))
				{
					RunMethod(result4.Item1, result4.Item2);
				}
			};
			AssetEvent.OnEnemyAssetLoaded += delegate
			{
				(MethodInfo, object[]) result3;
				while (_InvokeWhenEnemyAssetLoaded.TryDequeue(out result3))
				{
					RunMethod(result3.Item1, result3.Item2);
				}
			};
			AssetEvent.OnSharedAssetLoaded += delegate
			{
				(MethodInfo, object[]) result2;
				while (_InvokeWhenSharedAssetLoaded.TryDequeue(out result2))
				{
					RunMethod(result2.Item1, result2.Item2);
				}
			};
			AssetEvent.OnAllAssetsLoaded += delegate
			{
				(MethodInfo, object[]) result;
				while (_InvokeWhenAllAssetsLoaded.TryDequeue(out result))
				{
					RunMethod(result.Item1, result.Item2);
				}
			};
		}

		public static void RegisterTypes()
		{
			Assembly obj = new StackFrame(1).GetMethod()?.GetType()?.Assembly ?? null;
			if (obj == null)
			{
				throw new NullReferenceException("Caller Assembly was null");
			}
			RegisterTypes(obj);
		}

		public static void RegisterTypes(Type target)
		{
			if (target == null)
			{
				throw new ArgumentNullException("target");
			}
			RegisterTypes(target.Assembly);
		}

		public static void RegisterTypes(Assembly target)
		{
			if (target == null)
			{
				throw new ArgumentNullException("target");
			}
			InjectAll(target);
			AddAutoInvokes(target);
		}

		private static void InjectAll(Assembly assem)
		{
			//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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			foreach (Type item in assem.GetTypes()?.Where((Type x) => Attribute.IsDefined(x, typeof(AutoInjectAttribute))) ?? Enumerable.Empty<Type>())
			{
				AutoInjectAttribute autoInjectAttribute = (AutoInjectAttribute)Attribute.GetCustomAttribute(item, typeof(AutoInjectAttribute));
				if (autoInjectAttribute.Interfaces.Length != 0)
				{
					RegisterTypeOptions val = new RegisterTypeOptions();
					val.set_Interfaces(Il2CppInterfaceCollection.op_Implicit(autoInjectAttribute.Interfaces));
					val.set_LogSuccess(RegisterTypeOptions.Default.LogSuccess);
					ClassInjector.RegisterTypeInIl2Cpp(item, val);
				}
				else
				{
					ClassInjector.RegisterTypeInIl2Cpp(item);
				}
			}
		}

		private static void AddAutoInvokes(Assembly assem)
		{
			foreach (MethodInfo item in assem.GetTypes()?.SelectMany((Type x) => x.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))?.Where((MethodInfo x) => x.IsStatic && Attribute.IsDefined(x, typeof(AutoInvokeAttribute))) ?? Enumerable.Empty<MethodInfo>())
			{
				AutoInvokeAttribute obj = (AutoInvokeAttribute)Attribute.GetCustomAttribute(item, typeof(AutoInvokeAttribute));
				object[] arguments = obj.Arguments;
				switch (obj.When)
				{
				case InvokeWhen.PluginLoaded:
					RunMethod(item, arguments);
					break;
				case InvokeWhen.StartGame:
					_InvokeWhenStartGame.Enqueue((item, arguments));
					break;
				case InvokeWhen.StartupAssetLoaded:
					_InvokeWhenStartupAssetLoaded.Enqueue((item, arguments));
					break;
				case InvokeWhen.EnemyAssetLoaded:
					_InvokeWhenEnemyAssetLoaded.Enqueue((item, arguments));
					break;
				case InvokeWhen.SharedAssetLoaded:
					_InvokeWhenSharedAssetLoaded.Enqueue((item, arguments));
					break;
				case InvokeWhen.AllAssetsLoaded:
					_InvokeWhenAllAssetsLoaded.Enqueue((item, arguments));
					break;
				}
			}
		}

		private static void RunMethod(MethodInfo method, params object[] args)
		{
			if (method.IsConstructor)
			{
				RuntimeHelpers.RunClassConstructor(method.DeclaringType.TypeHandle);
			}
			else
			{
				method.Invoke(null, args);
			}
		}
	}
	[BepInPlugin("GTFO.FloLib", "FloLib", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class EntryPoint : BasePlugin
	{
		private Harmony _Harmony;

		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			_Harmony = new Harmony("FloLib.Harmony");
			_Harmony.PatchAll();
			Automation.RegisterTypes(((object)this).GetType());
		}

		public override bool Unload()
		{
			_Harmony.UnpatchSelf();
			return ((BasePlugin)this).Unload();
		}
	}
	internal static class Logger
	{
		internal static bool LogExceptionInDetail;

		private static readonly ManualLogSource _Logger;

		static Logger()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			_Logger = new ManualLogSource("FloLib");
			Logger.Sources.Add((ILogSource)(object)_Logger);
		}

		private static string Format(object msg)
		{
			return msg.ToString();
		}

		public static void Info(BepInExInfoLogInterpolatedStringHandler handler)
		{
			_Logger.LogInfo(handler);
		}

		public static void Info(string str)
		{
			_Logger.LogMessage((object)str);
		}

		public static void Info(object data)
		{
			_Logger.LogMessage((object)Format(data));
		}

		public static void Debug(BepInExDebugLogInterpolatedStringHandler handler)
		{
			_Logger.LogDebug(handler);
		}

		public static void Debug(string str)
		{
			_Logger.LogDebug((object)str);
		}

		public static void Debug(object data)
		{
			_Logger.LogDebug((object)Format(data));
		}

		public static void Error(BepInExErrorLogInterpolatedStringHandler handler)
		{
			_Logger.LogError(handler);
		}

		public static void Error(string str)
		{
			_Logger.LogError((object)str);
		}

		public static void Error(object data)
		{
			_Logger.LogError((object)Format(data));
		}

		public static void Fatal(BepInExFatalLogInterpolatedStringHandler handler)
		{
			_Logger.LogFatal(handler);
		}

		public static void Fatal(string str)
		{
			_Logger.LogFatal((object)str);
		}

		public static void Fatal(object data)
		{
			_Logger.LogFatal((object)Format(data));
		}

		public static void Warn(BepInExWarningLogInterpolatedStringHandler handler)
		{
			_Logger.LogWarning(handler);
		}

		public static void Warn(string str)
		{
			_Logger.LogWarning((object)str);
		}

		public static void Warn(object data)
		{
			_Logger.LogWarning((object)Format(data));
		}

		[Conditional("DEBUG")]
		public static void DebugOnly(object data)
		{
		}

		public static void Exception(Exception e)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			if (LogExceptionInDetail)
			{
				_Logger.LogError((object)e.ToString());
				return;
			}
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(2, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(e.GetType().Name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(e.Message);
			}
			_Logger.LogError(val);
		}
	}
	internal static class TaskQueue
	{
		public const float INTERVAL = 0.15f;

		private static readonly ConcurrentQueue<(Action action, string? name)> q;

		public static Coroutine mainCoroutine { get; private set; }

		private static IEnumerator MainLoop()
		{
			while (true)
			{
				if (q.TryDequeue(out (Action, string) result))
				{
					CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(ExecuteTask(result.Item1, (result.Item2 == null) ? "unnamed" : result.Item2)), (Action)null);
				}
				yield return (object)new WaitForSeconds(0.15f);
			}
		}

		private static IEnumerator ExecuteTask(Action task, string name)
		{
			try
			{
				task?.Invoke();
			}
			catch (Exception ex)
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(46, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Exception occurred during execution of task ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				Logger.Error(val);
			}
			yield break;
		}

		public static void AddTask(Action task, string name = null)
		{
			q.Enqueue((task, name));
		}

		static TaskQueue()
		{
			q = new ConcurrentQueue<(Action, string)>();
			Logger.Debug("TaskQueue: Coroutine started");
			mainCoroutine = CoroutineManager.StartPersistantCoroutine(CollectionExtensions.WrapToIl2Cpp(MainLoop()));
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.1.3+git35c0c2a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "FloLib";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "gitd7090d7-dirty-master";

		public const string SemVer = "1.0.0+gitd7090d7-dirty-master";

		public const string GitRevShort = "d7090d7-dirty";

		public const string GitRevLong = "d7090d7625ec9ea5a37260ec10ba96729e107216-dirty";

		public const string GitBranch = "master";

		public const string GitTag = null;

		public const int GitCommitsSinceTag = 0;

		public const bool GitIsDirty = true;
	}
}
namespace FloLib.Utils
{
	public enum CoroutineLifeTime
	{
		Forever,
		Lobby,
		Level,
		BetweenRecall
	}
	public static class Coroutines
	{
		private static MonoBehaviour _Runner;

		private static readonly Queue<Coroutine> _Coroutines_Lobby = new Queue<Coroutine>();

		private static readonly Queue<Coroutine> _Coroutines_Level = new Queue<Coroutine>();

		private static readonly Queue<Coroutine> _Coroutines_CPLoad = new Queue<Coroutine>();

		[AutoInvoke(InvokeWhen.StartGame)]
		internal static void Init()
		{
			//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_000b: Expected O, but got Unknown
			GameObject val = new GameObject();
			Object.DontDestroyOnLoad((Object)val);
			_Runner = (MonoBehaviour)(object)val.AddComponent<EmptyMB>();
			LevelAPI.OnLevelCleanup += LevelAPI_OnLevelCleanup;
			Inject_SNet_Capture.OnBufferRecalled += Inject_SNet_Capture_OnBufferRecalled;
		}

		private static void Inject_SNet_Capture_OnBufferRecalled(eBufferType obj)
		{
			StopAll(CoroutineLifeTime.BetweenRecall);
		}

		private static void LevelAPI_OnLevelCleanup()
		{
			StopAll();
			StopAll(CoroutineLifeTime.BetweenRecall);
		}

		public static void StopAll(CoroutineLifeTime lifeTime = CoroutineLifeTime.Level)
		{
			Queue<Coroutine> queue = lifeTime switch
			{
				CoroutineLifeTime.Lobby => _Coroutines_Lobby, 
				CoroutineLifeTime.Level => _Coroutines_Level, 
				CoroutineLifeTime.BetweenRecall => _Coroutines_CPLoad, 
				_ => throw new NotSupportedException($"{"CoroutineLifeTime"}: {lifeTime} is not supported!"), 
			};
			Coroutine result;
			while (queue.TryDequeue(out result))
			{
				_Runner.StopCoroutine(result);
			}
		}

		public static void Stop(Coroutine coroutine)
		{
			_Runner.StopCoroutine(coroutine);
		}

		public static Coroutine Start(IEnumerator coroutine, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever)
		{
			switch (lifeTime)
			{
			case CoroutineLifeTime.Forever:
				return MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine);
			case CoroutineLifeTime.Lobby:
			{
				Coroutine val = MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine);
				_Coroutines_Lobby.Enqueue(val);
				return val;
			}
			case CoroutineLifeTime.Level:
			{
				Coroutine val = MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine);
				_Coroutines_Level.Enqueue(val);
				return val;
			}
			case CoroutineLifeTime.BetweenRecall:
			{
				Coroutine val = MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine);
				_Coroutines_CPLoad.Enqueue(val);
				return val;
			}
			default:
				throw new NotSupportedException($"{"CoroutineLifeTime"}: {lifeTime} is not supported!!");
			}
		}

		public static Coroutine DoWait(float delay, Action onDone, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever)
		{
			return Start(Wait(delay, onDone), lifeTime);
		}

		public static Coroutine DoWaitRealtime(float delay, Action onDone, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever)
		{
			return Start(WaitRealtime(delay, onDone), lifeTime);
		}

		public static Coroutine DoBlink(BlinkInfo blinkInfo, Action<bool> onBlinkChanged, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever)
		{
			return Start(Blink(blinkInfo, onBlinkChanged), lifeTime);
		}

		public static Coroutine DoLerp(LerpInfo lerpInfo, Action<float> onValueChanged, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever)
		{
			return Start(Lerp(lerpInfo, onValueChanged), lifeTime);
		}

		public static IEnumerator Wait(float delay, Action onDone)
		{
			yield return (object)new WaitForSeconds(delay);
			onDone?.Invoke();
		}

		public static IEnumerator WaitRealtime(float delay, Action onDone)
		{
			yield return (object)new WaitForSecondsRealtime(delay);
			onDone?.Invoke();
		}

		public static IEnumerator Blink(BlinkInfo info, Action<bool> onBlinkChanged)
		{
			float time = 0f;
			bool lastCond = false;
			onBlinkChanged?.Invoke(obj: false);
			while (time < info.Duration)
			{
				bool flag = BlinkByProgress(Mathf.Repeat(time * info.Speed, 1f));
				if (flag != lastCond)
				{
					onBlinkChanged?.Invoke(flag);
					lastCond = flag;
				}
				time += Time.deltaTime;
				yield return null;
			}
			onBlinkChanged?.Invoke(info.EndBlinkState);
		}

		public static IEnumerator Lerp(LerpInfo info, Action<float> onValueChanged)
		{
			float time = 0f;
			onValueChanged?.Invoke(info.From);
			while (time < info.Duration)
			{
				float num = info.Easing.Evaluate(time / info.Duration);
				float obj = Mathf.Lerp(info.From, info.To, num);
				onValueChanged?.Invoke(obj);
				time += Time.deltaTime;
				yield return null;
			}
			onValueChanged?.Invoke(info.To);
		}

		private static bool BlinkByProgress(float progress)
		{
			return progress % 0.25f < 0.125f;
		}
	}
	public struct BlinkInfo
	{
		public bool EndBlinkState;

		public float Speed;

		public float Duration;

		public static readonly BlinkInfo InDefault = new BlinkInfo
		{
			Duration = 0.33f,
			Speed = 3f,
			EndBlinkState = true
		};

		public static readonly BlinkInfo OutDefault = new BlinkInfo
		{
			Duration = 0.33f,
			Speed = 3f,
			EndBlinkState = false
		};
	}
	public struct LerpInfo
	{
		public float From;

		public float To;

		public float Duration;

		public EaseFunc.Type Easing;

		public LerpInfo(float from, float to, float duration, EaseFunc.Type ease = EaseFunc.Type.Linear)
		{
			From = from;
			To = to;
			Duration = duration;
			Easing = ease;
		}
	}
	public static class EaseFunc
	{
		public enum Type : byte
		{
			Linear,
			Zero,
			One,
			InQuad,
			OutQuad,
			InOutQuad,
			InCubic,
			OutCubic,
			InOutCubic,
			InQuart,
			OutQuart,
			InOutQuart,
			InQuint,
			OutQuint,
			InOutQuint,
			InSine,
			OutSine,
			InOutSine,
			InExpo,
			OutExpo,
			InOutExpo,
			InCirc,
			OutCirc,
			InOutCirc,
			InElastic,
			OutElastic,
			InOutElastic,
			InBack,
			OutBack,
			InOutBack,
			InBounce,
			OutBounce,
			InOutBounce
		}

		public static float Evaluate(this Type type, float t)
		{
			t = Mathf.Clamp01(t);
			return type switch
			{
				Type.Linear => t, 
				Type.Zero => 0f, 
				Type.One => 1f, 
				Type.InQuad => InQuad(t), 
				Type.OutQuad => OutQuad(t), 
				Type.InOutQuad => InOutQuad(t), 
				Type.InCubic => InCubic(t), 
				Type.OutCubic => OutCubic(t), 
				Type.InOutCubic => InOutCubic(t), 
				Type.InQuart => InQuart(t), 
				Type.OutQuart => OutQuart(t), 
				Type.InOutQuart => InOutQuart(t), 
				Type.InQuint => InQuint(t), 
				Type.OutQuint => OutQuint(t), 
				Type.InOutQuint => InOutQuint(t), 
				Type.InSine => InSine(t), 
				Type.OutSine => OutSine(t), 
				Type.InOutSine => InOutSine(t), 
				Type.InExpo => InExpo(t), 
				Type.OutExpo => OutExpo(t), 
				Type.InOutExpo => InOutExpo(t), 
				Type.InCirc => InCirc(t), 
				Type.OutCirc => OutCirc(t), 
				Type.InOutCirc => InOutCirc(t), 
				Type.InElastic => InElastic(t), 
				Type.OutElastic => OutElastic(t), 
				Type.InOutElastic => InOutElastic(t), 
				Type.InBack => InBack(t), 
				Type.OutBack => OutBack(t), 
				Type.InOutBack => InOutBack(t), 
				Type.InBounce => InBounce(t), 
				Type.OutBounce => OutBounce(t), 
				Type.InOutBounce => InOutBounce(t), 
				_ => throw new ArgumentOutOfRangeException("type", "Given type was invalid!"), 
			};
		}

		public static float InQuad(float t)
		{
			return t * t;
		}

		public static float OutQuad(float t)
		{
			return 1f - InQuad(1f - t);
		}

		public static float InOutQuad(float t)
		{
			if ((double)t < 0.5)
			{
				return InQuad(t * 2f) / 2f;
			}
			return 1f - InQuad((1f - t) * 2f) / 2f;
		}

		public static float InCubic(float t)
		{
			return t * t * t;
		}

		public static float OutCubic(float t)
		{
			return 1f - InCubic(1f - t);
		}

		public static float InOutCubic(float t)
		{
			if ((double)t < 0.5)
			{
				return InCubic(t * 2f) / 2f;
			}
			return 1f - InCubic((1f - t) * 2f) / 2f;
		}

		public static float InQuart(float t)
		{
			return t * t * t * t;
		}

		public static float OutQuart(float t)
		{
			return 1f - InQuart(1f - t);
		}

		public static float InOutQuart(float t)
		{
			if ((double)t < 0.5)
			{
				return InQuart(t * 2f) / 2f;
			}
			return 1f - InQuart((1f - t) * 2f) / 2f;
		}

		public static float InQuint(float t)
		{
			return t * t * t * t * t;
		}

		public static float OutQuint(float t)
		{
			return 1f - InQuint(1f - t);
		}

		public static float InOutQuint(float t)
		{
			if ((double)t < 0.5)
			{
				return InQuint(t * 2f) / 2f;
			}
			return 1f - InQuint((1f - t) * 2f) / 2f;
		}

		public static float InSine(float t)
		{
			return (float)(0.0 - Math.Cos((double)t * Math.PI / 2.0));
		}

		public static float OutSine(float t)
		{
			return (float)Math.Sin((double)t * Math.PI / 2.0);
		}

		public static float InOutSine(float t)
		{
			return (float)(Math.Cos((double)t * Math.PI) - 1.0) / -2f;
		}

		public static float InExpo(float t)
		{
			return (float)Math.Pow(2.0, 10f * (t - 1f));
		}

		public static float OutExpo(float t)
		{
			return 1f - InExpo(1f - t);
		}

		public static float InOutExpo(float t)
		{
			if ((double)t < 0.5)
			{
				return InExpo(t * 2f) / 2f;
			}
			return 1f - InExpo((1f - t) * 2f) / 2f;
		}

		public static float InCirc(float t)
		{
			return 0f - ((float)Math.Sqrt(1f - t * t) - 1f);
		}

		public static float OutCirc(float t)
		{
			return 1f - InCirc(1f - t);
		}

		public static float InOutCirc(float t)
		{
			if ((double)t < 0.5)
			{
				return InCirc(t * 2f) / 2f;
			}
			return 1f - InCirc((1f - t) * 2f) / 2f;
		}

		public static float InElastic(float t)
		{
			return 1f - OutElastic(1f - t);
		}

		public static float OutElastic(float t)
		{
			float num = 0.3f;
			return (float)Math.Pow(2.0, -10f * t) * (float)Math.Sin((double)(t - num / 4f) * (Math.PI * 2.0) / (double)num) + 1f;
		}

		public static float InOutElastic(float t)
		{
			if ((double)t < 0.5)
			{
				return InElastic(t * 2f) / 2f;
			}
			return 1f - InElastic((1f - t) * 2f) / 2f;
		}

		public static float InBack(float t)
		{
			float num = 1.70158f;
			return t * t * ((num + 1f) * t - num);
		}

		public static float OutBack(float t)
		{
			return 1f - InBack(1f - t);
		}

		public static float InOutBack(float t)
		{
			if ((double)t < 0.5)
			{
				return InBack(t * 2f) / 2f;
			}
			return 1f - InBack((1f - t) * 2f) / 2f;
		}

		public static float InBounce(float t)
		{
			return 1f - OutBounce(1f - t);
		}

		public static float OutBounce(float t)
		{
			float num = 2.75f;
			float num2 = 7.5625f;
			if (t < 1f / num)
			{
				return num2 * t * t;
			}
			if (t < 2f / num)
			{
				t -= 1.5f / num;
				return num2 * t * t + 0.75f;
			}
			if ((double)t < 2.5 / (double)num)
			{
				t -= 2.25f / num;
				return num2 * t * t + 0.9375f;
			}
			t -= 2.625f / num;
			return num2 * t * t + 63f / 64f;
		}

		public static float InOutBounce(float t)
		{
			if ((double)t < 0.5)
			{
				return InBounce(t * 2f) / 2f;
			}
			return 1f - InBounce((1f - t) * 2f) / 2f;
		}
	}
	public static class EasyDetour
	{
		public unsafe delegate void StaticVoidDelegate(Il2CppMethodInfo* methodInfo);

		public unsafe delegate void InstanceVoidDelegate(IntPtr instancePtr, Il2CppMethodInfo* methodInfo);

		public static bool TryCreate<T>(DetourDescriptor descriptor, T to, out T originalCall, out INativeDetour detourInstance) where T : Delegate
		{
			try
			{
				nint methodPointer = descriptor.GetMethodPointer();
				detourInstance = INativeDetour.CreateAndApply<T>((IntPtr)methodPointer, to, ref originalCall);
				return detourInstance != null;
			}
			catch (Exception ex)
			{
				Logger.Error("Exception Thrown while creating Detour:");
				Logger.Error(ex.ToString());
			}
			originalCall = null;
			detourInstance = null;
			return false;
		}
	}
	public struct DetourDescriptor
	{
		public Type Type;

		public Type ReturnType;

		public Type[] ArgTypes;

		public string MethodName;

		public bool IsGeneric;

		public unsafe nint GetMethodPointer()
		{
			if (Type == null)
			{
				throw new MissingFieldException("Field Type is not set!");
			}
			if (ReturnType == null)
			{
				throw new MissingFieldException("Field ReturnType is not set! If you mean 'void' do typeof(void)");
			}
			if (string.IsNullOrEmpty(MethodName))
			{
				throw new MissingFieldException("Field MethodName is not set or valid!");
			}
			Il2CppType.From(Type, true);
			IntPtr nativeClassPointer = Il2CppClassPointerStore.GetNativeClassPointer(Type);
			string fullName = GetFullName(ReturnType);
			string[] array;
			if (ArgTypes == null || ArgTypes.Length == 0)
			{
				array = Array.Empty<string>();
			}
			else
			{
				int num = ArgTypes.Length;
				array = new string[num];
				for (int i = 0; i < num; i++)
				{
					Type type = ArgTypes[i];
					array[i] = GetFullName(type);
				}
			}
			void** ptr = (void**)IL2CPP.GetIl2CppMethod(nativeClassPointer, IsGeneric, MethodName, fullName, array).ToPointer();
			if (ptr == null)
			{
				return (nint)ptr;
			}
			return (nint)(*ptr);
		}

		private static string GetFullName(Type type)
		{
			bool isPointer = type.IsPointer;
			if (isPointer)
			{
				type = type.GetElementType();
			}
			if (type.IsPrimitive || type == typeof(string))
			{
				if (isPointer)
				{
					return type.MakePointerType().FullName;
				}
				return type.FullName;
			}
			Type val = Il2CppType.From(type, true);
			if (isPointer)
			{
				return val.MakePointerType().FullName;
			}
			return val.FullName;
		}
	}
	public struct HalfColor
	{
		public Half R;

		public Half G;

		public Half B;

		public Half A;

		public HalfColor()
		{
			R = (Half)0f;
			G = (Half)0f;
			B = (Half)0f;
			A = (Half)0f;
		}

		public HalfColor(float r, float g, float b, float a)
		{
			R = (Half)r;
			G = (Half)g;
			B = (Half)b;
			A = (Half)a;
		}

		public static implicit operator Color(HalfColor halfCol)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			return new Color((float)halfCol.R, (float)halfCol.G, (float)halfCol.B, (float)halfCol.A);
		}

		public static implicit operator HalfColor(Color col)
		{
			//IL_0009: 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_002d: 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)
			HalfColor result = new HalfColor();
			result.R = (Half)col.r;
			result.G = (Half)col.g;
			result.B = (Half)col.b;
			result.A = (Half)col.a;
			return result;
		}
	}
	public struct HalfRGBColor
	{
		public Half R;

		public Half G;

		public Half B;

		public static implicit operator Color(HalfRGBColor halfCol)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			return new Color((float)halfCol.R, (float)halfCol.G, (float)halfCol.B);
		}

		public static implicit operator HalfRGBColor(Color col)
		{
			//IL_000a: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			HalfRGBColor result = default(HalfRGBColor);
			result.R = (Half)col.r;
			result.G = (Half)col.g;
			result.B = (Half)col.b;
			return result;
		}
	}
	public class RNG
	{
		private const int Float01Precision = 2000000000;

		private const float Float01Inv = 5E-10f;

		private static uint _UniqueIDForRandomSeed = 0u;

		private Random _Rand;

		private int _Seed;

		public static GlobalRNG Global { get; private set; } = new GlobalRNG();


		public float Float01 => (float)_Rand.Next(0, 2000000001) * 5E-10f;

		public float FloatMinusOneToPlusOne => (float)_Rand.Next(-2000000000, 2000000001) * 5E-10f;

		public int Int0ToPositive => _Rand.Next(0, int.MaxValue);

		public int Int0ToNegative => _Rand.Next(int.MinValue, 1);

		public int Int => _Rand.Next(int.MinValue, int.MaxValue);

		public RNG()
		{
			if (_UniqueIDForRandomSeed == uint.MaxValue)
			{
				_UniqueIDForRandomSeed = 0u;
			}
			else
			{
				_UniqueIDForRandomSeed++;
			}
			_Seed = $"{_UniqueIDForRandomSeed} {Environment.TickCount64}".GetHashCode();
			_Rand = new Random(_Seed);
		}

		public RNG(int seed)
		{
			_Seed = seed;
			_Rand = new Random(seed);
		}

		public virtual void Reset(int? newSeed = null)
		{
			if (newSeed.HasValue)
			{
				_Seed = newSeed.Value;
			}
			_Rand = new Random(_Seed);
		}

		public bool Probability(float probability)
		{
			if (probability <= 0f)
			{
				return false;
			}
			if (probability >= 1f)
			{
				return true;
			}
			return Float01 < probability;
		}

		public bool OneIn(int cases)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			if (cases <= 0)
			{
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(46, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("RNG");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("OneIn");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" received ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(cases);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (0 or negative); fallback to false");
				}
				Logger.Warn(val);
				return false;
			}
			if (cases == 1)
			{
				return true;
			}
			return _Rand.Next(0, cases) == 0;
		}

		public T Choice<T>(params T[] items)
		{
			return Choice((IEnumerable<T>)items);
		}

		public T Choice<T>(IEnumerable<T> items)
		{
			if (IsChoiceHaveSimpleScenarioValue(items, out var value))
			{
				return value;
			}
			int maxValue = items.Count();
			int index = _Rand.Next(0, maxValue);
			return items.ElementAt(index);
		}

		public T[] Choice<T>(IEnumerable<T> items, int count)
		{
			if (IsChoiceHaveSimpleScenarioValue(items, out var value))
			{
				return new T[1] { value };
			}
			return items.OrderBy((T x) => _Rand.NextDouble()).Take(count).ToArray();
		}

		public T WeightedChoice<T>(IEnumerable<(T item, float weight)> itemTuples)
		{
			if (IsChoiceHaveSimpleScenarioValue<(T, float)>(itemTuples, out var value))
			{
				return value.Item1;
			}
			T[] array = itemTuples.Select(((T item, float weight) x) => x.item).ToArray();
			float[] array2 = itemTuples.Select(((T item, float weight) x) => x.weight).ToArray();
			float num = 0f;
			for (int i = 0; i < array2.Length; i++)
			{
				float num2 = array2[i];
				if (num2 <= 0f)
				{
					array2[i] = -1f;
				}
				else
				{
					num = (array2[i] = num + num2);
				}
			}
			if (num <= 0f)
			{
				return Choice(array);
			}
			float num3 = Float01 * num;
			for (int j = 0; j < array2.Length; j++)
			{
				if (j == array2.Length - 1 || num3 <= array2[j])
				{
					return array[j];
				}
			}
			throw new InvalidOperationException("What? this should never happen");
		}

		private static bool IsChoiceHaveSimpleScenarioValue<T>(IEnumerable<T> items, out T value)
		{
			int num = items.Count();
			if (num <= 0)
			{
				throw new ArgumentException("Argument Item Count is 0!", "items");
			}
			if (num == 1)
			{
				value = items.First();
				return true;
			}
			value = default(T);
			return false;
		}
	}
	public sealed class GlobalRNG : RNG
	{
		public sealed override void Reset(int? newSeed = null)
		{
			Logger.Warn("Resetting Seed Value is not allowed on RNG.Global");
		}
	}
}
namespace FloLib.Utils.Extensions
{
	public static class ColorExtension
	{
		public static string ToHex(this Color input)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return "#" + ColorUtility.ToHtmlStringRGB(input);
		}

		public static string ToHexRGBA(this Color input)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return "#" + ColorUtility.ToHtmlStringRGBA(input);
		}

		public static void GetColorInfo(this Color input, out Color baseColor, out float colorMultiplier)
		{
			//IL_000c: 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_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_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)
			float num = 0f;
			float num2 = 0f;
			float r = input.r;
			float g = input.g;
			float b = input.b;
			float num3 = Mathf.Abs(r);
			float num4 = Mathf.Abs(g);
			float num5 = Mathf.Abs(b);
			if (num3 > num2)
			{
				num2 = num3;
				num = r;
			}
			if (num4 > num2)
			{
				num2 = num4;
				num = g;
			}
			if (num5 > num2)
			{
				num2 = num5;
				num = b;
			}
			if (num2 > 0f)
			{
				baseColor = new Color(r / num, g / num, b / num, 1f);
				colorMultiplier = num;
			}
			else
			{
				baseColor = Color.black;
				colorMultiplier = 1f;
			}
		}
	}
	public static class ComponentExtension
	{
		public static bool TryGetComp<T>(this Component comp, out T component)
		{
			component = comp.GetComponent<T>();
			return component != null;
		}

		public static bool TryGetVirtualScene(this Component comp, out GUIX_VirtualScene scene)
		{
			GUIX_VirtualSceneLink component = comp.GetComponent<GUIX_VirtualSceneLink>();
			if ((Object)(object)component == (Object)null)
			{
				scene = null;
				return false;
			}
			scene = component.m_virtualScene;
			return (Object)(object)scene != (Object)null;
		}

		public static string GetGameObjectPath(this Component comp)
		{
			return comp.gameObject.GetPath();
		}
	}
	public static class GameObjectExtension
	{
		public static bool TryGetComp<T>(this GameObject obj, out T component)
		{
			component = obj.GetComponent<T>();
			return component != null;
		}

		public static T GetCompInParentOrChild<T>(this GameObject obj)
		{
			T val = obj.GetComponentInParent<T>();
			if (val == null)
			{
				val = obj.GetComponentInChildren<T>();
				if (val == null)
				{
					obj.GetComponent<T>();
				}
			}
			return val;
		}

		public static string GetPath(this GameObject obj)
		{
			string text = "/" + ((Object)obj).name;
			while ((Object)(object)obj.transform.parent != (Object)null)
			{
				obj = ((Component)obj.transform.parent).gameObject;
				text = "/" + ((Object)obj).name + text;
			}
			return text;
		}
	}
	public static class Il2CppBoxingExtension
	{
		public static Object BoxToIl2CppObject(this bool value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Boolean val = default(Boolean);
			val.m_value = value;
			return ((Boolean)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this byte value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Byte val = default(Byte);
			val.m_value = value;
			return ((Byte)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this sbyte value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			SByte val = default(SByte);
			val.m_value = value;
			return ((SByte)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this char value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Char val = default(Char);
			val.m_value = value;
			return ((Char)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this short value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Int16 val = default(Int16);
			val.m_value = value;
			return ((Int16)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this ushort value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			UInt16 val = default(UInt16);
			val.m_value = value;
			return ((UInt16)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this int value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Int32 val = default(Int32);
			val.m_value = value;
			return ((Int32)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this uint value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			UInt32 val = default(UInt32);
			val.m_value = value;
			return ((UInt32)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this long value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Int64 val = default(Int64);
			val.m_value = value;
			return ((Int64)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this ulong value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			UInt64 val = default(UInt64);
			val.m_value = value;
			return ((UInt64)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this float value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Single val = default(Single);
			val.m_value = value;
			return ((Single)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this double value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Double val = default(Double);
			val.m_value = value;
			return ((Double)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this nint value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			IntPtr val = default(IntPtr);
			val.m_value = value;
			return ((IntPtr)(ref val)).BoxIl2CppObject();
		}
	}
	public static class Il2CppObjectExtension
	{
		public static bool CanCastToType<T>(this Il2CppObjectBase obj) where T : Il2CppObjectBase
		{
			return obj.TryCast<T>() != null;
		}

		public static bool TryCastToType<T>(this Il2CppObjectBase obj, out T result) where T : Il2CppObjectBase
		{
			result = obj.TryCast<T>();
			return result != null;
		}
	}
	public static class LGLightExtension
	{
		public static void SetColor(this IEnumerable<LG_Light> lights, Color color)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			foreach (LG_Light light in lights)
			{
				light.ChangeColor(color);
			}
		}

		public static void SetEnabled(this IEnumerable<LG_Light> lights, bool enabled)
		{
			foreach (LG_Light light in lights)
			{
				light.SetEnabled(enabled);
			}
		}

		public static bool Is(this LG_Light light, LightCategory lightCategory)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			return (int)light.m_category == (int)lightCategory;
		}

		public static bool IsAny(this LG_Light light, params LightCategory[] categories)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			for (int i = 0; i < categories.Length; i++)
			{
				if ((int)light.m_category == (int)categories[i])
				{
					return true;
				}
			}
			return false;
		}
	}
	public enum LightCategory
	{
		General = 0,
		Special = 1,
		Independent = 3,
		Sign = 5,
		Door = 4,
		DoorImportant = 6,
		Emergency = 2
	}
	public static class TerminalExtension
	{
		public static void SetPowered(this LG_ComputerTerminal terminal, bool isPowered)
		{
			terminal.OnProximityExit();
			Interact_ComputerTerminal componentInChildren = ((Component)terminal).GetComponentInChildren<Interact_ComputerTerminal>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				((Behaviour)componentInChildren).enabled = isPowered;
				((Interact_Base)componentInChildren).SetActive(isPowered);
			}
			GUIX_VirtualSceneLink component = ((Component)terminal).GetComponent<GUIX_VirtualSceneLink>();
			if ((Object)(object)component != (Object)null && (Object)(object)component.m_virtualScene != (Object)null)
			{
				GUIX_VirtualCamera virtualCamera = component.m_virtualScene.virtualCamera;
				float num = (isPowered ? 0.3f : 0f);
				float num2 = (isPowered ? 1000f : 0f);
				virtualCamera.SetFovAndClip(virtualCamera.paramCamera.fieldOfView, num, num2);
			}
			if ((Object)(object)terminal.m_text != (Object)null)
			{
				((Behaviour)terminal.m_text).enabled = isPowered;
			}
			if (!isPowered)
			{
				PlayerAgent localInteractionSource = terminal.m_localInteractionSource;
				if ((Object)(object)localInteractionSource != (Object)null && localInteractionSource.FPItemHolder.InTerminalTrigger)
				{
					terminal.ExitFPSView();
				}
			}
		}
	}
	public static class VectorExtension
	{
		public static string ToFormattedString(this Vector2 vector)
		{
			//IL_0017: 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)
			return $"x: {vector.x:0.0000}, y: {vector.y:0.0000}";
		}

		public static string ToFormattedString(this Vector3 vector)
		{
			//IL_0018: 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_0054: Unknown result type (might be due to invalid IL or missing references)
			return $"x: {vector.x:0.0000}, y: {vector.y:0.0000} z: {vector.z:0.0000}";
		}

		public static string ToFormattedString(this Vector4 vector)
		{
			//IL_0018: 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_0054: 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)
			return $"x: {vector.x:0.0000}, y: {vector.y:0.0000} z: {vector.z:0.0000} w: {vector.w:0.0000}";
		}
	}
}
namespace FloLib.Utils.Comps
{
	[AutoInject]
	internal sealed class EmptyMB : MonoBehaviour
	{
	}
}
namespace FloLib.Networks
{
	public static class GlobalNetAction<P> where P : struct
	{
		private static string _EventName;

		private static bool _IsSetup;

		public static SNet_ChannelType SendChannel { get; set; }

		public static SNet_Player LastSender { get; private set; }

		public static ulong LastSenderID { get; private set; }

		public static event Action<ulong, P> OnReceive;

		public static event Action<ulong, P> OnReceiveLocally;

		static GlobalNetAction()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			SendChannel = (SNet_ChannelType)2;
			_IsSetup = false;
			Setup();
		}

		public static void Setup()
		{
			if (!_IsSetup)
			{
				_EventName = UName.Get(typeof(P), "NA");
				NetworkAPI.RegisterEvent<P>(_EventName, (Action<ulong, P>)Received);
				_IsSetup = true;
			}
		}

		public static void Send(P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			SendToLocal(payload);
			TaskQueue.AddTask(delegate
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel);
			}, "GlobalNetAction.Send");
		}

		public static void SendTo(P payload, SNet_Player target)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			if (target.IsLocal)
			{
				SendToLocal(payload);
				return;
			}
			TaskQueue.AddTask(delegate
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel);
			}, "GlobalNetAction.SendTo");
		}

		public static void SendTo(P payload, SNet_SendGroup group)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			Enumerator<SNet_Player> enumerator = SNet_PlayerSendGroupManager.GetGroup(group).GetEnumerator();
			while (enumerator.MoveNext())
			{
				SNet_Player current = enumerator.Current;
				SendTo(payload, current);
			}
		}

		private static void SendToLocal(P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			SNet_Player val = (LastSender = SNet.LocalPlayer);
			if ((Object)(object)val != (Object)null)
			{
				LastSenderID = val.Lookup;
			}
			GlobalNetAction<P>.OnReceive?.Invoke(LastSenderID, payload);
			GlobalNetAction<P>.OnReceiveLocally?.Invoke(LastSenderID, payload);
		}

		private static void Received(ulong sender, P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			SNet_Player lastSender = default(SNet_Player);
			if (!SNet.Core.TryGetPlayer(sender, ref lastSender, false))
			{
				LastSender = null;
				LastSenderID = 0uL;
				Logger.Error("NetAction sender was invalid!");
			}
			LastSender = lastSender;
			LastSenderID = sender;
			GlobalNetAction<P>.OnReceive?.Invoke(sender, payload);
		}
	}
	public static class GlobalNetMasterAction<P> where P : struct
	{
		public static Func<ulong, P, bool> IsActionValid;

		private static string _AskEventName;

		private static string _EventName;

		private static bool _IsSetup;

		public static SNet_ChannelType SendChannel { get; set; }

		public static SNet_Player LastSender { get; private set; }

		public static ulong LastSenderID { get; private set; }

		public static event Action<ulong, P> OnReceive;

		public static event Action<ulong, P> OnMasterReceive;

		static GlobalNetMasterAction()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			SendChannel = (SNet_ChannelType)2;
			IsActionValid = (ulong sender, P p) => true;
			_IsSetup = false;
			Setup();
		}

		public static void Setup()
		{
			if (!_IsSetup)
			{
				_AskEventName = UName.Get(typeof(P), "NMA0");
				_EventName = UName.Get(typeof(P), "NMA1");
				NetworkAPI.RegisterEvent<P>(_AskEventName, (Action<ulong, P>)ReceivedAsk);
				NetworkAPI.RegisterEvent<P>(_EventName, (Action<ulong, P>)Received);
				_IsSetup = true;
			}
		}

		public static void Ask(P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
			}
			else
			{
				if (!SNet.HasMaster)
				{
					return;
				}
				if (SNet.IsMaster)
				{
					Func<ulong, P, bool> isActionValid = IsActionValid;
					if (isActionValid == null || isActionValid(SNet.LocalPlayer.Lookup, payload))
					{
						TaskQueue.AddTask(delegate
						{
							//IL_000b: Unknown result type (might be due to invalid IL or missing references)
							NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel);
						}, "GlobalNetMasterAction.Master");
						GlobalNetMasterAction<P>.OnReceive?.Invoke(SNet.LocalPlayer.Lookup, payload);
						GlobalNetMasterAction<P>.OnMasterReceive?.Invoke(SNet.LocalPlayer.Lookup, payload);
					}
				}
				else
				{
					TaskQueue.AddTask(delegate
					{
						//IL_0010: Unknown result type (might be due to invalid IL or missing references)
						NetworkAPI.InvokeEvent<P>(_AskEventName, payload, SNet.Master, SendChannel);
					}, "GlobalNetMasterAction.Ask.Client");
				}
			}
		}

		private static void ReceivedAsk(ulong sender, P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			if (!SNet.IsMaster)
			{
				Logger.Error("Non Master Received Ask Action!");
				return;
			}
			Func<ulong, P, bool> isActionValid = IsActionValid;
			if (isActionValid == null || isActionValid(sender, payload))
			{
				TaskQueue.AddTask(delegate
				{
					//IL_000b: Unknown result type (might be due to invalid IL or missing references)
					NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel);
				}, "GlobalNetMasterAction.ReceivedAsk.Master");
				GlobalNetMasterAction<P>.OnReceive?.Invoke(SNet.LocalPlayer.Lookup, payload);
				GlobalNetMasterAction<P>.OnMasterReceive?.Invoke(sender, payload);
			}
		}

		private static void Received(ulong sender, P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			SNet_Player lastSender = default(SNet_Player);
			if (!SNet.Core.TryGetPlayer(sender, ref lastSender, false))
			{
				LastSender = null;
				LastSenderID = 0uL;
				Logger.Error("NetMasterAction sender was invalid!");
				return;
			}
			LastSender = lastSender;
			LastSenderID = sender;
			if (!LastSender.IsMaster)
			{
				Logger.Error("Sender was not a master");
			}
			else
			{
				GlobalNetMasterAction<P>.OnReceive?.Invoke(sender, payload);
			}
		}
	}
	internal static class UName
	{
		private static readonly SHA1 SHA = SHA1.Create();

		public static string Get(Type type, string prefix)
		{
			return prefix + GetHash(type.FullName);
		}

		public static string GetHash(string text)
		{
			return Convert.ToBase64String(SHA.ComputeHash(Encoding.Unicode.GetBytes(text + "this is salt text, Awesome!")));
		}
	}
}
namespace FloLib.Networks.Replications
{
	public interface IStateReplicatorHolder<S> where S : struct
	{
		StateReplicator<S> Replicator { get; }

		void OnStateChange(S oldState, S state, bool isRecall);
	}
	public sealed class ReplicatorHandshake
	{
		public delegate void ClientRequestedSyncDel(SNet_Player requestedPlayer);

		public struct Packet
		{
			public uint replicatorID;

			public PacketAction action;
		}

		public enum PacketAction : byte
		{
			Created,
			Destroyed,
			SyncRequest
		}

		public sealed class Data
		{
			public bool SetupOnHost;

			public bool SetupOnClient;
		}

		private readonly Dictionary<uint, Data> _Lookup = new Dictionary<uint, Data>();

		public string EventName { get; private set; }

		public bool IsReadyToSync { get; private set; }

		public event ClientRequestedSyncDel OnClientSyncRequested;

		public static ReplicatorHandshake Create(string guid)
		{
			if (string.IsNullOrWhiteSpace(guid))
			{
				return null;
			}
			string text = "RHs" + guid;
			if (!NetworkAPI.IsEventRegistered(text))
			{
				return new ReplicatorHandshake(text);
			}
			return null;
		}

		private ReplicatorHandshake(string eventName)
		{
			EventName = eventName;
			NetworkAPI.RegisterEvent<Packet>(eventName, (Action<ulong, Packet>)OnSyncAction);
			Inject_OnRecallDone.OnRecallDone += delegate
			{
				Logger.Warn("ReplicatorHandshake: client sending sync request");
				ClientSyncRequest();
			};
		}

		private void ClientSyncRequest()
		{
			if (SNet.IsMaster)
			{
				return;
			}
			foreach (uint replicatorID in _Lookup.Keys)
			{
				TaskQueue.AddTask(delegate
				{
					NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
					{
						replicatorID = replicatorID,
						action = PacketAction.SyncRequest
					}, SNet.Master, (SNet_ChannelType)2);
				}, $"SyncReplicatorID_{replicatorID}");
			}
		}

		public void Reset()
		{
			_Lookup.Clear();
		}

		private void OnSyncAction(ulong sender, Packet packet)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			if (!SNet.IsMaster && sender == SNet.Master.Lookup)
			{
				if (packet.action == PacketAction.Created)
				{
					SetHostState(packet.replicatorID, isSetup: true);
				}
				else if (packet.action == PacketAction.Destroyed)
				{
					SetHostState(packet.replicatorID, isSetup: false);
				}
			}
			else
			{
				if (!SNet.IsMaster)
				{
					return;
				}
				if (packet.action == PacketAction.Created)
				{
					SetClientState(packet.replicatorID, isSetup: true);
				}
				else if (packet.action == PacketAction.Destroyed)
				{
					SetClientState(packet.replicatorID, isSetup: false);
				}
				else
				{
					if (packet.action != PacketAction.SyncRequest)
					{
						return;
					}
					SNet_Player requestedPlayer = default(SNet_Player);
					if (!SNet.TryGetPlayer(sender, ref requestedPlayer))
					{
						bool flag = default(bool);
						BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(32, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Cannot find player from sender: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<ulong>(sender);
						}
						Logger.Error(val);
					}
					else
					{
						this.OnClientSyncRequested?.Invoke(requestedPlayer);
					}
				}
			}
		}

		public void UpdateCreated(uint id)
		{
			if (SNet.IsInLobby)
			{
				if (SNet.IsMaster)
				{
					SetHostState(id, isSetup: true);
					TaskQueue.AddTask(delegate
					{
						NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
						{
							replicatorID = id,
							action = PacketAction.Created
						}, (SNet_ChannelType)2);
					}, "UpdateCreated.Master");
				}
				else if (SNet.HasMaster)
				{
					SetClientState(id, isSetup: true);
					TaskQueue.AddTask(delegate
					{
						NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
						{
							replicatorID = id,
							action = PacketAction.Created
						}, SNet.Master, (SNet_ChannelType)2);
					}, "UpdateCreated.Client");
				}
				else
				{
					Logger.Error("Handshake::MASTER is NULL in lobby; This should NOT happen!!!!!!!!!!!!");
				}
			}
			else
			{
				Logger.Error("Handshake::Session Type StateReplicator cannot be created without lobby!");
			}
		}

		public void UpdateDestroyed(uint id)
		{
			if (SNet.IsInLobby)
			{
				if (SNet.IsMaster)
				{
					SetHostState(id, isSetup: true);
					TaskQueue.AddTask(delegate
					{
						NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
						{
							replicatorID = id,
							action = PacketAction.Destroyed
						}, (SNet_ChannelType)2);
					}, "UpdateDestroyed.Master");
				}
				else if (SNet.HasMaster)
				{
					SetClientState(id, isSetup: true);
					TaskQueue.AddTask(delegate
					{
						NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
						{
							replicatorID = id,
							action = PacketAction.Destroyed
						}, SNet.Master, (SNet_ChannelType)2);
					}, "UpdateDestroyed.Client");
				}
				else
				{
					Logger.Error("Handshake::MASTER is NULL in lobby; This should NOT happen!!!!!!!!!!!!");
				}
			}
			else
			{
				Logger.Error("Handshake::Session Type StateReplicator cannot be created without lobby!");
			}
		}

		private void SetHostState(uint id, bool isSetup)
		{
			if (_Lookup.TryGetValue(id, out var value))
			{
				value.SetupOnHost = isSetup;
			}
			else
			{
				_Lookup[id] = new Data
				{
					SetupOnHost = isSetup
				};
			}
			UpdateSyncState(id);
		}

		private void SetClientState(uint id, bool isSetup)
		{
			if (_Lookup.TryGetValue(id, out var value))
			{
				value.SetupOnClient = isSetup;
			}
			else
			{
				_Lookup[id] = new Data
				{
					SetupOnClient = isSetup
				};
			}
			UpdateSyncState(id);
		}

		private void UpdateSyncState(uint id)
		{
			bool isReadyToSync = IsReadyToSync;
			if (_Lookup.TryGetValue(id, out var value))
			{
				IsReadyToSync = value.SetupOnHost && value.SetupOnClient;
			}
			else
			{
				IsReadyToSync = false;
			}
			if (IsReadyToSync && isReadyToSync != IsReadyToSync && SNet.HasMaster && !SNet.IsMaster)
			{
				TaskQueue.AddTask(delegate
				{
					NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
					{
						replicatorID = id,
						action = PacketAction.SyncRequest
					}, SNet.Master, (SNet_ChannelType)2);
				}, "Client.UpdateSyncState.SyncRequest");
			}
		}
	}
	public delegate void OnReceiveDel<S>(ulong sender, uint replicatorID, S newState) where S : struct;
	public static class StatePayloads
	{
		public enum Size
		{
			State4Byte = 4,
			State8Byte = 8,
			State16Byte = 16,
			State32Byte = 32,
			State48Byte = 48,
			State64Byte = 64,
			State80Byte = 80,
			State96Byte = 96,
			State128Byte = 128,
			State196Byte = 196,
			State256Byte = 256
		}

		public static Size GetSizeType(int size)
		{
			Size size2 = Size.State8Byte;
			foreach (object value in Enum.GetValues(typeof(Size)))
			{
				if (size <= (int)value && (int)size2 < (int)value)
				{
					size2 = (Size)value;
					break;
				}
			}
			return size2;
		}

		public static IReplicatorEvent<S> CreateEvent<S>(Size size, string eventName, OnReceiveDel<S> onReceiveCallback) where S : struct
		{
			return size switch
			{
				Size.State4Byte => ReplicatorPayloadWrapper<S, StatePayload4Byte>.Create(eventName, onReceiveCallback), 
				Size.State8Byte => ReplicatorPayloadWrapper<S, StatePayload8Byte>.Create(eventName, onReceiveCallback), 
				Size.State16Byte => ReplicatorPayloadWrapper<S, StatePayload16Byte>.Create(eventName, onReceiveCallback), 
				Size.State32Byte => ReplicatorPayloadWrapper<S, StatePayload32Byte>.Create(eventName, onReceiveCallback), 
				Size.State48Byte => ReplicatorPayloadWrapper<S, StatePayload48Byte>.Create(eventName, onReceiveCallback), 
				Size.State64Byte => ReplicatorPayloadWrapper<S, StatePayload64Byte>.Create(eventName, onReceiveCallback), 
				Size.State80Byte => ReplicatorPayloadWrapper<S, StatePayload80Byte>.Create(eventName, onReceiveCallback), 
				Size.State96Byte => ReplicatorPayloadWrapper<S, StatePayload96Byte>.Create(eventName, onReceiveCallback), 
				Size.State128Byte => ReplicatorPayloadWrapper<S, StatePayload128Byte>.Create(eventName, onReceiveCallback), 
				Size.State196Byte => ReplicatorPayloadWrapper<S, StatePayload196Byte>.Create(eventName, onReceiveCallback), 
				Size.State256Byte => ReplicatorPayloadWrapper<S, StatePayload256Byte>.Create(eventName, onReceiveCallback), 
				_ => null, 
			};
		}

		public static S Get<S>(byte[] bytes, int bytesLength) where S : struct
		{
			int num = Marshal.SizeOf(typeof(S));
			if (num > bytesLength)
			{
				throw new ArgumentException($"StateData Exceed size of {bytesLength} : Unable to Deserialize", "S");
			}
			IntPtr intPtr = Marshal.AllocHGlobal(num);
			Marshal.Copy(bytes, 0, intPtr, num);
			S result = (S)Marshal.PtrToStructure(intPtr, typeof(S));
			Marshal.FreeHGlobal(intPtr);
			return result;
		}

		public static void Set<S>(S stateData, int size, ref byte[] payloadBytes) where S : struct
		{
			if (Marshal.SizeOf(stateData) > size)
			{
				throw new ArgumentException($"StateData Exceed size of {size} : Unable to Serialize", "S");
			}
			byte[] array = new byte[size];
			IntPtr intPtr = Marshal.AllocHGlobal(size);
			Marshal.StructureToPtr(stateData, intPtr, fDeleteOld: false);
			Marshal.Copy(intPtr, array, 0, size);
			Marshal.FreeHGlobal(intPtr);
			payloadBytes = array;
		}
	}
	public interface IReplicatorEvent<S> where S : struct
	{
		string Name { get; }

		bool IsRegistered { get; }

		void Invoke(uint replicatorID, S data);

		void Invoke(uint replicatorID, S data, SNet_ChannelType channelType);

		void Invoke(uint replicatorID, S data, SNet_Player target);

		void Invoke(uint replicatorID, S data, SNet_Player target, SNet_ChannelType channelType);
	}
	public class ReplicatorPayloadWrapper<S, P> : IReplicatorEvent<S> where S : struct where P : struct, IStatePayload
	{
		public string Name { get; private set; }

		public bool IsRegistered { get; private set; }

		public static IReplicatorEvent<S> Create(string eventName, OnReceiveDel<S> onReceiveCallback)
		{
			ReplicatorPayloadWrapper<S, P> replicatorPayloadWrapper = new ReplicatorPayloadWrapper<S, P>();
			replicatorPayloadWrapper.Register(eventName, onReceiveCallback);
			if (!replicatorPayloadWrapper.IsRegistered)
			{
				return null;
			}
			return replicatorPayloadWrapper;
		}

		public void Register(string eventName, OnReceiveDel<S> onReceiveCallback)
		{
			if (!IsRegistered && !NetworkAPI.IsEventRegistered(eventName))
			{
				NetworkAPI.RegisterEvent<P>(eventName, (Action<ulong, P>)delegate(ulong sender, P payload)
				{
					onReceiveCallback?.Invoke(sender, payload.ID, payload.Get<S>());
				});
				IsRegistered = true;
				Name = eventName;
			}
		}

		public void Invoke(uint replicatorID, S data)
		{
			P payload = new P
			{
				ID = replicatorID
			};
			payload.Set(data);
			TaskQueue.AddTask(delegate
			{
				NetworkAPI.InvokeEvent<P>(Name, payload, (SNet_ChannelType)2);
			}, "ReplicatorPayloadWrapper.Invoke(uint, S)");
		}

		public void Invoke(uint replicatorID, S data, SNet_ChannelType channelType)
		{
			//IL_000d: 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)
			P payload = new P
			{
				ID = replicatorID
			};
			payload.Set(data);
			TaskQueue.AddTask(delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				NetworkAPI.InvokeEvent<P>(Name, payload, channelType);
			}, "ReplicatorPayloadWrapper.Invoke(uint, S, SNet_ChannelType)");
		}

		public void Invoke(uint replicatorID, S data, SNet_Player target)
		{
			P payload = new P
			{
				ID = replicatorID
			};
			payload.Set(data);
			TaskQueue.AddTask(delegate
			{
				NetworkAPI.InvokeEvent<P>(Name, payload, target, (SNet_ChannelType)2);
			}, "ReplicatorPayloadWrapper.Invoke(uint, S, SNet_Player)");
		}

		public void Invoke(uint replicatorID, S data, SNet_Player target, SNet_ChannelType channelType)
		{
			//IL_0014: 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)
			P payload = new P
			{
				ID = replicatorID
			};
			payload.Set(data);
			TaskQueue.AddTask(delegate
			{
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				NetworkAPI.InvokeEvent<P>(Name, payload, target, channelType);
			}, "ReplicatorPayloadWrapper.Invoke(uint, S, SNet_Player, SNet_ChannelType)");
		}
	}
	public interface IStatePayload
	{
		uint ID { get; set; }

		S Get<S>() where S : struct;

		void Set<S>(S stateData) where S : struct;
	}
	public struct StatePayload4Byte : IStatePayload
	{
		public const int Size = 4;

		private uint id;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
		public byte[] PayloadBytes;

		public uint ID
		{
			get
			{
				return id;
			}
			set
			{
				id = value;
			}
		}

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 4);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 4, ref PayloadBytes);
		}
	}
	public struct StatePayload8Byte : IStatePayload
	{
		public const int Size = 8;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 8);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 8, ref PayloadBytes);
		}
	}
	public struct StatePayload16Byte : IStatePayload
	{
		public const int Size = 16;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 16);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 16, ref PayloadBytes);
		}
	}
	public struct StatePayload32Byte : IStatePayload
	{
		public const int Size = 32;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 32);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 32, ref PayloadBytes);
		}
	}
	public struct StatePayload48Byte : IStatePayload
	{
		public const int Size = 48;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 48)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 48);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 48, ref PayloadBytes);
		}
	}
	public struct StatePayload64Byte : IStatePayload
	{
		public const int Size = 64;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 64);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 64, ref PayloadBytes);
		}
	}
	public struct StatePayload80Byte : IStatePayload
	{
		public const int Size = 80;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 80);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 80, ref PayloadBytes);
		}
	}
	public struct StatePayload96Byte : IStatePayload
	{
		public const int Size = 96;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 96);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 96, ref PayloadBytes);
		}
	}
	public struct StatePayload128Byte : IStatePayload
	{
		public const int Size = 128;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 128);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 128, ref PayloadBytes);
		}
	}
	public struct StatePayload196Byte : IStatePayload
	{
		public const int Size = 196;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 196)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 196);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 196, ref PayloadBytes);
		}
	}
	public struct StatePayload256Byte : IStatePayload
	{
		public const int Size = 256;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 256);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 256, ref PayloadBytes);
		}
	}
	public enum LifeTimeType
	{
		Forever,
		Level
	}
	public sealed class StateReplicator<S> where S : struct
	{
		private readonly Dictionary<eBufferType, S> _RecallStateSnapshots = new Dictionary<eBufferType, S>();

		public static readonly string Name;

		public static readonly string HashName;

		public static readonly string ClientRequestEventName;

		public static readonly string HostSetStateEventName;

		public static readonly string HostSetRecallStateEventName;

		public static readonly int StateSize;

		public static readonly StatePayloads.Size StateSizeType;

		private static readonly IReplicatorEvent<S> _C_RequestEvent;

		private static readonly IReplicatorEvent<S> _H_SetStateEvent;

		private static readonly IReplicatorEvent<S> _H_SetRecallStateEvent;

		private static readonly ReplicatorHandshake _Handshake;

		private static readonly Dictionary<uint, StateReplicator<S>> _Replicators;

		public bool IsValid => ID != 0;

		public bool IsInvalid => ID == 0;

		public uint ID { get; private set; }

		public LifeTimeType LifeTime { get; private set; }

		public IStateReplicatorHolder<S> Holder { get; private set; }

		public S State { get; private set; }

		public bool ClientSendStateAllowed { get; set; } = true;


		public bool CanSendToClient
		{
			get
			{
				if (SNet.IsInLobby)
				{
					return SNet.IsMaster;
				}
				return false;
			}
		}

		public bool CanSendToHost
		{
			get
			{
				if (SNet.IsInLobby && !SNet.IsMaster && SNet.HasMaster)
				{
					return ClientSendStateAllowed;
				}
				return false;
			}
		}

		public bool IsHandshakeSetup { get; private set; }

		public event Action<S, S, bool> OnStateChanged;

		public void SetupHandshake()
		{
			if (!IsInvalid && !IsHandshakeSetup)
			{
				_Handshake.UpdateCreated(ID);
				IsHandshakeSetup = true;
			}
		}

		public void SetState(S state)
		{
			if (!IsInvalid)
			{
				DoSync(state);
			}
		}

		public void SetStateUnsynced(S state)
		{
			if (!IsInvalid)
			{
				State = state;
			}
		}

		public void Unload()
		{
			if (IsValid)
			{
				_Replicators.Remove(ID);
				_RecallStateSnapshots.Clear();
				_Handshake.UpdateDestroyed(ID);
				IsHandshakeSetup = false;
				ID = 0u;
			}
		}

		private void DoSync(S newState)
		{
			if (!IsInvalid)
			{
				if (CanSendToClient)
				{
					_H_SetStateEvent.Invoke(ID, newState);
					Internal_ChangeState(newState, isRecall: false);
				}
				else if (CanSendToHost)
				{
					_C_RequestEvent.Invoke(ID, newState, SNet.Master);
				}
			}
		}

		private void Internal_ChangeState(S state, bool isRecall)
		{
			if (!IsInvalid)
			{
				S state2 = State;
				State = state;
				this.OnStateChanged?.Invoke(state2, state, isRecall);
				Holder?.OnStateChange(state2, state, isRecall);
			}
		}

		private void SendDropInState(SNet_Player target)
		{
			if (!IsInvalid)
			{
				if ((Object)(object)target == (Object)null)
				{
					Logger.Error("SendDropInState::Target was null??");
				}
				else
				{
					_H_SetRecallStateEvent.Invoke(ID, State, target);
				}
			}
		}

		public void ClearAllRecallSnapshot()
		{
			if (!IsInvalid)
			{
				_RecallStateSnapshots.Clear();
			}
		}

		private void SaveSnapshot(eBufferType type)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (!IsInvalid)
			{
				_RecallStateSnapshots[type] = State;
			}
		}

		private void RestoreSnapshot(eBufferType type)
		{
			//IL_0017: 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_0046: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			if (IsInvalid || !CanSendToClient)
			{
				return;
			}
			if (_RecallStateSnapshots.TryGetValue(type, out var value))
			{
				_H_SetRecallStateEvent.Invoke(ID, value);
				Internal_ChangeState(value, isRecall: true);
				return;
			}
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(29, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("RestoreSnapshot");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("::There was no snapshot for ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eBufferType>(type);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("?");
			}
			Logger.Error(val);
		}

		static StateReplicator()
		{
			_Replicators = new Dictionary<uint, StateReplicator<S>>();
			Name = typeof(S).Name;
			StateSize = Marshal.SizeOf(typeof(S));
			StateSizeType = StatePayloads.GetSizeType(StateSize);
			using (MD5.Create())
			{
				HashName = UName.GetHash(typeof(S).FullName);
				ClientRequestEventName = "SRs" + Name + "-" + HashName;
				HostSetStateEventName = "SRr" + Name + "-" + HashName;
				HostSetRecallStateEventName = "SRre" + Name + "-" + HashName;
				_C_RequestEvent = StatePayloads.CreateEvent<S>(StateSizeType, ClientRequestEventName, ClientRequestEventCallback);
				_H_SetStateEvent = StatePayloads.CreateEvent<S>(StateSizeType, HostSetStateEventName, HostSetStateEventCallback);
				_H_SetRecallStateEvent = StatePayloads.CreateEvent<S>(StateSizeType, HostSetRecallStateEventName, HostSetRecallStateEventCallback);
				_Handshake = ReplicatorHandshake.Create(Name + "-" + HashName);
				_Handshake.OnClientSyncRequested += ClientSyncRequested;
				Inject_SNet_Capture.OnBufferCapture += BufferStored;
				Inject_SNet_Capture.OnBufferRecalled += BufferRecalled;
				Inject_Builder.BeforeBuildStart += LevelCleanedUp;
				LevelAPI.OnLevelCleanup += LevelCleanedUp;
			}
		}

		public static void Setup()
		{
		}

		private static void ClientSyncRequested(SNet_Player requestedPlayer)
		{
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.IsValid)
				{
					value.SendDropInState(requestedPlayer);
				}
			}
		}

		private static void BufferStored(eBufferType type)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.IsValid)
				{
					value.SaveSnapshot(type);
				}
			}
		}

		private static void BufferRecalled(eBufferType type)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.IsValid)
				{
					value.RestoreSnapshot(type);
				}
			}
		}

		private static void LevelCleanedUp()
		{
			UnloadSessionReplicator();
		}

		private StateReplicator()
		{
		}

		public static StateReplicator<S> Create(uint replicatorID, S startState, LifeTimeType lifeTime, IStateReplicatorHolder<S> owner = null)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			if (replicatorID == 0)
			{
				Logger.Error("Replicator ID 0 is reserved for empty!");
				return null;
			}
			if (_Replicators.ContainsKey(replicatorID))
			{
				Logger.Error("Replicator ID has already assigned!");
				return null;
			}
			StateReplicator<S> stateReplicator = new StateReplicator<S>
			{
				ID = replicatorID,
				LifeTime = lifeTime,
				Holder = owner,
				State = startState
			};
			switch (lifeTime)
			{
			case LifeTimeType.Forever:
				stateReplicator.IsHandshakeSetup = true;
				break;
			case LifeTimeType.Level:
				stateReplicator.SetupHandshake();
				break;
			default:
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(22, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("LifeTime is invalid!: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<LifeTimeType>(lifeTime);
				}
				Logger.Error(val);
				return null;
			}
			}
			_Replicators[replicatorID] = stateReplicator;
			return stateReplicator;
		}

		public static void UnloadSessionReplicator()
		{
			List<uint> list = new List<uint>();
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.LifeTime == LifeTimeType.Level)
				{
					list.Add(value.ID);
					value.Unload();
				}
			}
			foreach (uint item in list)
			{
				_Replicators.Remove(item);
			}
			_Handshake.Reset();
		}

		private static void ClientRequestEventCallback(ulong sender, uint replicatorID, S newState)
		{
			if (SNet.IsMaster && _Replicators.TryGetValue(replicatorID, out var value))
			{
				value.SetState(newState);
			}
		}

		private static void HostSetStateEventCallback(ulong sender, uint replicatorID, S newState)
		{
			if (SNet.HasMaster && SNet.Master.Lookup == sender && _Replicators.TryGetValue(replicatorID, out var value))
			{
				value.Internal_ChangeState(newState, isRecall: false);
			}
		}

		private static void HostSetRecallStateEventCallback(ulong sender, uint replicatorID, S newState)
		{
			if (SNet.HasMaster && SNet.Master.Lookup == sender && _Replicators.TryGetValue(replicatorID, out var value))
			{
				value.Internal_ChangeState(newState, isRecall: true);
			}
		}
	}
}
namespace FloLib.Networks.PayloadStructs
{
	public struct PL_Agent
	{
		public ushort AgentID;

		public PL_Agent()
		{
			AgentID = 0;
		}

		public PL_Agent(Agent agent)
		{
			AgentID = agent.GlobalID;
		}

		public void Set(Agent agent)
		{
			AgentID = agent.GlobalID;
		}

		public bool TryGet(out Agent agent)
		{
			IReplicator val = default(IReplicator);
			if (!SNet_Replication.TryGetReplicator(AgentID, ref val))
			{
				agent = null;
				return false;
			}
			if (val == null)
			{
				agent = null;
				return false;
			}
			if (val.ReplicatorSupplier == null)
			{
				agent = null;
				return false;
			}
			MonoBehaviour val2 = ((Il2CppObjectBase)val.ReplicatorSupplier).TryCast<MonoBehaviour>();
			if ((Object)(object)val2 == (Object)null)
			{
				agent = null;
				return false;
			}
			agent = ((Component)val2).GetComponent<Agent>();
			return (Object)(object)agent != (Object)null;
		}
	}
}
namespace FloLib.Networks.Inject
{
	[HarmonyPatch]
	internal class Inject_OnRecallDone
	{
		public static event Action OnRecallDone;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(SNet_SyncManager), "OnRecallDone")]
		private static void Post_OnRecallDone(SNet_SyncManager __instance)
		{
			Inject_OnRecallDone.OnRecallDone?.Invoke();
		}
	}
	[HarmonyPatch(typeof(SNet_Capture))]
	internal static class Inject_SNet_Capture
	{
		public static event Action<eBufferType> OnBufferCapture;

		public static event Action<eBufferType> OnBufferRecalled;

		[HarmonyPatch("TriggerCapture")]
		[HarmonyPrefix]
		private static void Pre_TriggerCapture(SNet_Capture __instance)
		{
			//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)
			eBufferType primedBufferType = __instance.PrimedBufferType;
			Inject_SNet_Capture.OnBufferCapture?.Invoke(primedBufferType);
		}

		[HarmonyPatch("RecallBuffer")]
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		private static void Post_RecallBuffer(SNet_Capture __instance, eBufferType bufferType)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.IsRecalling)
			{
				Inject_SNet_Capture.OnBufferRecalled?.Invoke(bufferType);
			}
		}
	}
}
namespace FloLib.Infos
{
	public sealed class ComponentList<T> : IEnumerable<T>, IEnumerable where T : Component
	{
		private readonly List<T> _InternalList = new List<T>();

		private T[] _ArrayCache = Array.Empty<T>();

		public T[] Items => _ArrayCache;

		internal void Add(T itemToAdd)
		{
			int id = ((Object)(object)itemToAdd).GetInstanceID();
			if (!_InternalList.Any((T t) => ((Object)(object)t).GetInstanceID() == id))
			{
				_InternalList.Add(itemToAdd);
				_ArrayCache = _InternalList.ToArray();
			}
		}

		internal void AddRange(IEnumerable<T> itemsToAdd)
		{
			foreach (T item in itemsToAdd)
			{
				Add(item);
			}
		}

		internal void Remove(T itemToRemove)
		{
			int id = ((Object)(object)itemToRemove).GetInstanceID();
			int num = _InternalList.FindIndex((T i) => ((Object)(object)i).GetInstanceID() == id);
			if (num > -1)
			{
				_InternalList.RemoveAt(num);
				_ArrayCache = _InternalList.ToArray();
			}
		}

		internal void Clear()
		{
			_InternalList.Clear();
			_ArrayCache = Array.Empty<T>();
		}

		public IEnumerator<T> GetEnumerator()
		{
			return _InternalList.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return _InternalList.GetEnumerator();
		}
	}
	public static class LG_LightInfo
	{
		public struct Data
		{
			public float PrefabIntensity;

			public LightMode SpawnedMode;

			public float SpawnedIntensity;

			public Color SpawnedColor;
		}

		public static bool TryGetLightData(LG_Light light, out Data data)
		{
			if ((Object)(object)light == (Object)null)
			{
				data = default(Data);
				return false;
			}
			if (!((Component)(object)light).TryGetComp<LightData>(out var component))
			{
				data = default(Data);
				return false;
			}
			data = component.CreateData();
			return true;
		}

		public static void RevertToSpawnedState(LG_Light light)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)light == (Object)null) && ((Component)(object)light).TryGetComp<LightData>(out var component))
			{
				light.ChangeColor(component.SpawnedColor);
				light.ChangeIntensity(component.SpawnedIntensity);
			}
		}
	}
	public enum LightMode
	{
		Off,
		On,
		Broken_Flickering
	}
	public static class LG_Objects
	{
		public static ComponentList<LG_SecurityDoor> SecurityDoors { get; private set; } = new ComponentList<LG_SecurityDoor>();


		public static ComponentList<LG_WeakDoor> WeakDoors { get; private set; } = new ComponentList<LG_WeakDoor>();


		public static ComponentList<LG_Light> Lights { get; private set; } = new ComponentList<LG_Light>();


		public static ComponentList<LG_ComputerTerminal> Terminals { get; private set; } = new ComponentList<LG_ComputerTerminal>();


		public static ComponentList<LG_LabDisplay> LabDisplays { get; private set; } = new ComponentList<LG_LabDisplay>();


		public static ComponentList<LG_DoorButton> DoorButtons { get; private set; } = new ComponentList<LG_DoorButton>();


		public static ComponentList<LG_WeakLock> WeakLocks { get; private set; } = new ComponentList<LG_WeakLock>();


		public static ComponentList<LG_HSUActivator_Core> HSUActivators { get; private set; } = new ComponentList<LG_HSUActivator_Core>();


		public static ComponentList<CarryItemPickup_Core> CarryItems { get; private set; } = new ComponentList<CarryItemPickup_Core>();


		public static ComponentList<GenericSmallPickupItem_Core> PickupItems { get; private set; } = new ComponentList<GenericSmallPickupItem_Core>();


		public static ComponentList<LG_Ladder> Ladders { get; private set; } = new ComponentList<LG_Ladder>();


		public static ComponentList<LG_WardenObjective_Reactor> Reactors { get; private set; } = new ComponentList<LG_WardenObjective_Reactor>();


		public static ComponentList<LG_PowerGeneratorCluster> GeneratorClusters { get; private set; } = new ComponentList<LG_PowerGeneratorCluster>();


		public static ComponentList<LG_PowerGenerator_Core> Generators { get; private set; } = new ComponentList<LG_PowerGenerator_Core>();


		[AutoInvoke(InvokeWhen.PluginLoaded)]
		internal static void Init()
		{
			LevelAPI.OnLevelCleanup += OnLevelCleanup;
		}

		private static void OnLevelCleanup()
		{
			SecurityDoors.Clear();
			WeakDoors.Clear();
			Lights.Clear();
			Terminals.Clear();
			LabDisplays.Clear();
			DoorButtons.Clear();
			WeakLocks.Clear();
			HSUActivators.Clear();
			CarryItems.Clear();
			PickupItems.Clear();
			Ladders.Clear();
			Reactors.Clear();
			GeneratorClusters.Clear();
			Generators.Clear();
		}

		public static O FindObjectInLevel<O>(bool includeInactive = false) where O : Object
		{
			return ((Component)Builder.CurrentFloor).GetComponentInChildren<O>(includeInactive);
		}

		public static IEnumerable<O> FindObjectsInLevel<O>(bool includeInactive = false) where O : Object
		{
			return (IEnumerable<O>)((Component)Builder.CurrentFloor).GetComponentsInChildren<O>(includeInactive);
		}

		public static LG_SecurityDoor FindSecurityDoor(LG_LayerType layer, eLocalZoneIndex localindex)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return FindSecurityDoor((eDimensionIndex)0, layer, localindex);
		}

		public static LG_SecurityDoor FindSecurityDoor(eDimensionIndex dim, LG_LayerType layer, eLocalZoneIndex localindex)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = default(LG_Zone);
			Builder.CurrentFloor.TryGetZoneByLocalIndex(dim, layer, localindex, ref val);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			if ((Object)(object)val.m_sourceGate == (Object)null)
			{
				return null;
			}
			if (val.m_sourceGate.SpawnedDoor == null)
			{
				return null;
			}
			return ((Il2CppObjectBase)val.m_sourceGate.SpawnedDoor).TryCast<LG_SecurityDoor>();
		}
	}
	public static class LocalPlayer
	{
		private static int? _InstanceID;

		public static bool HasAgent { get; private set; }

		public static PlayerAgent Agent { get; private set; }

		public static LocalPlayerAgent LocalAgent { get; private set; }

		public static bool TryGetAgent(out PlayerAgent agent)
		{
			agent = Agent;
			return HasAgent;
		}

		public static bool TryGetLocalAgent(out LocalPlayerAgent agent)
		{
			agent = LocalAgent;
			return HasAgent;
		}

		public static Vector3 GetPosition()
		{
			//IL_0012: 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)
			if (HasAgent)
			{
				return ((Agent)Agent).Position;
			}
			return Vector3.zero;
		}

		public static Vector3 GetPosition(Vector3 fallback)
		{
			//IL_0012: 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)
			if (HasAgent)
			{
				return ((Agent)Agent).Position;
			}
			return fallback;
		}

		public static Vector3 GetEyePosition()
		{
			//IL_0012: 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)
			if (HasAgent)
			{
				return ((Agent)Agent).EyePosition;
			}
			return Vector3.zero;
		}

		public static Vector3 GetEyePosition(Vector3 fallback)
		{
			//IL_0012: 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)
			if (HasAgent)
			{
				return ((Agent)Agent).EyePosition;
			}
			return fallback;
		}

		[AutoInvoke(InvokeWhen.StartupAssetLoaded)]
		internal static void Init()
		{
			Coroutines.Start(UpdatePlayerInfo());
		}

		private static IEnumerator UpdatePlayerInfo()
		{
			while (true)
			{
				if (PlayerManager.HasLocalPlayerAgent())
				{
					PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent();
					int instanceID = ((Object)localPlayerAgent).GetInstanceID();
					if (!_InstanceID.HasValue || _InstanceID.Value != instanceID)
					{
						Agent = localPlayerAgent;
						LocalAgent = ((Il2CppObjectBase)localPlayerAgent).Cast<LocalPlayerAgent>();
						_InstanceID = ((Object)localPlayerAgent).GetInstanceID();
						HasAgent = true;
					}
				}
				else
				{
					Agent = null;
					LocalAgent = null;
					_InstanceID = null;
					HasAgent = false;
				}
				yield return null;
			}
		}
	}
}
namespace FloLib.Infos.Inject
{
	[HarmonyPatch]
	internal static class Inject_Builder
	{
		internal static event Action BeforeBuildStart;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Builder), "BuildDone")]
		[HarmonyPriority(800)]
		private static void Post_BuildDone()
		{
			LG_Objects.Terminals.AddRange(Find<LG_ComputerTerminal>());
			LG_Objects.LabDisplays.AddRange(Find<LG_LabDisplay>());
			LG_Objects.DoorButtons.AddRange(Find<LG_DoorButton>());
			LG_Objects.WeakLocks.AddRange(Find<LG_WeakLock>());
			LG_Objects.HSUActivators.AddRange(Find<LG_HSUActivator_Core>());
			LG_Objects.CarryItems.AddRange(Find<CarryItemPickup_Core>());
			LG_Objects.PickupItems.AddRange(Find<GenericSmallPickupItem_Core>());
			LG_Objects.Ladders.AddRange(Find<LG_Ladder>());
			LG_Objects.Reactors.AddRange(Find<LG_WardenObjective_Reactor>());
			LG_Objects.GeneratorClusters.AddRange(Find<LG_PowerGeneratorCluster>());
			LG_Objects.Generators.AddRange(Find<LG_PowerGenerator_Core>());
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Builder), "Build")]
		private static void Pre_Build()
		{
			Inject_Builder.BeforeBuildStart?.Invoke();
		}

		private static IEnumerable<T> Find<T>() where T : Object
		{
			return LG_Objects.FindObjectsInLevel<T>();
		}
	}
	[HarmonyPatch(typeof(LG_BuildZoneLightsJob), "Build")]
	internal static class Inject_LG_LightBuild
	{
		[HarmonyPriority(0)]
		private static void Prefix(LG_BuildZoneLightsJob __instance, out List<LG_Light> __state)
		{
			__state = new List<LG_Light>();
			Enumerator<AIG_CourseNode> enumerator = __instance.m_zone.m_courseNodes.GetEnumerator();
			while (enumerator.MoveNext())
			{
				foreach (LG_Light componentsInChild in ((Component)enumerator.Current.m_area).GetComponentsInChildren<LG_Light>())
				{
					LightData lightData = ((Component)componentsInChild).gameObject.AddComponent<LightData>();
					LG_PointLight result2;
					if (((Il2CppObjectBase)(object)componentsInChild).TryCastToType<LG_SpotLight>(out LG_SpotLight result))
					{
						lightData.PrefabIntensity.Set(result.m_spotLight.intensity);
					}
					else if (((Il2CppObjectBase)(object)componentsInChild).TryCastToType<LG_PointLight>(out result2))
					{
						lightData.PrefabIntensity.Set(result2.m_pointLight.intensity);
					}
					else
					{
						if (!((Il2CppObjectBase)(object)componentsInChild).TryCastToType<LG_SpotLightAmbient>(out LG_SpotLightAmbient result3))
						{
							continue;
						}
						lightData.PrefabIntensity.Set(result3.m_spotLight.intensity);
					}
					__state.Add(componentsInChild);
				}
			}
			LG_Objects.Lights.AddRange(__state);
		}

		[HarmonyPriority(0)]
		private static void Postfix(List<LG_Light> __state)
		{
			//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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			bool flag = default(bool);
			foreach (LG_Light item in __state)
			{
				LightData component = ((Component)item).GetComponent<LightData>();
				if ((Object)(object)component == (Object)null)
				{
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(32, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Found Light without ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("LightData");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" Component! ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((Component)(object)item).GetGameObjectPath());
					}
					Logger.Error(val);
				}
				else
				{
					component.SpawnedIntensity = item.m_intensity;
					component.SpawnedColor = item.m_color;
					component.SpawnedMode = GetLightMode(item);
				}
			}
			__state.Clear();
		}

		private static LightMode GetLightMode(LG_Light light)
		{
			if (light.GetC_Light().LightUpdator != null)
			{
				return LightMode.Broken_Flickering;
			}
			if (((Component)light).gameObject.active)
			{
				return LightMode.On;
			}
			return LightMode.Off;
		}
	}
	[HarmonyPatch(typeof(LG_SecurityDoor), "Setup")]
	internal static class Inject_LG_SecDoor
	{
		private static void Postfix(LG_SecurityDoor __instance)
		{
			LG_Objects.SecurityDoors.Add(__instance);
		}
	}
	[HarmonyPatch(typeof(LG_WeakDoor), "Setup")]
	internal static class Inject_LG_WeakDoor
	{
		private static void Postfix(LG_WeakDoor __instance)
		{
			LG_Objects.WeakDoors.Add(__instance);
		}
	}
}
namespace FloLib.Infos.Comps
{
	[AutoInject]
	internal sealed class LightData : MonoBehaviour
	{
		public Il2CppValueField<float> PrefabIntensity;

		public LightMode SpawnedMode;

		public float SpawnedIntensity;

		public Color SpawnedColor;

		public LG_LightInfo.Data CreateData()
		{
			//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)
			LG_LightInfo.Data result = default(LG_LightInfo.Data);
			result.PrefabIntensity = Il2CppValueField<float>.op_Implicit(PrefabIntensity);
			result.SpawnedMode = SpawnedMode;
			result.SpawnedIntensity = SpawnedIntensity;
			result.SpawnedColor = SpawnedColor;
			return result;
		}
	}
}
namespace FloLib.Game.ScreenShakes
{
	public sealed class ScreenShake
	{
		[AutoInvoke(InvokeWhen.StartupAssetLoaded)]
		internal static void Init()
		{
			GlobalNetAction<ScreenShakeDescriptor>.OnReceive += OnReceive;
		}

		public static void Trigger(ScreenShakeDescriptor data)
		{
			GlobalNetAction<ScreenShakeDescriptor>.Send(data);
		}

		private static void OnReceive(ulong sender, ScreenShakeDescriptor data)
		{
			if (LocalPlayer.TryGetAgent(out var agent))
			{
				FPSCamera fPSCamera = agent.FPSCamera;
				MonoBehaviourExtensions.StartCoroutine((MonoBehaviour)(object)fPSCamera, DoShake(fPSCamera, data));
			}
		}

		private static IEnumerator DoShake(FPSCamera camera, ScreenShakeDescriptor data)
		{
			float time = 0f;
			while (time < data.Duration)
			{
				float num = 1f;
				if (data.Mode == ScreenShakeMode.PositionFalloff)
				{
					float num2 = Vector3.Distance(data.Position, camera.Position);
					num = Mathf.InverseLerp(data.FalloffEnd, data.FalloffStart, num2);
				}
				float t = data.Modifier switch
				{
					ScreenShakeModifier.PingPong => Mathf.PingPong(Mathf.InverseLerp(data.Duration, 0f, time) * 2f, 1f), 
					ScreenShakeModifier.Increase => Mathf.InverseLerp(0f, data.Duration, time), 
					ScreenShakeModifier.Decrease => Mathf.InverseLerp(data.Duration, 0f, time), 
					_ => 1f, 
				};
				t = data.IntensityEasing.Evaluate(t);
				float constantCameraShakeAmount = num * t * data.Intensity;
				camera.SetConstantCameraShakeAmount(constantCameraShakeAmount);
				time += Time.deltaTime;
				yield return null;
			}
			camera.SetConstantCameraShakeAmount(0f);
		}
	}
	public struct ScreenShakeDescriptor
	{
		public ScreenShakeMode Mode;

		public ScreenShakeModifier Modifier;

		public Vector3 Position;

		public float Intensity;

		public float Duration;

		public float FalloffStart;

		public float FalloffEnd;

		public EaseFunc.Type IntensityEasing;
	}
	public enum ScreenShakeMode : byte
	{
		Global,
		PositionFalloff
	}
	public enum ScreenShakeModifier : byte
	{
		PingPong,
		Increase,
		Decrease,
		Constant
	}
}
namespace FloLib.Game.Projectiles
{
	public class Projectile : MonoBehaviour
	{
	}
}
namespace FloLib.Game.Explosions
{
	public sealed class Explosion
	{
		public static readonly Color DefaultFlashColor = new Color(1f, 0.2f, 0f, 1f);

		[AutoInvoke(InvokeWhen.StartupAssetLoaded)]
		internal static void Init()
		{
			ExplosionEffectPooling.Initialize();
			GlobalNetAction<ExplosionDescriptor>.OnReceive += OnReceive;
		}

		private static void OnReceive(ulong sender, ExplosionDescriptor data)
		{
			Internal_TriggerExplosion(data);
		}

		public static void Trigger(ExplosionDescriptor data)
		{
			GlobalNetAction<ExplosionDescriptor>.Send(data);
		}

		internal static void Internal_TriggerExplosion(ExplosionDescriptor data)
		{
			//IL_0006: 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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			CellSound.Post(EVENTS.STICKYMINEEXPLODE, data.Position);
			LightFlash(data.Position, data.MaxDamageRange, data.LightColor);
			if (!SNet.IsMaster)
			{
				return;
			}
			Il2CppReferenceArray<Collider> val = Physics.OverlapSphere(data.Position, data.MaxDamageRange, LayerManager.MASK_EXPLOSION_TARGETS);
			if (((Il2CppArrayBase<Collider>)(object)val).Count < 1)
			{
				return;
			}
			DamageUtil.IncrementSearchID();
			uint searchID = DamageUtil.SearchID;
			foreach (Collider item in (Il2CppArrayBase<Collider>)(object)val)
			{
				ProcessExplosion(data, item, searchID);
			}
		}

		private static void ProcessExplosion(ExplosionDescriptor data, Collider target, uint searchID)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)target == (Object)null || (Object)(object)((Component)target).gameObject == (Object)null || !((Component)target).gameObject.TryGetComp<IDamageable>(out var component))
			{
				return;
			}
			component = component.GetBaseDamagable();
			if (component == null || component.TempSearchID == searchID)
			{
				return;
			}
			Vector3 damagablePosition = GetDamagablePosition(component);
			component.TempSearchID = searchID;
			float distance = Vector3.Distance(data.Position, damagablePosition);
			if (!IsExplosionBlocked(data.Position, damagablePosition, target))
			{
				float num = CalcBaseRangeDamage(data.MaxDamage, distance, data.MaxDamageRange, data.MinDamageRange);
				if ((Object)(object)((Il2CppObjectBase)component).TryCast<Dam_EnemyDamageBase>() != (Object)null)
				{
					num *= (float)data.DamageMultiplierToEnemy;
				}
				else if ((Object)(object)((Il2CppObjectBase)component).TryCast<Dam_PlayerDamageBase>() != (Object)null)
				{
					num *= (float)data.DamageMultiplierToPlayer;
				}
				Agent baseAgent = component.GetBaseAgent();
				if ((Object)(object)baseAgent != (Object)null && baseAgent.GlobalID == data.Inflictor.AgentID)
				{
					num *= (float)data.DamageMultiplierToInflictor;
				}
				if (Mathf.Abs(num) > float.Epsilon)
				{
					component.ExplosionDamage(num, data.Position, Vector3.up * 1000f, 0u);
				}
			}
		}

		private static Vector3 GetDamagablePosition(IDamageable damagable)
		{
			//IL_0018: 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)
			Agent baseAgent = damagable.GetBaseAgent();
			if ((Object)(object)baseAgent != (Object)null)
			{
				return baseAgent.EyePosition;
			}
			return damagable.DamageTargetPos;
		}

		private static bool IsExplosionBlocked(Vector3 pos1, Vector3 pos2, Collider targetCollider)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			RaycastHit val = default(RaycastHit);
			if (Physics.Linecast(pos1, pos2, ref val, LayerManager.MASK_EXPLOSION_BLOCKERS))
			{
				if 

plugins/Inas07-ExtraObjectiveSetup/Inas07.ExtraObjectiveSetup.dll

Decompiled 7 hours ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
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 System.Text.Json;
using System.Text.Json.Serialization;
using AIGraph;
using AK;
using Agents;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using ChainedPuzzles;
using Enemies;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.BaseClasses.CustomTerminalDefinition;
using ExtraObjectiveSetup.Expedition;
using ExtraObjectiveSetup.Expedition.Gears;
using ExtraObjectiveSetup.Expedition.IndividualGeneratorGroup;
using ExtraObjectiveSetup.ExtendedWardenEvents;
using ExtraObjectiveSetup.Instances;
using ExtraObjectiveSetup.Instances.ChainedPuzzle;
using ExtraObjectiveSetup.JSON;
using ExtraObjectiveSetup.Objectives.ActivateSmallHSU;
using ExtraObjectiveSetup.Objectives.GeneratorCluster;
using ExtraObjectiveSetup.Objectives.IndividualGenerator;
using ExtraObjectiveSetup.Objectives.ObjectiveCounter;
using ExtraObjectiveSetup.Objectives.TerminalUplink;
using ExtraObjectiveSetup.Tweaks.BossEvents;
using ExtraObjectiveSetup.Tweaks.Scout;
using ExtraObjectiveSetup.Tweaks.TerminalPosition;
using ExtraObjectiveSetup.Tweaks.TerminalTweak;
using ExtraObjectiveSetup.Utils;
using FloLib.Networks.Replications;
using GTFO.API;
using GTFO.API.Extensions;
using GTFO.API.JSON.Converters;
using GTFO.API.Utilities;
using GameData;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using StateMachines;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("Inas07.ExtraObjectiveSetup")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+0ed85c89f89e18967872da5c48fee511edd6ad21")]
[assembly: AssemblyProduct("Inas07.ExtraObjectiveSetup")]
[assembly: AssemblyTitle("Inas07.ExtraObjectiveSetup")]
[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 ExtraObjectiveSetup
{
	public static class EOSNetworking
	{
		public const uint INVALID_ID = 0u;

		public const uint FOREVER_REPLICATOR_ID_START = 1000u;

		public const uint REPLICATOR_ID_START = 10000u;

		private static uint currentForeverID;

		private static uint currentID;

		private static HashSet<uint> foreverUsedIDs;

		private static HashSet<uint> usedIDs;

		public static uint AllotReplicatorID()
		{
			while (currentID >= 10000 && usedIDs.Contains(currentID))
			{
				currentID++;
			}
			if (currentID < 10000)
			{
				EOSLogger.Error("Replicator ID depleted. How?");
				return 0u;
			}
			uint num = currentID;
			usedIDs.Add(num);
			currentID++;
			return num;
		}

		public static bool TryAllotID(uint id)
		{
			return usedIDs.Add(id);
		}

		public static uint AllotForeverReplicatorID()
		{
			while (currentForeverID < 10000 && foreverUsedIDs.Contains(currentForeverID))
			{
				currentForeverID++;
			}
			if (currentForeverID >= 10000)
			{
				EOSLogger.Error("Forever Replicator ID depleted.");
				return 0u;
			}
			uint num = currentForeverID;
			foreverUsedIDs.Add(num);
			currentForeverID++;
			return num;
		}

		private static void Clear()
		{
			usedIDs.Clear();
			currentID = 10000u;
		}

		public static void ClearForever()
		{
			foreverUsedIDs.Clear();
			currentForeverID = 1000u;
		}

		static EOSNetworking()
		{
			currentForeverID = 1000u;
			currentID = 10000u;
			foreverUsedIDs = new HashSet<uint>();
			usedIDs = new HashSet<uint>();
			LevelAPI.OnBuildStart += Clear;
			LevelAPI.OnLevelCleanup += Clear;
		}
	}
	public sealed class BatchBuildManager
	{
		private Dictionary<BatchName, Action> OnBatchDone = new Dictionary<BatchName, Action>();

		public static BatchBuildManager Current { get; private set; }

		public void Init()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (OnBatchDone.Count > 0)
			{
				return;
			}
			foreach (object value in Enum.GetValues(typeof(BatchName)))
			{
				OnBatchDone[(BatchName)value] = null;
			}
		}

		public void Add_OnBatchDone(BatchName batchName, Action action)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: 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)
			Dictionary<BatchName, Action> onBatchDone = OnBatchDone;
			onBatchDone[batchName] = (Action)Delegate.Combine(onBatchDone[batchName], action);
		}

		public void Remove_OnBatchDone(BatchName batchName, Action action)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: 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)
			Dictionary<BatchName, Action> onBatchDone = OnBatchDone;
			onBatchDone[batchName] = (Action)Delegate.Remove(onBatchDone[batchName], action);
		}

		public Action Get_OnBatchDone(BatchName batchName)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return OnBatchDone[batchName];
		}

		private BatchBuildManager()
		{
		}

		static BatchBuildManager()
		{
			Current = new BatchBuildManager();
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Inas.ExtraObjectiveSetup", "ExtraObjectiveSetup", "1.6.4")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas";

		public const string PLUGIN_NAME = "ExtraObjectiveSetup";

		public const string VERSION = "1.6.4";

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			m_Harmony = new Harmony("ExtraObjectiveSetup");
			m_Harmony.PatchAll();
			SetupManagers();
		}

		private void SetupManagers()
		{
			BatchBuildManager.Current.Init();
			IndividualGeneratorObjectiveManager.Current.Init();
			GeneratorClusterObjectiveManager.Current.Init();
			HSUActivatorObjectiveManager.Current.Init();
			UplinkObjectiveManager.Current.Init();
			TerminalPositionOverrideManager.Current.Init();
			ScoutScreamEventManager.Current.Init();
			BossDeathEventManager.Current.Init();
			ExpeditionDefinitionManager.Current.Init();
			ExpeditionGearManager.Current.Init();
			ExpeditionIGGroupManager.Current.Init();
			GeneratorClusterInstanceManager.Current.Init();
			HSUActivatorInstanceManager.Current.Init();
			PowerGeneratorInstanceManager.Current.Init();
			TerminalInstanceManager.Current.Init();
			ObjectiveCounterManager.Current.Init();
		}
	}
}
namespace ExtraObjectiveSetup.Utils
{
	public static class EOSTerminalUtils
	{
		public static List<LG_ComputerTerminal> FindTerminal(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, Predicate<LG_ComputerTerminal> predicate)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_0034: 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_0074: 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)
			LG_Zone val = default(LG_Zone);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, localIndex, ref val) || (Object)(object)val == (Object)null)
			{
				EOSLogger.Error($"SelectTerminal: Could NOT find zone {(dimensionIndex, layerType, localIndex)}");
				return null;
			}
			if (val.TerminalsSpawnedInZone.Count <= 0)
			{
				EOSLogger.Error($"SelectTerminal: Could not find any terminals in zone {(dimensionIndex, layerType, localIndex)}");
				return null;
			}
			List<LG_ComputerTerminal> list = new List<LG_ComputerTerminal>();
			Enumerator<LG_ComputerTerminal> enumerator = val.TerminalsSpawnedInZone.GetEnumerator();
			while (enumerator.MoveNext())
			{
				LG_ComputerTerminal current = enumerator.Current;
				if (predicate != null)
				{
					if (predicate(current))
					{
						list.Add(current);
					}
				}
				else
				{
					list.Add(current);
				}
			}
			return list;
		}

		public static TerminalLogFileData GetLocalLog(this LG_ComputerTerminal terminal, string logName)
		{
			Dictionary<string, TerminalLogFileData> localLogs = terminal.GetLocalLogs();
			logName = logName.ToUpperInvariant();
			if (!localLogs.ContainsKey(logName))
			{
				return null;
			}
			return localLogs[logName];
		}

		public static void ResetInitialOutput(this LG_ComputerTerminal terminal)
		{
			terminal.m_command.ClearOutputQueueAndScreenBuffer();
			terminal.m_command.AddInitialTerminalOutput();
			if (terminal.IsPasswordProtected)
			{
				terminal.m_command.AddPasswordProtectedOutput((Il2CppStringArray)null);
			}
		}

		public static List<WardenObjectiveEventData> GetUniqueCommandEvents(this LG_ComputerTerminal terminal, string command)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected I4, but got Unknown
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			List<WardenObjectiveEventData> result = new List<WardenObjectiveEventData>();
			if ((Object)(object)terminal.ConnectedReactor != (Object)null)
			{
				return result;
			}
			uint num = 0u;
			if (terminal.SpawnNode.m_dimension.IsMainDimension)
			{
				LG_LayerType layerType = terminal.SpawnNode.LayerType;
				switch ((int)layerType)
				{
				case 0:
					num = RundownManager.ActiveExpedition.LevelLayoutData;
					break;
				case 1:
					num = RundownManager.ActiveExpedition.SecondaryLayout;
					break;
				case 2:
					num = RundownManager.ActiveExpedition.ThirdLayout;
					break;
				default:
					EOSLogger.Error($"GetCommandEvents: Unimplemented layer type {terminal.SpawnNode.LayerType}");
					return result;
				}
			}
			else
			{
				num = terminal.SpawnNode.m_dimension.DimensionData.LevelLayoutData;
			}
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(num);
			if (block == null)
			{
				EOSLogger.Error($"GetCommandEvents: {terminal.ItemKey} is in {terminal.SpawnNode.LayerType}, {terminal.SpawnNode.m_dimension.DimensionIndex} but its LevelLayoutData is not found!");
				return result;
			}
			int num2 = terminal.SpawnNode.m_zone.TerminalsSpawnedInZone.IndexOf(terminal);
			ExpeditionZoneData val = null;
			Enumerator<ExpeditionZoneData> enumerator = block.Zones.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ExpeditionZoneData current = enumerator.Current;
				if (current.LocalIndex == terminal.SpawnNode.m_zone.LocalIndex)
				{
					val = current;
					break;
				}
			}
			if (val == null)
			{
				EOSLogger.Error("GetCommandEvents: Cannot find target zone data.");
				return result;
			}
			if (num2 >= val.TerminalPlacements.Count)
			{
				EOSLogger.Debug("GetCommandEvents: TerminalDataIndex >= TargetZoneData.TerminalPlacements.Count: found a custom terminal, skipped");
				return result;
			}
			Enumerator<CustomTerminalCommand> enumerator2 = val.TerminalPlacements[num2].UniqueCommands.GetEnumerator();
			while (enumerator2.MoveNext())
			{
				CustomTerminalCommand current2 = enumerator2.Current;
				if (current2.Command.ToLower().Equals(command.ToLower()))
				{
					return current2.CommandEvents.ToManaged<WardenObjectiveEventData>();
				}
			}
			EOSLogger.Error("GetCommandEvents: command '" + command + "' not found on " + terminal.ItemKey);
			return result;
		}

		public static LG_ComputerTerminal SelectPasswordTerminal(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, eSeedType seedType, int staticSeed = 1)
		{
			//IL_0000: 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_0030: 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_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: 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_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Expected I4, but got Unknown
			//IL_00bd: 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_00bf: 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_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)
			if ((int)seedType == 0)
			{
				EOSLogger.Error($"SelectTerminal: unsupported seed type {seedType}");
				return null;
			}
			List<LG_ComputerTerminal> list = FindTerminal(dimensionIndex, layerType, localIndex, (LG_ComputerTerminal x) => !x.HasPasswordPart);
			if (list == null)
			{
				EOSLogger.Error($"SelectTerminal: Could not find zone {(dimensionIndex, layerType, localIndex)}!");
				return null;
			}
			if (list.Count <= 0)
			{
				EOSLogger.Error($"SelectTerminal: Could not find any terminals without a password part in zone {(dimensionIndex, layerType, localIndex)}, putting the password on random (session) already used terminal.");
				LG_Zone val = default(LG_Zone);
				Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, localIndex, ref val);
				return val.TerminalsSpawnedInZone[Builder.SessionSeedRandom.Range(0, val.TerminalsSpawnedInZone.Count, "NO_TAG")];
			}
			switch (seedType - 1)
			{
			case 0:
				return list[Builder.SessionSeedRandom.Range(0, list.Count, "NO_TAG")];
			case 1:
				return list[Builder.BuildSeedRandom.Range(0, list.Count, "NO_TAG")];
			case 2:
				Random.InitState(staticSeed);
				return list[Random.Range(0, list.Count)];
			default:
				EOSLogger.Error("SelectTerminal: did not have a valid SeedType!!");
				return null;
			}
		}

		public static void BuildPassword(LG_ComputerTerminal terminal, TerminalPasswordData data)
		{
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0427: Unknown result type (might be due to invalid IL or missing references)
			//IL_042c: 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_0499: Unknown result type (might be due to invalid IL or missing references)
			//IL_049e: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cc: Expected O, but got Unknown
			//IL_04ce: Expected O, but got Unknown
			if (!data.PasswordProtected)
			{
				return;
			}
			if (terminal.IsPasswordProtected)
			{
				EOSLogger.Error("EOSTerminalUtils.BuildPassword: " + terminal.PublicName + " is already password-protected!");
				return;
			}
			if (!data.GeneratePassword)
			{
				terminal.LockWithPassword(data.Password, new string[1] { data.PasswordHintText });
				return;
			}
			if (data.TerminalZoneSelectionDatas.Count <= 0)
			{
				EOSLogger.Error($"Tried to generate a password for terminal {terminal.PublicName} with no {typeof(TerminalZoneSelectionData).Name}!! This is not allowed.");
				return;
			}
			string codeWord = SerialGenerator.GetCodeWord();
			string passwordHintText = data.PasswordHintText;
			string text = "<b>[Forgot your password?]</b> Backup security key(s) located in logs on ";
			int num = data.PasswordPartCount;
			if (codeWord.Length % num != 0)
			{
				EOSLogger.Error($"Build() password.Length ({codeWord.Length}) not divisible by passwordParts ({num}). Defaulting to 1.");
				num = 1;
			}
			string[] array = ((num > 1) ? Il2CppArrayBase<string>.op_Implicit((Il2CppArrayBase<string>)(object)StringUtils.SplitIntoChunksArray(codeWord, codeWord.Length / num)) : new string[1] { codeWord });
			string text2 = "";
			if (data.ShowPasswordPartPositions)
			{
				for (int i = 0; i < array[0].Length; i++)
				{
					text2 += "-";
				}
			}
			HashSet<LG_ComputerTerminal> hashSet = new HashSet<LG_ComputerTerminal>();
			LG_Zone val = default(LG_Zone);
			for (int j = 0; j < num; j++)
			{
				int index = j % data.TerminalZoneSelectionDatas.Count;
				List<CustomTerminalZoneSelectionData> list = data.TerminalZoneSelectionDatas[index];
				int index2 = Builder.SessionSeedRandom.Range(0, list.Count, "NO_TAG");
				CustomTerminalZoneSelectionData customTerminalZoneSelectionData = list[index2];
				LG_ComputerTerminal val2;
				if ((int)customTerminalZoneSelectionData.SeedType == 0)
				{
					if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(customTerminalZoneSelectionData.DimensionIndex, customTerminalZoneSelectionData.LayerType, customTerminalZoneSelectionData.LocalIndex, ref val) || (Object)(object)val == (Object)null)
					{
						EOSLogger.Error($"BuildPassword: seedType {0} specified but cannot find zone {customTerminalZoneSelectionData.GlobalZoneIndexTuple()}");
					}
					if (val.TerminalsSpawnedInZone.Count <= 0)
					{
						EOSLogger.Error($"BuildPassword: seedType {0} specified but cannot find terminal zone {customTerminalZoneSelectionData.GlobalZoneIndexTuple()}");
					}
					val2 = val.TerminalsSpawnedInZone[customTerminalZoneSelectionData.TerminalIndex];
				}
				else
				{
					val2 = SelectPasswordTerminal(customTerminalZoneSelectionData.DimensionIndex, customTerminalZoneSelectionData.LayerType, customTerminalZoneSelectionData.LocalIndex, customTerminalZoneSelectionData.SeedType);
				}
				if ((Object)(object)val2 == (Object)null)
				{
					EOSLogger.Error($"BuildPassword: CRITICAL ERROR, could not get a LG_ComputerTerminal for password part ({j + 1}/{num}) for {terminal.PublicName} backup log.");
					continue;
				}
				string text3 = "";
				string text4;
				if (data.ShowPasswordPartPositions)
				{
					for (int k = 0; k < j; k++)
					{
						text3 += text2;
					}
					text4 = text3 + array[j];
					for (int l = j; l < num - 1; l++)
					{
						text4 += text2;
					}
				}
				else
				{
					text4 = array[j];
				}
				string value = (data.ShowPasswordPartPositions ? $"0{j + 1}" : $"0{Builder.SessionSeedRandom.Range(0, 9, "NO_TAG")}");
				TerminalLogFileData val3 = new TerminalLogFileData
				{
					FileName = $"key{value}_{LG_TerminalPasswordLinkerJob.GetTerminalNumber(terminal)}{(val2.HasPasswordPart ? "_1" : "")}.LOG",
					FileContent = new LocalizedText
					{
						UntranslatedText = string.Format(Text.Get((num > 1) ? 1431221909u : 2260297836u), text4),
						Id = 0u
					}
				};
				val2.AddLocalLog(val3, true);
				if (!hashSet.Contains(val2))
				{
					if (j > 0)
					{
						text += ", ";
					}
					text = text + val2.PublicName + " in " + val2.SpawnNode.m_zone.AliasName;
				}
				hashSet.Add(val2);
				val2.HasPasswordPart = true;
			}
			string text5 = text + ".";
			if (data.ShowPasswordLength)
			{
				terminal.LockWithPassword(codeWord, new string[3]
				{
					passwordHintText,
					text5,
					"Char[" + codeWord.Length + "]"
				});
			}
			else
			{
				terminal.LockWithPassword(codeWord, new string[2] { passwordHintText, text5 });
			}
		}

		public static void AddUniqueCommand(LG_ComputerTerminal terminal, CustomCommand cmd)
		{
			//IL_0053: 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_0141: 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)
			if (terminal.m_command.m_commandsPerString.ContainsKey(cmd.Command))
			{
				EOSLogger.Error("Duplicate command name: '" + cmd.Command + "', cannot add command");
				return;
			}
			TERM_Command val = default(TERM_Command);
			if (!terminal.m_command.TryGetUniqueCommandSlot(ref val))
			{
				EOSLogger.Error("Cannot get more unique command slot, max: 5");
				return;
			}
			terminal.m_command.AddCommand(val, cmd.Command, cmd.CommandDesc, cmd.SpecialCommandRule, ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(cmd.CommandEvents), ListExtensions.ToIl2Cpp<TerminalOutput>(cmd.PostCommandOutputs));
			for (int i = 0; i < cmd.CommandEvents.Count; i++)
			{
				WardenObjectiveEventData val2 = cmd.CommandEvents[i];
				if (val2.ChainPuzzle == 0)
				{
					continue;
				}
				ChainedPuzzleDataBlock block = GameDataBlockBase<ChainedPuzzleDataBlock>.GetBlock(val2.ChainPuzzle);
				if (block == null)
				{
					continue;
				}
				LG_Area val3;
				Transform val4;
				if (terminal.SpawnNode != null)
				{
					val3 = terminal.SpawnNode.m_area;
					val4 = terminal.m_wardenObjectiveSecurityScanAlign;
				}
				else
				{
					LG_WardenObjective_Reactor connectedReactor = terminal.ConnectedReactor;
					object obj;
					if (connectedReactor == null)
					{
						obj = null;
					}
					else
					{
						AIG_CourseNode spawnNode = connectedReactor.SpawnNode;
						obj = ((spawnNode != null) ? spawnNode.m_area : null);
					}
					if (obj == null)
					{
						obj = null;
					}
					val3 = (LG_Area)obj;
					LG_WardenObjective_Reactor connectedReactor2 = terminal.ConnectedReactor;
					val4 = ((connectedReactor2 != null) ? connectedReactor2.m_chainedPuzzleAlign : null) ?? null;
				}
				if ((Object)(object)val3 == (Object)null)
				{
					EOSLogger.Error("Terminal Source Area is not found! Cannot create chained puzzle for command " + cmd.Command + "!");
					continue;
				}
				ChainedPuzzleInstance val5 = ChainedPuzzleManager.CreatePuzzleInstance(block, val3, val4.position, val4, val2.UseStaticBioscanPoints);
				List<WardenObjectiveEventData> events = ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(cmd.CommandEvents.GetRange(i, cmd.CommandEvents.Count - i));
				val5.OnPuzzleSolved += Action.op_Implicit((Action)delegate
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(events, (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
				});
				terminal.SetChainPuzzleForCommand(val, i, val5);
			}
		}
	}
	public static class EOSUtils
	{
		public static List<T> ToManaged<T>(this List<T> il2cppList)
		{
			List<T> list = new List<T>();
			Enumerator<T> enumerator = il2cppList.GetEnumerator();
			while (enumerator.MoveNext())
			{
				T current = enumerator.Current;
				list.Add(current);
			}
			return list;
		}

		public static void ResetProgress(this ChainedPuzzleInstance chainedPuzzle)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: 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_0075: 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_0098: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			if (chainedPuzzle.Data.DisableSurvivalWaveOnComplete)
			{
				chainedPuzzle.m_sound = new CellSoundPlayer(chainedPuzzle.m_parent.position);
			}
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)chainedPuzzle.m_chainedPuzzleCores)
			{
				ResetChild(item);
			}
			if (SNet.IsMaster)
			{
				pChainedPuzzleState state = chainedPuzzle.m_stateReplicator.State;
				pChainedPuzzleState val = default(pChainedPuzzleState);
				val.status = (eChainedPuzzleStatus)0;
				val.currentSurvivalWave_EventID = state.currentSurvivalWave_EventID;
				val.isSolved = false;
				val.isActive = false;
				pChainedPuzzleState val2 = val;
				chainedPuzzle.m_stateReplicator.InteractWithState(val2, new pChainedPuzzleInteraction
				{
					type = (eChainedPuzzleInteraction)2
				});
			}
			static void ResetChild(iChainedPuzzleCore ICore)
			{
				CP_Bioscan_Core val3 = ((Il2CppObjectBase)ICore).TryCast<CP_Bioscan_Core>();
				if ((Object)(object)val3 != (Object)null)
				{
					((Il2CppObjectBase)val3.m_spline).Cast<CP_Holopath_Spline>();
					((Il2CppObjectBase)val3.PlayerScanner).Cast<CP_PlayerScanner>().ResetScanProgression(0f);
					val3.Deactivate();
				}
				else
				{
					CP_Cluster_Core val4 = ((Il2CppObjectBase)ICore).TryCast<CP_Cluster_Core>();
					if ((Object)(object)val4 == (Object)null)
					{
						EOSLogger.Error("ResetChild: found iChainedPuzzleCore that is neither CP_Bioscan_Core nor CP_Cluster_Core...");
					}
					else
					{
						((Il2CppObjectBase)val4.m_spline).Cast<CP_Holopath_Spline>();
						foreach (iChainedPuzzleCore item2 in (Il2CppArrayBase<iChainedPuzzleCore>)(object)val4.m_childCores)
						{
							ResetChild(item2);
						}
						val4.Deactivate();
					}
				}
			}
		}
	}
	public class EOSColor
	{
		public float r { get; set; }

		public float g { get; set; }

		public float b { get; set; }

		public float a { get; set; } = 1f;


		public Color ToUnityColor()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			return new Color(r, g, b, a);
		}
	}
	public static class VanillaTMPPros
	{
		public const string VANILLA_CP_PREFAB_PATH = "Assets/AssetPrefabs/Complex/Generic/ChainedPuzzles/CP_Bioscan_sustained_RequireAll.prefab";

		public static GameObject Instantiate(GameObject parent = null)
		{
			GameObject loadedAsset = AssetAPI.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/Complex/Generic/ChainedPuzzles/CP_Bioscan_sustained_RequireAll.prefab");
			if ((Object)(object)loadedAsset == (Object)null)
			{
				EOSLogger.Error("VanillaTMPPros.Instantiate: Cannot find TMPPro from vanilla CP!");
				return null;
			}
			GameObject gameObject = ((Component)loadedAsset.transform.GetChild(0).GetChild(1).GetChild(0)).gameObject;
			if (!((Object)(object)parent != (Object)null))
			{
				return Object.Instantiate<GameObject>(gameObject.gameObject);
			}
			return Object.Instantiate<GameObject>(gameObject.gameObject, parent.transform);
		}
	}
	public class Vec4 : Vec3
	{
		[JsonPropertyOrder(-9)]
		public float w { get; set; }

		public Vector4 ToVector4()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			return new Vector4(base.x, base.y, base.z, w);
		}
	}
	public class Vec3
	{
		[JsonPropertyOrder(-10)]
		public float x { get; set; }

		[JsonPropertyOrder(-10)]
		public float y { get; set; }

		[JsonPropertyOrder(-10)]
		public float z { get; set; }

		public Vector3 ToVector3()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(x, y, z);
		}

		public Quaternion ToQuaternion()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return Quaternion.Euler(x, y, z);
		}
	}
	public static class EOSLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("ExtraObjectiveSetup");

		public static void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		public static void Log(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)8, (object)str);
			}
		}

		public static void Warning(string format, params object[] args)
		{
			Warning(string.Format(format, args));
		}

		public static void Warning(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)4, (object)str);
			}
		}

		public static void Error(string format, params object[] args)
		{
			Error(string.Format(format, args));
		}

		public static void Error(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)2, (object)str);
			}
		}

		public static void Debug(string format, params object[] args)
		{
			Debug(string.Format(format, args));
		}

		public static void Debug(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)32, (object)str);
			}
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.TerminalTweak
{
	public struct TerminalState
	{
		public bool Enabled;

		public TerminalState()
		{
			Enabled = true;
		}

		public TerminalState(bool Enabled)
		{
			this.Enabled = true;
			this.Enabled = Enabled;
		}

		public TerminalState(TerminalState o)
		{
			Enabled = true;
			Enabled = o.Enabled;
		}
	}
	public class TerminalWrapper
	{
		public LG_ComputerTerminal lgTerminal { get; private set; }

		public StateReplicator<TerminalState> stateReplicator { get; private set; }

		private void ChangeStateUnsynced(bool enabled)
		{
			EOSLogger.Debug($"{lgTerminal.ItemKey} state, enabled: {enabled}");
			lgTerminal.OnProximityExit();
			Interact_ComputerTerminal componentInChildren = ((Component)lgTerminal).GetComponentInChildren<Interact_ComputerTerminal>(true);
			bool flag = enabled;
			if ((Object)(object)componentInChildren != (Object)null)
			{
				((Behaviour)componentInChildren).enabled = flag;
				((Interact_Base)componentInChildren).SetActive(flag);
			}
			lgTerminal.m_interfaceScreen.SetActive(flag);
			lgTerminal.m_loginScreen.SetActive(flag);
			if ((Object)(object)lgTerminal.m_text != (Object)null)
			{
				((Behaviour)lgTerminal.m_text).enabled = flag;
			}
			if (!flag)
			{
				PlayerAgent localInteractionSource = lgTerminal.m_localInteractionSource;
				if ((Object)(object)localInteractionSource != (Object)null && localInteractionSource.FPItemHolder.InTerminalTrigger)
				{
					lgTerminal.ExitFPSView();
				}
			}
		}

		public void ChangeState(bool enabled)
		{
			ChangeStateUnsynced(enabled);
			if (SNet.IsMaster)
			{
				stateReplicator.SetState(new TerminalState
				{
					Enabled = enabled
				});
			}
		}

		private void OnStateChanged(TerminalState oldState, TerminalState newState, bool isRecall)
		{
			if (isRecall)
			{
				ChangeStateUnsynced(newState.Enabled);
			}
		}

		public static TerminalWrapper Instantiate(LG_ComputerTerminal lgTerminal, uint replicatorID)
		{
			if ((Object)(object)lgTerminal == (Object)null || replicatorID == 0)
			{
				return null;
			}
			TerminalWrapper terminalWrapper = new TerminalWrapper();
			terminalWrapper.lgTerminal = lgTerminal;
			terminalWrapper.stateReplicator = StateReplicator<TerminalState>.Create(replicatorID, new TerminalState
			{
				Enabled = true
			}, (LifeTimeType)1, (IStateReplicatorHolder<TerminalState>)null);
			terminalWrapper.stateReplicator.OnStateChanged += terminalWrapper.OnStateChanged;
			return terminalWrapper;
		}

		private TerminalWrapper()
		{
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.TerminalPosition
{
	public class TerminalPosition : BaseInstanceDefinition
	{
		public Vec3 Position { get; set; } = new Vec3();


		public Vec3 Rotation { get; set; } = new Vec3();

	}
	internal class TerminalPositionOverrideManager : InstanceDefinitionManager<TerminalPosition>
	{
		public static TerminalPositionOverrideManager Current;

		protected override string DEFINITION_NAME => "TerminalPosition";

		private TerminalPositionOverrideManager()
		{
		}

		static TerminalPositionOverrideManager()
		{
			Current = new TerminalPositionOverrideManager();
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.Scout
{
	public class EventsOnZoneScoutScream : GlobalZoneIndex
	{
		public bool SuppressVanillaScoutWave { get; set; }

		public List<WardenObjectiveEventData> EventsOnScoutScream { get; set; } = new List<WardenObjectiveEventData>();

	}
	internal class ScoutScreamEventManager : ZoneDefinitionManager<EventsOnZoneScoutScream>
	{
		public static ScoutScreamEventManager Current;

		protected override string DEFINITION_NAME => "EventsOnScoutScream";

		private ScoutScreamEventManager()
		{
		}

		static ScoutScreamEventManager()
		{
			Current = new ScoutScreamEventManager();
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.BossEvents
{
	public struct FiniteBDEState
	{
		public int ApplyToHibernateCount;

		public int ApplyToWaveCount;

		public FiniteBDEState()
		{
			ApplyToHibernateCount = int.MaxValue;
			ApplyToWaveCount = int.MaxValue;
		}

		public FiniteBDEState(FiniteBDEState other)
		{
			ApplyToHibernateCount = int.MaxValue;
			ApplyToWaveCount = int.MaxValue;
			ApplyToHibernateCount = other.ApplyToHibernateCount;
			ApplyToHibernateCount = other.ApplyToWaveCount;
		}

		public FiniteBDEState(int ApplyToHibernateCount, int ApplyToWaveCount)
		{
			this.ApplyToHibernateCount = int.MaxValue;
			this.ApplyToWaveCount = int.MaxValue;
			this.ApplyToHibernateCount = ApplyToHibernateCount;
			this.ApplyToWaveCount = ApplyToWaveCount;
		}
	}
	public class EventsOnZoneBossDeath : GlobalZoneIndex
	{
		public bool ApplyToHibernate { get; set; } = true;


		public int ApplyToHibernateCount { get; set; } = int.MaxValue;


		public bool ApplyToWave { get; set; }

		public int ApplyToWaveCount { get; set; } = int.MaxValue;


		public List<uint> BossIDs { get; set; } = new List<uint> { 29u, 36u, 37u };


		public List<WardenObjectiveEventData> EventsOnBossDeath { get; set; } = new List<WardenObjectiveEventData>();


		[JsonIgnore]
		public StateReplicator<FiniteBDEState> FiniteBDEStateReplicator { get; private set; }

		[JsonIgnore]
		public int RemainingWaveBDE
		{
			get
			{
				if (FiniteBDEStateReplicator == null)
				{
					return ApplyToWaveCount;
				}
				return FiniteBDEStateReplicator.State.ApplyToWaveCount;
			}
		}

		[JsonIgnore]
		public int RemainingHibernateBDE
		{
			get
			{
				if (FiniteBDEStateReplicator == null)
				{
					return ApplyToHibernateCount;
				}
				return FiniteBDEStateReplicator.State.ApplyToHibernateCount;
			}
		}

		public void SetupReplicator(uint replicatorID)
		{
			if (ApplyToHibernateCount != int.MaxValue || ApplyToWaveCount != int.MaxValue)
			{
				FiniteBDEStateReplicator = StateReplicator<FiniteBDEState>.Create(replicatorID, new FiniteBDEState
				{
					ApplyToHibernateCount = ApplyToHibernateCount,
					ApplyToWaveCount = ApplyToWaveCount
				}, (LifeTimeType)1, (IStateReplicatorHolder<FiniteBDEState>)null);
				FiniteBDEStateReplicator.OnStateChanged += OnStateChanged;
			}
		}

		private void OnStateChanged(FiniteBDEState oldState, FiniteBDEState newState, bool isRecall)
		{
		}

		internal void Destroy()
		{
			FiniteBDEStateReplicator = null;
		}
	}
	internal class BossDeathEventManager : ZoneDefinitionManager<EventsOnZoneBossDeath>
	{
		public enum Mode
		{
			HIBERNATE,
			WAVE
		}

		public static BossDeathEventManager Current;

		public const int UNLIMITED_COUNT = int.MaxValue;

		private ConcurrentDictionary<(eDimensionIndex, LG_LayerType, eLocalZoneIndex), EventsOnZoneBossDeath> LevelBDEs { get; } = new ConcurrentDictionary<(eDimensionIndex, LG_LayerType, eLocalZoneIndex), EventsOnZoneBossDeath>();


		protected override string DEFINITION_NAME => "EventsOnBossDeath";

		public bool TryConsumeBDEventsExecutionTimes(EventsOnZoneBossDeath def, Mode mode)
		{
			//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_000e: Unknown result type (might be due to invalid IL or missing references)
			return TryConsumeBDEventsExecutionTimes(def.DimensionIndex, def.LayerType, def.LocalIndex, mode);
		}

		public bool TryConsumeBDEventsExecutionTimes(eDimensionIndex dimensionIndex, LG_LayerType layer, eLocalZoneIndex localIndex, Mode mode)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: 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_002f: Unknown result type (might be due to invalid IL or missing references)
			if (!LevelBDEs.ContainsKey((dimensionIndex, layer, localIndex)))
			{
				EOSLogger.Error($"BossDeathEventManager: got an unregistered entry: {(dimensionIndex, layer, localIndex, mode)}");
				return false;
			}
			EventsOnZoneBossDeath eventsOnZoneBossDeath = LevelBDEs[(dimensionIndex, layer, localIndex)];
			int num = ((mode == Mode.HIBERNATE) ? eventsOnZoneBossDeath.RemainingHibernateBDE : eventsOnZoneBossDeath.RemainingWaveBDE);
			if (num == int.MaxValue)
			{
				return true;
			}
			if (num > 0)
			{
				FiniteBDEState state = eventsOnZoneBossDeath.FiniteBDEStateReplicator.State;
				if (SNet.IsMaster)
				{
					eventsOnZoneBossDeath.FiniteBDEStateReplicator.SetState(new FiniteBDEState
					{
						ApplyToHibernateCount = ((mode == Mode.HIBERNATE) ? (num - 1) : state.ApplyToHibernateCount),
						ApplyToWaveCount = ((mode == Mode.WAVE) ? (num - 1) : state.ApplyToWaveCount)
					});
				}
				return true;
			}
			return false;
		}

		private void Clear()
		{
			foreach (EventsOnZoneBossDeath value in LevelBDEs.Values)
			{
				value.Destroy();
			}
			LevelBDEs.Clear();
		}

		private void SetupForCurrentExpedition()
		{
			if (!definitions.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData))
			{
				return;
			}
			foreach (EventsOnZoneBossDeath definition in definitions[RundownManager.ActiveExpedition.LevelLayoutData].Definitions)
			{
				if (LevelBDEs.ContainsKey(definition.GlobalZoneIndexTuple()))
				{
					EOSLogger.Error($"BossDeathEvent: found duplicate setup for zone {definition.GlobalZoneIndexTuple()}, will overwrite!");
				}
				if (definition.ApplyToHibernateCount != int.MaxValue || definition.ApplyToWaveCount != int.MaxValue)
				{
					uint num = EOSNetworking.AllotReplicatorID();
					if (num != 0)
					{
						definition.SetupReplicator(num);
					}
					else
					{
						EOSLogger.Error("BossDeathEvent: replicator ID depleted, cannot setup replicator!");
					}
				}
				LevelBDEs[definition.GlobalZoneIndexTuple()] = definition;
			}
		}

		private BossDeathEventManager()
		{
			LevelAPI.OnBuildStart += delegate
			{
				Clear();
				SetupForCurrentExpedition();
			};
			LevelAPI.OnLevelCleanup += Clear;
		}

		static BossDeathEventManager()
		{
			Current = new BossDeathEventManager();
		}
	}
}
namespace ExtraObjectiveSetup.Patches
{
	[HarmonyPatch]
	internal class Patch_CheckAndExecuteEventsOnTrigger
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(WardenObjectiveManager), "CheckAndExecuteEventsOnTrigger", new Type[]
		{
			typeof(WardenObjectiveEventData),
			typeof(eWardenObjectiveEventTrigger),
			typeof(bool),
			typeof(float)
		})]
		private static bool Pre_CheckAndExecuteEventsOnTrigger(WardenObjectiveEventData eventToTrigger, eWardenObjectiveEventTrigger trigger, bool ignoreTrigger, float currentDuration)
		{
			//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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected I4, but got Unknown
			if (eventToTrigger == null || (!ignoreTrigger && eventToTrigger.Trigger != trigger) || ((double)currentDuration != 0.0 && eventToTrigger.Delay <= currentDuration))
			{
				return true;
			}
			uint num = (uint)(int)eventToTrigger.Type;
			if (!EOSWardenEventManager.Current.HasEventDefinition(num))
			{
				return true;
			}
			string value = (EOSWardenEventManager.Current.IsVanillaEventID(num) ? "overriding vanilla event implementation..." : "executing...");
			EOSLogger.Debug($"WardenEvent: found definition for event ID {num}, {value}");
			EOSWardenEventManager.Current.ExecuteEvent(eventToTrigger, currentDuration);
			return false;
		}
	}
	[HarmonyPatch]
	internal class Patch_EventsOnBossDeath
	{
		private static HashSet<ushort> ExecutedForInstances;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemySync), "OnSpawn")]
		private static void Post_SpawnEnemy(EnemySync __instance, pEnemySpawnData spawnData)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: 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_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Invalid comparison between Unknown and I4
			//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: Invalid comparison between Unknown and I4
			//IL_00c1: 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_00c8: Invalid comparison between Unknown and I4
			//IL_00a9: 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_00b0: Invalid comparison between Unknown and I4
			//IL_012a: 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)
			AIG_CourseNode val = default(AIG_CourseNode);
			if (!((pCourseNode)(ref spawnData.courseNode)).TryGet(ref val) || val == null)
			{
				EOSLogger.Error("Failed to get spawnnode for a boss! Skipped EventsOnBossDeath for it");
				return;
			}
			LG_Zone zone = val.m_zone;
			EventsOnZoneBossDeath def = BossDeathEventManager.Current.GetDefinition(zone.DimensionIndex, zone.Layer.m_type, zone.LocalIndex);
			if (def == null)
			{
				return;
			}
			EnemyAgent enemy = __instance.m_agent;
			if (!def.BossIDs.Contains(((GameDataBlockBase<EnemyDataBlock>)(object)enemy.EnemyData).persistentID) || ((((int)spawnData.mode != 4 && (int)spawnData.mode != 3) || !def.ApplyToHibernate) && ((int)spawnData.mode != 1 || !def.ApplyToWave)))
			{
				return;
			}
			BossDeathEventManager.Mode mode = (((int)spawnData.mode != 4) ? BossDeathEventManager.Mode.WAVE : BossDeathEventManager.Mode.HIBERNATE);
			enemy.OnDeadCallback += Action.op_Implicit((Action)delegate
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Invalid comparison between Unknown and I4
				if ((int)GameStateManager.CurrentStateName == 10)
				{
					if (!BossDeathEventManager.Current.TryConsumeBDEventsExecutionTimes(def, mode))
					{
						EOSLogger.Debug($"EventsOnBossDeath: execution times depleted for {def.GlobalZoneIndexTuple()}, {mode}");
					}
					else
					{
						ushort globalID = ((Agent)enemy).GlobalID;
						if (ExecutedForInstances.Contains(globalID))
						{
							ExecutedForInstances.Remove(globalID);
						}
						else
						{
							def.EventsOnBossDeath.ForEach(delegate(WardenObjectiveEventData e)
							{
								WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
							});
							ExecutedForInstances.Add(globalID);
						}
					}
				}
			});
			EOSLogger.Debug($"EventsOnBossDeath: added for enemy with id  {((GameDataBlockBase<EnemyDataBlock>)(object)enemy.EnemyData).persistentID}, mode: {spawnData.mode}");
		}

		static Patch_EventsOnBossDeath()
		{
			ExecutedForInstances = new HashSet<ushort>();
			LevelAPI.OnLevelCleanup += ExecutedForInstances.Clear;
		}
	}
	[HarmonyPatch]
	internal class Patch_EventsOnZoneScoutScream
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(ES_ScoutScream), "CommonUpdate")]
		private static bool Pre_ES_ScoutScream_CommonUpdate(ES_ScoutScream __instance)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_003f: Invalid comparison between Unknown and I4
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			AIG_CourseNode courseNode = ((Agent)((ES_Base)__instance).m_enemyAgent).CourseNode;
			EventsOnZoneScoutScream definition = ScoutScreamEventManager.Current.GetDefinition(courseNode.m_dimension.DimensionIndex, courseNode.LayerType, courseNode.m_zone.LocalIndex);
			if (definition == null)
			{
				return true;
			}
			if ((int)__instance.m_state != 3 || __instance.m_stateDoneTimer >= Clock.Time)
			{
				return true;
			}
			if (definition.EventsOnScoutScream != null && definition.EventsOnScoutScream.Count > 0)
			{
				EOSLogger.Debug($"EventsOnZoneScoutScream: found config for {definition.GlobalZoneIndexTuple()}, executing events.");
				definition.EventsOnScoutScream.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
			if (!definition.SuppressVanillaScoutWave)
			{
				if (SNet.IsMaster && ((Agent)((ES_Base)__instance).m_enemyAgent).CourseNode != null)
				{
					if (RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings != 0 && RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation != 0)
					{
						ushort num = default(ushort);
						Mastermind.Current.TriggerSurvivalWave(((Agent)((ES_Base)__instance).m_enemyAgent).CourseNode, RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings, RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation, ref num, (SurvivalWaveSpawnType)0, 0f, 2f, true, false, default(Vector3), "");
					}
					else
					{
						Debug.LogError(Object.op_Implicit("ES_ScoutScream, a scout is screaming but we can't spawn a wave because the the scout settings are not set for this expedition! ScoutWaveSettings: " + RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings + " ScoutWavePopulation: " + RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation));
					}
				}
			}
			else
			{
				EOSLogger.Debug("Vanilla scout wave suppressed.");
			}
			if (SNet.IsMaster)
			{
				((ES_Base)__instance).m_enemyAgent.AI.m_behaviour.ChangeState((EB_States)5);
			}
			((MachineState<ES_Base>)(object)__instance).m_machine.ChangeState(2);
			__instance.m_state = (ScoutScreamState)4;
			return false;
		}
	}
}
namespace ExtraObjectiveSetup.Patches.Uplink
{
	[HarmonyPatch]
	internal static class CorruptedUplinkConfirm
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalCorruptedUplinkConfirm")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalCorruptedUplinkConfirm(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result)
		{
			LG_ComputerTerminal receiver = __instance.m_terminal;
			LG_ComputerTerminal sender = __instance.m_terminal.CorruptedUplinkReceiver;
			if ((Object)(object)sender == (Object)null)
			{
				EOSLogger.Error("TerminalCorruptedUplinkConfirm() critical failure because terminal does not have a CorruptedUplinkReceiver (sender).");
				__result = false;
				return false;
			}
			if (sender.m_isWardenObjective)
			{
				return true;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(sender);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(sender);
			UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			receiver.m_command.AddOutput((TerminalLineType)0, string.Format(Text.Get(2816126705u), sender.PublicName), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
			if ((Object)(object)sender.ChainedPuzzleForWardenObjective != (Object)null)
			{
				ChainedPuzzleInstance chainedPuzzleForWardenObjective = sender.ChainedPuzzleForWardenObjective;
				chainedPuzzleForWardenObjective.OnPuzzleSolved += Action.op_Implicit((Action)delegate
				{
					receiver.m_command.StartTerminalUplinkSequence(string.Empty, true);
					UplinkObjectiveManager.Current.ChangeState(sender, new UplinkState
					{
						Status = UplinkStatus.InProgress,
						CurrentRoundIndex = 0
					});
				});
				sender.m_command.AddOutput("", true);
				sender.m_command.AddOutput(Text.Get(3268596368u), true);
				sender.m_command.AddOutput(Text.Get(2277987284u), true);
				receiver.m_command.AddOutput("", true);
				receiver.m_command.AddOutput(Text.Get(3268596368u), true);
				receiver.m_command.AddOutput(Text.Get(2277987284u), true);
				if (SNet.IsMaster)
				{
					sender.ChainedPuzzleForWardenObjective.AttemptInteract((eChainedPuzzleInteraction)0);
				}
			}
			else
			{
				receiver.m_command.StartTerminalUplinkSequence(string.Empty, true);
				UplinkObjectiveManager.Current.ChangeState(sender, new UplinkState
				{
					Status = UplinkStatus.InProgress,
					CurrentRoundIndex = 0
				});
			}
			__result = true;
			return false;
		}
	}
	[HarmonyPatch]
	internal static class CorruptedUplinkConnect
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalCorruptedUplinkConnect")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalCorruptedUplinkConnect(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result)
		{
			//IL_01b4: 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_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Expected O, but got Unknown
			LG_ComputerTerminal terminal = __instance.m_terminal;
			if (terminal.m_isWardenObjective)
			{
				return true;
			}
			__result = false;
			LG_ComputerTerminal corruptedUplinkReceiver = terminal.CorruptedUplinkReceiver;
			if ((Object)(object)corruptedUplinkReceiver == (Object)null)
			{
				EOSLogger.Error("TerminalCorruptedUplinkConnect() critical failure because terminal does not have a CorruptedUplinkReceiver.");
				return false;
			}
			if (LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != 0 && LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != terminal.SyncID)
			{
				__instance.AddOngoingUplinkOutput();
				__result = false;
				return false;
			}
			LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = terminal.SyncID;
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (definition.UseUplinkAddress)
			{
				param1 = param1.ToUpper();
				EOSLogger.Debug("TerminalCorruptedUplinkConnect, param1: " + param1 + ", TerminalUplink: " + ((Object)terminal.UplinkPuzzle).ToString());
			}
			else
			{
				param1 = terminal.UplinkPuzzle.TerminalUplinkIP.ToUpper();
				EOSLogger.Debug("TerminalCorruptedUplinkConnect, not using uplink address, TerminalUplink: " + ((Object)terminal.UplinkPuzzle).ToString());
			}
			if (!definition.UseUplinkAddress || param1 == terminal.UplinkPuzzle.TerminalUplinkIP)
			{
				if (corruptedUplinkReceiver.m_command.HasRegisteredCommand((TERM_Command)27))
				{
					terminal.m_command.AddUplinkCorruptedOutput();
				}
				else
				{
					terminal.m_command.AddUplinkCorruptedOutput();
					terminal.m_command.AddOutput("", true);
					terminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(3492863045u), corruptedUplinkReceiver.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
					terminal.m_command.AddOutput((TerminalLineType)0, Text.Get(2761366063u), 0.6f, (TerminalSoundType)0, (TerminalSoundType)0);
					terminal.m_command.AddOutput("", true);
					terminal.m_command.AddOutput((TerminalLineType)0, Text.Get(3435969025u), 0.8f, (TerminalSoundType)0, (TerminalSoundType)0);
					corruptedUplinkReceiver.m_command.AddCommand((TERM_Command)27, "UPLINK_CONFIRM", new LocalizedText
					{
						UntranslatedText = Text.Get(112719254u),
						Id = 0u
					}, (TERM_CommandRule)2);
					corruptedUplinkReceiver.m_command.AddOutput((TerminalLineType)0, string.Format(Text.Get(1173595354u), terminal.PublicName), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
				}
			}
			else
			{
				terminal.m_command.AddUplinkWrongAddressError(param1);
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class StartTerminalUplinkSequence
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "StartTerminalUplinkSequence")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_StartTerminalUplinkSequence(LG_ComputerTerminalCommandInterpreter __instance, string uplinkIp, bool corrupted)
		{
			if (!corrupted)
			{
				LG_ComputerTerminal uplinkTerminal = __instance.m_terminal;
				if (uplinkTerminal.m_isWardenObjective)
				{
					return true;
				}
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(uplinkTerminal);
				uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(uplinkTerminal);
				UplinkDefinition uplinkConfig = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
				uplinkTerminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2583360288u), uplinkIp), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
				__instance.TerminalUplinkSequenceOutputs(uplinkTerminal, false);
				uplinkTerminal.m_command.OnEndOfQueue = Action.op_Implicit((Action)delegate
				{
					EOSLogger.Debug("UPLINK CONNECTION DONE!");
					uplinkTerminal.UplinkPuzzle.Connected = true;
					uplinkTerminal.UplinkPuzzle.CurrentRound.ShowGui = true;
					uplinkTerminal.UplinkPuzzle.OnStartSequence();
					uplinkConfig.EventsOnCommence.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
					});
					int num2 = uplinkConfig.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == 0);
					((num2 != -1) ? uplinkConfig.RoundOverrides[num2] : null)?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
					});
				});
			}
			else
			{
				LG_ComputerTerminal terminal = __instance.m_terminal;
				LG_ComputerTerminal sender = __instance.m_terminal.CorruptedUplinkReceiver;
				if (sender.m_isWardenObjective)
				{
					return true;
				}
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex2 = TerminalInstanceManager.Current.GetGlobalZoneIndex(sender);
				uint zoneInstanceIndex2 = TerminalInstanceManager.Current.GetZoneInstanceIndex(sender);
				UplinkDefinition uplinkConfig2 = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex2, zoneInstanceIndex2);
				sender.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2056072887u), sender.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
				sender.m_command.AddOutput("", true);
				terminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2056072887u), sender.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
				terminal.m_command.AddOutput("", true);
				terminal.m_command.TerminalUplinkSequenceOutputs(sender, false);
				terminal.m_command.TerminalUplinkSequenceOutputs(terminal, true);
				terminal.m_command.OnEndOfQueue = Action.op_Implicit((Action)delegate
				{
					EOSLogger.Debug("UPLINK CONNECTION DONE!");
					sender.UplinkPuzzle.Connected = true;
					sender.UplinkPuzzle.CurrentRound.ShowGui = true;
					sender.UplinkPuzzle.OnStartSequence();
					uplinkConfig2.EventsOnCommence.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
					});
					int num = uplinkConfig2.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == 0);
					((num != -1) ? uplinkConfig2.RoundOverrides[num] : null)?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
					});
				});
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class TerminalUplinkConnect
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkConnect")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkConnect(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result)
		{
			LG_ComputerTerminal terminal = __instance.m_terminal;
			if (terminal.m_isWardenObjective)
			{
				return true;
			}
			if (LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != 0 && LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != terminal.SyncID)
			{
				__instance.AddOngoingUplinkOutput();
				return false;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance.m_terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (!definition.UseUplinkAddress)
			{
				param1 = __instance.m_terminal.UplinkPuzzle.TerminalUplinkIP;
			}
			if (!definition.UseUplinkAddress || param1 == __instance.m_terminal.UplinkPuzzle.TerminalUplinkIP)
			{
				__instance.m_terminal.TrySyncSetCommandRule((TERM_Command)25, (TERM_CommandRule)1);
				if ((Object)(object)__instance.m_terminal.ChainedPuzzleForWardenObjective != (Object)null)
				{
					ChainedPuzzleInstance chainedPuzzleForWardenObjective = __instance.m_terminal.ChainedPuzzleForWardenObjective;
					chainedPuzzleForWardenObjective.OnPuzzleSolved += Action.op_Implicit((Action)delegate
					{
						__instance.StartTerminalUplinkSequence(param1, false);
					});
					__instance.AddOutput("", true);
					__instance.AddOutput(Text.Get(3268596368u), true);
					__instance.AddOutput(Text.Get(3041541194u), true);
					if (SNet.IsMaster)
					{
						__instance.m_terminal.ChainedPuzzleForWardenObjective.AttemptInteract((eChainedPuzzleInteraction)0);
					}
				}
				else
				{
					__instance.StartTerminalUplinkSequence(param1, false);
				}
				__result = true;
			}
			else
			{
				__instance.AddUplinkWrongAddressError(param1);
				__result = false;
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class TerminalUplinkSequenceOutput
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkSequenceOutputs")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkSequenceOutputs(LG_ComputerTerminal terminal, bool corrupted)
		{
			if (terminal.m_isWardenObjective)
			{
				return true;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (definition == null)
			{
				if (!((Object)(object)terminal.CorruptedUplinkReceiver != (Object)null))
				{
					return true;
				}
				LG_ComputerTerminal corruptedUplinkReceiver = terminal.CorruptedUplinkReceiver;
				globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(corruptedUplinkReceiver);
				zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(corruptedUplinkReceiver);
				definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
				if (definition == null || definition.DisplayUplinkWarning)
				{
					return true;
				}
			}
			terminal.m_command.AddOutput((TerminalLineType)3, Text.Get(3418104670u), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
			terminal.m_command.AddOutput("", true);
			if (!corrupted)
			{
				terminal.m_command.AddOutput(string.Format(Text.Get(947485599u), terminal.UplinkPuzzle.CurrentRound.CorrectPrefix), true);
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class TerminalUplinkVerify
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkVerify")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkVerify(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result)
		{
			if (__instance.m_terminal.m_isWardenObjective)
			{
				return true;
			}
			TerminalUplinkPuzzle uplinkPuzzle = __instance.m_terminal.UplinkPuzzle;
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance.m_terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(__instance.m_terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			int CurrentRoundIndex = uplinkPuzzle.m_roundIndex;
			int num = definition.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == CurrentRoundIndex);
			UplinkRound roundOverride = ((num != -1) ? definition.RoundOverrides[num] : null);
			TimeSettings timeSettings = ((num != -1) ? roundOverride.OverrideTimeSettings : definition.DefaultTimeSettings);
			float num2 = ((timeSettings.TimeToStartVerify >= 0f) ? timeSettings.TimeToStartVerify : definition.DefaultTimeSettings.TimeToStartVerify);
			float timeToCompleteVerify = ((timeSettings.TimeToCompleteVerify >= 0f) ? timeSettings.TimeToCompleteVerify : definition.DefaultTimeSettings.TimeToCompleteVerify);
			float num3 = ((timeSettings.TimeToRestoreFromFail >= 0f) ? timeSettings.TimeToRestoreFromFail : definition.DefaultTimeSettings.TimeToRestoreFromFail);
			if (uplinkPuzzle.Connected)
			{
				__instance.AddOutput((TerminalLineType)3, Text.Get(2734004688u), num2, (TerminalSoundType)0, (TerminalSoundType)0);
				if (!uplinkPuzzle.Solved && uplinkPuzzle.CurrentRound.CorrectCode.ToUpper() == param1.ToUpper())
				{
					__instance.AddOutput(string.Format(Text.Get(1221800228u), uplinkPuzzle.CurrentProgress), true);
					if (uplinkPuzzle.TryGoToNextRound())
					{
						int newRoundIndex = uplinkPuzzle.m_roundIndex;
						int num4 = definition.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == newRoundIndex);
						UplinkRound newRoundOverride = ((num4 != -1) ? definition.RoundOverrides[num4] : null);
						roundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
						{
							WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)2, false, 0f);
						});
						if (roundOverride != null && (Object)(object)roundOverride.ChainedPuzzleToEndRoundInstance != (Object)null)
						{
							TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.UplinkTerminal.ScanRequiredToProgress");
							if (block != null)
							{
								__instance.AddOutput((TerminalLineType)4, Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
							}
							ChainedPuzzleInstance chainedPuzzleToEndRoundInstance = roundOverride.ChainedPuzzleToEndRoundInstance;
							chainedPuzzleToEndRoundInstance.OnPuzzleSolved += Action.op_Implicit((Action)delegate
							{
								__instance.AddOutput((TerminalLineType)4, Text.Get(27959760u), timeToCompleteVerify, (TerminalSoundType)0, (TerminalSoundType)0);
								__instance.AddOutput("", true);
								__instance.AddOutput(string.Format(Text.Get(4269617288u), uplinkPuzzle.CurrentProgress, uplinkPuzzle.CurrentRound.CorrectPrefix), true);
								__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
								{
									EOSLogger.Log("UPLINK VERIFICATION GO TO NEXT ROUND!");
									uplinkPuzzle.CurrentRound.ShowGui = true;
									newRoundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
									{
										WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
									});
									UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
									{
										Status = UplinkStatus.InProgress,
										CurrentRoundIndex = uplinkPuzzle.m_roundIndex
									});
								});
							});
							if (SNet.IsMaster)
							{
								roundOverride.ChainedPuzzleToEndRoundInstance.AttemptInteract((eChainedPuzzleInteraction)0);
							}
						}
						else
						{
							__instance.AddOutput((TerminalLineType)4, Text.Get(27959760u), timeToCompleteVerify, (TerminalSoundType)0, (TerminalSoundType)0);
							__instance.AddOutput("", true);
							__instance.AddOutput(string.Format(Text.Get(4269617288u), uplinkPuzzle.CurrentProgress, uplinkPuzzle.CurrentRound.CorrectPrefix), true);
							__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
							{
								EOSLogger.Log("UPLINK VERIFICATION GO TO NEXT ROUND!");
								uplinkPuzzle.CurrentRound.ShowGui = true;
								newRoundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
								{
									WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
								});
								UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
								{
									Status = UplinkStatus.InProgress,
									CurrentRoundIndex = uplinkPuzzle.m_roundIndex
								});
							});
						}
					}
					else
					{
						__instance.AddOutput((TerminalLineType)3, Text.Get(1780488547u), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
						__instance.AddOutput("", true);
						__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
						{
							roundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
							{
								WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)2, false, 0f);
							});
							uplinkPuzzle.CurrentRound.ShowGui = false;
							if (roundOverride != null && (Object)(object)roundOverride.ChainedPuzzleToEndRoundInstance != (Object)null)
							{
								ChainedPuzzleInstance chainedPuzzleToEndRoundInstance2 = roundOverride.ChainedPuzzleToEndRoundInstance;
								chainedPuzzleToEndRoundInstance2.OnPuzzleSolved += Action.op_Implicit((Action)delegate
								{
									__instance.AddOutput((TerminalLineType)0, string.Format(Text.Get(3928683780u), uplinkPuzzle.TerminalUplinkIP), 2f, (TerminalSoundType)0, (TerminalSoundType)0);
									__instance.AddOutput("", true);
									__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
									{
										EOSLogger.Error("UPLINK VERIFICATION SEQUENCE DONE!");
										LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = 0u;
										uplinkPuzzle.Solved = true;
										Action onPuzzleSolved2 = uplinkPuzzle.OnPuzzleSolved;
										if (onPuzzleSolved2 != null)
										{
											onPuzzleSolved2.Invoke();
										}
										UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
										{
											Status = UplinkStatus.Finished,
											CurrentRoundIndex = uplinkPuzzle.m_roundIndex
										});
									});
								});
								if (SNet.IsMaster)
								{
									roundOverride.ChainedPuzzleToEndRoundInstance.AttemptInteract((eChainedPuzzleInteraction)0);
								}
							}
							else
							{
								__instance.AddOutput((TerminalLineType)0, string.Format(Text.Get(3928683780u), uplinkPuzzle.TerminalUplinkIP), 2f, (TerminalSoundType)0, (TerminalSoundType)0);
								__instance.AddOutput("", true);
								EOSLogger.Error("UPLINK VERIFICATION SEQUENCE DONE!");
								LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = 0u;
								uplinkPuzzle.Solved = true;
								Action onPuzzleSolved = uplinkPuzzle.OnPuzzleSolved;
								if (onPuzzleSolved != null)
								{
									onPuzzleSolved.Invoke();
								}
								UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
								{
									Status = UplinkStatus.Finished,
									CurrentRoundIndex = uplinkPuzzle.m_roundIndex
								});
							}
						});
					}
				}
				else if (uplinkPuzzle.Solved)
				{
					__instance.AddOutput("", true);
					__instance.AddOutput((TerminalLineType)1, Text.Get(4080876165u), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
					__instance.AddOutput((TerminalLineType)0, Text.Get(4104839742u), 6f, (TerminalSoundType)0, (TerminalSoundType)0);
				}
				else
				{
					__instance.AddOutput("", true);
					__instance.AddOutput((TerminalLineType)1, string.Format(Text.Get(507647514u), uplinkPuzzle.CurrentRound.CorrectPrefix), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
					__instance.AddOutput((TerminalLineType)0, Text.Get(4104839742u), num3, (TerminalSoundType)0, (TerminalSoundType)0);
				}
			}
			else
			{
				__instance.AddOutput("", true);
				__instance.AddOutput(Text.Get(403360908u), true);
			}
			__result = false;
			return false;
		}
	}
	[HarmonyPatch]
	internal static class UplinkGUI_Update
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminal), "Update")]
		private static void Post_LG_ComputerTerminal_Update(LG_ComputerTerminal __instance)
		{
			if (!__instance.m_isWardenObjective && __instance.UplinkPuzzle != null)
			{
				__instance.UplinkPuzzle.UpdateGUI(false);
			}
		}
	}
}
namespace ExtraObjectiveSetup.Patches.PowerGenerator
{
	[HarmonyPatch]
	internal static class Patch_LG_PowerGeneratorCluster
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGeneratorCluster), "Setup")]
		private static void Post_PowerGeneratorCluster_Setup(LG_PowerGeneratorCluster __instance)
		{
			uint instanceIndex = GeneratorClusterInstanceManager.Current.Register(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = GeneratorClusterInstanceManager.Current.GetGlobalZoneIndex(__instance);
			GeneratorClusterDefinition definition = GeneratorClusterObjectiveManager.Current.GetDefinition(globalZoneIndex, instanceIndex);
			if (definition == null)
			{
				return;
			}
			EOSLogger.Debug("Found LG_PowerGeneratorCluster and its definition! Building this Generator cluster...");
			__instance.m_serialNumber = SerialGenerator.GetUniqueSerialNo();
			__instance.m_itemKey = "GENERATOR_CLUSTER_" + __instance.m_serialNumber;
			__instance.m_terminalItem = GOUtil.GetInterfaceFromComp<iTerminalItem>(__instance.m_terminalItemComp);
			__instance.m_terminalItem.Setup(__instance.m_itemKey, (AIG_CourseNode)null);
			__instance.m_terminalItem.FloorItemStatus = (eFloorInventoryObjectStatus)4;
			if (__instance.SpawnNode != null)
			{
				__instance.m_terminalItem.FloorItemLocation = __instance.SpawnNode.m_zone.NavInfo.GetFormattedText((LG_NavInfoFormat)7);
			}
			List<Transform> list = new List<Transform>((IEnumerable<Transform>)__instance.m_generatorAligns);
			uint numberOfGenerators = definition.NumberOfGenerators;
			__instance.m_generators = Il2CppReferenceArray<LG_PowerGenerator_Core>.op_Implicit((LG_PowerGenerator_Core[])(object)new LG_PowerGenerator_Core[numberOfGenerators]);
			if (list.Count >= numberOfGenerators)
			{
				for (int i = 0; i < numberOfGenerators; i++)
				{
					int index = Builder.BuildSeedRandom.Range(0, list.Count, "NO_TAG");
					LG_PowerGenerator_Core val = GOUtil.SpawnChildAndGetComp<LG_PowerGenerator_Core>(__instance.m_generatorPrefab, list[index]);
					((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)__instance.m_generators)[i] = val;
					val.SpawnNode = __instance.SpawnNode;
					PowerGeneratorInstanceManager.Current.MarkAsGCGenerator(__instance, val);
					val.Setup();
					val.SetCanTakePowerCell(true);
					Debug.Log(Object.op_Implicit("Spawning generator at alignIndex: " + index));
					list.RemoveAt(index);
				}
			}
			else
			{
				Debug.LogError(Object.op_Implicit("LG_PowerGeneratorCluster does NOT have enough generator aligns to support the warden objective! Has " + list.Count + " needs " + numberOfGenerators));
			}
			__instance.ObjectiveItemSolved = true;
			if (definition.EndSequenceChainedPuzzle != 0)
			{
				GeneratorClusterObjectiveManager.Current.RegisterForChainedPuzzleBuild(__instance, definition);
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_LG_PowerGenerator_Core_SyncStatusChanged
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGenerator_Core), "SyncStatusChanged")]
		private static void Post_SyncStatusChanged(LG_PowerGenerator_Core __instance, pPowerGeneratorState state, bool isDropinState)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_00a5: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: 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)
			uint zoneInstanceIndex = PowerGeneratorInstanceManager.Current.GetZoneInstanceIndex(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance);
			LG_PowerGeneratorCluster parentGeneratorCluster = PowerGeneratorInstanceManager.Current.GetParentGeneratorCluster(__instance);
			GeneratorClusterDefinition generatorClusterDefinition = null;
			if ((Object)(object)parentGeneratorCluster != (Object)null)
			{
				uint zoneInstanceIndex2 = GeneratorClusterInstanceManager.Current.GetZoneInstanceIndex(parentGeneratorCluster);
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex2 = GeneratorClusterInstanceManager.Current.GetGlobalZoneIndex(parentGeneratorCluster);
				generatorClusterDefinition = GeneratorClusterObjectiveManager.Current.GetDefinition(globalZoneIndex2, zoneInstanceIndex2);
			}
			ePowerGeneratorStatus status = state.status;
			if (generatorClusterDefinition != null)
			{
				EOSLogger.Log($"LG_PowerGeneratorCluster.powerGenerator.OnSyncStatusChanged! status: {status}, isDropinState: {isDropinState}");
				if ((int)status == 0)
				{
					uint num = 0u;
					for (int i = 0; i < ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Length; i++)
					{
						if ((int)((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators)[i].m_stateReplicator.State.status == 0)
						{
							num++;
						}
					}
					EOSLogger.Log($"Generator Cluster PowerCell inserted ({num} / {((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count})");
					List<List<WardenObjectiveEventData>> eventsOnInsertCell = generatorClusterDefinition.EventsOnInsertCell;
					int num2 = (int)(num - 1);
					if (!isDropinState)
					{
						if (num2 >= 0 && num2 < eventsOnInsertCell.Count)
						{
							EOSLogger.Log($"Executing events ({num} / {((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count}). Event count: {eventsOnInsertCell[num2].Count}");
							eventsOnInsertCell[num2].ForEach(delegate(WardenObjectiveEventData e)
							{
								WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
							});
						}
						if (num == ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count && !parentGeneratorCluster.m_endSequenceTriggered)
						{
							EOSLogger.Log("All generators powered, executing end sequence");
							((MonoBehaviour)__instance).StartCoroutine(parentGeneratorCluster.ObjectiveEndSequence());
							parentGeneratorCluster.m_endSequenceTriggered = true;
						}
					}
					else if (num != ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count)
					{
						parentGeneratorCluster.m_endSequenceTriggered = false;
					}
				}
			}
			IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (definition != null && definition.EventsOnInsertCell != null && (int)status == 0 && !isDropinState)
			{
				definition.EventsOnInsertCell.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
			ExpeditionIGGroup expeditionIGGroup = ExpeditionIGGroupManager.Current.FindGroupDefOf(__instance);
			if (expeditionIGGroup == null)
			{
				return;
			}
			int num3 = 0;
			foreach (LG_PowerGenerator_Core generatorInstance in expeditionIGGroup.GeneratorInstances)
			{
				if ((int)generatorInstance.m_stateReplicator.State.status == 0)
				{
					num3++;
				}
			}
			if (isDropinState)
			{
				return;
			}
			if (num3 == expeditionIGGroup.GeneratorInstances.Count && expeditionIGGroup.PlayEndSequenceOnGroupComplete)
			{
				Coroutine val = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(ExpeditionIGGroupManager.PlayGroupEndSequence(expeditionIGGroup)), (Action)null);
				WorldEventManager.m_worldEventEventCoroutines.Add(val);
				return;
			}
			int num4 = num3 - 1;
			if (num4 >= 0 && num4 < expeditionIGGroup.EventsOnInsertCell.Count)
			{
				expeditionIGGroup.EventsOnInsertCell[num4].ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_LG_PowerGenerator_Core_Setup
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGenerator_Core), "Setup")]
		private static void Post_PowerGenerator_Setup(LG_PowerGenerator_Core __instance)
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00b2: 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_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)
			iCarryItemInteractionTarget powerCellInteraction = __instance.m_powerCellInteraction;
			powerCellInteraction.AttemptCarryItemInsert += Action<SNet_Player, Item>.op_Implicit((Action<SNet_Player, Item>)delegate(SNet_Player p, Item item)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				Item val2 = default(Item);
				if (PlayerBackpackManager.TryGetItemInLevelFromItemData(item.Get_pItemData(), ref val2))
				{
					((Il2CppObjectBase)val2).Cast<ItemInLevel>().CanWarp = false;
				}
				else
				{
					EOSLogger.Error($"Inserting sth other than PowerCell ({item.PublicName}) into {__instance.m_itemKey}, how?");
				}
			});
			if (PowerGeneratorInstanceManager.Current.IsGCGenerator(__instance))
			{
				return;
			}
			uint num = PowerGeneratorInstanceManager.Current.Register(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance);
			IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, num);
			if (definition != null)
			{
				Vector3 val = definition.Position.ToVector3();
				Quaternion rotation = definition.Rotation.ToQuaternion();
				if (val != Vector3.zero)
				{
					((Component)__instance).transform.position = val;
					((Component)__instance).transform.rotation = rotation;
					__instance.m_sound.UpdatePosition(val);
					EOSLogger.Debug("LG_PowerGenerator_Core: modified position / rotation");
				}
				if (definition.ForceAllowPowerCellInsertion)
				{
					__instance.SetCanTakePowerCell(true);
				}
				EOSLogger.Debug($"LG_PowerGenerator_Core: overriden, instance {num} in {globalZoneIndex}");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGenerator_Core), "SyncStatusChanged")]
		private static void Post_SyncStatusChanged(LG_PowerGenerator_Core __instance, pPowerGeneratorState state, bool isDropinState)
		{
			//IL_0030: 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: Invalid comparison between Unknown and I4
			uint zoneInstanceIndex = PowerGeneratorInstanceManager.Current.GetZoneInstanceIndex(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance);
			IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (!(definition == null || definition.EventsOnInsertCell == null || (int)state.status > 0 || isDropinState) && definition.EventsOnInsertCell.Count > 0)
			{
				definition.EventsOnInsertCell.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
		}
	}
}
namespace ExtraObjectiveSetup.Patches.Terminal
{
	[HarmonyPatch]
	internal static class Patch_FixHiddenCommandExecution
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReceiveCommand")]
		private static void Pre_TerminalInterpreter_ReceiveCommand(LG_ComputerTerminalCommandInterpreter __instance, ref TERM_Command cmd)
		{
			//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_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Expected I4, but got Unknown
			TERM_Command val = cmd;
			switch (val - 1)
			{
			case 0:
			case 1:
			case 2:
			case 3:
			case 11:
			case 13:
			case 14:
			case 17:
			case 18:
			case 19:
			case 20:
			case 21:
			case 22:
			case 23:
			case 24:
			case 25:
			case 26:
			case 27:
			case 28:
			case 31:
			case 32:
			case 33:
			case 42:
				if (__instance.m_terminal.CommandIsHidden(cmd))
				{
					cmd = (TERM_Command)10;
				}
				break;
			case 4:
			case 5:
			case 6:
			case 7:
			case 8:
			case 9:
			case 10:
			case 12:
			case 15:
			case 16:
			case 29:
			case 30:
			case 34:
			case 35:
			case 36:
			case 37:
			case 38:
			case 39:
			case 40:
			case 41:
				break;
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_FixRepeatablePuzzleBugs
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(CP_Cluster_Core), "OnSyncStateChange")]
		private static bool Pre_CheckEventsOnPuzzleSolved(CP_Cluster_Core __instance, eClusterStatus newStatus, bool isDropinState)
		{
			//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_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			//IL_004b: 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_0052: Invalid comparison between Unknown and I4
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Invalid comparison between Unknown and I4
			pClusterState currentState = __instance.m_sync.GetCurrentState();
			if (isDropinState && (int)newStatus == 3)
			{
				__instance.m_spline.SetVisible(false);
				for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Length; i++)
				{
					((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores)[i].Deactivate();
				}
				return false;
			}
			if (!isDropinState && (int)currentState.status == 3 && (int)newStatus == 1)
			{
				__instance.m_spline.Reveal(0f);
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class Patch_LG_ComputerTerminal_Setup
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminal), "Setup")]
		private static void Post_LG_ComputerTerminal_Setup(LG_ComputerTerminal __instance)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: 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_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			uint instanceIndex = TerminalInstanceManager.Current.Register(__instance);
			TerminalInstanceManager.Current.SetupTerminalWrapper(__instance);
			if (__instance.SpawnNode == null)
			{
				return;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance);
			TerminalPosition definition = TerminalPositionOverrideManager.Current.GetDefinition(globalZoneIndex, instanceIndex);
			if (definition != null)
			{
				if (definition.Position.ToVector3() != Vector3.zeroVector)
				{
					((Component)__instance).transform.position = definition.Position.ToVector3();
					((Component)__instance).transform.rotation = definition.Rotation.ToQuaternion();
				}
				EOSLogger.Debug($"TerminalPositionOverride: {definition.LocalIndex}, {definition.LayerType}, {definition.DimensionIndex}, TerminalIndex {definition.InstanceIndex}");
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_RepeatableCommandEventFix
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "SetupCommandEvents")]
		private static void Post_ResetRepeatableUniqueCommandChainedPuzzle(LG_ComputerTerminalCommandInterpreter __instance)
		{
			//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_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			LG_ComputerTerminal terminal = __instance.m_terminal;
			ChainedPuzzleInstance val = default(ChainedPuzzleInstance);
			foreach (TERM_Command uNIQUE_CMD in TerminalInstanceManager.UNIQUE_CMDS)
			{
				if (!__instance.m_commandsPerEnum.ContainsKey(uNIQUE_CMD))
				{
					continue;
				}
				string text = __instance.m_commandsPerEnum[uNIQUE_CMD];
				if ((int)__instance.m_terminal.GetCommandRule(uNIQUE_CMD) != 0)
				{
					continue;
				}
				List<WardenObjectiveEventData> uniqueCommandEvents = __instance.m_terminal.GetUniqueCommandEvents(text);
				for (int i = 0; i < uniqueCommandEvents.Count; i++)
				{
					if (uniqueCommandEvents[i].ChainPuzzle != 0)
					{
						if (__instance.m_terminal.TryGetChainPuzzleForCommand(uNIQUE_CMD, i, ref val) && (Object)(object)val != (Object)null)
						{
							ChainedPuzzleInstance obj = val;
							obj.OnPuzzleSolved += Action.op_Implicit((Action)val.ResetProgress);
						}
						EOSLogger.Debug($"TerminalTweak: {terminal.ItemKey}, command {text} set to be repeatable!");
					}
				}
			}
		}
	}
}
namespace ExtraObjectiveSetup.Patches.LGFactory
{
	[HarmonyPatch]
	internal class Patch_LG_Factory_NextBatch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_Factory), "NextBatch")]
		private static void Post_LG_Factory_NextBatch(LG_Factory __instance)
		{
			//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_0025: 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 = __instance.m_batchStep - 1;
			if (num >= 0)
			{
				BatchName batchName = ((Il2CppArrayBase<LG_FactoryBatch>)(object)__instance.m_batches)[num].m_batchName;
				Action action = BatchBuildManager.Current.Get_OnBatchDone(batchName);
				if (action != null)
				{
					EOSLogger.Warning($"On Batch '{batchName}' Done: {action.GetInvocationList().Length} injected jobs");
					action();
				}
			}
		}
	}
}
namespace ExtraObjectiveSetup.Patches.HSUActivator
{
	[HarmonyPatch]
	internal class SetupFromCustomGeomorph
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_HSUActivator_Core), "SetupFromCustomGeomorph")]
		private static void Post_LG_HSUActivator_Core_SetupFromCustomGeomorph(LG_HSUActivator_Core __instance)
		{
			//IL_0033: 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_0058: 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_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: 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_0245: Unknown result type (might be due to invalid IL or missing references)
			uint instanceIndex = HSUActivatorInstanceManager.Current.Register(__instance);
			HSUActivatorDefinition definition = HSUActivatorObjectiveManager.Current.GetDefinition(__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex, instanceIndex);
			if (definition == null)
			{
				return;
			}
			if (__instance.m_isWardenObjective)
			{
				EOSLogger.Error("BuildCustomHSUActivator: the HSUActivator has been set up by vanilla! Aborting custom setup...");
				EOSLogger.Error($"HSUActivator in {__instance.SpawnNode.m_zone.LocalIndex}, {__instance.SpawnNode.LayerType}, {__instance.SpawnNode.m_dimension.DimensionIndex}");
				return;
			}
			__instance.m_linkedItemGoingIn = __instance.SpawnPickupItemOnAlign(definition.ItemFromStart, __instance.m_itemGoingInAlign, false, -1);
			__instance.m_linkedItemComingOut = __instance.SpawnPickupItemOnAlign(definition.ItemAfterActivation, __instance.m_itemComingOutAlign, false, -1);
			LG_LevelInteractionManager.DeregisterTerminalItem(((Component)__instance.m_linkedItemGoingIn).GetComponentInChildren<iTerminalItem>());
			LG_LevelInteractionManager.DeregisterTerminalItem(((Component)__instance.m_linkedItemComingOut).GetComponentInChildren<iTerminalItem>());
			__instance.m_linkedItemGoingIn.SetPickupInteractionEnabled(false);
			__instance.m_linkedItemComingOut.SetPickupInteractionEnabled(false);
			__instance.m_insertHSUInteraction.OnInteractionSelected = Action<PlayerAgent>.op_Implicit((Action<PlayerAgent>)delegate
			{
			});
			__instance.m_sequencerInsertItem.OnSequenceDone = Action.op_Implicit((Action)delegate
			{
				//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_0011: 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)
				pHSUActivatorState state2 = __instance.m_stateReplicator.State;
				if (!state2.isSequenceIncomplete)
				{
					EOSLogger.Log(">>>>>> HSUInsertSequenceDone! Sequence was already complete");
				}
				state2.isSequenceIncomplete = false;
				__instance.m_stateReplicator.SetStateUnsynced(state2);
				EOSLogger.Log(">>>>>> HSUInsertSequenceDone!");
				if (__instance.m_triggerExtractSequenceRoutine != null)
				{
					((MonoBehaviour)__instance).StopCoroutine(__instance.m_triggerExtractSequenceRoutine);
				}
			});
			__instance.m_sequencerExtractItem.OnSequenceDone = Action.op_Implicit((Action)delegate
			{
				//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_0024: 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_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)
				SNet_StateReplicator<pHSUActivatorState, pHSUActivatorInteraction> stateReplicator = __instance.m_stateReplicator;
				pHSUActivatorState state = __instance.m_stateReplicator.State;
				state.isSequenceIncomplete = true;
				stateReplicator.SetStateUnsynced(state);
				if (SNet.IsMaster)
				{
					__instance.AttemptInteract(new pHSUActivatorInteraction
					{
						type = (eHSUActivatorInteractionType)2
					});
				}
			});
			EOSLogger.Debug($"HSUActivator: {(definition.DimensionIndex, definition.LayerType, definition.LocalIndex, definition.InstanceIndex)}, custom setup complete");
		}
	}
	[HarmonyPatch]
	internal class SyncStatusChanged
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_HSUActivator_Core), "SyncStatusChanged")]
		private static bool Pre_LG_HSUActivator_Core_SyncStatusChanged(LG_HSUActivator_Core __instance, pHSUActivatorState newState, bool isRecall)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: 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_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Expected I4, but got Unknown
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.m_isWardenObjective)
			{
				return true;
			}
			uint zoneInstanceIndex = HSUActivatorInstanceManager.Current.GetZoneInstanceIndex(__instance);
			if (zoneInstanceIndex == uint.MaxValue)
			{
				EOSLogger.Error($"Found unregistered HSUActivator!! {HSUActivatorInstanceManager.Current.GetGlobalZoneIndex(__instance)}");
				return true;
			}
			HSUActivatorDefinition definition = HSUActivatorObjectiveManager.Current.GetDefinition(__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex, zoneInstanceIndex);
			if (definition == null)
			{
				return true;
			}
			if (__instance.m_triggerExtractSequenceRoutine != null)
			{
				((MonoBehaviour)__instance).StopCoroutine(__instance.m_triggerExtractSequenceRoutine);
			}
			bool goingInVisibleForPostCulling = __instance.m_goingInVisibleForPostCulling;
			bool comingOutVisibleForPostCulling = __instance.m_comingOutVisibleForPostCulling;
			EOSLogger.Debug("LG_HSUActivator_Core.OnSyncStatusChanged " + ((object)(eHSUActivatorStatus)(ref newState.status)).ToString());
			eHSUActivatorStatus status = newState.status;
			switch ((int)status)
			{
			case 0:
				__instance.m_insertHSUInteraction.SetActive(true);
				__instance.ResetItem(__instance.m_itemGoingInAlign, __instance.m_linkedItemGoingIn, false, false, true, ref goingInVisibleForPostCulling);
				__instance.ResetItem(__instance.m_itemComingOutAlign, __instance.m_linkedItemComingOut, false, false, true, ref comingOutVisibleForPostCulling);
				__instance.m_sequencerWaitingForItem.StartSequence();
				__instance.m_sequencerInsertItem.StopSequence();
				__instance.m_sequencerExtractItem.StopSequence();
				__instance.m_sequencerExtractionDone.StopSequence();
				break;
			case 1:
				__instance.m_insertHSUInteraction.SetActive(false);
				__instance.ResetItem(__instance.m_itemGoingInAlign, __instance.m_linkedItemGoingIn, true, false, true, ref goingInVisibleForPostCulling);
				__instance.ResetItem(__instance.m_itemComingOutAlign, __instance.m_linkedItemComingOut, false, false, true, ref comingOutVisibleForPostCulling);
				__instance.m_sequencerWaitingFor

plugins/Inas07-ExtraSurvivalWaveSettings/Inas07.ExtraSurvivalWaveSettings.dll

Decompiled 7 hours ago
using System;
using System.Collections;
using System.Collections.Concurrent;
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 AIGraph;
using AK;
using Agents;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using GTFO.API;
using GameData;
using HarmonyLib;
using Il2CppSystem;
using LevelGeneration;
using Localization;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("Inas07.ExtraSurvivalWaveSettings")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Inas07.ExtraSurvivalWaveSettings")]
[assembly: AssemblyTitle("Inas07.ExtraSurvivalWaveSettings")]
[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 ExtraSurvivalWaveSettings
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Inas.ExtraSurvivalWaveSettings", "ExtraSurvivalWaveSettings", "1.1.1")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas";

		public const string PLUGIN_NAME = "ExtraSurvivalWaveSettings";

		public const string VERSION = "1.1.1";

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			m_Harmony = new Harmony("ExtraSurvivalWaveSettings");
			m_Harmony.PatchAll();
		}
	}
	public class SurvivalWaveManager
	{
		public static readonly SurvivalWaveManager Current;

		private ConcurrentDictionary<string, List<ushort>> WaveEventsMap = new ConcurrentDictionary<string, List<ushort>>();

		public void SpawnWave(WardenObjectiveEventData e)
		{
			//IL_006c: 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_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: 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_0087: Invalid comparison between Unknown and I4
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Invalid comparison between Unknown and I4
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ef: 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_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Invalid comparison between Unknown and I4
			//IL_0352: Unknown result type (might be due to invalid IL or missing references)
			//IL_0355: Invalid comparison between Unknown and I4
			//IL_00e8: 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_00f1: Invalid comparison between Unknown and I4
			//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_03c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cc: Invalid comparison between Unknown and I4
			//IL_0370: Unknown result type (might be due to invalid IL or missing references)
			//IL_0389: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Invalid comparison between Unknown and I4
			//IL_03ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0403: Unknown result type (might be due to invalid IL or missing references)
			//IL_041c: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: 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_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Invalid comparison between Unknown and I4
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			if (!SNet.IsMaster)
			{
				return;
			}
			PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent();
			if ((Object)(object)localPlayerAgent == (Object)null)
			{
				ESWSLogger.Error("SpawnWave: LocalPlayerAgent is null, wtf?");
				return;
			}
			GenericEnemyWaveData enemyWaveData = e.EnemyWaveData;
			if (enemyWaveData.WaveSettings == 0 || enemyWaveData.WavePopulation == 0)
			{
				ESWSLogger.Error("SpawnWave: WaveSettings or WavePopulation is 0");
				return;
			}
			SurvivalWaveSettingsDataBlock block = GameDataBlockBase<SurvivalWaveSettingsDataBlock>.GetBlock(enemyWaveData.WaveSettings);
			SurvivalWavePopulationDataBlock block2 = GameDataBlockBase<SurvivalWavePopulationDataBlock>.GetBlock(enemyWaveData.WavePopulation);
			if (block == null || block2 == null)
			{
				return;
			}
			AIG_CourseNode val = ((Agent)localPlayerAgent).CourseNode;
			SurvivalWaveSpawnType val2 = (SurvivalWaveSpawnType)0;
			Vector3 val3 = Vector3.zero;
			if (block.m_overrideWaveSpawnType)
			{
				LG_Zone val4 = default(LG_Zone);
				if ((int)block.m_survivalWaveSpawnType != 1 && (int)block.m_survivalWaveSpawnType != 2 && (int)block.m_survivalWaveSpawnType != 3)
				{
					val2 = block.m_survivalWaveSpawnType;
				}
				else if (Builder.CurrentFloor.TryGetZoneByLocalIndex(e.DimensionIndex, e.Layer, e.LocalIndex, ref val4) && (Object)(object)val4 != (Object)null)
				{
					val = val4.m_courseNodes[0];
					val2 = (SurvivalWaveSpawnType)1;
					if ((int)block.m_survivalWaveSpawnType == 2 || (int)block.m_survivalWaveSpawnType == 3)
					{
						if (e.Count < val4.m_courseNodes.Count)
						{
							val = val4.m_courseNodes[e.Count];
							val2 = (SurvivalWaveSpawnType)2;
							if ((int)block.m_survivalWaveSpawnType == 3)
							{
								val3 = e.Position;
								val2 = (SurvivalWaveSpawnType)3;
							}
						}
						else
						{
							ESWSLogger.Error($"SpawnWave: SpawnType InSuppliedCourseNode(_OnPosition) is specified but cannot find AREA_{(ushort)(65 + e.Count)} in ({e.DimensionIndex}, {e.Layer}, {e.LocalIndex}), falling back to SpawnType: InSuppliedCourseNodeZone");
						}
					}
				}
				else
				{
					ESWSLogger.Error($"SpawnWave: Failed to find zone with GlobalIndex ({e.DimensionIndex}, {e.Layer}, {e.LocalIndex}), falling back to default spawn type");
				}
			}
			Mastermind current = Mastermind.Current;
			AIG_CourseNode obj = val;
			uint waveSettings = enemyWaveData.WaveSettings;
			uint wavePopulation = enemyWaveData.WavePopulation;
			SurvivalWaveSpawnType val5 = val2;
			float spawnDelay = enemyWaveData.SpawnDelay;
			Vector3 val6 = val3;
			ushort num = default(ushort);
			if (!current.TriggerSurvivalWave(obj, waveSettings, wavePopulation, ref num, val5, spawnDelay, (float)enemyWaveData.AreaDistance, val6, true, false, default(Vector3), ""))
			{
				ESWSLogger.Error("SpawnWave: Critical ERROR! Failed spawning enemy wave");
				return;
			}
			WardenObjectiveManager.RegisterSurvivalWaveID(num);
			ESWSLogger.Log($"SpawnWave: Enemy wave spawned ({val2}) with eventID {num}");
			if (enemyWaveData.TriggerAlarm)
			{
				WardenObjectiveManager.Current.m_sound.UpdatePosition(val.Position);
				WardenObjectiveManager.Current.m_sound.Post(EVENTS.APEX_PUZZLE_START_ALARM, true);
				ESWSLogger.Debug("SpawnWave: Trigger Alarm (prolly bugged when there're multiple alarms)");
			}
			if (!string.IsNullOrEmpty(LocalizedText.op_Implicit(enemyWaveData.IntelMessage)))
			{
				GuiManager.PlayerLayer.m_wardenIntel.ShowSubObjectiveMessage("", LocalizedText.op_Implicit(enemyWaveData.IntelMessage), false, 200f, 8f, (Action)null);
			}
			if ((int)val2 == 1)
			{
				ESWSLogger.Log($"Spawning in: ({e.DimensionIndex}, {e.Layer}, {e.LocalIndex})");
			}
			else if ((int)val2 == 2)
			{
				ESWSLogger.Log($"Spawning in: ({e.DimensionIndex}, {e.Layer}, {e.LocalIndex}, AREA_{(ushort)(65 + e.Count)})");
			}
			string worldEventObjectFilter = e.WorldEventObjectFilter;
			if (!string.IsNullOrEmpty(worldEventObjectFilter))
			{
				if (!WaveEventsMap.ContainsKey(worldEventObjectFilter))
				{
					WaveEventsMap[worldEventObjectFilter] = new List<ushort>();
				}
				WaveEventsMap[worldEventObjectFilter].Add(num);
				ESWSLogger.Debug($"SpawnWave: Registered wave with filter {worldEventObjectFilter}, number of waves assigned: {WaveEventsMap[worldEventObjectFilter].Count}");
			}
		}

		public void StopNamedWaves(string waveName)
		{
			if (string.IsNullOrEmpty(waveName))
			{
				return;
			}
			if (!WaveEventsMap.Remove(waveName, out var value))
			{
				ESWSLogger.Error("Wave Filter " + waveName + " is unregistered, cannot stop wave.");
				return;
			}
			ESWSLogger.Debug($"StopNamedWaves: Stopping waves with name {waveName}, wave count: {value.Count}");
			value.ForEach(delegate(ushort eventID)
			{
				MastermindEvent val = default(MastermindEvent);
				if (Mastermind.Current.TryGetEvent(eventID, ref val))
				{
					val.StopEvent();
				}
				else
				{
					ESWSLogger.Error($"Wave with ID {eventID}: cannot find event. Are you debugging a level?");
				}
			});
		}

		internal void OnStopAllWave()
		{
			WaveEventsMap.Clear();
		}

		public void Clear()
		{
			WaveEventsMap.Clear();
		}

		private SurvivalWaveManager()
		{
		}

		static SurvivalWaveManager()
		{
			Current = new SurvivalWaveManager();
			LevelAPI.OnLevelCleanup += Current.Clear;
		}
	}
	internal static class ESWSLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("ExtraSurvivalWaveSettings");

		public static void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		public static void Log(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)8, (object)str);
			}
		}

		public static void Warning(string format, params object[] args)
		{
			Warning(string.Format(format, args));
		}

		public static void Warning(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)4, (object)str);
			}
		}

		public static void Error(string format, params object[] args)
		{
			Error(string.Format(format, args));
		}

		public static void Error(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)2, (object)str);
			}
		}

		public static void Debug(string format, params object[] args)
		{
			Debug(string.Format(format, args));
		}

		public static void Debug(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)32, (object)str);
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_CheckAndExecuteEventsOnTrigger
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(WardenObjectiveManager), "CheckAndExecuteEventsOnTrigger", new Type[]
		{
			typeof(WardenObjectiveEventData),
			typeof(eWardenObjectiveEventTrigger),
			typeof(bool),
			typeof(float)
		})]
		private static bool Pre_CheckAndExecuteEventsOnTrigger(WardenObjectiveEventData eventToTrigger, eWardenObjectiveEventTrigger trigger, bool ignoreTrigger, float currentDuration)
		{
			//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_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_0030: 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_0035: Invalid comparison between Unknown and I4
			if (eventToTrigger == null || (!ignoreTrigger && eventToTrigger.Trigger != trigger) || ((double)currentDuration != 0.0 && eventToTrigger.Delay <= currentDuration))
			{
				return true;
			}
			bool flag = false;
			eWardenObjectiveEventType type = eventToTrigger.Type;
			if (type - 9 <= 1)
			{
				flag = true;
				Coroutine val = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(Handle(eventToTrigger, 0f)), (Action)null);
				WorldEventManager.m_worldEventEventCoroutines.Add(val);
			}
			return !flag;
		}

		internal static IEnumerator Handle(WardenObjectiveEventData e, float currentDuration)
		{
			float num = Mathf.Max(e.Delay - currentDuration, 0f);
			if (num > 0f)
			{
				yield return (object)new WaitForSeconds(num);
			}
			if (e.Condition.ConditionIndex >= 0 && WorldEventManager.GetCondition(e.Condition.ConditionIndex) != e.Condition.IsTrue)
			{
				yield break;
			}
			WardenObjectiveManager.DisplayWardenIntel(e.Layer, e.WardenIntel);
			if (e.DialogueID != 0)
			{
				PlayerDialogManager.WantToStartDialog(e.DialogueID, -1, false, false);
			}
			if (e.SoundID != 0)
			{
				WardenObjectiveManager.Current.m_sound.Post(e.SoundID, true);
				string text = ((Object)e.SoundSubtitle).ToString();
				if (!string.IsNullOrWhiteSpace(text))
				{
					GuiManager.PlayerLayer.ShowMultiLineSubtitle(text);
				}
			}
			eWardenObjectiveEventType type = e.Type;
			if ((int)type != 9)
			{
				if ((int)type == 10)
				{
					if (string.IsNullOrEmpty(e.WorldEventObjectFilter))
					{
						WardenObjectiveManager.StopAlarms();
						WardenObjectiveManager.StopAllWardenObjectiveEnemyWaves();
						WardenObjectiveManager.Current.m_sound.Post(EVENTS.ALARM_AMBIENT_STOP, true);
						SurvivalWaveManager.Current.OnStopAllWave();
					}
					else
					{
						SurvivalWaveManager.Current.StopNamedWaves(e.WorldEventObjectFilter);
					}
				}
			}
			else
			{
				SurvivalWaveManager.Current.SpawnWave(e);
			}
		}
	}
}

plugins/Inas07-LegacyGeos/FlowGeos (ReactorTerminalResolver).dll

Decompiled 7 hours ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using GTFO.API;
using HarmonyLib;
using LevelGeneration;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("FlowGeos")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("FlowGeos")]
[assembly: AssemblyTitle("FlowGeos")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace FlowGeos;

[BepInPlugin("FlowGeos", "FlowGeos", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class EntryPoint : BasePlugin
{
	private Harmony m_Harmony;

	public override void Load()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		m_Harmony = new Harmony("FlowGeos");
		m_Harmony.PatchAll();
	}
}
internal static class FlowGeosLogger
{
	private static readonly ManualLogSource _logger;

	static FlowGeosLogger()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Expected O, but got Unknown
		_logger = new ManualLogSource("FlowGeos");
		Logger.Sources.Add((ILogSource)(object)_logger);
	}

	private static string Format(object msg)
	{
		return msg.ToString();
	}

	public static void Info(object data)
	{
		_logger.LogMessage((object)Format(data));
	}

	public static void Verbose(object data)
	{
	}

	public static void Debug(object data)
	{
		_logger.LogDebug((object)Format(data));
	}

	public static void Error(object data)
	{
		_logger.LogError((object)Format(data));
	}
}
[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "Start")]
internal static class Inject_WO_Reactor
{
	private static void Postfix(LG_WardenObjective_Reactor __instance)
	{
		if ((Object)(object)__instance.m_terminalPrefab == (Object)null)
		{
			FlowGeosLogger.Info("Resolving Terminal Prefab for reactor!");
			__instance.m_terminalPrefab = AssetAPI.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/Complex/Generic/FunctionMarkers/Terminal_Floor.prefab");
			if ((Object)(object)__instance.m_terminalPrefab == (Object)null)
			{
				FlowGeosLogger.Error("We tried to resolve terminal prefab for reactor but it doesn't work...");
			}
		}
	}
}

plugins/Inas07-LocalProgression/Inas07.LocalProgression.dll

Decompiled 7 hours 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 System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BoosterImplants;
using CellMenu;
using DropServer;
using GTFO.API;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using LocalProgression.Component;
using LocalProgression.Data;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using SNetwork;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("Inas07.LocalProgression")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+ab8c78f9ff6b5b5d947a46310ee1438e1340cc16")]
[assembly: AssemblyProduct("Inas07.LocalProgression")]
[assembly: AssemblyTitle("Inas07.LocalProgression")]
[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 LocalProgression
{
	internal static class Assets
	{
		internal static GameObject NoBoosterIcon { get; private set; }

		internal static void Init()
		{
			NoBoosterIcon = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/CM_ExpeditionSectorIcon.prefab");
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Inas.LocalProgression", "LocalProgression", "1.3.7")]
	public class EntryPoint : BasePlugin
	{
		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			m_Harmony = new Harmony("LocalProgression");
			m_Harmony.PatchAll();
			EventAPI.OnManagersSetup += LocalProgressionManager.Current.Init;
			AssetAPI.OnAssetBundlesLoaded += Assets.Init;
		}
	}
	internal static class JSON
	{
		private static JsonSerializerOptions _setting;

		public static T Deserialize<T>(string json)
		{
			return JsonSerializer.Deserialize<T>(json, _setting);
		}

		public static string Serialize<T>(T value)
		{
			return JsonSerializer.Serialize(value, _setting);
		}

		static JSON()
		{
			_setting = new JsonSerializerOptions
			{
				ReadCommentHandling = JsonCommentHandling.Skip,
				IncludeFields = false,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true,
				IgnoreReadOnlyProperties = true
			};
			_setting.Converters.Add(new JsonStringEnumConverter());
		}
	}
	public class LocalProgressionManager
	{
		public const string CONFIG_FILE_NAME = "ProgressionConfig.json";

		public static readonly LocalProgressionManager Current;

		private CM_PageRundown_New rundownPage;

		public static readonly string DirPath;

		public string LP_CONFIG_DIR => Path.Combine(MTFOPathAPI.CustomPath, "LocalProgressionConfig");

		public string CONFIG_PATH => Path.Combine(LP_CONFIG_DIR, "ProgressionConfig.json");

		public RundownProgressonConfig RundownProgressonConfig { get; private set; } = new RundownProgressonConfig();


		private RundownProgressionData CurrentRundownPData { get; } = new RundownProgressionData();


		internal RundownProgData nativeProgData { get; private set; }

		internal void SetCurrentRundownPageInstance(CM_PageRundown_New __instance)
		{
			rundownPage = __instance;
		}

		private void UpdateRundownPageExpeditionIconProgression()
		{
			//IL_0066: 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_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			//IL_00e8: 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_011e: 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_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_032d: 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_039b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0409: Unknown result type (might be due to invalid IL or missing references)
			//IL_0427: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b4: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)rundownPage == (Object)null)
			{
				return;
			}
			uint rundownID = CurrentRundownPData.RundownID;
			if (rundownID == 0)
			{
				LPLogger.Warning("UpdateRundownPageExpeditionIconProgression: rundown_id == 0!");
				return;
			}
			RundownDataBlock block = GameDataBlockBase<RundownDataBlock>.GetBlock(rundownID);
			LPLogger.Log($"CM_PageRundown_New.UpdateRundownExpeditionProgression, overwrite with LocalProgression Data, RundownID {CurrentRundownPData.RundownID}");
			nativeProgData = ComputeLocalProgressionDataToRundownProgData();
			if ((Object)(object)rundownPage.m_tierMarker1 != (Object)null)
			{
				rundownPage.m_tierMarker1.SetProgression(nativeProgData, new RundownTierProgressionData());
				if (rundownPage.m_expIconsTier1 != null)
				{
					UpdateTierIconsWithProgression(rundownPage.m_expIconsTier1, rundownPage.m_tierMarker1, thisTierUnlocked: true);
				}
			}
			if ((Object)(object)rundownPage.m_tierMarker2 != (Object)null)
			{
				rundownPage.m_tierMarker2.SetProgression(nativeProgData, block.ReqToReachTierB);
				if (rundownPage.m_expIconsTier2 != null)
				{
					UpdateTierIconsWithProgression(rundownPage.m_expIconsTier2, rundownPage.m_tierMarker2, nativeProgData.tierBUnlocked && block.UseTierUnlockRequirements);
				}
			}
			if ((Object)(object)rundownPage.m_tierMarker3 != (Object)null)
			{
				rundownPage.m_tierMarker3.SetProgression(nativeProgData, block.ReqToReachTierC);
				if (rundownPage.m_expIconsTier3 != null)
				{
					UpdateTierIconsWithProgression(rundownPage.m_expIconsTier3, rundownPage.m_tierMarker3, nativeProgData.tierCUnlocked && block.UseTierUnlockRequirements);
				}
			}
			if ((Object)(object)rundownPage.m_tierMarker4 != (Object)null)
			{
				rundownPage.m_tierMarker4.SetProgression(nativeProgData, block.ReqToReachTierD);
				if (rundownPage.m_expIconsTier4 != null)
				{
					UpdateTierIconsWithProgression(rundownPage.m_expIconsTier4, rundownPage.m_tierMarker4, nativeProgData.tierDUnlocked && block.UseTierUnlockRequirements);
				}
			}
			if ((Object)(object)rundownPage.m_tierMarker5 != (Object)null)
			{
				rundownPage.m_tierMarker5.SetProgression(nativeProgData, block.ReqToReachTierE);
				if (rundownPage.m_expIconsTier5 != null)
				{
					UpdateTierIconsWithProgression(rundownPage.m_expIconsTier5, rundownPage.m_tierMarker5, nativeProgData.tierEUnlocked && block.UseTierUnlockRequirements);
				}
			}
			if (!((Object)(object)rundownPage.m_tierMarkerSectorSummary != (Object)null))
			{
				return;
			}
			rundownPage.m_tierMarkerSectorSummary.SetSectorIconTextForMain($"<color=orange>[{nativeProgData.clearedMain}/{nativeProgData.totalMain}]</color>", "#FFFFFFCC");
			rundownPage.m_tierMarkerSectorSummary.SetSectorIconTextForSecondary($"<color=orange>[{nativeProgData.clearedSecondary}/{nativeProgData.totalSecondary}]</color>", "#CCCCCCCC");
			rundownPage.m_tierMarkerSectorSummary.SetSectorIconTextForThird($"<color=orange>[{nativeProgData.clearedThird}/{nativeProgData.totalThird}]</color>", "#CCCCCCCC");
			rundownPage.m_tierMarkerSectorSummary.SetSectorIconTextForAllCleared($"<color=orange>[{nativeProgData.clearedAllClear}/{nativeProgData.totalAllClear}]</color>", "#CCCCCCCC");
			RundownTierMarker_NoBoosterIcon component = ((Component)rundownPage.m_tierMarkerSectorSummary).GetComponent<RundownTierMarker_NoBoosterIcon>();
			if (!((Object)(object)component != (Object)null) || !TryGetRundownConfig(rundownID, out var rundownConf))
			{
				return;
			}
			int value = rundownConf.ComputeNoBoosterClearPossibleCount();
			if (rundownConf.EnableNoBoosterUsedProgressionForRundown && (rundownConf.AlwaysShowIcon || CurrentRundownPData.NoBoosterAllClearCount > 0))
			{
				if (rundownConf.EnableNoBoosterUsedProgressionForRundown)
				{
					value = nativeProgData.totalMain;
				}
				component.SetVisible(visible: true);
				component.SetSectorIconText($"<color=orange>[{CurrentRundownPData.NoBoosterAllClearCount}/{value}]</color>");
			}
			else
			{
				component.SetVisible(visible: false);
			}
		}

		private void UpdateTierIconsWithProgression(List<CM_ExpeditionIcon_New> tierIcons, CM_RundownTierMarker tierMarker, bool thisTierUnlocked)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			if (tierIcons == null || tierIcons.Count == 0)
			{
				if (tierMarker != null)
				{
					tierMarker.SetVisible(false, 0f);
				}
				return;
			}
			for (int i = 0; i < tierIcons.Count; i++)
			{
				CM_ExpeditionIcon_New val = tierIcons[i];
				string rundownProgressionExpeditionKey = RundownManager.GetRundownProgressionExpeditionKey(tierIcons[i].Tier, tierIcons[i].ExpIndex);
				ExpeditionProgressionData value;
				bool flag = CurrentRundownPData.LPData.TryGetValue(rundownProgressionExpeditionKey, out value);
				string text = "0";
				string text2 = (RundownManager.HasSecondaryLayer(tierIcons[i].DataBlock) ? "0" : "-");
				string text3 = (RundownManager.HasThirdLayer(tierIcons[i].DataBlock) ? "0" : "-");
				string text4 = (RundownManager.HasAllCompletetionPossibility(tierIcons[i].DataBlock) ? "0" : "-");
				if (flag)
				{
					if (value.MainCompletionCount > 0)
					{
						text = value.MainCompletionCount.ToString();
					}
					if (value.SecondaryCompletionCount > 0)
					{
						text2 = value.SecondaryCompletionCount.ToString();
					}
					if (value.ThirdCompletionCount > 0)
					{
						text3 = value.ThirdCompletionCount.ToString();
					}
					if (value.AllClearCount > 0)
					{
						text4 = value.AllClearCount.ToString();
					}
				}
				if (CheckExpeditionUnlocked(val.DataBlock, val.Tier))
				{
					if (flag)
					{
						rundownPage.SetIconStatus(val, (eExpeditionIconStatus)4, text, text2, text3, text4, 1f, false, (eExpeditionAccessibility)0);
					}
					else
					{
						rundownPage.SetIconStatus(val, (eExpeditionIconStatus)2, "-", "-", "-", "-", 1f, false, (eExpeditionAccessibility)0);
					}
				}
				else if (flag)
				{
					rundownPage.SetIconStatus(val, (eExpeditionIconStatus)1, text, text2, text3, text4, 1f, false, (eExpeditionAccessibility)0);
				}
				else if (val.DataBlock.HideOnLocked)
				{
					((RectTransformComp)val).SetVisible(false);
				}
				else
				{
					rundownPage.SetIconStatus(val, (eExpeditionIconStatus)0, "-", "-", "-", "-", 1f, false, (eExpeditionAccessibility)0);
				}
			}
			if (thisTierUnlocked)
			{
				if (tierMarker != null)
				{
					tierMarker.SetStatus((eRundownTierMarkerStatus)1);
				}
			}
			else if (tierMarker != null)
			{
				tierMarker.SetStatus((eRundownTierMarkerStatus)0);
			}
		}

		private RundownProgData ComputeLocalProgressionDataToRundownProgData()
		{
			//IL_0002: 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_00e5: 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)
			RundownProgData progressionData = default(RundownProgData);
			if (CurrentRundownPData.RundownID == 0)
			{
				LPLogger.Error("ComputeLocalProgressionDataToRundownProgData: rundown_id == 0...");
				return progressionData;
			}
			RundownDataBlock block = GameDataBlockBase<RundownDataBlock>.GetBlock(CurrentRundownPData.RundownID);
			if (block == null)
			{
				LPLogger.Error($"ComputeLocalProgressionDataToRundownProgData: cannot get rundown datablock with rundown_id: {CurrentRundownPData.RundownID}");
				return progressionData;
			}
			progressionData.clearedMain = CurrentRundownPData.MainClearCount;
			progressionData.clearedSecondary = CurrentRundownPData.SecondaryClearCount;
			progressionData.clearedThird = CurrentRundownPData.ThirdClearCount;
			progressionData.clearedAllClear = CurrentRundownPData.AllClearCount;
			AccumulateTierClearance(block, (eRundownTier)1, ref progressionData);
			AccumulateTierClearance(block, (eRundownTier)2, ref progressionData);
			AccumulateTierClearance(block, (eRundownTier)3, ref progressionData);
			AccumulateTierClearance(block, (eRundownTier)4, ref progressionData);
			AccumulateTierClearance(block, (eRundownTier)5, ref progressionData);
			return progressionData;
		}

		private void AccumulateTierClearance(RundownDataBlock rundownDB, eRundownTier tier, ref RundownProgData progressionData)
		{
			//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_0023: Expected I4, but got Unknown
			//IL_0061: 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_010e: Unknown result type (might be due to invalid IL or missing references)
			List<ExpeditionInTierData> val = rundownDB.TierA;
			switch (tier - 1)
			{
			case 1:
				val = rundownDB.TierB;
				break;
			case 2:
				val = rundownDB.TierC;
				break;
			case 3:
				val = rundownDB.TierD;
				break;
			case 4:
				val = rundownDB.TierE;
				break;
			default:
				LPLogger.Error($"Unsupported eRundownTier {tier}");
				return;
			case 0:
				break;
			}
			int num = 0;
			Enumerator<ExpeditionInTierData> enumerator = val.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ExpeditionInTierData current = enumerator.Current;
				if (current.Enabled && (!current.HideOnLocked || CheckExpeditionUnlocked(current, tier)))
				{
					progressionData.totalMain++;
					if (RundownManager.HasSecondaryLayer(current))
					{
						progressionData.totalSecondary++;
					}
					if (RundownManager.HasThirdLayer(current))
					{
						progressionData.totalThird++;
					}
					if (RundownManager.HasAllCompletetionPossibility(current))
					{
						progressionData.totalAllClear++;
					}
					if (current.Descriptive.IsExtraExpedition)
					{
						progressionData.totatlExtra++;
					}
					string uniqueExpeditionKey = RundownManager.GetUniqueExpeditionKey(rundownDB, tier, num);
					if (CurrentRundownPData.LPData.ContainsKey(uniqueExpeditionKey))
					{
						progressionData.clearedExtra++;
					}
					num++;
				}
			}
		}

		private bool CheckTierUnlocked(eRundownTier tier)
		{
			//IL_0013: 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_002f: Expected I4, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			RundownDataBlock block = GameDataBlockBase<RundownDataBlock>.GetBlock(CurrentRundownPData.RundownID);
			RundownTierProgressionData val = null;
			switch (tier - 1)
			{
			case 0:
				return true;
			case 1:
				val = block.ReqToReachTierB;
				break;
			case 2:
				val = block.ReqToReachTierC;
				break;
			case 3:
				val = block.ReqToReachTierD;
				break;
			case 4:
				val = block.ReqToReachTierE;
				break;
			default:
				LPLogger.Error("Unsupporrted tier: {0}", tier);
				return true;
			}
			if (CurrentRundownPData.MainClearCount >= val.MainSectors && CurrentRundownPData.SecondaryClearCount >= val.SecondarySectors && CurrentRundownPData.ThirdClearCount >= val.ThirdSectors)
			{
				return CurrentRundownPData.AllClearCount >= val.AllClearedSectors;
			}
			return false;
		}

		private bool CheckExpeditionUnlocked(ExpeditionInTierData expedition, eRundownTier tier)
		{
			//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_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected I4, but got Unknown
			//IL_002f: 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_00a7: Expected I4, but got Unknown
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			eExpeditionAccessibility accessibility = expedition.Accessibility;
			switch ((int)accessibility)
			{
			case 1:
			case 3:
				return false;
			case 2:
				return true;
			case 0:
				return CheckTierUnlocked(tier);
			case 4:
			{
				RundownTierProgressionData customProgressionLock = expedition.CustomProgressionLock;
				if (CurrentRundownPData.MainClearCount >= customProgressionLock.MainSectors && CurrentRundownPData.SecondaryClearCount >= customProgressionLock.SecondarySectors && CurrentRundownPData.ThirdClearCount >= customProgressionLock.ThirdSectors)
				{
					return CurrentRundownPData.AllClearCount >= customProgressionLock.AllClearedSectors;
				}
				return false;
			}
			case 5:
			{
				ExpeditionIndex unlockedByExpedition = expedition.UnlockedByExpedition;
				string rundownProgressionExpeditionKey = RundownManager.GetRundownProgressionExpeditionKey(unlockedByExpedition.Tier, (int)unlockedByExpedition.Exp);
				return CurrentRundownPData.LPData.ContainsKey(rundownProgressionExpeditionKey);
			}
			default:
				LPLogger.Warning("Unsupported eExpeditionAccessibility: {0}", expedition.Accessibility);
				return true;
			}
		}

		private void SetNativeRundownProgression()
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_00bd: 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_0103: 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_011f: 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_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, Expedition> expeditions = RundownManager.RundownProgression.Expeditions;
			if (expeditions.Count > 0)
			{
				LPLogger.Warning($"Non-empty native rundown progression data! RundownID: {CurrentRundownPData.RundownID}");
				expeditions.Clear();
			}
			Dictionary<string, ExpeditionProgressionData> lPData = CurrentRundownPData.LPData;
			Layer val2 = default(Layer);
			Layer val3 = default(Layer);
			Layer val4 = default(Layer);
			foreach (string key in lPData.Keys)
			{
				Expedition val = new Expedition();
				ExpeditionProgressionData expeditionProgressionData = lPData[key];
				val.AllLayerCompletionCount = expeditionProgressionData.AllClearCount;
				val.Layers = new LayerSet<Layer>();
				val2.CompletionCount = expeditionProgressionData.MainCompletionCount;
				val2.State = (LayerProgressionState)((expeditionProgressionData.MainCompletionCount > 0) ? 3 : 0);
				val3.CompletionCount = expeditionProgressionData.SecondaryCompletionCount;
				val3.State = (LayerProgressionState)((expeditionProgressionData.SecondaryCompletionCount > 0) ? 3 : 0);
				val4.CompletionCount = expeditionProgressionData.ThirdCompletionCount;
				val4.State = (LayerProgressionState)((expeditionProgressionData.ThirdCompletionCount > 0) ? 3 : 0);
				val.Layers.SetLayer((ExpeditionLayers)0, val2);
				val.Layers.SetLayer((ExpeditionLayers)1, val3);
				val.Layers.SetLayer((ExpeditionLayers)2, val4);
				LPLogger.Warning($"{val2.CompletionCount}, {val3.CompletionCount}, {val4.CompletionCount}");
				expeditions[key] = val;
			}
		}

		private void InitConfig()
		{
			if (!Directory.Exists(LP_CONFIG_DIR))
			{
				Directory.CreateDirectory(LP_CONFIG_DIR);
			}
			if (!File.Exists(CONFIG_PATH))
			{
				StreamWriter streamWriter = File.CreateText(CONFIG_PATH);
				streamWriter.WriteLine(JSON.Serialize(new RundownProgressonConfig()));
				streamWriter.Flush();
				streamWriter.Close();
				RundownProgressonConfig = new RundownProgressonConfig();
			}
			ReloadConfig();
			RundownManager.OnRundownProgressionUpdated += Action.op_Implicit((Action)ReloadConfig);
		}

		private void ReloadConfig()
		{
			try
			{
				RundownProgressonConfig = JSON.Deserialize<RundownProgressonConfig>(File.ReadAllText(CONFIG_PATH));
			}
			catch
			{
				LPLogger.Error("Cannot reload RundownProgressonConfig, probably the file is invalid");
				RundownProgressonConfig = new RundownProgressonConfig();
			}
		}

		public bool TryGetRundownConfig(uint RundownID, out RundownConfig rundownConf)
		{
			rundownConf = RundownProgressonConfig.Configs.Find((RundownConfig rundownConf) => rundownConf.RundownID == RundownID);
			return rundownConf != null;
		}

		public bool TryGetExpeditionConfig(uint RundownID, eRundownTier tier, int expIndex, out ExpeditionProgressionConfig expConf)
		{
			//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)
			expConf = null;
			if (TryGetRundownConfig(RundownID, out var rundownConf))
			{
				expConf = rundownConf.Expeditions.Find((ExpeditionProgressionConfig e) => e.Tier == tier && e.ExpeditionIndex == expIndex);
			}
			return expConf != null;
		}

		public void RecordExpeditionSuccessForCurrentRundown(string expeditionKey, bool mainLayerCleared, bool secondaryLayerCleared, bool thirdLayerCleared, bool clearedWithNoBooster)
		{
			if (RundownManager.ActiveExpedition.ExcludeFromProgression)
			{
				return;
			}
			UpdateLPDataToActiveRundown();
			bool flag = mainLayerCleared && secondaryLayerCleared && thirdLayerCleared;
			Dictionary<string, ExpeditionProgressionData> lPData = CurrentRundownPData.LPData;
			if (!lPData.ContainsKey(expeditionKey))
			{
				lPData[expeditionKey] = new ExpeditionProgressionData
				{
					ExpeditionKey = expeditionKey,
					MainCompletionCount = (mainLayerCleared ? 1 : 0),
					SecondaryCompletionCount = (secondaryLayerCleared ? 1 : 0),
					ThirdCompletionCount = (thirdLayerCleared ? 1 : 0),
					AllClearCount = (flag ? 1 : 0),
					NoBoosterAllClearCount = (clearedWithNoBooster ? 1 : 0)
				};
				CurrentRundownPData.MainClearCount += (mainLayerCleared ? 1 : 0);
				CurrentRundownPData.SecondaryClearCount += (secondaryLayerCleared ? 1 : 0);
				CurrentRundownPData.ThirdClearCount += (thirdLayerCleared ? 1 : 0);
				CurrentRundownPData.AllClearCount += (flag ? 1 : 0);
				CurrentRundownPData.NoBoosterAllClearCount += (clearedWithNoBooster ? 1 : 0);
			}
			else
			{
				ExpeditionProgressionData expeditionProgressionData = lPData[expeditionKey];
				if (expeditionProgressionData.MainCompletionCount == 0 && mainLayerCleared)
				{
					CurrentRundownPData.MainClearCount++;
				}
				if (expeditionProgressionData.SecondaryCompletionCount == 0 && secondaryLayerCleared)
				{
					CurrentRundownPData.SecondaryClearCount++;
				}
				if (expeditionProgressionData.ThirdCompletionCount == 0 && thirdLayerCleared)
				{
					CurrentRundownPData.ThirdClearCount++;
				}
				if (expeditionProgressionData.AllClearCount == 0 && flag)
				{
					CurrentRundownPData.AllClearCount++;
				}
				if (expeditionProgressionData.NoBoosterAllClearCount == 0 && clearedWithNoBooster)
				{
					CurrentRundownPData.NoBoosterAllClearCount++;
				}
				expeditionProgressionData.MainCompletionCount += (mainLayerCleared ? 1 : 0);
				expeditionProgressionData.SecondaryCompletionCount += (secondaryLayerCleared ? 1 : 0);
				expeditionProgressionData.ThirdCompletionCount += (thirdLayerCleared ? 1 : 0);
				expeditionProgressionData.AllClearCount += (flag ? 1 : 0);
				expeditionProgressionData.NoBoosterAllClearCount += (clearedWithNoBooster ? 1 : 0);
			}
			SaveRundownLPDataToDisk();
		}

		public void UpdateLPDataToActiveRundown()
		{
			uint num = ActiveRundownID();
			if (num == 0)
			{
				LPLogger.Debug("UpdateLPDataToActiveRundown: cannot find any active rundown!");
				return;
			}
			LPLogger.Warning($"Update LPData to rundown_id: {num}");
			CurrentRundownPData.Reset();
			RundownDataBlock block = GameDataBlockBase<RundownDataBlock>.GetBlock(num);
			if (block == null)
			{
				LPLogger.Error($"Didn't find Rundown Datablock with rundown id {num}");
				return;
			}
			Dictionary<string, ExpeditionProgressionData> dictionary = ReadRundownLPData(((GameDataBlockBase<RundownDataBlock>)(object)block).name);
			CurrentRundownPData.RundownID = num;
			CurrentRundownPData.RundownName = ((GameDataBlockBase<RundownDataBlock>)(object)block).name;
			CurrentRundownPData.LPData = dictionary;
			foreach (ExpeditionProgressionData value in dictionary.Values)
			{
				CurrentRundownPData.MainClearCount += ((value.MainCompletionCount > 0) ? 1 : 0);
				CurrentRundownPData.SecondaryClearCount += ((value.SecondaryCompletionCount > 0) ? 1 : 0);
				CurrentRundownPData.ThirdClearCount += ((value.ThirdCompletionCount > 0) ? 1 : 0);
				CurrentRundownPData.AllClearCount += ((value.AllClearCount > 0) ? 1 : 0);
				CurrentRundownPData.NoBoosterAllClearCount += ((value.NoBoosterAllClearCount > 0) ? 1 : 0);
			}
		}

		internal void Init()
		{
			if (!Directory.Exists(DirPath))
			{
				Directory.CreateDirectory(DirPath);
			}
			RundownManager.OnRundownProgressionUpdated += Action.op_Implicit((Action)OnNativeRundownProgressionUpdated);
			InitConfig();
		}

		internal void OnNativeRundownProgressionUpdated()
		{
			UpdateLPDataToActiveRundown();
			if (!((Object)(object)rundownPage == (Object)null) && ((CM_PageBase)rundownPage).m_isActive)
			{
				UpdateRundownPageExpeditionIconProgression();
			}
		}

		public bool AllSectorCompletedWithoutBoosterAndCheckpoint()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Invalid comparison between Unknown and I4
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Invalid comparison between Unknown and I4
			if (RundownManager.HasSecondaryLayer(RundownManager.ActiveExpedition) && (int)WardenObjectiveManager.CurrentState.second_status != 40)
			{
				return false;
			}
			if (RundownManager.HasThirdLayer(RundownManager.ActiveExpedition) && (int)WardenObjectiveManager.CurrentState.third_status != 40)
			{
				return false;
			}
			bool flag = CheckpointManager.CheckpointUsage == 0;
			if (flag)
			{
				foreach (PlayerBoosterImplantState item in (Il2CppArrayBase<PlayerBoosterImplantState>)(object)BoosterImplantManager.Current.m_boosterPlayers)
				{
					if (item == null)
					{
						continue;
					}
					foreach (pBoosterImplantData item2 in (Il2CppArrayBase<pBoosterImplantData>)(object)item.BoosterImplantDatas)
					{
						if (item2.BoosterImplantID != 0)
						{
							flag = false;
							break;
						}
					}
				}
			}
			return flag;
		}

		public uint ActiveRundownID()
		{
			uint num = default(uint);
			if (!RundownManager.TryGetIdFromLocalRundownKey(RundownManager.ActiveRundownKey, ref num) || num == 0)
			{
				return 0u;
			}
			return num;
		}

		public string ExpeditionKey(eRundownTier tier, int expIndex)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return RundownManager.GetRundownProgressionExpeditionKey(tier, expIndex);
		}

		public ExpeditionProgressionData GetExpeditionLP(uint RundownID, eRundownTier tier, int expIndex)
		{
			//IL_0007: 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)
			ExpeditionProgressionData result = new ExpeditionProgressionData
			{
				ExpeditionKey = ExpeditionKey(tier, expIndex)
			};
			Dictionary<string, ExpeditionProgressionData> dictionary;
			if (CurrentRundownPData.RundownID != RundownID)
			{
				RundownDataBlock block = GameDataBlockBase<RundownDataBlock>.GetBlock(RundownID);
				if (block == null)
				{
					LPLogger.Error($"Didn't find Rundown Datablock with rundown id {RundownID}");
					return result;
				}
				dictionary = ReadRundownLPData(((GameDataBlockBase<RundownDataBlock>)(object)block).name);
			}
			else
			{
				dictionary = CurrentRundownPData.LPData;
			}
			string key = ExpeditionKey(tier, expIndex);
			if (dictionary.TryGetValue(key, out var value))
			{
				return value;
			}
			return result;
		}

		static LocalProgressionManager()
		{
			Current = new LocalProgressionManager();
			DirPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GTFO-Modding", "LocalProgression");
		}

		private LocalProgressionManager()
		{
		}

		private static string RundownLPDataPath(string rundownName)
		{
			char[] invalidPathChars = Path.GetInvalidPathChars();
			foreach (char oldChar in invalidPathChars)
			{
				rundownName = rundownName.Replace(oldChar, '_');
			}
			return Path.Combine(DirPath, rundownName);
		}

		private static string NBSClearDataPath(string rundownName)
		{
			return RundownLPDataPath(rundownName) + " - NBSClear";
		}

		private bool TryReadAggregatedFormatData(string datapath, out Dictionary<string, ExpeditionProgressionData> dataDict)
		{
			dataDict = new Dictionary<string, ExpeditionProgressionData>();
			bool result = true;
			FileStream fileStream = null;
			BinaryReader binaryReader = null;
			try
			{
				fileStream = File.Open(datapath, FileMode.Open);
				binaryReader = new BinaryReader(fileStream, Encoding.UTF8, leaveOpen: false);
				int num = binaryReader.ReadInt32();
				for (int i = 0; i < num; i++)
				{
					ExpeditionProgressionData expeditionProgressionData = new ExpeditionProgressionData();
					expeditionProgressionData.ExpeditionKey = binaryReader.ReadString();
					expeditionProgressionData.MainCompletionCount = binaryReader.ReadInt32();
					expeditionProgressionData.SecondaryCompletionCount = binaryReader.ReadInt32();
					expeditionProgressionData.ThirdCompletionCount = binaryReader.ReadInt32();
					expeditionProgressionData.AllClearCount = binaryReader.ReadInt32();
					expeditionProgressionData.NoBoosterAllClearCount = binaryReader.ReadInt32();
					dataDict[expeditionProgressionData.ExpeditionKey] = expeditionProgressionData;
				}
			}
			catch (EndOfStreamException)
			{
				dataDict.Clear();
				result = false;
			}
			finally
			{
				binaryReader?.Close();
				fileStream?.Close();
			}
			return result;
		}

		private bool TryReadOldFormatData(string datapath, out Dictionary<string, ExpeditionProgressionData> dataDict)
		{
			dataDict = new Dictionary<string, ExpeditionProgressionData>();
			bool result = true;
			FileStream fileStream = null;
			BinaryReader binaryReader = null;
			if (!File.Exists(datapath))
			{
				return true;
			}
			try
			{
				fileStream = File.Open(datapath, FileMode.Open);
				binaryReader = new BinaryReader(fileStream, Encoding.UTF8, leaveOpen: false);
				int num = binaryReader.ReadInt32();
				for (int i = 0; i < num; i++)
				{
					ExpeditionProgressionData expeditionProgressionData = new ExpeditionProgressionData();
					expeditionProgressionData.ExpeditionKey = binaryReader.ReadString();
					expeditionProgressionData.MainCompletionCount = binaryReader.ReadInt32();
					expeditionProgressionData.SecondaryCompletionCount = binaryReader.ReadInt32();
					expeditionProgressionData.ThirdCompletionCount = binaryReader.ReadInt32();
					expeditionProgressionData.AllClearCount = binaryReader.ReadInt32();
					dataDict[expeditionProgressionData.ExpeditionKey] = expeditionProgressionData;
				}
			}
			catch (EndOfStreamException)
			{
				dataDict.Clear();
				result = false;
			}
			finally
			{
				binaryReader?.Close();
				fileStream?.Close();
			}
			return result;
		}

		private bool TryReadNBSClearData(string datapath, out Dictionary<string, ExpeditionProgressionData> dataDict)
		{
			dataDict = new Dictionary<string, ExpeditionProgressionData>();
			bool result = true;
			FileStream fileStream = null;
			BinaryReader binaryReader = null;
			if (!File.Exists(datapath))
			{
				return true;
			}
			try
			{
				fileStream = File.Open(datapath, FileMode.Open);
				binaryReader = new BinaryReader(fileStream, Encoding.UTF8, leaveOpen: false);
				int num = binaryReader.ReadInt32();
				for (int i = 0; i < num; i++)
				{
					ExpeditionProgressionData expeditionProgressionData = new ExpeditionProgressionData();
					expeditionProgressionData.ExpeditionKey = binaryReader.ReadString();
					expeditionProgressionData.NoBoosterAllClearCount = binaryReader.ReadInt32();
					dataDict[expeditionProgressionData.ExpeditionKey] = expeditionProgressionData;
				}
			}
			catch (EndOfStreamException)
			{
				dataDict.Clear();
				result = false;
			}
			finally
			{
				binaryReader?.Close();
				fileStream?.Close();
			}
			return result;
		}

		private void WriteOldFormatDataToDisk(string filepath, Dictionary<string, ExpeditionProgressionData> dataDict)
		{
			using FileStream output = File.Open(filepath, FileMode.Create);
			using BinaryWriter binaryWriter = new BinaryWriter(output, Encoding.UTF8, leaveOpen: false);
			binaryWriter.Write(dataDict.Count);
			foreach (string key in dataDict.Keys)
			{
				ExpeditionProgressionData expeditionProgressionData = dataDict[key];
				binaryWriter.Write(key);
				binaryWriter.Write(expeditionProgressionData.MainCompletionCount);
				binaryWriter.Write(expeditionProgressionData.SecondaryCompletionCount);
				binaryWriter.Write(expeditionProgressionData.ThirdCompletionCount);
				binaryWriter.Write(expeditionProgressionData.AllClearCount);
			}
		}

		private void WriteNBSClearDataToDisk(string filepath, Dictionary<string, ExpeditionProgressionData> dataDict)
		{
			using FileStream output = File.Open(filepath, FileMode.Create);
			using BinaryWriter binaryWriter = new BinaryWriter(output, Encoding.UTF8, leaveOpen: false);
			binaryWriter.Write(dataDict.Count);
			foreach (string key in dataDict.Keys)
			{
				ExpeditionProgressionData expeditionProgressionData = dataDict[key];
				binaryWriter.Write(key);
				binaryWriter.Write(expeditionProgressionData.NoBoosterAllClearCount);
			}
		}

		private Dictionary<string, ExpeditionProgressionData> ReadRundownLPData(string rundownName)
		{
			string text = RundownLPDataPath(rundownName);
			string text2 = NBSClearDataPath(rundownName);
			Dictionary<string, ExpeditionProgressionData> dataDict = new Dictionary<string, ExpeditionProgressionData>();
			if (File.Exists(text))
			{
				if (TryReadAggregatedFormatData(text, out dataDict))
				{
					LPLogger.Warning(rundownName + " - aggregated format");
					WriteOldFormatDataToDisk(text, dataDict);
					WriteNBSClearDataToDisk(text2, dataDict);
					LPLogger.Warning("wrote old format and nbs data");
				}
				else if (TryReadOldFormatData(text, out dataDict))
				{
					LPLogger.Warning(rundownName + " - old format");
					if (TryReadNBSClearData(text2, out var dataDict2))
					{
						foreach (string key in dataDict.Keys)
						{
							dataDict[key].NoBoosterAllClearCount = (dataDict2.TryGetValue(key, out var value) ? value.NoBoosterAllClearCount : 0);
						}
					}
				}
				else
				{
					LPLogger.Error("Something went wrong with localprogression data, contact the plugin developer...");
				}
			}
			return dataDict;
		}

		internal RundownProgressionData GetLPDataForCurrentRundown()
		{
			return CurrentRundownPData;
		}

		private void SaveRundownLPDataToDisk()
		{
			string rundownName = CurrentRundownPData.RundownName;
			Dictionary<string, ExpeditionProgressionData> lPData = CurrentRundownPData.LPData;
			string text = RundownLPDataPath(rundownName);
			string filepath = NBSClearDataPath(rundownName);
			LPLogger.Warning($"SaveData: saving {CurrentRundownPData.RundownName} LPData to '{text}'");
			WriteOldFormatDataToDisk(text, lPData);
			WriteNBSClearDataToDisk(filepath, lPData);
		}
	}
	internal static class LPLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("LocalProgression");

		public static void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		public static void Log(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)8, (object)str);
			}
		}

		public static void Warning(string format, params object[] args)
		{
			Warning(string.Format(format, args));
		}

		public static void Warning(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)4, (object)str);
			}
		}

		public static void Error(string format, params object[] args)
		{
			Error(string.Format(format, args));
		}

		public static void Error(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)2, (object)str);
			}
		}

		public static void Debug(string format, params object[] args)
		{
			Debug(string.Format(format, args));
		}

		public static void Debug(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)32, (object)str);
			}
		}
	}
	public static class Utils
	{
		public static bool TryGetComponent<T>(this GameObject obj, out T comp)
		{
			comp = obj.GetComponent<T>();
			return comp != null;
		}
	}
}
namespace LocalProgression.Patches
{
	[HarmonyPatch]
	internal static class Patches_CM_ExpeditionWindow
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_ExpeditionWindow), "Setup")]
		private static void Post_Setup(CM_ExpeditionWindow __instance)
		{
			ExpeditionWindow_NoBoosterIcon expeditionWindow_NoBoosterIcon = ((Component)__instance).gameObject.AddComponent<ExpeditionWindow_NoBoosterIcon>();
			expeditionWindow_NoBoosterIcon.m_window = __instance;
			expeditionWindow_NoBoosterIcon.InitialSetup();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_ExpeditionWindow), "SetExpeditionInfo")]
		private static void Post_SetExpeditionInfo(CM_ExpeditionWindow __instance)
		{
			//IL_002e: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
			ExpeditionWindow_NoBoosterIcon component = ((Component)__instance).gameObject.GetComponent<ExpeditionWindow_NoBoosterIcon>();
			if (!((Object)(object)component == (Object)null))
			{
				float num = 0f;
				float num2 = 410f;
				((RectTransformComp)__instance.m_sectorIconMain).SetPosition(new Vector2(num, 0f));
				num += num2;
				if (RundownManager.HasSecondaryLayer(__instance.m_data))
				{
					num += num2;
				}
				if (RundownManager.HasThirdLayer(__instance.m_data))
				{
					num += num2;
				}
				ExpeditionProgressionData expeditionLP = LocalProgressionManager.Current.GetExpeditionLP(LocalProgressionManager.Current.ActiveRundownID(), __instance.m_tier, __instance.m_expIndex);
				if (RundownManager.HasAllCompletetionPossibility(__instance.m_data) && expeditionLP.AllClearCount > 0)
				{
					num += num2;
				}
				component.SetIconPosition(new Vector2(num, 0f));
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(CM_ExpeditionWindow), "SetVisible")]
		private static bool Pre_SetVisible(CM_ExpeditionWindow __instance, bool visible, bool inMenuBar)
		{
			//IL_0028: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Invalid comparison between Unknown and I4
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Invalid comparison between Unknown and I4
			//IL_00bf: 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: Invalid comparison between Unknown and I4
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Invalid comparison between Unknown and I4
			//IL_033d: Unknown result type (might be due to invalid IL or missing references)
			ExpeditionWindow_NoBoosterIcon component = ((Component)__instance).GetComponent<ExpeditionWindow_NoBoosterIcon>();
			if (!visible)
			{
				return true;
			}
			if (__instance.m_data == null)
			{
				return true;
			}
			uint rundownID = LocalProgressionManager.Current.ActiveRundownID();
			ExpeditionProgressionData expeditionLP = LocalProgressionManager.Current.GetExpeditionLP(rundownID, __instance.m_tier, __instance.m_expIndex);
			((Component)__instance).gameObject.SetActive(visible);
			((RectTransformComp)__instance.m_joinWindow).SetVisible(!inMenuBar && !SNet.IsInLobby);
			((RectTransformComp)__instance.m_hostButton).SetVisible(!inMenuBar && !SNet.IsInLobby && (int)__instance.m_status != 0 && (int)__instance.m_status != 5 && (int)__instance.m_status != 1);
			((RectTransformComp)__instance.m_changeExpeditionButton).SetVisible(SNet.IsMaster && !((RectTransformComp)__instance.m_hostButton).IsVisible && !inMenuBar && SNet.IsInLobby && RundownManager.ActiveExpedition != null && (int)__instance.m_status != 0 && (int)__instance.m_status != 5 && (int)__instance.m_status != 1);
			__instance.m_bottomStripes.SetActive(!((RectTransformComp)__instance.m_hostButton).IsVisible && !((RectTransformComp)__instance.m_changeExpeditionButton).IsVisible);
			((Component)__instance.m_title).gameObject.SetActive(false);
			((Component)__instance.m_wardenObjective).gameObject.SetActive(false);
			((Component)__instance.m_wardenIntel).gameObject.SetActive(false);
			((Component)__instance.m_depthTitle).gameObject.SetActive(false);
			((Component)__instance.m_artifactHeatTitle).gameObject.SetActive(false);
			CoroutineManager.BlinkIn(__instance.m_title, 0.3f, (Transform)null);
			CoroutineManager.BlinkIn(__instance.m_wardenObjective, 1.1f, (Transform)null);
			CoroutineManager.BlinkIn(__instance.m_wardenIntel, 2.5f, (Transform)null);
			CoroutineManager.BlinkIn(__instance.m_depthTitle, 3f, (Transform)null);
			CoroutineManager.BlinkIn(__instance.m_artifactHeatTitle, 3.25f, (Transform)null);
			float num = 1.8f;
			float num2 = 0.4f;
			__instance.m_sectorIconMain.Setup((LG_LayerType)0, __instance.m_root, true, expeditionLP.MainCompletionCount > 0, true, 0.5f, 0.8f);
			((RectTransformComp)__instance.m_sectorIconMain).SetVisible(false);
			((RectTransformComp)__instance.m_sectorIconSecond).SetVisible(false);
			((RectTransformComp)__instance.m_sectorIconThird).SetVisible(false);
			((RectTransformComp)__instance.m_sectorIconAllCompleted).SetVisible(false);
			component.SetVisible(visible: false);
			__instance.m_sectorIconMain.StopBlink();
			__instance.m_sectorIconSecond.StopBlink();
			__instance.m_sectorIconThird.StopBlink();
			__instance.m_sectorIconAllCompleted.StopBlink();
			__instance.m_sectorIconMain.BlinkIn(num);
			num += num2;
			if (RundownManager.HasSecondaryLayer(__instance.m_data))
			{
				__instance.m_sectorIconSecond.Setup((LG_LayerType)1, __instance.m_root, true, expeditionLP.SecondaryCompletionCount > 0, true, 0.5f, 0.8f);
				__instance.m_sectorIconSecond.BlinkIn(num);
				num += num2;
			}
			if (RundownManager.HasThirdLayer(__instance.m_data))
			{
				__instance.m_sectorIconThird.Setup((LG_LayerType)2, __instance.m_root, true, expeditionLP.ThirdCompletionCount > 0, true, 0.5f, 0.8f);
				__instance.m_sectorIconThird.BlinkIn(num);
				num += num2;
			}
			if (expeditionLP.AllClearCount > 0)
			{
				__instance.m_sectorIconAllCompleted.BlinkIn(num);
				num += num2;
			}
			bool flag = expeditionLP.NoBoosterAllClearCount > 0;
			if ((LocalProgressionManager.Current.TryGetRundownConfig(rundownID, out var rundownConf) && rundownConf.EnableNoBoosterUsedProgressionForRundown && (rundownConf.AlwaysShowIcon || flag)) || (LocalProgressionManager.Current.TryGetExpeditionConfig(rundownID, __instance.m_tier, __instance.m_expIndex, out var expConf) && expConf.EnableNoBoosterUsedProgression && (expConf.AlwaysShowIcon || flag)))
			{
				component.SetupNoBoosterUsedIcon(flag);
				component.BlinkIn(num);
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class Patches_CM_ExpeditionIcon
	{
		private static readonly Color BORDER_COLOR = new Color(0f, 1f, 82f / 85f, 1f);

		private static readonly Color TEXT_COLOR = new Color(0f, 1f, 0.5882353f, 1f);

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_ExpeditionIcon_New), "UpdateBorderColor")]
		private static void Post_UpdateBorderColor(CM_ExpeditionIcon_New __instance)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_0033: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			if ((int)__instance.Status != 5)
			{
				uint rundownID = LocalProgressionManager.Current.ActiveRundownID();
				if (((LocalProgressionManager.Current.TryGetRundownConfig(rundownID, out var rundownConf) && rundownConf.EnableNoBoosterUsedProgressionForRundown) || (LocalProgressionManager.Current.TryGetExpeditionConfig(rundownID, __instance.Tier, __instance.ExpIndex, out var expConf) && expConf.EnableNoBoosterUsedProgression)) && LocalProgressionManager.Current.GetExpeditionLP(rundownID, __instance.Tier, __instance.ExpIndex).NoBoosterAllClearCount > 0)
				{
					__instance.SetBorderColor(BORDER_COLOR);
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_CM_PageExpeditionSuccess
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_PageExpeditionSuccess), "Setup")]
		private static void Post_Setup(CM_PageExpeditionSuccess __instance)
		{
			if ((Object)(object)((Component)__instance).GetComponent<ExpeditionSuccessPage_NoBoosterIcon>() == (Object)null)
			{
				ExpeditionSuccessPage_NoBoosterIcon expeditionSuccessPage_NoBoosterIcon = ((Component)__instance).gameObject.AddComponent<ExpeditionSuccessPage_NoBoosterIcon>();
				expeditionSuccessPage_NoBoosterIcon.m_page = __instance;
				expeditionSuccessPage_NoBoosterIcon.Setup();
			}
		}
	}
	[HarmonyPatch]
	internal class Patches_CM_PageRundown_New
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_PageRundown_New), "Setup")]
		private static void Post_Setup(CM_PageRundown_New __instance)
		{
			LocalProgressionManager.Current.SetCurrentRundownPageInstance(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_PageRundown_New), "PlaceRundown")]
		private static void Post_PlaceRundown(CM_PageRundown_New __instance)
		{
			LocalProgressionManager.Current.OnNativeRundownProgressionUpdated();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_PageRundown_New), "OnEnable")]
		private static void Post_OnEnable(CM_PageRundown_New __instance)
		{
			LocalProgressionManager.Current.OnNativeRundownProgressionUpdated();
		}
	}
	[HarmonyPatch]
	internal class Patches_CM_RundownTierMarker
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_RundownTierMarker), "Setup")]
		private static void Post_Setup(CM_RundownTierMarker __instance)
		{
			RundownTierMarker_NoBoosterIcon rundownTierMarker_NoBoosterIcon = ((Component)__instance).gameObject.AddComponent<RundownTierMarker_NoBoosterIcon>();
			rundownTierMarker_NoBoosterIcon.m_tierMarker = __instance;
			rundownTierMarker_NoBoosterIcon.Setup();
		}
	}
	[HarmonyPatch]
	internal class FixEndScreen
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(DiscordManager), "UpdateDiscordDetails")]
		private static bool Pre_UpdateDiscordDetails()
		{
			return false;
		}
	}
	[HarmonyPatch]
	internal class Patches_GS_ExpeditionSuccess
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(GS_ExpeditionSuccess), "Enter")]
		private static void DoChangeState(GS_ExpeditionSuccess __instance)
		{
			//IL_000c: 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_0029: Invalid comparison between Unknown and I4
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Invalid comparison between Unknown and I4
			pActiveExpedition activeExpeditionData = RundownManager.GetActiveExpeditionData();
			string text = LocalProgressionManager.Current.ExpeditionKey(activeExpeditionData.tier, activeExpeditionData.expeditionIndex);
			bool mainLayerCleared = (int)WardenObjectiveManager.CurrentState.main_status == 40;
			bool secondaryLayerCleared = (int)WardenObjectiveManager.CurrentState.second_status == 40;
			bool thirdLayerCleared = (int)WardenObjectiveManager.CurrentState.third_status == 40;
			bool clearedWithNoBooster = LocalProgressionManager.Current.AllSectorCompletedWithoutBoosterAndCheckpoint();
			LPLogger.Debug("Level cleared, recording - " + text);
			LocalProgressionManager.Current.RecordExpeditionSuccessForCurrentRundown(text, mainLayerCleared, secondaryLayerCleared, thirdLayerCleared, clearedWithNoBooster);
		}
	}
}
namespace LocalProgression.Data
{
	public class ExpeditionProgressionData
	{
		public string ExpeditionKey { get; set; } = string.Empty;


		public int MainCompletionCount { get; set; }

		public int SecondaryCompletionCount { get; set; }

		public int ThirdCompletionCount { get; set; }

		public int AllClearCount { get; set; }

		public int NoBoosterAllClearCount { get; set; }
	}
	public class ExpeditionProgressionConfig
	{
		public eRundownTier Tier { get; set; }

		public int ExpeditionIndex { get; set; }

		public bool EnableNoBoosterUsedProgression { get; set; }

		public bool AlwaysShowIcon { get; set; } = true;

	}
	public class RundownConfig
	{
		public uint RundownID { get; set; }

		public bool EnableNoBoosterUsedProgressionForRundown { get; set; }

		public bool AlwaysShowIcon { get; set; } = true;


		public List<ExpeditionProgressionConfig> Expeditions { get; set; } = new List<ExpeditionProgressionConfig>
		{
			new ExpeditionProgressionConfig()
		};


		internal int ComputeNoBoosterClearPossibleCount()
		{
			if (EnableNoBoosterUsedProgressionForRundown)
			{
				return int.MaxValue;
			}
			return Expeditions.TakeWhile((ExpeditionProgressionConfig conf) => conf.EnableNoBoosterUsedProgression).Count();
		}
	}
	public class RundownProgressonConfig
	{
		public List<RundownConfig> Configs { get; set; } = new List<RundownConfig>
		{
			new RundownConfig()
		};

	}
	public class RundownProgressionData
	{
		public string RundownName { get; set; } = string.Empty;


		public uint RundownID { get; set; }

		public Dictionary<string, ExpeditionProgressionData> LPData { get; set; } = new Dictionary<string, ExpeditionProgressionData>();


		public int MainClearCount { get; set; }

		public int SecondaryClearCount { get; set; }

		public int ThirdClearCount { get; set; }

		public int AllClearCount { get; set; }

		public int NoBoosterAllClearCount { get; set; }

		public void Reset()
		{
			RundownName = string.Empty;
			RundownID = 0u;
			LPData.Clear();
			int num2 = (NoBoosterAllClearCount = 0);
			int num4 = (AllClearCount = num2);
			int num6 = (ThirdClearCount = num4);
			int mainClearCount = (SecondaryClearCount = num6);
			MainClearCount = mainClearCount;
		}
	}
}
namespace LocalProgression.Component
{
	public class ExpeditionSuccessPage_NoBoosterIcon : MonoBehaviour
	{
		internal CM_PageExpeditionSuccess m_page;

		private CM_ExpeditionSectorIcon m_completeWithNoBoosterIcon;

		private SpriteRenderer m_icon;

		private SpriteRenderer m_bg;

		private TextMeshPro m_title;

		private TextMeshPro m_rightSideText;

		private NoBoosterIconGOWrapper Wrapper;

		internal void Setup()
		{
			if ((Object)(object)m_page == (Object)null)
			{
				LPLogger.Error("ExpeditionSuccess_NoBooster: Assign the page instance before setup");
			}
			else
			{
				if ((Object)(object)m_completeWithNoBoosterIcon != (Object)null)
				{
					return;
				}
				if ((Object)(object)Assets.NoBoosterIcon == (Object)null)
				{
					AssetAPI.OnAssetBundlesLoaded += delegate
					{
						LoadAsset();
						AssetAPI.OnAssetBundlesLoaded -= LoadAsset;
					};
				}
				else
				{
					LoadAsset();
				}
			}
		}

		private void LoadAsset()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Assets.NoBoosterIcon == (Object)null)
			{
				LPLogger.Error("ExpeditionSuccess_NoBooster.Setup: cannot instantiate NoBooster icon...");
				return;
			}
			m_completeWithNoBoosterIcon = ((Il2CppObjectBase)((GuiLayer)((CM_PageBase)m_page).m_guiLayer).AddRectComp(Assets.NoBoosterIcon, (GuiAnchor)1, new Vector2(1200f, 0f), m_page.m_sectorIconAlign)).Cast<CM_ExpeditionSectorIcon>();
			Wrapper = new NoBoosterIconGOWrapper(((Component)m_completeWithNoBoosterIcon).gameObject);
			m_bg = Wrapper.BGGO.GetComponent<SpriteRenderer>();
			m_icon = Wrapper.IconGO.GetComponent<SpriteRenderer>();
			m_title = Object.Instantiate<TextMeshPro>(m_page.m_sectorIconMain.m_title);
			m_title.transform.SetParent(Wrapper.ObjectiveIcon.transform, false);
			m_rightSideText = Object.Instantiate<TextMeshPro>(m_page.m_sectorIconMain.m_rightSideText);
			m_rightSideText.transform.SetParent(Wrapper.RightSideText.transform, false);
			m_completeWithNoBoosterIcon.m_title = m_title;
			m_completeWithNoBoosterIcon.m_rightSideText = m_rightSideText;
			((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(false);
		}

		private void OnEnable()
		{
			//IL_003b: 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: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Invalid comparison between Unknown and I4
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(false);
			uint rundownID = LocalProgressionManager.Current.ActiveRundownID();
			pActiveExpedition activeExpeditionData = RundownManager.GetActiveExpeditionData();
			if ((LocalProgressionManager.Current.TryGetRundownConfig(rundownID, out var rundownConf) && rundownConf.EnableNoBoosterUsedProgressionForRundown) || (LocalProgressionManager.Current.TryGetExpeditionConfig(rundownID, activeExpeditionData.tier, activeExpeditionData.expeditionIndex, out var expConf) && expConf.EnableNoBoosterUsedProgression))
			{
				bool boosterUnused = LocalProgressionManager.Current.AllSectorCompletedWithoutBoosterAndCheckpoint();
				int num = 1;
				bool flag = RundownManager.HasSecondaryLayer(RundownManager.ActiveExpedition);
				bool flag2 = RundownManager.HasThirdLayer(RundownManager.ActiveExpedition);
				num += (flag ? 1 : 0);
				num += (flag2 ? 1 : 0);
				num += ((flag && (int)WardenObjectiveManager.CurrentState.second_status == 40 && flag2 && (int)WardenObjectiveManager.CurrentState.second_status == 40) ? 1 : 0);
				float num2 = m_page.m_time_sectorIcon + (float)num * 0.7f;
				SetupNoBoosterUsedIcon(boosterUnused);
				((RectTransformComp)m_completeWithNoBoosterIcon).SetPosition(new Vector2((float)num * 400f, 0f));
				m_completeWithNoBoosterIcon.BlinkIn(num2);
			}
		}

		private void SetupNoBoosterUsedIcon(bool boosterUnused)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: 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_00c5: 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_00e1: 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)
			CM_ExpeditionSectorIcon completeWithNoBoosterIcon = m_completeWithNoBoosterIcon;
			completeWithNoBoosterIcon.m_isFinishedAll = true;
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconMainSkull, completeWithNoBoosterIcon.m_iconMainBG, false, false, 0.5f, 0.7f);
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconSecondarySkull, completeWithNoBoosterIcon.m_iconSecondaryBG, false, false, 0.5f, 0.7f);
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconThirdSkull, completeWithNoBoosterIcon.m_iconThirdBG, false, false, 0.5f, 0.7f);
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconFinishedAllSkull, completeWithNoBoosterIcon.m_iconFinishedAllBG, false, false, 0.5f, 0.7f);
			Color color = m_icon.color;
			Color color2 = m_bg.color;
			m_icon.color = new Color(color.r, color.g, color.b, boosterUnused ? 1f : 0.4f);
			m_bg.color = new Color(color2.r, color2.g, color2.b, boosterUnused ? 1f : 0.3f);
			((TMP_Text)m_title).alpha = (boosterUnused ? 1f : 0.2f);
			completeWithNoBoosterIcon.m_titleVisible = true;
			completeWithNoBoosterIcon.m_isCleared = boosterUnused;
			if (boosterUnused)
			{
				completeWithNoBoosterIcon.m_isFinishedAll = true;
			}
			else
			{
				completeWithNoBoosterIcon.m_isFinishedAll = false;
				completeWithNoBoosterIcon.m_type = (LG_LayerType)0;
			}
			((Component)completeWithNoBoosterIcon.m_rightSideText).gameObject.SetActive(false);
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.ExpeditionSuccessPage.AllClearWithNoBoosterUsed");
			if (block != null)
			{
				((TMP_Text)completeWithNoBoosterIcon.m_title).SetText(Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID), true);
			}
			else
			{
				((TMP_Text)completeWithNoBoosterIcon.m_title).SetText("<color=orange>OMNIPOTENT</color>", true);
			}
			((Component)completeWithNoBoosterIcon.m_title).gameObject.SetActive(true);
		}

		private void OnDestroy()
		{
			m_icon = (m_bg = null);
			m_completeWithNoBoosterIcon = null;
			Wrapper.Destory();
		}

		static ExpeditionSuccessPage_NoBoosterIcon()
		{
			ClassInjector.RegisterTypeInIl2Cpp<ExpeditionSuccessPage_NoBoosterIcon>();
		}
	}
	internal class ExpeditionWindow_NoBoosterIcon : MonoBehaviour
	{
		internal CM_ExpeditionWindow m_window;

		private CM_ExpeditionSectorIcon m_completeWithNoBoosterIcon;

		private NoBoosterIconGOWrapper Wrapper;

		private SpriteRenderer m_icon;

		private SpriteRenderer m_bg;

		private TextMeshPro m_title;

		private TextMeshPro m_rightSideText;

		internal void InitialSetup()
		{
			if ((Object)(object)m_window == (Object)null)
			{
				LPLogger.Error("ExpeditionSuccess_NoBooster: Assign the page instance before setup");
			}
			else
			{
				if ((Object)(object)m_completeWithNoBoosterIcon != (Object)null)
				{
					return;
				}
				if ((Object)(object)Assets.NoBoosterIcon == (Object)null)
				{
					AssetAPI.OnAssetBundlesLoaded += delegate
					{
						LoadAsset();
						AssetAPI.OnAssetBundlesLoaded -= LoadAsset;
					};
				}
				else
				{
					LoadAsset();
				}
			}
		}

		private void LoadAsset()
		{
			if ((Object)(object)Assets.NoBoosterIcon == (Object)null)
			{
				LPLogger.Error("ExpeditionSuccess_NoBooster.Setup: cannot instantiate NoBooster icon...");
				return;
			}
			m_completeWithNoBoosterIcon = GOUtil.SpawnChildAndGetComp<CM_ExpeditionSectorIcon>(Assets.NoBoosterIcon, m_window.m_sectorIconAlign);
			Wrapper = new NoBoosterIconGOWrapper(((Component)m_completeWithNoBoosterIcon).gameObject);
			m_bg = Wrapper.BGGO.GetComponent<SpriteRenderer>();
			m_icon = Wrapper.IconGO.GetComponent<SpriteRenderer>();
			m_title = Object.Instantiate<TextMeshPro>(m_window.m_sectorIconMain.m_title);
			m_title.transform.SetParent(Wrapper.ObjectiveIcon.transform, false);
			m_rightSideText = Object.Instantiate<TextMeshPro>(m_window.m_sectorIconMain.m_rightSideText);
			m_rightSideText.transform.SetParent(Wrapper.RightSideText.transform, false);
			m_completeWithNoBoosterIcon.m_title = m_title;
			m_completeWithNoBoosterIcon.m_rightSideText = m_rightSideText;
			((RectTransformComp)m_completeWithNoBoosterIcon).SetAnchor((GuiAnchor)1, true);
			((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(false);
			m_completeWithNoBoosterIcon.SortAsPopupLayer();
			m_completeWithNoBoosterIcon.m_root = m_window.m_root;
		}

		internal void SetVisible(bool visible)
		{
			((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(visible);
		}

		internal void SetIconPosition(Vector2 position)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			((RectTransformComp)m_completeWithNoBoosterIcon).SetPosition(position);
		}

		internal void BlinkIn(float delay)
		{
			m_completeWithNoBoosterIcon.BlinkIn(delay);
		}

		internal void SetupNoBoosterUsedIcon(bool boosterUnused)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: 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_00c5: 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_00e1: 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)
			CM_ExpeditionSectorIcon completeWithNoBoosterIcon = m_completeWithNoBoosterIcon;
			completeWithNoBoosterIcon.m_isFinishedAll = true;
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconMainSkull, completeWithNoBoosterIcon.m_iconMainBG, false, false, 0.5f, 0.7f);
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconSecondarySkull, completeWithNoBoosterIcon.m_iconSecondaryBG, false, false, 0.5f, 0.7f);
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconThirdSkull, completeWithNoBoosterIcon.m_iconThirdBG, false, false, 0.5f, 0.7f);
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconFinishedAllSkull, completeWithNoBoosterIcon.m_iconFinishedAllBG, false, false, 0.5f, 0.7f);
			Color color = m_icon.color;
			Color color2 = m_bg.color;
			m_icon.color = new Color(color.r, color.g, color.b, boosterUnused ? 1f : 0.4f);
			m_bg.color = new Color(color2.r, color2.g, color2.b, boosterUnused ? 1f : 0.3f);
			((TMP_Text)m_title).alpha = (boosterUnused ? 1f : 0.2f);
			completeWithNoBoosterIcon.m_titleVisible = true;
			completeWithNoBoosterIcon.m_isCleared = boosterUnused;
			if (boosterUnused)
			{
				completeWithNoBoosterIcon.m_isFinishedAll = true;
			}
			else
			{
				completeWithNoBoosterIcon.m_isFinishedAll = false;
				completeWithNoBoosterIcon.m_type = (LG_LayerType)0;
			}
			((Component)completeWithNoBoosterIcon.m_rightSideText).gameObject.SetActive(false);
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.ExpeditionSuccessPage.AllClearWithNoBoosterUsed");
			if (block != null)
			{
				((TMP_Text)completeWithNoBoosterIcon.m_title).SetText(Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID), true);
			}
			else
			{
				((TMP_Text)completeWithNoBoosterIcon.m_title).SetText("<color=orange>OMNIPOTENT</color>", true);
			}
			((Component)completeWithNoBoosterIcon.m_title).gameObject.SetActive(true);
		}

		private void OnDestroy()
		{
			m_icon = (m_bg = null);
			m_completeWithNoBoosterIcon = null;
			Wrapper.Destory();
		}

		static ExpeditionWindow_NoBoosterIcon()
		{
			ClassInjector.RegisterTypeInIl2Cpp<ExpeditionWindow_NoBoosterIcon>();
		}
	}
	public class NoBoosterIconGOWrapper
	{
		public GameObject GameObject { get; private set; }

		public GameObject ObjectiveIcon
		{
			get
			{
				GameObject gameObject = GameObject;
				if (gameObject == null)
				{
					return null;
				}
				return ((Component)gameObject.transform.GetChild(0)).gameObject;
			}
		}

		public GameObject BGHolder
		{
			get
			{
				GameObject objectiveIcon = ObjectiveIcon;
				if (objectiveIcon == null)
				{
					return null;
				}
				return ((Component)objectiveIcon.transform.GetChild(2)).gameObject;
			}
		}

		public GameObject SkullHolder
		{
			get
			{
				GameObject objectiveIcon = ObjectiveIcon;
				if (objectiveIcon == null)
				{
					return null;
				}
				return ((Component)objectiveIcon.transform.GetChild(3)).gameObject;
			}
		}

		public GameObject BGGO
		{
			get
			{
				GameObject bGHolder = BGHolder;
				if (bGHolder == null)
				{
					return null;
				}
				return ((Component)bGHolder.transform.GetChild(4)).gameObject;
			}
		}

		public GameObject IconGO
		{
			get
			{
				GameObject skullHolder = SkullHolder;
				if (skullHolder == null)
				{
					return null;
				}
				return ((Component)skullHolder.transform.GetChild(4)).gameObject;
			}
		}

		public GameObject TitleGO
		{
			get
			{
				GameObject objectiveIcon = ObjectiveIcon;
				if (objectiveIcon == null)
				{
					return null;
				}
				return ((Component)objectiveIcon.transform.GetChild(1)).gameObject;
			}
		}

		public GameObject RightSideText
		{
			get
			{
				GameObject gameObject = GameObject;
				if (gameObject == null)
				{
					return null;
				}
				return ((Component)gameObject.transform.GetChild(2)).gameObject;
			}
		}

		public NoBoosterIconGOWrapper(GameObject iconGO)
		{
			GameObject = iconGO;
		}

		public void Destory()
		{
			if ((Object)(object)GameObject != (Object)null)
			{
				Object.Destroy((Object)(object)GameObject);
			}
			GameObject = null;
		}
	}
	internal class RundownTierMarker_NoBoosterIcon : MonoBehaviour
	{
		internal CM_RundownTierMarker m_tierMarker;

		private CM_ExpeditionSectorIcon m_completeWithNoBoosterIcon;

		private SpriteRenderer m_icon;

		private SpriteRenderer m_bg;

		private TextMeshPro m_title;

		private TextMeshPro m_rightSideText;

		private NoBoosterIconGOWrapper Wrapper;

		internal void Setup()
		{
			if ((Object)(object)m_tierMarker == (Object)null)
			{
				LPLogger.Error("ExpeditionSuccess_NoBooster: Assign the page instance before setup");
			}
			else
			{
				if ((Object)(object)m_completeWithNoBoosterIcon != (Object)null)
				{
					return;
				}
				if ((Object)(object)Assets.NoBoosterIcon == (Object)null)
				{
					AssetAPI.OnAssetBundlesLoaded += delegate
					{
						LoadAsset();
						AssetAPI.OnAssetBundlesLoaded -= LoadAsset;
					};
				}
				else
				{
					LoadAsset();
				}
			}
		}

		private void LoadAsset()
		{
			//IL_0139: 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_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: 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_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Assets.NoBoosterIcon == (Object)null)
			{
				LPLogger.Error("ExpeditionSuccess_NoBooster.Setup: cannot instantiate NoBooster icon...");
				return;
			}
			m_completeWithNoBoosterIcon = GOUtil.SpawnChildAndGetComp<CM_ExpeditionSectorIcon>(Assets.NoBoosterIcon, m_tierMarker.m_sectorIconAlign_main);
			Wrapper = new NoBoosterIconGOWrapper(((Component)m_completeWithNoBoosterIcon).gameObject);
			m_bg = Wrapper.BGGO.GetComponent<SpriteRenderer>();
			m_icon = Wrapper.IconGO.GetComponent<SpriteRenderer>();
			m_title = Object.Instantiate<TextMeshPro>(m_tierMarker.m_sectorIconSummaryMain.m_title);
			m_title.transform.SetParent(Wrapper.ObjectiveIcon.transform, false);
			m_rightSideText = Object.Instantiate<TextMeshPro>(m_tierMarker.m_sectorIconSummaryMain.m_rightSideText);
			m_rightSideText.transform.SetParent(Wrapper.RightSideText.transform, false);
			m_completeWithNoBoosterIcon.m_title = m_title;
			m_completeWithNoBoosterIcon.m_rightSideText = m_rightSideText;
			SetupNoBoosterUsedIcon(boosterUnused: true);
			float num = 0.16f;
			Vector3 localScale = default(Vector3);
			((Vector3)(ref localScale))..ctor(num, num, num);
			_ = num / 0.16f;
			((Component)m_completeWithNoBoosterIcon).transform.localScale = localScale;
			Vector2 val = ((RectTransformComp)m_tierMarker.m_sectorIconSummarySecondary).GetPosition() - ((RectTransformComp)m_tierMarker.m_sectorIconSummaryMain).GetPosition();
			((RectTransformComp)m_completeWithNoBoosterIcon).SetPosition(val * 4f);
			((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(false);
		}

		internal void SetVisible(bool visible)
		{
			((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(visible);
		}

		internal void SetSectorIconText(string text)
		{
			((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(true);
			m_completeWithNoBoosterIcon.SetRightSideText(text);
		}

		private void SetupNoBoosterUsedIcon(bool boosterUnused)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: 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_00c5: 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_00e1: 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)
			CM_ExpeditionSectorIcon completeWithNoBoosterIcon = m_completeWithNoBoosterIcon;
			completeWithNoBoosterIcon.m_isFinishedAll = true;
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconMainSkull, completeWithNoBoosterIcon.m_iconMainBG, false, false, 0.5f, 0.7f);
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconSecondarySkull, completeWithNoBoosterIcon.m_iconSecondaryBG, false, false, 0.5f, 0.7f);
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconThirdSkull, completeWithNoBoosterIcon.m_iconThirdBG, false, false, 0.5f, 0.7f);
			completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconFinishedAllSkull, completeWithNoBoosterIcon.m_iconFinishedAllBG, false, false, 0.5f, 0.7f);
			Color color = m_icon.color;
			Color color2 = m_bg.color;
			m_icon.color = new Color(color.r, color.g, color.b, boosterUnused ? 1f : 0.4f);
			m_bg.color = new Color(color2.r, color2.g, color2.b, boosterUnused ? 1f : 0.3f);
			((TMP_Text)m_title).alpha = (boosterUnused ? 1f : 0.2f);
			completeWithNoBoosterIcon.m_titleVisible = true;
			completeWithNoBoosterIcon.m_isCleared = boosterUnused;
			if (boosterUnused)
			{
				completeWithNoBoosterIcon.m_isFinishedAll = true;
			}
			else
			{
				completeWithNoBoosterIcon.m_isFinishedAll = false;
				completeWithNoBoosterIcon.m_type = (LG_LayerType)0;
			}
			((Component)completeWithNoBoosterIcon.m_rightSideText).gameObject.SetActive(false);
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.ExpeditionSuccessPage.AllClearWithNoBoosterUsed");
			if (block != null)
			{
				((TMP_Text)completeWithNoBoosterIcon.m_title).SetText(Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID), true);
			}
			else
			{
				((TMP_Text)completeWithNoBoosterIcon.m_title).SetText("<color=orange>OMNIPOTENT</color>", true);
			}
			((Component)completeWithNoBoosterIcon.m_title).gameObject.SetActive(true);
		}

		static RundownTierMarker_NoBoosterIcon()
		{
			ClassInjector.RegisterTypeInIl2Cpp<RundownTierMarker_NoBoosterIcon>();
		}
	}
}

plugins/randomuserhi-AggroFix/AggroFix.dll

Decompiled 7 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using AIGraph;
using API;
using Agents;
using AggroFix.BepInEx;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Enemies;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using StateMachines;
using UnityEngine;
using UnityEngine.Analytics;

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

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace AggroFix
{
	[HarmonyPatch]
	internal static class Fix
	{
		private static bool patch = true;

		private static bool IsTargetReachable(AIG_CourseNode source, AIG_CourseNode target)
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Invalid comparison between Unknown and I4
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Invalid comparison between Unknown and I4
			if (source == null || target == null)
			{
				return false;
			}
			if (source.NodeID == target.NodeID)
			{
				return true;
			}
			AIG_SearchID.IncrementSearchID();
			ushort searchID = AIG_SearchID.SearchID;
			Queue<AIG_CourseNode> queue = new Queue<AIG_CourseNode>();
			queue.Enqueue(source);
			while (queue.Count > 0)
			{
				AIG_CourseNode val = queue.Dequeue();
				((AIG_CourseGraphMember)val).m_searchID = searchID;
				Enumerator<AIG_CoursePortal> enumerator = val.m_portals.GetEnumerator();
				while (enumerator.MoveNext())
				{
					AIG_CoursePortal current = enumerator.Current;
					LG_Gate gate = current.Gate;
					object obj;
					if (gate == null)
					{
						obj = null;
					}
					else
					{
						iLG_Door_Core spawnedDoor = gate.SpawnedDoor;
						obj = ((spawnedDoor != null) ? ((Il2CppObjectBase)spawnedDoor).TryCast<LG_SecurityDoor>() : null);
					}
					LG_SecurityDoor val2 = (LG_SecurityDoor)obj;
					if ((Object)(object)val2 != (Object)null && (int)val2.LastStatus != 10 && (int)val2.LastStatus != 16)
					{
						continue;
					}
					AIG_CourseNode oppositeNode = current.GetOppositeNode(val);
					if (((AIG_CourseGraphMember)oppositeNode).m_searchID != searchID)
					{
						if (oppositeNode.NodeID == target.NodeID)
						{
							return true;
						}
						queue.Enqueue(oppositeNode);
					}
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(EnemyCourseNavigation), "UpdateTracking")]
		[HarmonyPostfix]
		private static void UpdateTracking(EnemyCourseNavigation __instance)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Invalid comparison between Unknown and I4
			if (!patch || !SNet.IsMaster)
			{
				return;
			}
			EnemyAgent owner = __instance.m_owner;
			if (((Agent)owner).CourseNode == null || __instance.m_targetRef == null || (Object)(object)__instance.m_targetRef.m_agent == (Object)null || (int)((StateMachine<ES_Base>)(object)owner.Locomotion).m_currentState.m_stateEnum == 14)
			{
				return;
			}
			if (!IsTargetReachable(((Agent)owner).CourseNode, __instance.m_targetRef.m_agent.CourseNode))
			{
				APILogger.Debug("Invalid current " + ((Il2CppObjectBase)__instance.m_targetRef.m_agent).Cast<PlayerAgent>().Owner.NickName);
				bool flag = false;
				int num = Random.RandomRangeInt(0, PlayerManager.PlayerAgentsInLevel.Count);
				PlayerAgent val = PlayerManager.PlayerAgentsInLevel[num];
				for (int i = 0; i < PlayerManager.PlayerAgentsInLevel.Count; i++)
				{
					APILogger.Debug("Checking " + val.Owner.NickName);
					if (((Agent)val).Alive && ((Object)val).GetInstanceID() != ((Object)__instance.m_targetRef.m_agent).GetInstanceID() && IsTargetReachable(((Agent)owner).CourseNode, ((Agent)val).CourseNode))
					{
						flag = true;
						break;
					}
					num = (num + 1) % PlayerManager.PlayerAgentsInLevel.Count;
					val = PlayerManager.PlayerAgentsInLevel[num];
				}
				if (flag)
				{
					APILogger.Debug("Rerouted to " + val.Owner.NickName);
					patch = false;
					((AgentAI)owner.AI).SetTarget((Agent)(object)val);
					patch = true;
				}
				else
				{
					APILogger.Debug("No valid target found " + ((Il2CppObjectBase)__instance.m_targetRef.m_agent).Cast<PlayerAgent>().Owner.NickName);
				}
			}
			else
			{
				APILogger.Debug("Current " + ((Il2CppObjectBase)__instance.m_targetRef.m_agent).Cast<PlayerAgent>().Owner.NickName);
			}
		}
	}
}
namespace AggroFix.BepInEx
{
	public static class Module
	{
		public const string GUID = "randomuserhi.AggroFix";

		public const string Name = "AggroFix";

		public const string Version = "0.0.1";
	}
	public static class ConfigManager
	{
		public static ConfigFile configFile;

		private static ConfigEntry<bool> debug;

		public static bool Debug
		{
			get
			{
				return debug.Value;
			}
			set
			{
				debug.Value = value;
			}
		}

		static ConfigManager()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, "AggroFix.cfg"), true);
			debug = configFile.Bind<bool>("Debug", "enable", false, "Enables debug messages when true.");
		}
	}
	[BepInPlugin("randomuserhi.AggroFix", "AggroFix", "0.0.1")]
	public class Plugin : BasePlugin
	{
		private static Harmony? harmony;

		public override void Load()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			APILogger.Log("Plugin is loaded!");
			harmony = new Harmony("randomuserhi.AggroFix");
			harmony.PatchAll();
			APILogger.Log("Debug is " + (ConfigManager.Debug ? "Enabled" : "Disabled"));
		}
	}
}
namespace API
{
	[HarmonyPatch(typeof(GameDataInit))]
	internal class GameDataInit_Patches
	{
		[HarmonyPatch("Initialize")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		public static void Initialize_Postfix()
		{
			Analytics.enabled = false;
		}
	}
	internal static class APILogger
	{
		private static readonly ManualLogSource logger;

		static APILogger()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			logger = new ManualLogSource("Rand-API");
			Logger.Sources.Add((ILogSource)(object)logger);
		}

		private static string Format(string module, object msg)
		{
			return $"[{module}]: {msg}";
		}

		public static void Info(string module, object data)
		{
			logger.LogMessage((object)Format(module, data));
		}

		public static void Verbose(string module, object data)
		{
		}

		public static void Log(object data)
		{
			logger.LogDebug((object)Format("AggroFix", data));
		}

		public static void Debug(object data)
		{
			if (ConfigManager.Debug)
			{
				Log(data);
			}
		}

		public static void Warn(object data)
		{
			logger.LogWarning((object)Format("AggroFix", data));
		}

		public static void Error(object data)
		{
			logger.LogError((object)Format("AggroFix", data));
		}
	}
}

plugins/randomuserhi-DamageSync/DamageSync.dll

Decompiled 7 hours ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using API;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using GameData;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using SNetwork;
using UnityEngine.Analytics;

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

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace DamageSync
{
	public static class ConfigManager
	{
		private static ConfigEntry<bool> debug;

		public static bool Debug => debug.Value;

		static ConfigManager()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			debug = new ConfigFile(Path.Combine(Paths.ConfigPath, "DamageSync.cfg"), true).Bind<bool>("Debug", "enable", false, "Enables debug messages when true.");
		}
	}
	public static class Module
	{
		public const string GUID = "randomuserhi.DamageSync";

		public const string Name = "DamageSync";

		public const string Version = "0.0.4";
	}
	[BepInPlugin("randomuserhi.DamageSync", "DamageSync", "0.0.4")]
	internal class Entry : BasePlugin
	{
		private Harmony harmony;

		public override void Load()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			APILogger.Debug("DamageSync", "Loaded DamageSync");
			harmony = new Harmony("randomuserhi.DamageSync");
			harmony.PatchAll();
			APILogger.Debug("DamageSync", "Debug is " + (ConfigManager.Debug ? "Enabled" : "Disabled"));
		}
	}
}
namespace DamageSync.Patches
{
	[HarmonyPatch(typeof(GameDataInit))]
	internal class GameDataInit_Patches
	{
		[HarmonyPatch("Initialize")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		public static void Initialize_Postfix()
		{
			Analytics.enabled = false;
		}
	}
	[HarmonyPatch]
	internal class DamageSync
	{
		[HarmonyPatch(typeof(Dam_EnemyDamageBase), "ProcessReceivedDamage")]
		[HarmonyPostfix]
		public static void ProcessReceivedDamage(Dam_EnemyDamageBase __instance)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (SNet.IsMaster)
			{
				pSetHealthData val = default(pSetHealthData);
				((SFloat16)(ref val.health)).Set(((Dam_SyncedDamageBase)__instance).Health, ((Dam_SyncedDamageBase)__instance).HealthMax);
				((Dam_SyncedDamageBase)__instance).m_setHealthPacket.Send(val, (SNet_ChannelType)3);
				if (ConfigManager.Debug)
				{
					APILogger.Debug("DamageSync", $"Sent health value: {((Dam_SyncedDamageBase)__instance).Health}");
				}
			}
		}

		[HarmonyPatch(typeof(Dam_EnemyDamageBase), "ReceiveSetHealth")]
		[HarmonyPostfix]
		public static void ReceiveSetHealth(Dam_EnemyDamageBase __instance)
		{
			if (!SNet.IsMaster && ConfigManager.Debug)
			{
				APILogger.Debug("DamageSync", $"Received health value: {((Dam_SyncedDamageBase)__instance).Health}");
			}
		}
	}
}
namespace API
{
	internal static class APILogger
	{
		private static readonly ManualLogSource logger;

		static APILogger()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			logger = new ManualLogSource("Rand-API");
			Logger.Sources.Add((ILogSource)(object)logger);
		}

		private static string Format(string module, object msg)
		{
			return $"[{module}]: {msg}";
		}

		public static void Info(string module, object data)
		{
			logger.LogMessage((object)Format(module, data));
		}

		public static void Verbose(string module, object data)
		{
		}

		public static void Debug(string module, object data)
		{
			logger.LogDebug((object)Format(module, data));
		}

		public static void Warn(string module, object data)
		{
			logger.LogWarning((object)Format(module, data));
		}

		public static void Error(string module, object data)
		{
			logger.LogError((object)Format(module, data));
		}
	}
}

plugins/randomuserhi-KillIndicatorFix/KillIndicatorFix.dll

Decompiled 7 hours 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 System.Text;
using API;
using Agents;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Enemies;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using KillIndicatorFix.BepInEx;
using KillIndicatorFix.Patches;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using UnityEngine;
using UnityEngine.Analytics;

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

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
internal static class BitHelper
{
	public const int SizeOfHalf = 2;

	public const int SizeOfVector3 = 12;

	public const int SizeOfQuaternion = 13;

	public const int SizeOfHalfVector3 = 6;

	public const int SizeOfHalfQuaternion = 7;

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	private static uint RotateLeft(uint value, int offset)
	{
		return (value << offset) | (value >> 32 - offset);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	private static uint RotateRight(uint value, int offset)
	{
		return (value >> offset) | (value << 32 - offset);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static long ReverseEndianness(long value)
	{
		return (long)ReverseEndianness((ulong)value);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static int ReverseEndianness(int value)
	{
		return (int)ReverseEndianness((uint)value);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static short ReverseEndianness(short value)
	{
		return (short)ReverseEndianness((ushort)value);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	private static ushort ReverseEndianness(ushort value)
	{
		return (ushort)((value >> 8) + (value << 8));
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	private static uint ReverseEndianness(uint value)
	{
		return RotateRight(value & 0xFF00FFu, 8) + RotateLeft(value & 0xFF00FF00u, 8);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	private static ulong ReverseEndianness(ulong value)
	{
		return ((ulong)ReverseEndianness((uint)value) << 32) + ReverseEndianness((uint)(value >> 32));
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	private unsafe static void _WriteBytes(byte* source, int size, byte[] destination, ref int index)
	{
		int num = 0;
		while (num < size)
		{
			destination[index++] = source[num++];
		}
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static void WriteBytes(byte value, byte[] destination, ref int index)
	{
		destination[index++] = value;
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static void WriteBytes(bool value, byte[] destination, ref int index)
	{
		destination[index++] = (value ? ((byte)1) : ((byte)0));
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static void WriteBytes(ulong value, byte[] destination, ref int index)
	{
		if (!BitConverter.IsLittleEndian)
		{
			value = ReverseEndianness(value);
		}
		_WriteBytes((byte*)(&value), 8, destination, ref index);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static void WriteBytes(uint value, byte[] destination, ref int index)
	{
		if (!BitConverter.IsLittleEndian)
		{
			value = ReverseEndianness(value);
		}
		_WriteBytes((byte*)(&value), 4, destination, ref index);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static void WriteBytes(ushort value, byte[] destination, ref int index)
	{
		if (!BitConverter.IsLittleEndian)
		{
			value = ReverseEndianness(value);
		}
		_WriteBytes((byte*)(&value), 2, destination, ref index);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static void WriteBytes(long value, byte[] destination, ref int index)
	{
		if (!BitConverter.IsLittleEndian)
		{
			value = ReverseEndianness(value);
		}
		_WriteBytes((byte*)(&value), 8, destination, ref index);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static void WriteBytes(int value, byte[] destination, ref int index)
	{
		if (!BitConverter.IsLittleEndian)
		{
			value = ReverseEndianness(value);
		}
		_WriteBytes((byte*)(&value), 4, destination, ref index);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static void WriteBytes(short value, byte[] destination, ref int index)
	{
		if (!BitConverter.IsLittleEndian)
		{
			value = ReverseEndianness(value);
		}
		_WriteBytes((byte*)(&value), 2, destination, ref index);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static void WriteBytes(float value, byte[] destination, ref int index)
	{
		int value2 = *(int*)(&value);
		if (!BitConverter.IsLittleEndian)
		{
			value2 = ReverseEndianness(value2);
		}
		_WriteBytes((byte*)(&value2), 4, destination, ref index);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static void WriteBytes(string value, byte[] destination, ref int index)
	{
		byte[] bytes = Encoding.UTF8.GetBytes(value);
		WriteBytes((ushort)bytes.Length, destination, ref index);
		Array.Copy(bytes, 0, destination, index, bytes.Length);
		index += bytes.Length;
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static void WriteBytes(byte[] buffer, byte[] destination, ref int index)
	{
		WriteBytes((ushort)buffer.Length, destination, ref index);
		Array.Copy(buffer, 0, destination, index, buffer.Length);
		index += buffer.Length;
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static void WriteHalf(float value, byte[] destination, ref int index)
	{
		WriteBytes(FloatToHalf(value), destination, ref index);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	private unsafe static uint AsUInt(float x)
	{
		return *(uint*)(&x);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	private unsafe static float AsFloat(uint x)
	{
		return *(float*)(&x);
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static float HalfToFloat(ushort x)
	{
		int num = (x & 0x7C00) >> 10;
		int num2 = (x & 0x3FF) << 13;
		int num3 = (int)(AsUInt(num2) >> 23);
		return AsFloat((uint)(((x & 0x8000) << 16) | (Convert.ToInt32(num != 0) * ((num + 112 << 23) | num2)) | ((Convert.ToInt32(num == 0) & Convert.ToInt32(num2 != 0)) * ((num3 - 37 << 23) | ((num2 << 150 - num3) & 0x7FE000)))));
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static ushort FloatToHalf(float x)
	{
		uint num = AsUInt(x) + 4096;
		uint num2 = (num & 0x7F800000) >> 23;
		uint num3 = num & 0x7FFFFFu;
		return (ushort)(((num & 0x80000000u) >> 16) | (Convert.ToInt32(num2 > 112) * (((num2 - 112 << 10) & 0x7C00) | (num3 >> 13))) | ((Convert.ToInt32(num2 < 113) & Convert.ToInt32(num2 > 101)) * ((8384512 + num3 >> (int)(125 - num2)) + 1 >> 1)) | (Convert.ToUInt32(num2 > 143) * 32767));
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static byte ReadByte(byte[] source, ref int index)
	{
		return source[index++];
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static bool ReadBool(byte[] source, ref int index)
	{
		return source[index++] != 0;
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static ulong ReadULong(byte[] source, ref int index)
	{
		fixed (byte* ptr = source)
		{
			byte* num = ptr + index;
			index += 8;
			ulong num2 = *(ulong*)num;
			if (!BitConverter.IsLittleEndian)
			{
				num2 = ReverseEndianness(num2);
			}
			return num2;
		}
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static long ReadLong(byte[] source, ref int index)
	{
		fixed (byte* ptr = source)
		{
			byte* num = ptr + index;
			index += 8;
			long num2 = *(long*)num;
			if (!BitConverter.IsLittleEndian)
			{
				num2 = ReverseEndianness(num2);
			}
			return num2;
		}
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static uint ReadUInt(byte[] source, ref int index)
	{
		fixed (byte* ptr = source)
		{
			byte* num = ptr + index;
			index += 4;
			uint num2 = *(uint*)num;
			if (!BitConverter.IsLittleEndian)
			{
				num2 = ReverseEndianness(num2);
			}
			return num2;
		}
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static int ReadInt(byte[] source, ref int index)
	{
		fixed (byte* ptr = source)
		{
			byte* num = ptr + index;
			index += 4;
			int num2 = *(int*)num;
			if (!BitConverter.IsLittleEndian)
			{
				num2 = ReverseEndianness(num2);
			}
			return num2;
		}
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static ushort ReadUShort(byte[] source, ref int index)
	{
		fixed (byte* ptr = source)
		{
			byte* num = ptr + index;
			index += 2;
			ushort num2 = *(ushort*)num;
			if (!BitConverter.IsLittleEndian)
			{
				num2 = ReverseEndianness(num2);
			}
			return num2;
		}
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static short ReadShort(byte[] source, ref int index)
	{
		fixed (byte* ptr = source)
		{
			byte* num = ptr + index;
			index += 2;
			short num2 = *(short*)num;
			if (!BitConverter.IsLittleEndian)
			{
				num2 = ReverseEndianness(num2);
			}
			return num2;
		}
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static float ReadHalf(byte[] source, ref int index)
	{
		return HalfToFloat(ReadUShort(source, ref index));
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public unsafe static float ReadFloat(byte[] source, ref int index)
	{
		fixed (byte* ptr = source)
		{
			byte* ptr2 = ptr + index;
			index += 4;
			if (!BitConverter.IsLittleEndian)
			{
				int num = ReverseEndianness(*(int*)ptr2);
				return *(float*)(&num);
			}
			return *(float*)ptr2;
		}
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static string ReadString(byte[] source, ref int index)
	{
		int num = ReadUShort(source, ref index);
		string @string = Encoding.UTF8.GetString(source, index, num);
		index += num;
		return @string;
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static void WriteBytes(Vector3 value, byte[] destination, ref int index)
	{
		//IL_0000: 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_001a: Unknown result type (might be due to invalid IL or missing references)
		WriteBytes(value.x, destination, ref index);
		WriteBytes(value.y, destination, ref index);
		WriteBytes(value.z, destination, ref index);
	}

	public static void WriteBytes(Quaternion value, byte[] destination, ref int index)
	{
		//IL_0000: 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_001b: 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_002d: 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_0036: 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_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: 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_00a1: 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_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: 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_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0153: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_012b: 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_0145: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c1: 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_018b: 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_01a5: Unknown result type (might be due to invalid IL or missing references)
		float num = value.x;
		byte b = 0;
		if (value.y > num)
		{
			num = value.y;
			b = 1;
		}
		if (value.z > num)
		{
			num = value.z;
			b = 2;
		}
		if (value.w > num)
		{
			num = value.w;
			b = 3;
		}
		WriteBytes(b, destination, ref index);
		switch (b)
		{
		case 0:
			if (value.x >= 0f)
			{
				WriteBytes(value.y, destination, ref index);
				WriteBytes(value.z, destination, ref index);
				WriteBytes(value.w, destination, ref index);
			}
			else
			{
				WriteBytes(0f - value.y, destination, ref index);
				WriteBytes(0f - value.z, destination, ref index);
				WriteBytes(0f - value.w, destination, ref index);
			}
			break;
		case 1:
			if (value.y >= 0f)
			{
				WriteBytes(value.x, destination, ref index);
				WriteBytes(value.z, destination, ref index);
				WriteBytes(value.w, destination, ref index);
			}
			else
			{
				WriteBytes(0f - value.x, destination, ref index);
				WriteBytes(0f - value.z, destination, ref index);
				WriteBytes(0f - value.w, destination, ref index);
			}
			break;
		case 2:
			if (value.z >= 0f)
			{
				WriteBytes(value.x, destination, ref index);
				WriteBytes(value.y, destination, ref index);
				WriteBytes(value.w, destination, ref index);
			}
			else
			{
				WriteBytes(0f - value.x, destination, ref index);
				WriteBytes(0f - value.y, destination, ref index);
				WriteBytes(0f - value.w, destination, ref index);
			}
			break;
		case 3:
			if (value.w >= 0f)
			{
				WriteBytes(value.x, destination, ref index);
				WriteBytes(value.y, destination, ref index);
				WriteBytes(value.z, destination, ref index);
			}
			else
			{
				WriteBytes(0f - value.x, destination, ref index);
				WriteBytes(0f - value.y, destination, ref index);
				WriteBytes(0f - value.z, destination, ref index);
			}
			break;
		}
	}

	public static Vector3 ReadVector3(byte[] source, ref int index)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(ReadFloat(source, ref index), ReadFloat(source, ref index), ReadFloat(source, ref index));
	}

	public static Quaternion ReadQuaternion(byte[] source, ref int index)
	{
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		byte b = ReadByte(source, ref index);
		float num = 0f;
		float num2 = 0f;
		float num3 = 0f;
		float num4 = 0f;
		switch (b)
		{
		case 0:
			num2 = ReadFloat(source, ref index);
			num3 = ReadFloat(source, ref index);
			num4 = ReadFloat(source, ref index);
			num = Mathf.Sqrt(1f - num2 * num2 - num3 * num3 - num4 * num4);
			break;
		case 1:
			num = ReadFloat(source, ref index);
			num3 = ReadFloat(source, ref index);
			num4 = ReadFloat(source, ref index);
			num2 = Mathf.Sqrt(1f - num * num - num3 * num3 - num4 * num4);
			break;
		case 2:
			num = ReadFloat(source, ref index);
			num2 = ReadFloat(source, ref index);
			num4 = ReadFloat(source, ref index);
			num3 = Mathf.Sqrt(1f - num * num - num2 * num2 - num4 * num4);
			break;
		case 3:
			num = ReadFloat(source, ref index);
			num2 = ReadFloat(source, ref index);
			num3 = ReadFloat(source, ref index);
			num4 = Mathf.Sqrt(1f - num * num - num2 * num2 - num3 * num3);
			break;
		}
		return new Quaternion(num, num2, num3, num4);
	}

	public static void WriteHalf(Vector3 value, byte[] destination, ref int index)
	{
		//IL_0000: 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_001a: Unknown result type (might be due to invalid IL or missing references)
		WriteHalf(value.x, destination, ref index);
		WriteHalf(value.y, destination, ref index);
		WriteHalf(value.z, destination, ref index);
	}

	public static void WriteHalf(Quaternion value, byte[] destination, ref int index)
	{
		//IL_0000: 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_001b: 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_002d: 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_0036: 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_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: 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_00a1: 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_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: 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_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0153: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_012b: 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_0145: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c1: 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_018b: 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_01a5: Unknown result type (might be due to invalid IL or missing references)
		float num = value.x;
		byte b = 0;
		if (value.y > num)
		{
			num = value.y;
			b = 1;
		}
		if (value.z > num)
		{
			num = value.z;
			b = 2;
		}
		if (value.w > num)
		{
			num = value.w;
			b = 3;
		}
		WriteBytes(b, destination, ref index);
		switch (b)
		{
		case 0:
			if (value.x >= 0f)
			{
				WriteHalf(value.y, destination, ref index);
				WriteHalf(value.z, destination, ref index);
				WriteHalf(value.w, destination, ref index);
			}
			else
			{
				WriteHalf(0f - value.y, destination, ref index);
				WriteHalf(0f - value.z, destination, ref index);
				WriteHalf(0f - value.w, destination, ref index);
			}
			break;
		case 1:
			if (value.y >= 0f)
			{
				WriteHalf(value.x, destination, ref index);
				WriteHalf(value.z, destination, ref index);
				WriteHalf(value.w, destination, ref index);
			}
			else
			{
				WriteHalf(0f - value.x, destination, ref index);
				WriteHalf(0f - value.z, destination, ref index);
				WriteHalf(0f - value.w, destination, ref index);
			}
			break;
		case 2:
			if (value.z >= 0f)
			{
				WriteHalf(value.x, destination, ref index);
				WriteHalf(value.y, destination, ref index);
				WriteHalf(value.w, destination, ref index);
			}
			else
			{
				WriteHalf(0f - value.x, destination, ref index);
				WriteHalf(0f - value.y, destination, ref index);
				WriteHalf(0f - value.w, destination, ref index);
			}
			break;
		case 3:
			if (value.w >= 0f)
			{
				WriteHalf(value.x, destination, ref index);
				WriteHalf(value.y, destination, ref index);
				WriteHalf(value.z, destination, ref index);
			}
			else
			{
				WriteHalf(0f - value.x, destination, ref index);
				WriteHalf(0f - value.y, destination, ref index);
				WriteHalf(0f - value.z, destination, ref index);
			}
			break;
		}
	}

	public static Vector3 ReadHalfVector3(byte[] source, ref int index)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		return new Vector3(ReadHalf(source, ref index), ReadHalf(source, ref index), ReadHalf(source, ref index));
	}

	public static Quaternion ReadHalfQuaternion(byte[] source, ref int index)
	{
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		byte b = ReadByte(source, ref index);
		float num = 0f;
		float num2 = 0f;
		float num3 = 0f;
		float num4 = 0f;
		switch (b)
		{
		case 0:
			num2 = ReadHalf(source, ref index);
			num3 = ReadHalf(source, ref index);
			num4 = ReadHalf(source, ref index);
			num = Mathf.Sqrt(1f - num2 * num2 - num3 * num3 - num4 * num4);
			break;
		case 1:
			num = ReadHalf(source, ref index);
			num3 = ReadHalf(source, ref index);
			num4 = ReadHalf(source, ref index);
			num2 = Mathf.Sqrt(1f - num * num - num3 * num3 - num4 * num4);
			break;
		case 2:
			num = ReadHalf(source, ref index);
			num2 = ReadHalf(source, ref index);
			num4 = ReadHalf(source, ref index);
			num3 = Mathf.Sqrt(1f - num * num - num2 * num2 - num4 * num4);
			break;
		case 3:
			num = ReadHalf(source, ref index);
			num2 = ReadHalf(source, ref index);
			num3 = ReadHalf(source, ref index);
			num4 = Mathf.Sqrt(1f - num * num - num2 * num2 - num3 * num3);
			break;
		}
		return new Quaternion(num, num2, num3, num4);
	}
}
namespace API
{
	internal static class APILogger
	{
		private static readonly ManualLogSource logger;

		static APILogger()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			logger = new ManualLogSource("Rand-API");
			Logger.Sources.Add((ILogSource)(object)logger);
		}

		private static string Format(string module, object msg)
		{
			return $"[{module}]: {msg}";
		}

		public static void Info(string module, object data)
		{
			logger.LogMessage((object)Format(module, data));
		}

		public static void Verbose(string module, object data)
		{
		}

		public static void Log(object data)
		{
			logger.LogDebug((object)Format("KillIndicatorFix", data));
		}

		public static void Debug(object data)
		{
			if (ConfigManager.Debug)
			{
				Log(data);
			}
		}

		public static void Warn(object data)
		{
			logger.LogWarning((object)Format("KillIndicatorFix", data));
		}

		public static void Error(object data)
		{
			logger.LogError((object)Format("KillIndicatorFix", data));
		}
	}
}
namespace KillIndicatorFix
{
	internal static class Utils
	{
		public const BindingFlags AnyBindingFlags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
	}
	public static class Kill
	{
		public static Action<EnemyAgent, ItemEquippable, long>? OnKillIndicator;

		private static void RegisterMethods(Type t)
		{
			foreach (MethodInfo item in from m in t.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
				where m.GetCustomAttribute<OnKillIndicator>() != null
				select m)
			{
				if (item.IsStatic)
				{
					try
					{
						string value = "OnKillIndicator";
						if (item.GetCustomAttribute<OnKillIndicator>() != null)
						{
							value = "OnKillIndicator";
							OnKillIndicator = (Action<EnemyAgent, ItemEquippable, long>)Delegate.Combine(OnKillIndicator, (Action<EnemyAgent, ItemEquippable, long>)item.CreateDelegate(typeof(Action<EnemyAgent, ItemEquippable, long>)));
						}
						APILogger.Debug($"Registered {value}: '{t.FullName}.{item.Name}'");
					}
					catch (Exception value2)
					{
						APILogger.Error($"Failed to register method: {value2}");
					}
				}
				else
				{
					APILogger.Error($"KillIndicatorFix attributes can only be applied to static methods. '{item}' is not static.");
				}
			}
		}

		public static void RegisterAll()
		{
			Type[] types = Assembly.GetCallingAssembly().GetTypes();
			for (int i = 0; i < types.Length; i++)
			{
				RegisterMethods(types[i]);
			}
		}

		public static void RegisterAll(Type type)
		{
			Type[] nestedTypes = type.GetNestedTypes(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (Type obj in nestedTypes)
			{
				RegisterMethods(obj);
				RegisterAll(obj);
			}
		}

		internal static void TriggerOnKillIndicator(EnemyAgent enemy, ItemEquippable item, long delay)
		{
			try
			{
				OnKillIndicator?.Invoke(enemy, item, delay);
			}
			catch (Exception value)
			{
				APILogger.Error($"TriggerOnKillIndicator: {value}");
			}
		}

		public static void TagEnemy(EnemyAgent enemy, ItemEquippable? item = null, Vector3? localHitPosition = null)
		{
			//IL_0085: 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_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			int instanceID = ((Object)enemy).GetInstanceID();
			long timestamp = ((DateTimeOffset)DateTime.Now).ToUnixTimeMilliseconds();
			if (!localHitPosition.HasValue)
			{
				localHitPosition = ((!KillIndicatorFix.Patches.Kill.taggedEnemies.ContainsKey(instanceID)) ? new Vector3?(((Agent)enemy).EyePosition - ((Component)enemy).transform.position) : new Vector3?(KillIndicatorFix.Patches.Kill.taggedEnemies[instanceID].localHitPosition));
			}
			if ((Object)(object)item == (Object)null)
			{
				item = PlayerManager.GetLocalPlayerAgent().Inventory.WieldedItem;
			}
			KillIndicatorFix.Patches.Kill.Tag value = new KillIndicatorFix.Patches.Kill.Tag(timestamp, localHitPosition.Value, item);
			if (KillIndicatorFix.Patches.Kill.taggedEnemies.ContainsKey(instanceID))
			{
				KillIndicatorFix.Patches.Kill.taggedEnemies[instanceID] = value;
			}
			else
			{
				KillIndicatorFix.Patches.Kill.taggedEnemies.Add(instanceID, value);
			}
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class OnKillIndicator : Attribute
	{
	}
}
namespace KillIndicatorFix.Patches
{
	[HarmonyPatch(typeof(GameDataInit))]
	internal class GameDataInit_Patches
	{
		[HarmonyPatch("Initialize")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		public static void Initialize_Postfix()
		{
			Analytics.enabled = false;
		}
	}
	[HarmonyPatch]
	internal static class Kill
	{
		public struct Tag
		{
			public long timestamp;

			public Vector3 localHitPosition;

			public ItemEquippable item;

			public Tag(long timestamp, Vector3 localHitPosition, ItemEquippable item)
			{
				//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)
				this.timestamp = timestamp;
				this.localHitPosition = localHitPosition;
				this.item = item;
			}
		}

		public static Dictionary<int, Tag> taggedEnemies = new Dictionary<int, Tag>();

		internal static bool sentryShot = false;

		public static void OnRundownStart()
		{
			APILogger.Debug("OnRundownStart => Reset Trackers and Markers.");
			taggedEnemies.Clear();
		}

		[HarmonyPatch(typeof(EnemyBehaviour), "ChangeState", new Type[] { typeof(EB_States) })]
		[HarmonyPrefix]
		public static void OnDead(EnemyBehaviour __instance, EB_States state)
		{
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			//IL_0111: 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)
			if (SNet.IsMaster || __instance.m_currentStateName == state || (int)state != 19)
			{
				return;
			}
			APILogger.Debug("EnemyAppearance.OnDead");
			try
			{
				EnemyAgent enemyAgent = __instance.m_ai.m_enemyAgent;
				int instanceID = ((Object)enemyAgent).GetInstanceID();
				long num = ((DateTimeOffset)DateTime.Now).ToUnixTimeMilliseconds();
				if (!taggedEnemies.ContainsKey(instanceID))
				{
					return;
				}
				Tag tag = taggedEnemies[instanceID];
				if (tag.timestamp <= num)
				{
					APILogger.Debug($"Received kill update {num - tag.timestamp} milliseconds after tag.");
				}
				else
				{
					APILogger.Debug("Received kill update for enemy that was tagged in the future? Possibly long overflow...");
				}
				if (tag.timestamp <= num && num - tag.timestamp < ConfigManager.TagBufferPeriod)
				{
					if (!enemyAgent.Damage.DeathIndicatorShown)
					{
						APILogger.Debug("Client side marker was not shown, showing server side one.");
						KillIndicatorFix.Kill.TriggerOnKillIndicator(enemyAgent, tag.item, num - tag.timestamp);
						CrosshairGuiLayer crosshairLayer = GuiManager.CrosshairLayer;
						if (crosshairLayer != null)
						{
							crosshairLayer.ShowDeathIndicator(((Component)enemyAgent).transform.position + tag.localHitPosition);
						}
						enemyAgent.Damage.DeathIndicatorShown = true;
					}
					else
					{
						APILogger.Debug("Client side marker was shown, not showing server side one.");
					}
				}
				else
				{
					APILogger.Debug("Client was no longer interested in this enemy, marker will not be shown.");
				}
				taggedEnemies.Remove(instanceID);
			}
			catch
			{
				APILogger.Debug("Something went wrong.");
			}
		}

		[HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "FireBullet")]
		[HarmonyPrefix]
		private static void Prefix_SentryGunFiringBullet(SentryGunInstance_Firing_Bullets __instance, bool doDamage, bool targetIsTagged)
		{
			if (doDamage)
			{
				sentryShot = true;
			}
		}

		[HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "FireBullet")]
		[HarmonyPostfix]
		private static void Postfix_SentryGunFiringBullet()
		{
			sentryShot = false;
		}

		[HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "UpdateFireShotgunSemi")]
		[HarmonyPrefix]
		private static void Prefix_ShotgunSentryFiring(SentryGunInstance_Firing_Bullets __instance, bool isMaster, bool targetIsTagged)
		{
			if (isMaster)
			{
				sentryShot = true;
			}
		}

		[HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "UpdateFireShotgunSemi")]
		[HarmonyPostfix]
		private static void Postfix_ShotgunSentryFiring()
		{
			sentryShot = false;
		}

		[HarmonyPatch(typeof(Dam_EnemyDamageLimb), "BulletDamage")]
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		public static void EnemyLimb_BulletDamage(Dam_EnemyDamageLimb __instance, float dam, Agent sourceAgent, Vector3 position, Vector3 direction, Vector3 normal, bool allowDirectionalBonus, float staggerMulti, float precisionMulti)
		{
			//IL_0039: 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_0097: 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_00bd: Unknown result type (might be due to invalid IL or missing references)
			if (!SNet.IsMaster || !sentryShot)
			{
				return;
			}
			PlayerAgent val = ((Il2CppObjectBase)sourceAgent).TryCast<PlayerAgent>();
			if ((Object)(object)val == (Object)null)
			{
				APILogger.Debug($"Could not find PlayerAgent, damage was done by agent of type: {sourceAgent.m_type}.");
			}
			else if (!val.Owner.IsBot && !sourceAgent.IsLocallyOwned)
			{
				Dam_EnemyDamageBase @base = __instance.m_base;
				EnemyAgent owner = @base.Owner;
				float num = dam;
				if (!@base.IsImortal)
				{
					num = __instance.ApplyWeakspotAndArmorModifiers(dam, precisionMulti);
					num = __instance.ApplyDamageFromBehindBonus(num, position, direction, 1f);
					bool willDie = ((Dam_SyncedDamageBase)@base).WillDamageKill(num);
					Network.SendHitIndicator((Agent)(object)owner, (byte)__instance.m_limbID, val, num > dam, willDie, position, __instance.m_armorDamageMulti < 1f);
				}
				else
				{
					Network.SendHitIndicator((Agent)(object)owner, (byte)__instance.m_limbID, val, num > dam, willDie: false, position, hitArmor: true);
				}
			}
		}

		[HarmonyPatch(typeof(Dam_PlayerDamageBase), "ReceiveBulletDamage")]
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		public static void Player_BulletDamage(Dam_PlayerDamageBase __instance, pBulletDamageData data)
		{
			//IL_004a: 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)
			Agent val = default(Agent);
			if (!SNet.IsMaster || !((pAgent)(ref data.source)).TryGet(ref val) || !sentryShot)
			{
				return;
			}
			PlayerAgent val2 = ((Il2CppObjectBase)val).TryCast<PlayerAgent>();
			if ((Object)(object)val2 == (Object)null)
			{
				APILogger.Debug($"Could not find PlayerAgent, damage was done by agent of type: {val.m_type}.");
			}
			else if (!val2.Owner.IsBot && !val.IsLocallyOwned)
			{
				PlayerAgent owner = __instance.Owner;
				if ((Object)(object)owner != (Object)(object)val2)
				{
					Network.SendHitIndicator((Agent)(object)owner, 0, val2, hitWeakspot: false, willDie: false, Vector3.zero);
				}
			}
		}

		[HarmonyPatch(typeof(Dam_EnemyDamageBase), "BulletDamage")]
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		public static void BulletDamage(Dam_EnemyDamageBase __instance, float dam, Agent sourceAgent, Vector3 position, Vector3 direction, bool allowDirectionalBonus, int limbID, float precisionMulti)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			if (SNet.IsMaster)
			{
				return;
			}
			PlayerAgent val = ((Il2CppObjectBase)sourceAgent).TryCast<PlayerAgent>();
			if ((Object)(object)val == (Object)null)
			{
				APILogger.Debug($"Could not find PlayerAgent, damage was done by agent of type: {sourceAgent.m_type}.");
			}
			else if (!val.Owner.IsBot)
			{
				EnemyAgent owner = __instance.Owner;
				int instanceID = ((Object)owner).GetInstanceID();
				long timestamp = ((DateTimeOffset)DateTime.Now).ToUnixTimeMilliseconds();
				float num = AgentModifierManager.ApplyModifier((Agent)(object)owner, (AgentModifier)7, Mathf.Clamp(dam, 0f, ((Dam_SyncedDamageBase)__instance).HealthMax));
				((Dam_SyncedDamageBase)__instance).Health = ((Dam_SyncedDamageBase)__instance).Health - num;
				Vector3 localHitPosition = position - ((Component)owner).transform.position;
				Tag value = new Tag(timestamp, localHitPosition, val.Inventory.WieldedItem);
				if (taggedEnemies.ContainsKey(instanceID))
				{
					taggedEnemies[instanceID] = value;
				}
				else
				{
					taggedEnemies.Add(instanceID, value);
				}
				APILogger.Debug($"{num} Bullet Damage done by {val.PlayerName}. IsBot: {val.Owner.IsBot}");
				APILogger.Debug($"Tracked current HP: {((Dam_SyncedDamageBase)__instance).Health}, [{((Object)owner).GetInstanceID()}]");
			}
		}

		[HarmonyPatch(typeof(Dam_EnemyDamageBase), "MeleeDamage")]
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		public static void MeleeDamage(Dam_EnemyDamageBase __instance, float dam, Agent sourceAgent, Vector3 position, Vector3 direction, int limbID, float staggerMulti, float precisionMulti, float sleeperMulti, bool skipLimbDestruction, DamageNoiseLevel damageNoiseLevel)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//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_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			if (SNet.IsMaster)
			{
				return;
			}
			PlayerAgent val = ((Il2CppObjectBase)sourceAgent).TryCast<PlayerAgent>();
			if ((Object)(object)val == (Object)null)
			{
				APILogger.Debug($"Could not find PlayerAgent, damage was done by agent of type: {sourceAgent.m_type}.");
			}
			else if (!val.Owner.IsBot)
			{
				EnemyAgent owner = __instance.Owner;
				int instanceID = ((Object)owner).GetInstanceID();
				long timestamp = ((DateTimeOffset)DateTime.Now).ToUnixTimeMilliseconds();
				float num = AgentModifierManager.ApplyModifier((Agent)(object)owner, (AgentModifier)6, Mathf.Clamp(dam, 0f, ((Dam_SyncedDamageBase)__instance).DamageMax));
				if ((int)__instance.Owner.Locomotion.CurrentStateEnum == 14)
				{
					num *= sleeperMulti;
				}
				((Dam_SyncedDamageBase)__instance).Health = ((Dam_SyncedDamageBase)__instance).Health - num;
				Vector3 localHitPosition = position - ((Component)owner).transform.position;
				Tag value = new Tag(timestamp, localHitPosition, val.Inventory.WieldedItem);
				if (taggedEnemies.ContainsKey(instanceID))
				{
					taggedEnemies[instanceID] = value;
				}
				else
				{
					taggedEnemies.Add(instanceID, value);
				}
				APILogger.Debug($"Melee Damage: {num}");
				APILogger.Debug($"Tracked current HP: {((Dam_SyncedDamageBase)__instance).Health}, [{((Object)owner).GetInstanceID()}]");
			}
		}

		[HarmonyPatch(typeof(Dam_EnemyDamageLimb), "ShowHitIndicator")]
		[HarmonyPrefix]
		public static void ShowDeathIndicator(Dam_EnemyDamageLimb __instance, bool hitWeakspot, bool willDie, Vector3 position, bool hitArmor)
		{
			EnemyAgent owner = __instance.m_base.Owner;
			((Object)owner).GetInstanceID();
			((DateTimeOffset)DateTime.Now).ToUnixTimeMilliseconds();
			if (willDie && !__instance.m_base.DeathIndicatorShown)
			{
				PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent();
				ItemEquippable item = localPlayerAgent.Inventory.WieldedItem;
				BackpackItem val = default(BackpackItem);
				if (sentryShot && PlayerBackpackManager.TryGetItem(localPlayerAgent.Owner, (InventorySlot)3, ref val))
				{
					item = ((Il2CppObjectBase)val.Instance).Cast<ItemEquippable>();
				}
				KillIndicatorFix.Kill.TriggerOnKillIndicator(owner, item, 0L);
			}
		}
	}
	[HarmonyPatch]
	internal static class Network
	{
		private static byte msgtype = 173;

		private static uint magickey = 10992881u;

		private static ushort repKey = 65531;

		public static void SendHitIndicator(Agent target, byte limbID, PlayerAgent player, bool hitWeakspot, bool willDie, Vector3 position, bool hitArmor = false)
		{
			//IL_0025: 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_00df: Unknown result type (might be due to invalid IL or missing references)
			if (SNet.IsMaster && !((Object)(object)player == (Object)(object)PlayerManager.GetLocalPlayerAgent()) && !player.Owner.IsBot)
			{
				SNet_ChannelType val = (SNet_ChannelType)0;
				SNet_SendGroup val2 = default(SNet_SendGroup);
				SNet_SendQuality val3 = default(SNet_SendQuality);
				int num = default(int);
				SNet.GetSendSettings(ref val, ref val2, ref val3, ref num);
				List<SNet_Player> val4 = new List<SNet_Player>(1);
				val4.Add(player.Owner);
				int index = 0;
				byte[] array = new byte[23];
				BitHelper.WriteBytes(repKey, array, ref index);
				BitHelper.WriteBytes(magickey, array, ref index);
				BitHelper.WriteBytes(msgtype, array, ref index);
				BitHelper.WriteBytes(12, array, ref index);
				BitHelper.WriteBytes((ushort)(target.m_replicator.Key + 1), array, ref index);
				BitHelper.WriteBytes(limbID, array, ref index);
				BitHelper.WriteBytes(hitWeakspot, array, ref index);
				BitHelper.WriteBytes(willDie, array, ref index);
				BitHelper.WriteHalf(position, array, ref index);
				BitHelper.WriteBytes(hitArmor, array, ref index);
				SNet.Core.SendBytes(Il2CppStructArray<byte>.op_Implicit(array), val3, num, val4);
				APILogger.Debug("Sent hit marker to " + player.PlayerName);
			}
		}

		[HarmonyPatch(typeof(SNet_Replication), "RecieveBytes")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static bool RecieveBytes_Prefix(Il2CppStructArray<byte> bytes, uint size, ulong messagerID)
		{
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: 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_014b: Unknown result type (might be due to invalid IL or missing references)
			if (size < 12)
			{
				return true;
			}
			ushort num = BitConverter.ToUInt16(Il2CppArrayBase<byte>.op_Implicit((Il2CppArrayBase<byte>)(object)bytes), 0);
			if (repKey == num)
			{
				if (BitConverter.ToUInt32(Il2CppArrayBase<byte>.op_Implicit((Il2CppArrayBase<byte>)(object)bytes), 2) != magickey)
				{
					APILogger.Debug("[Networking] Magic key is incorrect.");
					return true;
				}
				byte b = ((Il2CppArrayBase<byte>)(object)bytes)[6];
				if (b != msgtype)
				{
					APILogger.Debug($"[Networking] msg type is incorrect. {b} {msgtype}");
					return true;
				}
				int num2 = BitConverter.ToInt32(Il2CppArrayBase<byte>.op_Implicit((Il2CppArrayBase<byte>)(object)bytes), 7);
				byte[] array = new byte[num2];
				Array.Copy(Il2CppArrayBase<byte>.op_Implicit((Il2CppArrayBase<byte>)(object)bytes), 11, array, 0, num2);
				int index = 0;
				ushort keyPlusOne = BitHelper.ReadUShort(array, ref index);
				byte b2 = BitHelper.ReadByte(array, ref index);
				bool flag = BitHelper.ReadBool(array, ref index);
				bool flag2 = BitHelper.ReadBool(array, ref index);
				Vector3 val = BitHelper.ReadHalfVector3(array, ref index);
				bool flag3 = BitHelper.ReadBool(array, ref index);
				pReplicator pRep = default(pReplicator);
				pRep.keyPlusOne = keyPlusOne;
				pAgent val2 = default(pAgent);
				val2.pRep = pRep;
				Agent val3 = default(Agent);
				((pAgent)(ref val2)).TryGet(ref val3);
				EnemyAgent val4 = ((Il2CppObjectBase)val3).TryCast<EnemyAgent>();
				if ((Object)(object)val4 != (Object)null)
				{
					APILogger.Debug("Received hit indicator for enemy.");
					Dam_EnemyDamageLimb obj = ((Il2CppArrayBase<Dam_EnemyDamageLimb>)(object)val4.Damage.DamageLimbs)[(int)b2];
					Kill.sentryShot = true;
					obj.ShowHitIndicator(flag, flag2, val, flag3);
					Kill.sentryShot = false;
					return false;
				}
				if ((Object)(object)((Il2CppObjectBase)val3).TryCast<PlayerAgent>() != (Object)null)
				{
					APILogger.Debug("Received hit indicator for player.");
					GuiManager.CrosshairLayer.PopFriendlyTarget();
					return false;
				}
				APILogger.Debug("Received hit indicator packet but could not get player / enemy agent. This should not happen.");
				return false;
			}
			return true;
		}
	}
}
namespace KillIndicatorFix.BepInEx
{
	public static class ConfigManager
	{
		private static ConfigEntry<bool> debug;

		private static ConfigEntry<int> tagBufferPeriod;

		public static bool Debug => debug.Value;

		public static int TagBufferPeriod => tagBufferPeriod.Value;

		static ConfigManager()
		{
			//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)
			ConfigFile val = new ConfigFile(Path.Combine(Paths.ConfigPath, "KillIndicatorFix.cfg"), true);
			debug = val.Bind<bool>("Debug", "enable", false, "Enables debug messages when true.");
			tagBufferPeriod = val.Bind<int>("Settings", "TagBufferPeriod", 1000, "Indicates a lee-way period in milliseconds where a kill indicator will still be shown for a given enemy long after it has been tagged (shot at).");
		}
	}
	[BepInPlugin("randomuserhi.KillIndicatorFix", "KillIndicatorFix", "0.1.4")]
	internal class Entry : BasePlugin
	{
		private Harmony? harmony;

		public override void Load()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			APILogger.Debug("Loaded KillIndicatorFix 0.1.4");
			harmony = new Harmony("randomuserhi.KillIndicatorFix");
			harmony.PatchAll();
			APILogger.Debug("Debug is " + (ConfigManager.Debug ? "Enabled" : "Disabled"));
			RundownManager.OnExpeditionGameplayStarted += Action.op_Implicit((Action)KillIndicatorFix.Patches.Kill.OnRundownStart);
		}
	}
	public static class Module
	{
		public const string GUID = "randomuserhi.KillIndicatorFix";

		public const string Name = "KillIndicatorFix";

		public const string Version = "0.1.4";
	}
}

plugins/Red_Leicester_Cheese-CheeseGeos/ReactorFix.dll

Decompiled 7 hours ago
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using GTFO.API;
using HarmonyLib;
using LevelGeneration;
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(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ReactorFix")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ReactorFix")]
[assembly: AssemblyTitle("ReactorFix")]
[assembly: TargetPlatform("Windows7.0")]
[assembly: SupportedOSPlatform("Windows7.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 ReactorFix
{
	[BepInPlugin("ReactorFix.GUID", "ReactorFix", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class EntryPoint : BasePlugin
	{
		private Harmony _Harmony = null;

		public override void Load()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			_Harmony = new Harmony("ReactorFix.Harmony");
			_Harmony.PatchAll();
			Harmony.CreateAndPatchAll(typeof(ReactorShutdownAndFontFix), (string)null);
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(32, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin has loaded with ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_Harmony.GetPatchedMethods().Count());
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" patches!");
			}
			Logger.Info(val);
		}

		public override bool Unload()
		{
			_Harmony.UnpatchSelf();
			return ((BasePlugin)this).Unload();
		}
	}
	internal static class Logger
	{
		private static readonly ManualLogSource _Logger;

		static Logger()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			_Logger = new ManualLogSource("ReactorFix");
			Logger.Sources.Add((ILogSource)(object)_Logger);
		}

		private static string Format(object msg)
		{
			return msg.ToString();
		}

		public static void Info(BepInExInfoLogInterpolatedStringHandler handler)
		{
			_Logger.LogInfo(handler);
		}

		public static void Info(string str)
		{
			_Logger.LogMessage((object)str);
		}

		public static void Info(object data)
		{
			_Logger.LogMessage((object)Format(data));
		}

		public static void Debug(BepInExDebugLogInterpolatedStringHandler handler)
		{
			_Logger.LogDebug(handler);
		}

		public static void Debug(string str)
		{
			_Logger.LogDebug((object)str);
		}

		public static void Debug(object data)
		{
			_Logger.LogDebug((object)Format(data));
		}

		public static void Error(BepInExErrorLogInterpolatedStringHandler handler)
		{
			_Logger.LogError(handler);
		}

		public static void Error(string str)
		{
			_Logger.LogError((object)str);
		}

		public static void Error(object data)
		{
			_Logger.LogError((object)Format(data));
		}

		public static void Fatal(BepInExFatalLogInterpolatedStringHandler handler)
		{
			_Logger.LogFatal(handler);
		}

		public static void Fatal(string str)
		{
			_Logger.LogFatal((object)str);
		}

		public static void Fatal(object data)
		{
			_Logger.LogFatal((object)Format(data));
		}

		public static void Warn(BepInExWarningLogInterpolatedStringHandler handler)
		{
			_Logger.LogWarning(handler);
		}

		public static void Warn(string str)
		{
			_Logger.LogWarning((object)str);
		}

		public static void Warn(object data)
		{
			_Logger.LogWarning((object)Format(data));
		}

		[Conditional("DEBUG")]
		public static void DebugOnly(object data)
		{
			_Logger.LogDebug((object)Format(data));
		}
	}
	[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "Start")]
	internal class ReactorShutdownAndFontFix
	{
		public string HelloDecomp = "Credit to flow for origially making this code";

		public static void Postfix(LG_WardenObjective_Reactor __instance)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			Logger.Info("Resolving Terminal Prefab for reactor!");
			__instance.m_terminalPrefab = AssetAPI.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/Complex/Generic/FunctionMarkers/Terminal_Floor.prefab");
			if ((Object)__instance.m_terminalPrefab == (Object)null)
			{
				Logger.Error("We tried to resolve terminal prefab for reactor but it doesn't work...");
			}
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.1.3+git35c0c2a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "ReactorFix";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = null;

		public const string SemVer = "1.0.0";

		public const string GitRevShort = null;

		public const string GitRevLong = null;

		public const string GitBranch = null;

		public const string GitTag = null;

		public const int GitCommitsSinceTag = 0;

		public const bool GitIsDirty = false;
	}
}

plugins/Untilted-ConfigurableGlobalWaveSettings/ConfigurableGlobalWaveSettings.dll

Decompiled 7 hours ago
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.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using Agents;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Enemies;
using GTFO.API.JSON;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("ConfigurableGlobalWaveSettings")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ConfigurableGlobalWaveSettings")]
[assembly: AssemblyTitle("ConfigurableGlobalWaveSettings")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ConfigurableGlobalWaveSettings;

public class GlobalWaveSettingsDataBlock : GWSPersistentData<GlobalWaveSettingsDataBlock>
{
	public List<GlobalWaveSettingsEntry> Blocks { get; set; }

	public GlobalWaveSettingsDataBlock()
	{
		Blocks = new List<GlobalWaveSettingsEntry>();
		Blocks.Add(new GlobalWaveSettingsEntry());
	}

	public static bool TryGetBlockByID(uint ID, out GlobalWaveSettingsEntry entry)
	{
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Expected O, but got Unknown
		entry = GWSPersistentData<GlobalWaveSettingsDataBlock>.CurrentData.Blocks.FirstOrDefault((GlobalWaveSettingsEntry x) => x.PersistentID == ID);
		if (entry == null)
		{
			ManualLogSource logger = Loader.Logger;
			bool flag = default(bool);
			BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(46, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Couldn't find GlobalWaveSettingsEntry with ID ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(ID);
			}
			logger.LogWarning(val);
			return false;
		}
		return true;
	}
}
public class GlobalWaveSettingsEntry
{
	public float AllowedTotalCost { get; set; }

	public float MaxHeat { get; set; }

	public float HeatCooldownSpeed { get; set; }

	public float[] BaseWeights { get; set; }

	public float[] HeatsOnSelect { get; set; }

	public float[] HeatsAtStart { get; set; }

	public float[] EnemyTypeCostsForWave { get; set; }

	public float[] EnemyTypeCostsTowardsCap { get; set; }

	public int[] WaveEnemyTypeLimits { get; set; }

	public bool AdjustHeatGrabCount { get; set; }

	public uint PersistentID { get; set; }

	public GlobalWaveSettingsEntry()
	{
		AllowedTotalCost = 25f;
		MaxHeat = 200f;
		HeatCooldownSpeed = 25f;
		PersistentID = 1u;
		BaseWeights = new float[5] { 1f, 1f, 0.5f, 0.15f, 0.1f };
		HeatsOnSelect = new float[5] { 2f, 3f, 15f, 150f, 100f };
		HeatsAtStart = new float[5] { 0.2f, 0.3f, 1.5f, 15f, 10f };
		EnemyTypeCostsForWave = new float[5] { 0.75f, 1f, 1f, 2f, 2f };
		EnemyTypeCostsTowardsCap = new float[5] { 0.75f, 1f, 1f, 2f, 2f };
		WaveEnemyTypeLimits = new int[5] { 1, 1, 1, 1, 1 };
		AdjustHeatGrabCount = false;
	}
}
public class GWSPersistentData<T> where T : GWSPersistentData<T>, new()
{
	private const string VERSION_REGEX = "\"PersistentDataVersion\": \"(.+?)\"";

	private static T s_CurrentData;

	private static readonly string s_fullPath = GetFullPath();

	public static T CurrentData
	{
		get
		{
			if (s_CurrentData != null)
			{
				return s_CurrentData;
			}
			s_CurrentData = Load();
			return s_CurrentData;
		}
		set
		{
			s_CurrentData = value;
		}
	}

	protected static string persistentPath => Path.Combine("PersistentData", typeof(T).Assembly.GetName().Name, typeof(T).Name + ".json");

	public virtual string PersistentDataVersion { get; set; } = "1.0.0";


	[JsonIgnore]
	public bool LoadingFailed { get; private set; }

	private static string GetFullPath()
	{
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Expected O, but got Unknown
		string TPersistentPath = persistentPath;
		PropertyInfo property = typeof(T).GetProperty("persistentPath", BindingFlags.Static | BindingFlags.NonPublic);
		if (property != null)
		{
			TPersistentPath = (string)property.GetValue(null, null);
		}
		if (Path.IsPathFullyQualified(TPersistentPath))
		{
			return TPersistentPath;
		}
		string fileName = Path.GetFileName(TPersistentPath);
		string text = Directory.GetFiles(Paths.PluginPath, fileName, SearchOption.AllDirectories).FirstOrDefault((string f) => f.EndsWith(TPersistentPath));
		if (string.IsNullOrEmpty(text))
		{
			ManualLogSource logger = Loader.Logger;
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(32, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Couldn't find existing data for ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(typeof(T).Name);
			}
			logger.LogDebug(val);
			return Path.Combine(Paths.PluginPath, TPersistentPath);
		}
		return text;
	}

	public static T Load()
	{
		return Load(s_fullPath);
	}

	public static T Load(string path)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		//IL_015c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0163: Expected O, but got Unknown
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Expected O, but got Unknown
		ManualLogSource logger = Loader.Logger;
		bool flag = default(bool);
		BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(14, 2, ref flag);
		if (flag)
		{
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Loading ");
			((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(typeof(T).Name);
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" from ");
			((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(path);
		}
		logger.LogDebug(val);
		T val2 = new T();
		if (File.Exists(path))
		{
			string text = File.ReadAllText(path);
			string text2 = "1.0.0";
			Match match = Regex.Match(text, "\"PersistentDataVersion\": \"(.+?)\"");
			if (match.Success)
			{
				text2 = match.Groups[1].Value ?? "";
			}
			if (text2 != val2.PersistentDataVersion)
			{
				ManualLogSource logger2 = Loader.Logger;
				BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(48, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(typeof(T).Name);
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" PersistentDataVersion mismatch: expected ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(val2.PersistentDataVersion);
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(", got ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(text2);
				}
				logger2.LogWarning(val3);
				File.WriteAllText(Path.ChangeExtension(path, null) + "-" + text2 + ".json", text);
				val2.Save(path);
				return val2;
			}
			T val4;
			try
			{
				val4 = JsonSerializer.Deserialize<T>(text, (JsonSerializerOptions)null);
			}
			catch (JsonException ex)
			{
				ManualLogSource logger3 = Loader.Logger;
				BepInExErrorLogInterpolatedStringHandler val5 = new BepInExErrorLogInterpolatedStringHandler(23, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val5).AppendLiteral("Failed to deserialize ");
					((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<string>(typeof(T).Name);
					((BepInExLogInterpolatedStringHandler)val5).AppendLiteral("\n");
					((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<JsonException>(ex);
				}
				logger3.LogError(val5);
				val2.LoadingFailed = true;
				return val2;
			}
			val2 = val4;
		}
		else
		{
			val2.Save(path);
		}
		return val2;
	}

	public void Save()
	{
		Save(s_fullPath);
	}

	public void Save(string path)
	{
		string contents = JsonSerializer.Serialize((object)(T)this, (JsonSerializerOptions)null);
		string directoryName = Path.GetDirectoryName(path);
		if (!Directory.Exists(directoryName))
		{
			Directory.CreateDirectory(directoryName);
		}
		File.WriteAllText(path, contents);
	}
}
[BepInPlugin("com.Untilted.ConfigurableGlobalWaveSettings", "ConfigurableGlobalWaveSettings", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Loader : BasePlugin
{
	public const string MODNAME = "ConfigurableGlobalWaveSettings";

	public const string AUTHOR = "Untilted";

	public const string GUID = "com.Untilted.ConfigurableGlobalWaveSettings";

	public const string VERSION = "1.0.0";

	public static ManualLogSource Logger;

	public override void Load()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		Logger = ((BasePlugin)this).Log;
		((BasePlugin)this).Log.LogMessage((object)"Loading ConfigurableGlobalWaveSettings");
		new Harmony("ConfigurableGlobalWaveSettings").PatchAll(typeof(SettingsPatches));
		_ = GWSPersistentData<GlobalWaveSettingsDataBlock>.CurrentData;
		((BasePlugin)this).Log.LogMessage((object)"Loaded ConfigurableGlobalWaveSettings");
	}
}
public static class RegexUtils
{
	public static bool TryMatchID(string input, string settingToMatch, out uint matchedID)
	{
		matchedID = 0u;
		if (string.IsNullOrEmpty(input))
		{
			return false;
		}
		Match match = new Regex(settingToMatch + "_([0-9]+)", RegexOptions.IgnoreCase).Match(input);
		if (!match.Success)
		{
			return false;
		}
		matchedID = uint.Parse(match.Groups[1].Value);
		return true;
	}
}
internal static class SettingsPatches
{
	private static GlobalWaveSettingsEntry currentSettings;

	[HarmonyPatch(typeof(Builder), "SetSessionIDSeed")]
	[HarmonyPostfix]
	[HarmonyWrapSafe]
	public static void SetupSettings()
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Expected O, but got Unknown
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Expected O, but got Unknown
		ManualLogSource logger = Loader.Logger;
		bool flag = default(bool);
		BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(25, 1, ref flag);
		if (flag)
		{
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ActiveExpedition DevInfo ");
			((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(RundownManager.ActiveExpedition.Descriptive.DevInfo);
		}
		logger.LogInfo(val);
		if (!RegexUtils.TryMatchID(RundownManager.ActiveExpedition.Descriptive.DevInfo, "globalwavesettings", out var matchedID))
		{
			ManualLogSource logger2 = Loader.Logger;
			val = new BepInExInfoLogInterpolatedStringHandler(64, 0, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("No GlobalWaveSettingsEntry matched for current level, using ID 1");
			}
			logger2.LogInfo(val);
			matchedID = 1u;
		}
		else
		{
			ManualLogSource logger3 = Loader.Logger;
			val = new BepInExInfoLogInterpolatedStringHandler(53, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("GlobalWaveSettingsEntry ID ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(matchedID);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" matched for current level");
			}
			logger3.LogInfo(val);
		}
		if (GlobalWaveSettingsDataBlock.TryGetBlockByID(matchedID, out var entry))
		{
			EnemyPopulationManager.Current.m_baseWeightTable = Il2CppStructArray<float>.op_Implicit(entry.BaseWeights);
			EnemyPopulationManager.Current.m_maxHeat = entry.MaxHeat;
			EnemyPopulationManager.Current.m_heatTable = Il2CppStructArray<float>.op_Implicit(entry.HeatsOnSelect);
			EnemyPopulationManager.Current.m_enemyTypeLimits = Il2CppStructArray<int>.op_Implicit(entry.WaveEnemyTypeLimits);
			EnemyPopulationManager.Current.SetCooldownFactor(entry.HeatCooldownSpeed);
			for (int i = 0; i < 5; i++)
			{
				EnemyPopulationManager.Current.m_heatTypes[i].m_heat = entry.HeatsAtStart[i];
			}
			EnemyCostManager.AllowedTotalCost = entry.AllowedTotalCost;
			EnemyCostManager.Current.m_enemyTypeCosts = Il2CppStructArray<float>.op_Implicit(entry.EnemyTypeCostsForWave);
			currentSettings = entry;
		}
	}

	[HarmonyPatch(typeof(EnemyAI), "ModeChange")]
	[HarmonyPrefix]
	public static bool AllocateCostTowardsCap(EnemyAI __instance)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Invalid comparison between Unknown and I4
		//IL_003f: 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 (currentSettings == null)
		{
			return true;
		}
		if ((int)((AgentAI)__instance).Mode == 1)
		{
			if (!(__instance.m_enemyAgent.m_enemyCost > 0f))
			{
				__instance.m_enemyAgent.m_enemyCost = currentSettings.EnemyTypeCostsTowardsCap[__instance.m_enemyAgent.EnemyData.EnemyType];
				EnemyCostManager.AddCost(((Agent)__instance.m_enemyAgent).DimensionIndex, __instance.m_enemyAgent.m_enemyCost);
			}
			return false;
		}
		return true;
	}

	[HarmonyPatch(typeof(EnemyPopulationManager), "GetNextType_UsingMaxLimits")]
	[HarmonyPostfix]
	public static void LogNextType(eEnemyType __result, List<eEnemyType> filters = null, eEnemyFilterType filterType = 1)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Expected O, but got Unknown
		//IL_001f: 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_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_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Expected O, but got Unknown
		//IL_008f: 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_00de: Expected O, but got Unknown
		//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
		ManualLogSource logger = Loader.Logger;
		bool flag = default(bool);
		BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(21, 1, ref flag);
		if (flag)
		{
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Wave GetNextType got ");
			((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eEnemyType>(__result);
		}
		logger.LogDebug(val);
		ManualLogSource logger2 = Loader.Logger;
		val = new BepInExDebugLogInterpolatedStringHandler(30, 1, ref flag);
		if (flag)
		{
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Using filterType ");
			((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eEnemyFilterType>(filterType);
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" and filters:");
		}
		logger2.LogDebug(val);
		Enumerator<eEnemyType> enumerator = filters.GetEnumerator();
		while (enumerator.MoveNext())
		{
			eEnemyType current = enumerator.Current;
			ManualLogSource logger3 = Loader.Logger;
			val = new BepInExDebugLogInterpolatedStringHandler(1, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eEnemyType>(current);
			}
			logger3.LogDebug(val);
		}
		Loader.Logger.LogDebug((object)"Wave Heats right now:");
		Enumerator<HeatType> enumerator2 = EnemyPopulationManager.Current.m_heatTypes.GetEnumerator();
		while (enumerator2.MoveNext())
		{
			HeatType current2 = enumerator2.Current;
			ManualLogSource logger4 = Loader.Logger;
			val = new BepInExDebugLogInterpolatedStringHandler(20, 3, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" type ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eEnemyType>(current2.m_enemyType);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" heat ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(current2.m_heat);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" weight ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(current2.m_weight);
			}
			logger4.LogDebug(val);
		}
	}

	[HarmonyPatch(typeof(EnemyPopulationManager), "GetWeightedRandomType")]
	[HarmonyPostfix]
	private static void AdjustGrabCount(EnemyPopulationManager __instance)
	{
		if (currentSettings != null && currentSettings.AdjustHeatGrabCount)
		{
			Enumerator<HeatType> enumerator = __instance.m_heatTypes.GetEnumerator();
			while (enumerator.MoveNext())
			{
				enumerator.Current.m_grabCountRef = __instance.m_globalGrabCount;
			}
		}
	}

	[HarmonyPatch(typeof(EnemyGroup), "SurvivalSpawning")]
	[HarmonyPrefix]
	private static void AdjustSurvivalWavePointsPrefix(EnemyGroup __instance, out bool __state)
	{
		if (__instance.m_nextSpawn > Clock.Time || !EnemyAllocator.AllowedToSpawn)
		{
			__state = false;
		}
		else
		{
			__state = true;
		}
	}

	[HarmonyPatch(typeof(EnemyGroup), "SurvivalSpawning")]
	[HarmonyPostfix]
	private static void AdjustSurvivalWavePointsPostfix(EnemyGroup __instance, bool __state)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		if (__state && !((Object)(object)__instance.SurvivalWave == (Object)null) && !(__instance.Data.populationScore > 1f))
		{
			float num = __instance.SurvivalWave.m_populationPointsPerWaveMax - __instance.SurvivalWave.m_populationPointsSpentDuringWave;
			if (num > 0f && num < 1f)
			{
				__instance.SurvivalWave.m_populationPointsSpentDuringWave = __instance.SurvivalWave.m_populationPointsPerWaveMax;
				SurvivalWave survivalWave = __instance.SurvivalWave;
				survivalWave.m_populationPointsSpentTotal += num;
			}
		}
	}
}