Decompiled source of ProjectEternalFriendly v1.6.18

plugins/ProjectEternal/net6/CustomEndScreen.dll

Decompiled 4 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CellMenu;
using GTFO.API;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
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("CustomEndScreen")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("CustomEndScreen")]
[assembly: AssemblyTitle("CustomEndScreen")]
[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 CustomEndScreen
{
	[HarmonyPatch(typeof(MainMenuGuiLayer), "AddPage")]
	public static class AddPagePatch
	{
		public static CM_PageBase defaultPageBase;

		public static bool Prefix(MainMenuGuiLayer __instance, eCM_MenuPage pageEnum, string pageResourcePath, ref CM_PageBase __result)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Invalid comparison between Unknown and I4
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected I4, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected I4, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected I4, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			EntryPoint.LogSource.LogDebug((object)pageResourcePath);
			if ((int)GameStateManager.Current.m_currentStateName == 1)
			{
				return true;
			}
			if (!pageResourcePath.Contains('/'))
			{
				return true;
			}
			((Il2CppArrayBase<CM_PageBase>)(object)__instance.m_pages)[(int)pageEnum] = GOUtil.SpawnChildAndGetComp<CM_PageBase>(AssetAPI.GetLoadedAsset<GameObject>(pageResourcePath), ((Component)((GuiLayer)__instance).GuiLayerBase).transform);
			((Il2CppArrayBase<CM_PageBase>)(object)__instance.m_pages)[(int)pageEnum].Setup(__instance);
			__result = ((Il2CppArrayBase<CM_PageBase>)(object)__instance.m_pages)[(int)pageEnum];
			__result.OnResolutionChange(__instance.m_currentScaledRes);
			return false;
		}
	}
	[HarmonyPatch(typeof(MainMenuGuiLayer), "OnExpeditionUpdated")]
	public static class ExpeditionUpdatedPatch
	{
		private static readonly List<string> RundownEightCustomScreens = new List<string>(4) { "CM_PageExpeditionSuccess_Completed", "CM_PageExpeditionSuccess_Resources expended_CellUI 2", "CM_PageExpeditionSuccess_SignalLost_CellUI", "CM_PageExpeditionSuccess_Stack Empty_CellUI 1" };

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

		private static string BackupOverride = string.Empty;

		public static void Prefix(MainMenuGuiLayer __instance, pActiveExpedition activeExpedition, ExpeditionInTierData expeditionInTierData)
		{
			if (CachedCustomExpeditions.TryGetValue(expeditionInTierData.Descriptive.PublicName, out string value))
			{
				BackupOverride = value;
			}
			else
			{
				BackupOverride = expeditionInTierData.SpecialOverrideData.CustomSuccessScreen;
			}
			if (!RundownEightCustomScreens.Contains(expeditionInTierData.SpecialOverrideData.CustomSuccessScreen))
			{
				if (!CachedCustomExpeditions.ContainsKey(expeditionInTierData.Descriptive.PublicName))
				{
					CachedCustomExpeditions.Add(expeditionInTierData.Descriptive.PublicName, expeditionInTierData.SpecialOverrideData.CustomSuccessScreen);
				}
				expeditionInTierData.SpecialOverrideData.CustomSuccessScreen = null;
			}
		}

		public static void Postfix(MainMenuGuiLayer __instance, pActiveExpedition activeExpedition, ExpeditionInTierData expeditionInTierData)
		{
			if (BackupOverride != null && BackupOverride.Contains('/'))
			{
				__instance.PageCustomExpeditionSuccess = __instance.AddPage((eCM_MenuPage)17, BackupOverride);
			}
		}
	}
	[BepInPlugin("com.Breeze.CustomEndScreen", "CustomEndScreen", "0.0.1")]
	[BepInProcess("GTFO.exe")]
	internal class EntryPoint : BasePlugin
	{
		public static ManualLogSource? LogSource { get; private set; }

		public static Harmony? m_Harmony { get; private set; }

		public override void Load()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			LogSource = ((BasePlugin)this).Log;
			m_Harmony = new Harmony("_CustomExpeditionSuccessScreen");
			m_Harmony.PatchAll();
		}
	}
}

plugins/ProjectEternal/net6/CustomRundownLabels.dll

Decompiled 4 months 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.Text.Json;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using GameData;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
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 = "")]
[assembly: AssemblyCompany("CustomRundownLabels")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("CustomRundownLabels")]
[assembly: AssemblyTitle("CustomRundownLabels")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace CustomRundownLabels;

public class ConfigSerializer<T> where T : new()
{
	private string JsonPath;

	private T JsonSettings;

	private FileStream JsonFile;

	private JsonSerializerOptions JsonOptions;

	public T Settings => JsonSettings;

	public ConfigSerializer(string jsonName)
	{
		JsonPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), jsonName + ".json");
		JsonSettings = new T();
		JsonOptions = new JsonSerializerOptions
		{
			AllowTrailingCommas = true,
			WriteIndented = true
		};
		if (File.Exists(JsonPath))
		{
			JsonFile = File.OpenRead(JsonPath);
			JsonSettings = JsonSerializer.Deserialize<T>(JsonFile, JsonOptions);
		}
		else
		{
			JsonFile = File.OpenWrite(JsonPath);
			JsonSerializer.Serialize(JsonFile, JsonSettings, JsonOptions);
		}
		JsonFile.Close();
	}
}
[BepInPlugin("me.bro.customrundownlabels", "CustomRundownLabels", "1.0.0")]
public class EntryPoint : BasePlugin
{
	public ConfigSerializer<fucking> Fucking;

	public override void Load()
	{
		PlayFabManager.OnTitleDataUpdated += Action.op_Implicit((Action)Setup);
	}

	public void Setup()
	{
		Fucking = new ConfigSerializer<fucking>("CustomRundownName");
		int num = 0;
		Enumerator<CM_RundownSelection> enumerator = MainMenuGuiLayer.Current.PageRundownNew.m_rundownSelections.GetEnumerator();
		while (enumerator.MoveNext())
		{
			CM_RundownSelection current = enumerator.Current;
			if ((Object)(object)current.m_altText != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)current.m_altText).gameObject);
			}
			((TMP_Text)current.m_rundownText).text = Fucking.Settings.Labels[num];
			num++;
		}
	}
}
public class fucking
{
	public bool UseCustomNames { get; set; }

	public List<string> Labels { get; set; }

	public fucking()
	{
		Labels = new List<string> { "R1", "R7", "R2", "R3", "R4", "R5", "R6", "R8" };
	}

	private void nextfucking()
	{
		Enumerator<CM_RundownSelection> enumerator = MainMenuGuiLayer.Current.PageRundownNew.m_rundownSelections.GetEnumerator();
		while (enumerator.MoveNext())
		{
			CM_RundownSelection current = enumerator.Current;
			uint num = uint.Parse(current.RundownKey.Substring("Local_".Length));
			if (GameDataBlockBase<RundownDataBlock>.s_blockByID != null && GameDataBlockBase<RundownDataBlock>.s_blockByID.ContainsKey(num))
			{
				RundownDataBlock val = GameDataBlockBase<RundownDataBlock>.s_blockByID[num];
				string untranslatedText = val.StorytellingData.Title.UntranslatedText;
				Labels.Add(untranslatedText);
			}
		}
	}
}

plugins/ProjectEternal/net6/LGTuner_Revised.dll

Decompiled 4 months 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 AssetShards;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Expedition;
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 LevelGeneration;
using LevelGeneration.Core;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[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+git32ee113-dirty-master")]
[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_0120: 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)
			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)
			{
				Logger.Info("menimme taenne");
				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("loysimme dimension ja levellayoutin");
							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.0.0")]
	[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 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();
			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 = "git32ee113-dirty-master";

		public const string SemVer = "1.0.0+git32ee113-dirty-master";

		public const string GitRevShort = "32ee113-dirty";

		public const string GitRevLong = "32ee113f774f28578bd63131db5298640efafe36-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_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_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_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			_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))
			{
				Logger.Info("trygetconfig failed, returning");
				return;
			}
			if (!_configContext.TryGetTileData(val, out var overrideData))
			{
				overrideData = _configContext.PopulateTileOverrideForZone(zone, val);
				if (overrideData == null)
				{
					Logger.Info("overridedata is null");
					return;
				}
			}
			if (!string.IsNullOrEmpty(overrideData.Geomorph))
			{
				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_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			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;

		[HarmonyWrapSafe]
		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.Configs
{
	public sealed class LayoutConfig
	{
		private TileOverrideData[,] _builtTileOverrides = new TileOverrideData[0, 0];

		public uint LevelLayoutID { get; set; }

		public Complex[] ExtraComplexResourceToLoad { get; set; } = Array.Empty<Complex>();


		public ZoneOverrideData[] ZoneOverrides { get; set; } = Array.Empty<ZoneOverrideData>();


		public TileOverrideData[] TileOverrides { get; set; } = Array.Empty<TileOverrideData>();


		[JsonIgnore]
		public int GridSize { get; private set; }

		[JsonIgnore]
		public int GridSizeHalf { get; private set; }

		public void Reset(int gridSize)
		{
			Array.ForEach(ZoneOverrides, delegate(ZoneOverrideData item)
			{
				item.Clear();
			});
			Array.Clear(_builtTileOverrides, 0, _builtTileOverrides.Length);
			GridSize = gridSize;
			GridSizeHalf = gridSize / 2;
			_builtTileOverrides = new TileOverrideData[GridSize, GridSize];
			TileOverrideData[] tileOverrides = TileOverrides;
			foreach (TileOverrideData tileOverrideData in tileOverrides)
			{
				if (_builtTileOverrides[tileOverrideData.X + GridSizeHalf, tileOverrideData.Z + GridSizeHalf] == null)
				{
					PutOverrideData(tileOverrideData);
					continue;
				}
				Logger.Error($"Duplicate tile data in layout: {LevelLayoutID}, ({tileOverrideData.X}, {tileOverrideData.Z})!");
			}
		}

		public bool TryGetTileData(LG_GridPosition normalGridPosition, out TileOverrideData overrideData)
		{
			//IL_0000: 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)
			int num = normalGridPosition.x + GridSizeHalf;
			if (num >= GridSize)
			{
				Logger.Error($"TryGetTileData grid x was out of range! {num}:{GridSize}");
				overrideData = null;
				return false;
			}
			int num2 = normalGridPosition.z + GridSizeHalf;
			if (num2 >= GridSize)
			{
				Logger.Error($"TryGetTileData grid Z was out of range! {num2}:{GridSize}");
				overrideData = null;
				return false;
			}
			overrideData = _builtTileOverrides[num, num2];
			return overrideData != null;
		}

		public void PutOverrideData(TileOverrideData data)
		{
			_builtTileOverrides[data.X + GridSizeHalf, data.Z + GridSizeHalf] = data;
		}

		public TileOverrideData PopulateTileOverrideForZone(LG_Zone zone, LG_GridPosition normalGridPosition)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGetZoneOverride(zone.LocalIndex, out var data))
			{
				return null;
			}
			if (TryGetTileData(normalGridPosition, out var overrideData))
			{
				overrideData.ZoneData = data;
				TryApplyOverrides(data, overrideData);
				return overrideData;
			}
			TileOverrideData tileOverrideData = new TileOverrideData
			{
				ZoneData = data,
				X = normalGridPosition.x,
				Z = normalGridPosition.z,
				OverridePlugWithNoGateChance = data.OverridePlugWithNoGateChance,
				PlugWithNoGateChance = data.PlugWithNoGateChance
			};
			TryApplyOverrides(data, tileOverrideData);
			PutOverrideData(tileOverrideData);
			return tileOverrideData;
		}

		private void TryApplyOverrides(ZoneOverrideData zoneOverrideData, TileOverrideData tileOverrideData)
		{
			if (zoneOverrideData.OverrideGeomorphs && string.IsNullOrEmpty(tileOverrideData.Geomorph))
			{
				ZoneOverrideData.GeomorphData? nextGeo = zoneOverrideData.GetNextGeo();
				if (nextGeo.HasValue)
				{
					tileOverrideData.Geomorph = nextGeo.Value.Geomorph;
					if (tileOverrideData.Rotation == RotateType.None)
					{
						tileOverrideData.Rotation = ZoneOverrideData.DirectionToRotate(nextGeo.Value.Direction);
					}
				}
			}
			if (zoneOverrideData.OverrideAltitudes && !tileOverrideData.OverrideAltitude)
			{
				int? nextAltitude = zoneOverrideData.GetNextAltitude();
				if (nextAltitude.HasValue)
				{
					tileOverrideData.OverrideAltitude = true;
					tileOverrideData.Altitude = nextAltitude.Value;
				}
			}
		}

		public bool TryGetZoneOverride(eLocalZoneIndex localIndex, out ZoneOverrideData data)
		{
			//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)
			data = ZoneOverrides.SingleOrDefault((ZoneOverrideData z) => z.LocalIndex == localIndex);
			return data != null;
		}
	}
	public sealed class TileOverrideData
	{
		public int X { get; set; }

		public int Z { get; set; }

		public bool OverrideAreaSeeds { get; set; }

		public uint[] AreaSeeds { get; set; } = Array.Empty<uint>();


		public RotateType Rotation { get; set; }

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


		public bool OverrideAltitude { get; set; }

		public int Altitude { get; set; }

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


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


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


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


		public bool OverridePlugWithNoGateChance { get; set; }

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


		[JsonIgnore]
		public ZoneOverrideData ZoneData { get; set; }
	}
	public sealed class ZoneOverrideData
	{
		public enum Direction
		{
			Unchanged,
			Random,
			Forward,
			Backward,
			Left,
			Right
		}

		public struct GeomorphData
		{
			public string Geomorph { get; set; }

			public Direction Direction { get; set; }
		}

		private int _curGeomorphIndex;

		private int _curAltitudeIndex;

		private int _curPlugIndex;

		public eLocalZoneIndex LocalIndex { get; set; }

		public bool OverrideGeomorphs { get; set; }

		public GeomorphData[] Geomorphs { get; set; } = Array.Empty<GeomorphData>();


		public bool OverrideAltitudes { get; set; }

		public int[] Altitudes { get; set; } = Array.Empty<int>();


		public bool OverridePlugs { get; set; }

		public string[] Plugs { get; set; } = Array.Empty<string>();


		public bool OverridePlugWithNoGateChance { get; set; }

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


		public void Clear()
		{
			_curGeomorphIndex = 0;
			_curAltitudeIndex = 0;
			_curPlugIndex = 0;
		}

		public GeomorphData? GetNextGeo()
		{
			if (Geomorphs == null || Geomorphs.Length == 0)
			{
				return null;
			}
			return Geomorphs[_curGeomorphIndex++ % Geomorphs.Length];
		}

		public int? GetNextAltitude()
		{
			if (Altitudes == null || Altitudes.Length == 0)
			{
				return null;
			}
			return Altitudes[_curAltitudeIndex++ % Altitudes.Length];
		}

		public string GetNextPlug()
		{
			if (Plugs == null || Plugs.Length == 0)
			{
				return string.Empty;
			}
			return Plugs[_curPlugIndex++ % Plugs.Length];
		}

		public static RotateType DirectionToRotate(Direction direction)
		{
			return direction switch
			{
				Direction.Unchanged => RotateType.None, 
				Direction.Random => RotateType.Towards_Random, 
				Direction.Forward => RotateType.Towards_Forward, 
				Direction.Backward => RotateType.Towards_Backward, 
				Direction.Left => RotateType.Towards_Left, 
				Direction.Right => RotateType.Towards_Right, 
				_ => throw new NotImplementedException($"DirectionType: {direction} is not supported"), 
			};
		}
	}
}

plugins/ProjectEternal/net6/Oxygen.dll

Decompiled 4 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.Json;
using System.Text.Json.Serialization;
using AK;
using Agents;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using GameEvent;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Localization;
using MTFO.Managers;
using Microsoft.CodeAnalysis;
using Oxygen.Components;
using Oxygen.Config;
using Oxygen.Utils;
using Oxygen.Utils.PartialData;
using Player;
using SNetwork;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Oxygen
{
	[BepInPlugin("Inas.Oxygen", "Oxygen", "1.3.2")]
	[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.*/)]
	public class Plugin : BasePlugin
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static Action <0>__OnBuildDone;

			public static Action <1>__OnLevelCleanup;

			public static Action <2>__Setup;

			public static Action <3>__OnLevelCleanup;

			public static Action <4>__OnBuildStart;

			public static Action <5>__OnLevelCleanup;

			public static LiveEditEventHandler <6>__Listener_FileChanged1;
		}

		public const string MODNAME = "Oxygen";

		public const string AUTHOR = "Inas";

		public const string GUID = "Inas.Oxygen";

		public const string VERSION = "1.3.2";

		public static readonly string OXYGEN_CONFIG_PATH = Path.Combine(ConfigManager.CustomPath, "Oxygen");

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

		private static LiveEditListener listener = null;

		public override void Load()
		{
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Expected O, but got Unknown
			if (!Directory.Exists(OXYGEN_CONFIG_PATH))
			{
				Directory.CreateDirectory(OXYGEN_CONFIG_PATH);
				StreamWriter streamWriter = File.CreateText(Path.Combine(OXYGEN_CONFIG_PATH, "Template.json"));
				streamWriter.WriteLine(ConfigManager.Serialize(new OxygenConfig()));
				streamWriter.Flush();
				streamWriter.Close();
			}
			ClassInjector.RegisterTypeInIl2Cpp<AirManager>();
			LevelAPI.OnBuildDone += AirManager.OnBuildDone;
			LevelAPI.OnLevelCleanup += AirManager.OnLevelCleanup;
			ClassInjector.RegisterTypeInIl2Cpp<AirBar>();
			LevelAPI.OnBuildStart += AirBar.Setup;
			LevelAPI.OnLevelCleanup += AirBar.OnLevelCleanup;
			ClassInjector.RegisterTypeInIl2Cpp<AirPlane>();
			LevelAPI.OnBuildStart += AirPlane.OnBuildStart;
			LevelAPI.OnLevelCleanup += AirPlane.OnLevelCleanup;
			new Harmony("Inas.Oxygen").PatchAll();
			foreach (string item in Directory.EnumerateFiles(OXYGEN_CONFIG_PATH, "*.json", SearchOption.AllDirectories))
			{
				ConfigManager.Load<OxygenConfig>(item, out var config);
				foreach (OxygenBlock block in config.Blocks)
				{
					foreach (uint fogSetting in block.FogSettings)
					{
						if (!lookup.ContainsKey(fogSetting))
						{
							lookup.Add(fogSetting, block);
						}
					}
				}
			}
			listener = LiveEdit.CreateListener(OXYGEN_CONFIG_PATH, "*.json", true);
			LiveEditListener obj = listener;
			object obj2 = <>O.<6>__Listener_FileChanged1;
			if (obj2 == null)
			{
				LiveEditEventHandler val = Listener_FileChanged1;
				<>O.<6>__Listener_FileChanged1 = val;
				obj2 = (object)val;
			}
			obj.FileChanged += (LiveEditEventHandler)obj2;
		}

		private static void Listener_FileChanged1(LiveEditEventArgs e)
		{
			Log.Warning("LiveEdit File Changed: " + e.FullPath + ".");
			LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content)
			{
				foreach (OxygenBlock block in ConfigManager.Deserialize<OxygenConfig>(content).Blocks)
				{
					foreach (uint fogSetting in block.FogSettings)
					{
						if (lookup.ContainsKey(fogSetting))
						{
							lookup.Remove(fogSetting);
						}
						lookup.Add(fogSetting, block);
						Log.Warning($"Replaced OxygenConfig for FogSetting: {fogSetting}.");
					}
				}
				if (GameStateManager.IsInExpedition)
				{
					AirManager.Current.UpdateAirConfig(AirManager.Current.FogSetting(), LiveEditForceUpdate: true);
				}
			});
		}
	}
}
namespace Oxygen.Utils
{
	internal static class Extension
	{
		public static T Instantiate<T>(this GameObject gameObject, string name) where T : Component
		{
			GameObject obj = Object.Instantiate<GameObject>(gameObject, gameObject.transform.parent, false);
			((Object)obj).name = name;
			return obj.GetComponent<T>();
		}
	}
	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);
		}
	}
	internal static class Log
	{
		private static ManualLogSource source;

		static Log()
		{
			source = Logger.CreateLogSource("Oxygen");
		}

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

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

		public static void Fatal(object msg)
		{
			source.LogFatal(msg);
		}

		public static void Info(object msg)
		{
			source.LogInfo(msg);
		}

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

		public static void Warning(object msg)
		{
			source.LogWarning(msg);
		}
	}
}
namespace Oxygen.Utils.PartialData
{
	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 == "LocalizedTextConverter");
				if ((object)type2 == null)
				{
					throw new Exception("Unable to Find LocalizedTextConverter 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);
				LocalizedTextConverter = (JsonConverter)Activator.CreateInstance(type2);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				Log.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)
			{
				Log.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}");
			}
		}
	}
}
namespace Oxygen.Patches
{
	[HarmonyPatch]
	internal class Patches_Dam_PlayerDamageLocal
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveNoAirDamage")]
		public static bool Pre_ReceiveNoAirDamage(Dam_PlayerDamageLocal __instance, pMiniDamageData data)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			float num = ((UFloat16)(ref data.damage)).Get(((Dam_SyncedDamageBase)__instance).HealthMax);
			((Dam_PlayerDamageBase)__instance).m_nextRegen = Clock.Time + ((Dam_PlayerDamageBase)__instance).Owner.PlayerData.healthRegenStartDelayAfterDamage;
			if (((Agent)((Dam_PlayerDamageBase)__instance).Owner).IsLocallyOwned)
			{
				DramaManager.CurrentState.OnLocalDamage(num);
				GameEventManager.PostEvent((eGameEvent)13, ((Dam_PlayerDamageBase)__instance).Owner, num, "", (Dictionary<string, string>)null);
			}
			else
			{
				DramaManager.CurrentState.OnTeammatesDamage(num);
			}
			if (((Dam_PlayerDamageBase)__instance).IgnoreAllDamage)
			{
				return false;
			}
			if (SNet.IsMaster && !((Dam_SyncedDamageBase)__instance).RegisterDamage(num))
			{
				((Dam_SyncedDamageBase)__instance).SendSetHealth(((Dam_SyncedDamageBase)__instance).Health);
			}
			__instance.Hitreact(((UFloat16)(ref data.damage)).Get(((Dam_SyncedDamageBase)__instance).HealthMax), Vector3.zero, true, false, false);
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveBulletDamage")]
		public static void Post_ReceiveBulletDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveMeleeDamage")]
		public static void Post_ReceiveMeleeDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveFireDamage")]
		public static void Post_ReceiveFireDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveShooterProjectileDamage")]
		public static void Post_ReceiveShooterProjectileDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveTentacleAttackDamage")]
		public static void Post_ReceiveTentacleAttackDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceivePushDamage")]
		public static void Post_ReceivePushDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveSetDead")]
		public static void Post_ReceiveSetDead()
		{
			AirManager.Current.ResetHealthToRegen();
		}
	}
	[HarmonyPatch(typeof(EnvironmentStateManager), "UpdateFog")]
	internal class EnvironmentStateManager_UpdateFog
	{
		public static void Prefix(EnvironmentStateManager __instance)
		{
			//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_002a: 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)
			if ((Object)(object)AirManager.Current == (Object)null)
			{
				return;
			}
			FogState val = ((Il2CppArrayBase<FogState>)(object)__instance.m_stateReplicator.State.FogStates)[__instance.m_latestKnownLocalDimensionCreationIndex];
			if (val.FogDataID != 0)
			{
				AirManager.Current.UpdateAirConfig(val.FogDataID);
				if (!AirManager.Current.HasAirConfig())
				{
					AirManager.Current.StopInfectionLoop();
				}
			}
		}
	}
	[HarmonyPatch(typeof(FogRepeller_Sphere), "StartRepelling")]
	internal class FogRepeller_Sphere_StartRepelling
	{
		public static void Postfix(ref FogRepeller_Sphere __instance)
		{
			if (__instance.m_infectionShield != null)
			{
				EffectVolumeManager.UnregisterVolume((EffectVolume)(object)__instance.m_infectionShield);
				((EffectVolume)__instance.m_infectionShield).contents = (eEffectVolumeContents)0;
				EffectVolumeManager.RegisterVolume((EffectVolume)(object)__instance.m_infectionShield);
			}
		}
	}
	[HarmonyPatch(typeof(LocalPlayerAgentSettings), "UpdateBlendTowardsTargetFogSetting")]
	internal class LocalPlayerAgentSettings_UpdateBlendTowardsTargetFogSetting
	{
		public static void Postfix(LocalPlayerAgentSettings __instance, float amount)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (!AirManager.Current.HasAirConfig())
			{
				AirPlane.Current.Unregister();
			}
			else
			{
				if (__instance.m_targetFogSettings == null || !SNet.LocalPlayer.HasPlayerAgent)
				{
					return;
				}
				PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent();
				if ((Object)(object)localPlayerAgent.FPSCamera == (Object)null)
				{
					return;
				}
				AirPlane current = AirPlane.Current;
				if (!((Object)(object)current == (Object)null) && RundownManager.ExpeditionIsStarted)
				{
					float num = 0f;
					Dimension val = default(Dimension);
					if (Dimension.GetDimension(((Agent)localPlayerAgent).DimensionIndex, ref val))
					{
						num = val.GroundY;
					}
					PreLitVolume prelitVolume = localPlayerAgent.FPSCamera.PrelitVolume;
					((EffectVolume)current.airPlane).invert = (double)prelitVolume.m_densityHeightMaxBoost > (double)prelitVolume.m_fogDensity;
					((EffectVolume)current.airPlane).contents = (eEffectVolumeContents)1;
					((EffectVolume)current.airPlane).modification = (eEffectVolumeModification)0;
					((EffectVolume)current.airPlane).modificationScale = AirManager.Current.AirLoss();
					current.airPlane.lowestAltitude = prelitVolume.m_densityHeightAltitude + num;
					current.airPlane.highestAltitude = prelitVolume.m_densityHeightAltitude + prelitVolume.m_densityHeightRange + num;
					AirPlane.Current.Register();
				}
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_PlayerAgent
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlayerAgent), "ReceiveModification")]
		public static void ReceiveModification(PlayerAgent __instance, ref EV_ModificationData data)
		{
			if (AirManager.Current.HasAirConfig())
			{
				if ((double)data.health != 0.0)
				{
					AirManager.Current.RemoveAir(data.health);
				}
				else
				{
					AirManager.Current.AddAir();
				}
				data.health = 0f;
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(PlayerAgent), "Setup")]
		internal static void Post_Setup(PlayerAgent __instance)
		{
			if (((Agent)__instance).IsLocallyOwned)
			{
				AirManager.Setup(__instance);
			}
		}
	}
}
namespace Oxygen.Config
{
	public class ConfigManager
	{
		private static readonly JsonSerializerOptions s_SerializerOptions;

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

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

		static ConfigManager()
		{
			s_SerializerOptions = new JsonSerializerOptions
			{
				AllowTrailingCommas = true,
				ReadCommentHandling = JsonCommentHandling.Skip,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true
			};
			s_SerializerOptions.Converters.Add(new JsonStringEnumConverter());
			if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized)
			{
				s_SerializerOptions.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter);
				s_SerializerOptions.Converters.Add(MTFOPartialDataUtil.LocalizedTextConverter);
				Log.Message("PartialData Support Found!");
			}
			else
			{
				s_SerializerOptions.Converters.Add(new LocalizedTextConverter());
			}
		}

		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(ConfigManager.CustomPath, "Oxygen", file));
			config = Deserialize<T>(file);
		}
	}
	public class AirText
	{
		public float x { get; set; }

		public float y { get; set; }

		public LocalizedText Text { get; set; }
	}
	public class OxygenConfig
	{
		public List<OxygenBlock> Blocks { get; set; } = new List<OxygenBlock>
		{
			new OxygenBlock()
		};

	}
	public class OxygenBlock
	{
		public float AirLoss { get; set; }

		public float AirGain { get; set; } = 1f;


		public float DamageTime { get; set; } = 1f;


		public float DamageAmount { get; set; }

		public bool ShatterGlass { get; set; }

		public float ShatterAmount { get; set; }

		public float DamageThreshold { get; set; } = 0.1f;


		public bool AlwaysDisplayAirBar { get; set; }

		public float HealthRegenProportion { get; set; } = 1f;


		public float TimeToStartHealthRegen { get; set; } = 3f;


		public float TimeToCompleteHealthRegen { get; set; } = 5f;


		public AirText AirText { get; set; }

		public List<uint> FogSettings { get; set; } = new List<uint> { 0u };

	}
}
namespace Oxygen.Components
{
	public class AirBar : MonoBehaviour
	{
		public static AirBar Current;

		private TextMeshPro m_airText;

		private TextMeshPro m_airTextLocalization;

		private float m_airTextX;

		private float m_airTextY;

		private float m_airTextZ;

		private RectTransform m_air1;

		private RectTransform m_air2;

		private SpriteRenderer m_airBar1;

		private SpriteRenderer m_airBar2;

		private float m_airWidth = 100f;

		private float m_barHeightMin = 3f;

		private float m_barHeightMax = 9f;

		private Color m_airLow = new Color(0f, 0.5f, 0.5f);

		private Color m_airHigh = new Color(0f, 0.3f, 0.8f);

		public AirBar(IntPtr value)
			: base(value)
		{
		}//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)


		public static void Setup()
		{
			if ((Object)(object)Current == (Object)null)
			{
				Current = ((Component)GuiManager.Current.m_playerLayer.m_playerStatus).gameObject.AddComponent<AirBar>();
				Current.Init();
			}
		}

		private void Init()
		{
			//IL_00e5: 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_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: 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_027a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)m_airText == (Object)null)
			{
				m_airText = ((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_healthText).gameObject.Instantiate<TextMeshPro>("AirText");
				TextMeshPro airText = m_airText;
				((TMP_Text)airText).fontSize = ((TMP_Text)airText).fontSize / 1.25f;
				m_airText.transform.Translate(0f, -30f, 0f);
			}
			if ((Object)(object)m_airTextLocalization == (Object)null)
			{
				m_airTextLocalization = ((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_pulseText).gameObject.Instantiate<TextMeshPro>("AirText Localization");
				((Behaviour)m_airTextLocalization).enabled = true;
				m_airTextLocalization.transform.Translate(300f - m_airWidth, -45f, 0f);
				m_airTextX = m_airTextLocalization.transform.position.x;
				m_airTextY = m_airTextLocalization.transform.position.y;
				m_airTextZ = m_airTextLocalization.transform.position.z;
			}
			if ((Object)(object)m_air1 == (Object)null)
			{
				m_air1 = ((Component)((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_health1).gameObject.transform.parent).gameObject.Instantiate<RectTransform>("AirFill Right");
				((Component)m_air1).transform.Translate(0f, -30f, 0f);
				SpriteRenderer component = ((Component)((Transform)m_air1).GetChild(0)).GetComponent<SpriteRenderer>();
				component.size = new Vector2(m_airWidth, component.size.y);
				m_airBar1 = ((Component)((Transform)m_air1).GetChild(1)).GetComponent<SpriteRenderer>();
				((Renderer)((Component)((Transform)m_air1).GetChild(2)).GetComponent<SpriteRenderer>()).enabled = false;
			}
			if ((Object)(object)m_air2 == (Object)null)
			{
				m_air2 = ((Component)((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_health2).gameObject.transform.parent).gameObject.Instantiate<RectTransform>("AirFill Left");
				((Component)m_air2).transform.Translate(0f, 30f, 0f);
				SpriteRenderer component2 = ((Component)((Transform)m_air2).GetChild(0)).GetComponent<SpriteRenderer>();
				component2.size = new Vector2(m_airWidth, component2.size.y);
				m_airBar2 = ((Component)((Transform)m_air2).GetChild(1)).GetComponent<SpriteRenderer>();
				((Renderer)((Component)((Transform)m_air2).GetChild(2)).GetComponent<SpriteRenderer>()).enabled = false;
			}
			UpdateAirBar(1f);
			SetVisible(vis: false);
		}

		public void UpdateAirBar(float air)
		{
			SetAirPercentageText(air);
			SetAirBar(m_airBar1, air);
			SetAirBar(m_airBar2, air);
		}

		private void SetAirBar(SpriteRenderer bar, float val)
		{
			//IL_001b: 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_0033: Unknown result type (might be due to invalid IL or missing references)
			bar.size = new Vector2(val * m_airWidth, Mathf.Lerp(m_barHeightMin, m_barHeightMax, val));
			bar.color = Color.Lerp(m_airLow, m_airHigh, val);
		}

		private void SetAirPercentageText(float val)
		{
			//IL_0001: 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_0029: 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)
			Color color = Color.Lerp(m_airLow, m_airHigh, val);
			((TMP_Text)m_airText).text = "O<size=75%>2</size>";
			((Graphic)m_airText).color = color;
			((TMP_Text)m_airText).ForceMeshUpdate(true, false);
			((Graphic)m_airTextLocalization).color = color;
			((TMP_Text)m_airTextLocalization).ForceMeshUpdate(true, false);
		}

		public void UpdateAirText(OxygenBlock config)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			if (config != null)
			{
				string text = LocalizedText.op_Implicit(config.AirText.Text);
				float x = config.AirText.x;
				float y = config.AirText.y;
				((TMP_Text)m_airTextLocalization).text = text;
				((TMP_Text)m_airTextLocalization).ForceMeshUpdate(true, false);
				CoroutineManager.BlinkIn(((Component)m_airTextLocalization).gameObject, 0f);
				m_airTextLocalization.transform.SetPositionAndRotation(new Vector3(m_airTextX + x, m_airTextY + y, m_airTextZ), m_airTextLocalization.transform.rotation);
			}
		}

		public void SetVisible(bool vis)
		{
			((Component)m_airText).gameObject.SetActive(vis);
			((Component)m_airTextLocalization).gameObject.SetActive(vis);
			((Component)m_air1).gameObject.SetActive(vis);
			((Component)m_air2).gameObject.SetActive(vis);
		}

		public static void OnLevelCleanup()
		{
			if (!((Object)(object)Current == (Object)null))
			{
				Current.SetVisible(vis: false);
			}
		}
	}
	public class AirManager : MonoBehaviour
	{
		public static AirManager Current;

		public PlayerAgent m_playerAgent;

		private HUDGlassShatter m_hudGlass;

		private Dam_PlayerDamageBase Damage;

		public OxygenBlock config;

		private uint fogSetting;

		private FogSettingsDataBlock fogSettingDB;

		private float airAmount = 1f;

		private float damageTick;

		private float glassShatterAmount;

		private bool m_isInInfectionLoop;

		private bool isRegeningHealth;

		private float healthToRegen;

		private float healthRegenTick;

		private float tickUntilHealthRegenHealthStart;

		private readonly float regenHealthTickInterval = 0.25f;

		private float healthRegenAmountPerInterval;

		internal bool PlayerShouldCough;

		private readonly float CoughPerLoss = 0.1f;

		private float CoughLoss;

		public AirManager(IntPtr value)
			: base(value)
		{
		}

		public static void Setup(PlayerAgent playerAgent)
		{
			Current = ((Component)playerAgent).gameObject.AddComponent<AirManager>();
		}

		public static void OnBuildDone()
		{
			if (!((Object)(object)Current == (Object)null))
			{
				Current.m_playerAgent = PlayerManager.GetLocalPlayerAgent();
				Current.m_hudGlass = ((Component)Current.m_playerAgent.FPSCamera).GetComponent<HUDGlassShatter>();
				Current.Damage = ((Component)Current.m_playerAgent).gameObject.GetComponent<Dam_PlayerDamageBase>();
				Current.UpdateAirConfig(RundownManager.ActiveExpedition.Expedition.FogSettings);
				AirBar.Current.UpdateAirText(Current.config);
			}
		}

		public static void OnLevelCleanup()
		{
			if (!((Object)(object)Current == (Object)null))
			{
				if (Current.m_isInInfectionLoop)
				{
					Current.StopInfectionLoop();
				}
				Current.config = null;
				Current.fogSetting = 0u;
				Current.fogSettingDB = null;
				Current.airAmount = 0f;
				Current.damageTick = 0f;
				Current.glassShatterAmount = 0f;
				Current.healthToRegen = 0f;
				Current.m_playerAgent = null;
				Current.m_hudGlass = null;
				Current.Damage = null;
			}
		}

		private void Update()
		{
			if (!RundownManager.ExpeditionIsStarted)
			{
				return;
			}
			if (!HasAirConfig())
			{
				AirBar.Current.SetVisible(vis: false);
				return;
			}
			if (airAmount == 1f)
			{
				if (config.AlwaysDisplayAirBar)
				{
					AirBar.Current.SetVisible(vis: true);
				}
				else
				{
					AirBar.Current.SetVisible(vis: false);
				}
			}
			else
			{
				AirBar.Current.SetVisible(vis: true);
			}
			if (airAmount <= config.DamageThreshold)
			{
				damageTick += Time.deltaTime;
				if (damageTick > config.DamageTime && ((Agent)m_playerAgent).Alive)
				{
					AirDamage();
				}
				isRegeningHealth = false;
			}
			else if (healthToRegen > 0f)
			{
				tickUntilHealthRegenHealthStart += Time.deltaTime;
				if (tickUntilHealthRegenHealthStart > config.TimeToStartHealthRegen)
				{
					if (healthRegenAmountPerInterval == 0f)
					{
						healthRegenAmountPerInterval = healthToRegen * (regenHealthTickInterval / config.TimeToCompleteHealthRegen);
					}
					RegenHealth();
					if (!isRegeningHealth)
					{
						Damage.m_nextRegen = Clock.Time + config.TimeToStartHealthRegen + config.TimeToCompleteHealthRegen;
						isRegeningHealth = true;
					}
				}
			}
			else
			{
				isRegeningHealth = false;
			}
		}

		public void AddAir()
		{
			if (HasAirConfig())
			{
				float airGain = config.AirGain;
				airAmount = Mathf.Clamp01(airAmount + airGain);
				AirBar.Current.UpdateAirBar(airAmount);
				if (fogSettingDB.Infection <= 0f && m_isInInfectionLoop)
				{
					StopInfectionLoop();
				}
			}
		}

		public void RemoveAir(float amount)
		{
			if (HasAirConfig())
			{
				amount = config.AirLoss;
				airAmount = Mathf.Clamp01(airAmount - amount);
				AirBar.Current.UpdateAirBar(airAmount);
				if (fogSettingDB.Infection <= 0f && amount > 0f)
				{
					StartInfectionLoop();
				}
			}
		}

		public void AirDamage()
		{
			float health = ((Dam_SyncedDamageBase)Damage).Health;
			float damageAmount = config.DamageAmount;
			Damage.m_nextRegen = Clock.Time + config.TimeToStartHealthRegen;
			if (!(health <= 1f))
			{
				((Dam_SyncedDamageBase)Damage).NoAirDamage(damageAmount);
				if (config.ShatterGlass)
				{
					glassShatterAmount += config.ShatterAmount;
					m_hudGlass.SetGlassShatterProgression(glassShatterAmount);
				}
				damageTick = 0f;
				tickUntilHealthRegenHealthStart = 0f;
				healthRegenAmountPerInterval = 0f;
				healthToRegen += damageAmount * config.HealthRegenProportion;
				CoughLoss += damageAmount;
				if (CoughLoss > CoughPerLoss)
				{
					PlayerShouldCough = true;
					CoughLoss = 0f;
				}
			}
		}

		public void RegenHealth()
		{
			if (healthToRegen <= 0f)
			{
				return;
			}
			tickUntilHealthRegenHealthStart = config.TimeToStartHealthRegen;
			healthRegenTick += Time.deltaTime;
			if (healthRegenTick > regenHealthTickInterval)
			{
				float num = healthRegenAmountPerInterval;
				if (num >= healthToRegen)
				{
					num = healthToRegen;
					healthToRegen = 0f;
					tickUntilHealthRegenHealthStart = 0f;
					healthRegenAmountPerInterval = 0f;
					isRegeningHealth = false;
				}
				else
				{
					healthToRegen -= num;
				}
				((Dam_SyncedDamageBase)Damage).AddHealth(num, (Agent)(object)m_playerAgent);
				healthRegenTick = 0f;
			}
		}

		public void UpdateAirConfig(uint fogsetting, bool LiveEditForceUpdate = false)
		{
			if (fogsetting != 0 && (fogsetting != fogSetting || LiveEditForceUpdate))
			{
				if (Plugin.lookup.ContainsKey(fogsetting))
				{
					config = Plugin.lookup[fogsetting];
				}
				else if (Plugin.lookup.ContainsKey(0u))
				{
					config = Plugin.lookup[0u];
				}
				else
				{
					config = null;
					airAmount = 1f;
				}
				fogSetting = fogsetting;
				fogSettingDB = GameDataBlockBase<FogSettingsDataBlock>.GetBlock(fogsetting);
				if (GameStateManager.IsInExpedition)
				{
					AirBar.Current.UpdateAirText(config);
				}
			}
		}

		public void ResetHealthToRegen()
		{
			healthRegenTick = 0f;
			healthToRegen = 0f;
			tickUntilHealthRegenHealthStart = 0f;
		}

		public float AirLoss()
		{
			if (config != null)
			{
				return config.AirLoss;
			}
			return 0f;
		}

		public bool AlwaysDisplayAirBar()
		{
			if (config != null)
			{
				return config.AlwaysDisplayAirBar;
			}
			return false;
		}

		public uint FogSetting()
		{
			return fogSetting;
		}

		public float HealthToRegen()
		{
			return healthToRegen;
		}

		public string AirText()
		{
			return LocalizedText.op_Implicit((config == null) ? null : config.AirText.Text);
		}

		public float AirTextX()
		{
			if (config != null)
			{
				return config.AirText.x;
			}
			return 0f;
		}

		public float AirTextY()
		{
			if (config != null)
			{
				return config.AirText.y;
			}
			return 0f;
		}

		public bool HasAirConfig()
		{
			return config != null;
		}

		public void StartInfectionLoop()
		{
			if (!m_isInInfectionLoop)
			{
				m_playerAgent.Sound.Post(EVENTS.INFECTION_EFFECT_LOOP_START, true);
				m_isInInfectionLoop = true;
			}
		}

		public void StopInfectionLoop()
		{
			if (m_isInInfectionLoop)
			{
				if ((Object)(object)m_playerAgent != (Object)null && m_playerAgent.Sound != null)
				{
					m_playerAgent.Sound.Post(EVENTS.INFECTION_EFFECT_LOOP_STOP, true);
				}
				m_isInInfectionLoop = false;
			}
		}
	}
	public class AirPlane : MonoBehaviour
	{
		public static AirPlane Current;

		public EV_Plane airPlane;

		private bool isAirPlaneRegistered;

		public AirPlane(IntPtr value)
			: base(value)
		{
		}

		public static void OnBuildStart()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			if ((Object)(object)Current == (Object)null)
			{
				Current = ((Component)LocalPlayerAgentSettings.Current).gameObject.AddComponent<AirPlane>();
			}
			Current.airPlane = new EV_Plane();
			uint num = RundownManager.ActiveExpedition.Expedition.FogSettings;
			if (num == 0)
			{
				num = 21u;
			}
			OxygenBlock oxygenBlock = (Plugin.lookup.ContainsKey(num) ? Plugin.lookup[num] : ((!Plugin.lookup.ContainsKey(0u)) ? null : Plugin.lookup[0u]));
			FogSettingsDataBlock block = GameDataBlockBase<FogSettingsDataBlock>.GetBlock(num);
			((EffectVolume)Current.airPlane).invert = block.DensityHeightMaxBoost > block.FogDensity;
			((EffectVolume)Current.airPlane).contents = (eEffectVolumeContents)1;
			((EffectVolume)Current.airPlane).modification = (eEffectVolumeModification)0;
			Current.airPlane.lowestAltitude = block.DensityHeightAltitude;
			Current.airPlane.highestAltitude = block.DensityHeightAltitude + block.DensityHeightRange;
			if (oxygenBlock != null)
			{
				((EffectVolume)Current.airPlane).modificationScale = oxygenBlock.AirLoss;
				Current.Register();
			}
		}

		public static void OnLevelCleanup()
		{
			if (!((Object)(object)Current == (Object)null))
			{
				Current.Unregister();
				Current.isAirPlaneRegistered = false;
				Current.airPlane = null;
			}
		}

		public void Register()
		{
			if (airPlane != null && !isAirPlaneRegistered)
			{
				EffectVolumeManager.RegisterVolume((EffectVolume)(object)airPlane);
				isAirPlaneRegistered = true;
			}
		}

		public void Unregister()
		{
			if (airPlane != null && isAirPlaneRegistered)
			{
				EffectVolumeManager.UnregisterVolume((EffectVolume)(object)airPlane);
				isAirPlaneRegistered = false;
			}
		}
	}
}

plugins/ProjectEternal/net6/PortalPuzzleChanger.dll

Decompiled 4 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.Json;
using System.Text.Json.Serialization;
using AK;
using Agents;
using AssetShards;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using ChainedPuzzles;
using Enemies;
using FX_EffectSystem;
using GTFO.API;
using GTFO.API.Components;
using GTFO.API.JSON.Converters;
using GTFO.API.Wrappers;
using GameData;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using LevelGeneration;
using MTFO.Managers;
using Microsoft.CodeAnalysis;
using Player;
using PortalPuzzleChanger.ConfigFiles;
using PortalPuzzleChanger.GameScripts;
using PortalPuzzleChanger.Plugin;
using SNetwork;
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("PortalPuzzleChanger")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("PortalPuzzleChanger")]
[assembly: AssemblyTitle("PortalPuzzleChanger")]
[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 PortalPuzzleChanger.Plugin
{
	[BepInPlugin("com.Breeze.PortalPuzzleChanger", "PortalPuzzleChanger", "0.0.1")]
	[BepInProcess("GTFO.exe")]
	internal class EntryPoint : BasePlugin
	{
		public static Dictionary<string, Sprite> CachedSprites;

		public static readonly JsonSerializerOptions SerializerOptions = new JsonSerializerOptions
		{
			ReadCommentHandling = JsonCommentHandling.Skip,
			PropertyNameCaseInsensitive = true,
			IncludeFields = true,
			AllowTrailingCommas = true,
			WriteIndented = true
		};

		public static ManualLogSource? LogSource { get; private set; }

		public static Harmony? m_Harmony { get; private set; }

		public override void Load()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			LogSource = ((BasePlugin)this).Log;
			m_Harmony = new Harmony("_PortalPuzzleChanger_");
			m_Harmony.PatchAll();
			SerializerOptions.Converters.Add((JsonConverter)new LocalizedTextConverter());
			SerializerOptions.Converters.Add((JsonConverter)new Vector3Converter());
			SerializerOptions.Converters.Add((JsonConverter)new Vector2Converter());
			SerializerOptions.Converters.Add((JsonConverter)new ColorConverter());
			PortalPuzzleChangerSetup.Load();
			EnemyTagChangerConfigSetup.Load();
			GrenadeLauncherConfigSetup.Load();
			ClassInjector.RegisterTypeInIl2Cpp<GrenadeProjectile>();
			AssetAPI.OnAssetBundlesLoaded += OnAssetsLoaded;
		}

		public void OnAssetsLoaded()
		{
			//IL_0060: 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)
			List<EnemyTagChanger> list = EnemyTagChangerConfigSetup.EnabledConfigs.Values.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (!string.IsNullOrEmpty(list[i].CustomImagePath))
				{
					Texture2D loadedAsset = AssetAPI.GetLoadedAsset<Texture2D>(list[i].CustomImagePath);
					Sprite val = Sprite.Create(loadedAsset, new Rect(0f, 0f, (float)((Texture)loadedAsset).width, (float)((Texture)loadedAsset).height), new Vector2(0.5f, 0.5f), 64f);
					((Object)val).hideFlags = (HideFlags)61;
					((Object)val).name = list[i].CustomImagePath;
					CachedSprites.Add(((Object)val).name, val);
					Debug("Created a sprite from path: " + list[i].CustomImagePath);
				}
			}
		}

		public static void Debug(string message)
		{
			LogSource.LogDebug((object)("[DEBUG] " + message));
		}

		public static void DebugWarning(string message)
		{
			LogSource.LogWarning((object)("[WARNING] " + message));
		}

		public static void DebugError(string message)
		{
			LogSource.LogError((object)("[ERROR] " + message));
		}
	}
	public class PortalPuzzleChangerSetup
	{
		public static Dictionary<uint, List<PortalEntry>> EnabledConfigs = new Dictionary<uint, List<PortalEntry>>();

		private static List<PortalChangerConfig>? Configs;

		public static string Name { get; } = "PortalPuzzleChanger.json";


		public static void Load()
		{
			string path = Path.Combine(ConfigManager.CustomPath, Name);
			if (File.Exists(path))
			{
				Configs = JsonSerializer.Deserialize<List<PortalChangerConfig>>(File.ReadAllText(path), EntryPoint.SerializerOptions);
				EntryPoint.Debug(Name + " has loaded successfully");
			}
			else
			{
				Configs = new List<PortalChangerConfig>
				{
					new PortalChangerConfig()
				};
				string contents = JsonSerializer.Serialize(Configs, EntryPoint.SerializerOptions);
				File.WriteAllText(path, contents);
				EntryPoint.DebugWarning(Name + " did not exist, creating it now");
			}
			EnabledConfigs.Clear();
			int count = Configs.Count;
			for (int i = 0; i < count; i++)
			{
				if (Configs[i].InternalEnabled)
				{
					EnabledConfigs.Add(Configs[i].MainLevelLayoutID, Configs[i].PortalEntries);
				}
			}
		}
	}
	public class EnemyTagChangerConfigSetup
	{
		public static Dictionary<uint, EnemyTagChanger> EnabledConfigs = new Dictionary<uint, EnemyTagChanger>();

		private static List<EnemyTagChanger>? Configs;

		public static string Name { get; } = "EnemyTags.json";


		public static void Load()
		{
			string path = Path.Combine(ConfigManager.CustomPath, Name);
			if (File.Exists(path))
			{
				Configs = JsonSerializer.Deserialize<List<EnemyTagChanger>>(File.ReadAllText(path), EntryPoint.SerializerOptions);
				EntryPoint.Debug(Name + " has loaded successfully");
			}
			else
			{
				Configs = new List<EnemyTagChanger>
				{
					new EnemyTagChanger()
				};
				string contents = JsonSerializer.Serialize(Configs, EntryPoint.SerializerOptions);
				File.WriteAllText(path, contents);
				EntryPoint.DebugWarning(Name + " did not exist, creating it now");
			}
			EnabledConfigs.Clear();
			int count = Configs.Count;
			for (int i = 0; i < count; i++)
			{
				if (Configs[i].internalEnabled)
				{
					EnabledConfigs.Add(Configs[i].EnemyID, Configs[i]);
				}
			}
		}
	}
	public class GrenadeLauncherConfigSetup
	{
		public static Dictionary<uint, GrenadeLauncherConfig> EnabledConfigs = new Dictionary<uint, GrenadeLauncherConfig>();

		private static List<GrenadeLauncherConfig>? Configs;

		public static string Name { get; } = "GrenadeLauncher.json";


		public static void Load()
		{
			string path = Path.Combine(ConfigManager.CustomPath, Name);
			if (File.Exists(path))
			{
				Configs = JsonSerializer.Deserialize<List<GrenadeLauncherConfig>>(File.ReadAllText(path), EntryPoint.SerializerOptions);
				EntryPoint.Debug(Name + " has loaded successfully");
			}
			else
			{
				Configs = new List<GrenadeLauncherConfig>
				{
					new GrenadeLauncherConfig()
				};
				string contents = JsonSerializer.Serialize(Configs, EntryPoint.SerializerOptions);
				File.WriteAllText(path, contents);
				EntryPoint.DebugWarning(Name + " did not exist, creating it now");
			}
			EnabledConfigs.Clear();
			int count = Configs.Count;
			for (int i = 0; i < count; i++)
			{
				if (Configs[i].internalEnabled)
				{
					EnabledConfigs.Add(Configs[i].PersistentID, Configs[i]);
				}
			}
		}
	}
}
namespace PortalPuzzleChanger.Patches
{
	[HarmonyPatch(typeof(LG_DimensionPortal), "Setup")]
	public static class DimensionPortalPatch
	{
		public static void Prefix(LG_DimensionPortal __instance)
		{
			//IL_002e: 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_0049: 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: 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_00aa: 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)
			if (!PortalPuzzleChangerSetup.EnabledConfigs.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData))
			{
				return;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) original = (__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex);
			List<PortalEntry> list = PortalPuzzleChangerSetup.EnabledConfigs[RundownManager.ActiveExpedition.LevelLayoutData];
			foreach (PortalEntry item in list)
			{
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) comparingTo = (item.DimensionIndex, item.LayerType, item.ZoneIndex);
				if (DoesZoneMatch(original, comparingTo))
				{
					__instance.m_targetDimension = item.TargetDimension;
					__instance.m_targetZone = item.TargetZoneIndex;
					__instance.PortalChainPuzzle = item.PortalChainedPuzzleId;
					EntryPoint.Debug("Changing the ChainedPuzzleID on " + __instance.PublicName);
				}
			}
		}

		public static void Postfix(LG_DimensionPortal __instance)
		{
			//IL_002e: 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_0049: 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_0091: 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)
			if (!PortalPuzzleChangerSetup.EnabledConfigs.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData))
			{
				return;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) original = (__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex);
			List<PortalEntry> list = PortalPuzzleChangerSetup.EnabledConfigs[RundownManager.ActiveExpedition.LevelLayoutData];
			foreach (PortalEntry item in list)
			{
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) comparingTo = (item.DimensionIndex, item.LayerType, item.ZoneIndex);
				if (DoesZoneMatch(original, comparingTo) && item.CreateTeamScanAsLast)
				{
					ChainedPuzzleInstance puzzleInstance = ChainedPuzzleManager.CreatePuzzleInstance(4u, __instance.SpawnNode.m_area, __instance.m_portalBioScanPoint.position, __instance.m_portalBioScanPoint);
					puzzleInstance.OnPuzzleSolved = __instance.m_portalChainPuzzleInstance.OnPuzzleSolved;
					__instance.m_portalChainPuzzleInstance.OnPuzzleSolved = Action.op_Implicit((Action)delegate
					{
						puzzleInstance.AttemptInteract((eChainedPuzzleInteraction)0);
					});
					EntryPoint.Debug("Adding team scan on " + __instance.PublicName);
				}
			}
		}

		private static bool DoesZoneMatch((eDimensionIndex, LG_LayerType, eLocalZoneIndex) original, (eDimensionIndex, LG_LayerType, eLocalZoneIndex) comparingTo)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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)
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) tuple = original;
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) tuple2 = comparingTo;
			return tuple.Item1 == tuple2.Item1 && tuple.Item2 == tuple2.Item2 && tuple.Item3 == tuple2.Item3;
		}
	}
	[HarmonyPatch(typeof(HackingTool), "Setup")]
	public static class HackingToolTest
	{
		public static void Postfix(HackingTool __instance)
		{
		}
	}
	[HarmonyPatch(typeof(EnemyAgent), "SyncPlaceNavMarkerTag")]
	internal static class EnemyTagPatch
	{
		public static void Postfix(EnemyAgent __instance)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			if (EnemyTagChangerConfigSetup.EnabledConfigs.ContainsKey(__instance.EnemyDataID))
			{
				EnemyTagChanger enemyTagChanger = EnemyTagChangerConfigSetup.EnabledConfigs[__instance.EnemyDataID];
				NavMarker tagMarker = __instance.m_tagMarker;
				if (!string.IsNullOrEmpty(enemyTagChanger.CustomImagePath))
				{
					SpriteRenderer component = ((Component)tagMarker.m_enemySubObj).GetComponent<SpriteRenderer>();
					component.sprite = EntryPoint.CachedSprites[enemyTagChanger.CustomImagePath];
				}
				tagMarker.SetColor(enemyTagChanger.TagColor);
			}
		}
	}
	[HarmonyPatch(typeof(GrenadeBase), "Awake")]
	internal static class GrenadeBase_Setup
	{
		public static void Postfix(GrenadeBase __instance)
		{
			GrenadeProjectile grenadeProjectile = ((Component)__instance).gameObject.AddComponent<GrenadeProjectile>();
			((Behaviour)grenadeProjectile).enabled = true;
			grenadeProjectile.GrenadeBase = __instance;
		}
	}
	[HarmonyPatch(typeof(GrenadeBase), "GrenadeDelay")]
	internal static class GrenadeBase_GrenadeDelay
	{
		public static bool Prefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(GrenadeBase), "Start")]
	internal static class GrenadeBase_Start
	{
		public static void Postfix(GrenadeBase __instance)
		{
			((MonoBehaviour)__instance).CancelInvoke("GrenadeDelay");
		}
	}
	[HarmonyPatch(typeof(BulletWeapon), "Fire")]
	internal static class BulletWeapon_Fire
	{
		public static void Prefix(BulletWeapon __instance)
		{
			if (GrenadeLauncherConfigSetup.EnabledConfigs.ContainsKey(((ItemEquippable)__instance).ArchetypeID))
			{
				GrenadeLauncherConfig config = GrenadeLauncherConfigSetup.EnabledConfigs[((ItemEquippable)__instance).ArchetypeID];
				GrenadeLauncherFire.Fire(__instance, config);
			}
		}
	}
	internal static class GrenadeLauncherFire
	{
		public static void Fire(BulletWeapon weapon, GrenadeLauncherConfig config)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: 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_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_0053: 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)
			pItemData val = default(pItemData);
			val.itemID_gearCRC = 136u;
			Vector3 targetLookDir = ((Agent)((Item)weapon).Owner).TargetLookDir;
			Vector3 normalized = ((Vector3)(ref targetLookDir)).normalized;
			ItemReplicationManager.ThrowItem(val, (delItemCallback)null, (ItemMode)3, ((Component)((ItemEquippable)weapon).MuzzleAlign).transform.position, ((Component)((ItemEquippable)weapon).MuzzleAlign).transform.rotation, normalized * config.ShootForce, ((Component)weapon).transform.position, ((Agent)((Item)weapon).Owner).CourseNode, ((Item)weapon).Owner);
			((Weapon)weapon).MaxRayDist = 0f;
		}
	}
}
namespace PortalPuzzleChanger.GameScripts
{
	public class GrenadeProjectile : ConsumableInstance
	{
		public GrenadeBase GrenadeBase;

		private static FX_Pool explosionPool;

		private float damageRadiusHigh;

		private float damageRadiusLow;

		private float damageValueHigh;

		private float damageValueLow;

		private float explosionForce;

		private readonly int explosionTargetMask = LayerManager.MASK_EXPLOSION_TARGETS;

		private readonly int explosionBlockMask = LayerManager.MASK_EXPLOSION_BLOCKERS;

		private bool madeNoise = false;

		private bool collision = false;

		private bool addForce = false;

		private float decayTime;

		private Rigidbody rigidbody;

		private CellSoundPlayer cellSoundPlayer;

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

		private void Awake()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			rigidbody = ((Component)this).GetComponent<Rigidbody>();
			cellSoundPlayer = new CellSoundPlayer();
			if (!Object.op_Implicit((Object)(object)explosionPool))
			{
				explosionPool = FX_Manager.GetEffectPool(AssetShardManager.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/FX_Effects/FX_Tripmine.prefab", false));
			}
		}

		private void Start()
		{
			GrenadeLauncherConfig grenadeLauncherConfig = GrenadeLauncherConfigSetup.EnabledConfigs[((Item)GrenadeBase).Owner.Inventory.WieldedItem.ArchetypeID];
			damageRadiusHigh = grenadeLauncherConfig.MaximumDamageRange.Radius;
			damageRadiusLow = grenadeLauncherConfig.MinimumDamageRange.Radius;
			damageValueHigh = grenadeLauncherConfig.MaximumDamageRange.Damage;
			damageValueLow = grenadeLauncherConfig.MinimumDamageRange.Damage;
			explosionForce = grenadeLauncherConfig.ExplosionForce;
		}

		private void FixedUpdate()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (rigidbody.useGravity)
			{
				Vector3 val = ((Component)this).transform.position + rigidbody.velocity * Time.fixedDeltaTime;
			}
			else if (!madeNoise)
			{
				MakeNoise();
				((Component)this).transform.position = Vector3.down * 100f;
				madeNoise = true;
			}
		}

		private void Update()
		{
			//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 (rigidbody.useGravity)
			{
				cellSoundPlayer.UpdatePosition(((Component)this).transform.position);
				if (collision)
				{
					DetonateSequence();
				}
			}
			else if (Time.time > decayTime)
			{
				((Item)GrenadeBase).ReplicationWrapper.Replicator.Despawn();
			}
		}

		private void OnCollisionEnter()
		{
			if (rigidbody.useGravity)
			{
				DetonateSequence();
			}
		}

		private void DetonateSequence()
		{
			//IL_001f: 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)
			Detonate();
			decayTime = Time.time + 10f;
			rigidbody.velocity = Vector3.zero;
			rigidbody.angularVelocity = Vector3.zero;
			rigidbody.useGravity = false;
		}

		private void Detonate()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			FX_EffectBase val = (FX_EffectBase)(object)explosionPool.AquireEffect();
			val.Play((FX_Trigger)null, ((Component)this).transform.position, Quaternion.LookRotation(Vector3.up));
			if (SNet.IsMaster)
			{
				DamageUtil.DoExplosionDamage(((Component)this).transform.position, damageRadiusHigh, damageValueHigh, explosionTargetMask, explosionBlockMask, addForce, explosionForce);
				DamageUtil.DoExplosionDamage(((Component)this).transform.position, damageRadiusLow, damageValueLow, explosionTargetMask, explosionBlockMask, addForce, explosionForce);
			}
		}

		private void MakeNoise()
		{
			//IL_000d: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: 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_00d9: 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_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: 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_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Expected O, but got Unknown
			List<string> list = new List<string>();
			Il2CppReferenceArray<Collider> val = Physics.OverlapSphere(((Component)this).transform.position, 50f, LayerManager.MASK_ENEMY_DAMAGABLE);
			foreach (Collider item in (Il2CppArrayBase<Collider>)(object)val)
			{
				Dam_EnemyDamageLimb component = ((Component)item).GetComponent<Dam_EnemyDamageLimb>();
				if ((Object)(object)component == (Object)null)
				{
					continue;
				}
				EnemyAgent glueTargetEnemyAgent = component.GlueTargetEnemyAgent;
				if (!((Object)(object)glueTargetEnemyAgent == (Object)null) && !list.Contains(((Object)((Component)glueTargetEnemyAgent).gameObject).name))
				{
					list.Add(((Object)((Component)glueTargetEnemyAgent).gameObject).name);
					if (!Physics.Linecast(((Component)this).transform.position, ((Agent)glueTargetEnemyAgent).EyePosition, LayerManager.MASK_WORLD))
					{
						NM_NoiseData val2 = new NM_NoiseData
						{
							position = ((Agent)glueTargetEnemyAgent).EyePosition,
							node = ((Agent)glueTargetEnemyAgent).CourseNode,
							type = (NM_NoiseType)0,
							radiusMin = 0.01f,
							radiusMax = 100f,
							yScale = 1f,
							noiseMaker = null,
							raycastFirstNode = false,
							includeToNeightbourAreas = false
						};
						NoiseManager.MakeNoise(val2);
					}
				}
			}
			cellSoundPlayer.Post(EVENTS.FRAGGRENADEEXPLODE, true);
		}

		public override void OnDespawn()
		{
			((ItemWrapped)this).OnDespawn();
		}
	}
}
namespace PortalPuzzleChanger.ConfigFiles
{
	public class EnemyTagChanger
	{
		public bool internalEnabled { get; set; }

		public string internalName { get; set; }

		public uint EnemyID { get; set; }

		public Color TagColor { get; set; }

		public string CustomImagePath { get; set; }

		public EnemyTagChanger()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			internalEnabled = false;
			internalName = string.Empty;
			EnemyID = 0u;
			TagColor = Color.red;
			CustomImagePath = string.Empty;
		}
	}
	public class GrenadeLauncherConfig
	{
		public DamageMinMax MaximumDamageRange { get; set; }

		public DamageMinMax MinimumDamageRange { get; set; }

		public float ExplosionForce { get; set; }

		public float ShootForce { get; set; }

		public uint PersistentID { get; set; }

		public string internalName { get; set; }

		public bool internalEnabled { get; set; }

		public GrenadeLauncherConfig()
		{
			MaximumDamageRange = new DamageMinMax();
			MinimumDamageRange = new DamageMinMax();
			ExplosionForce = 1000f;
			PersistentID = 0u;
			internalName = string.Empty;
			internalEnabled = false;
		}
	}
	public class DamageMinMax
	{
		public float Radius { get; set; }

		public float Damage { get; set; }

		public DamageMinMax()
		{
			Radius = 0f;
			Damage = 0f;
		}
	}
	public class PortalChangerConfig
	{
		public uint MainLevelLayoutID { get; set; }

		public bool InternalEnabled { get; set; }

		public string? InternalName { get; set; }

		public List<PortalEntry> PortalEntries { get; set; }

		public PortalChangerConfig()
		{
			PortalEntries = new List<PortalEntry>
			{
				new PortalEntry()
			};
			InternalEnabled = false;
			InternalName = "Test";
			MainLevelLayoutID = 0u;
		}
	}
	public class PortalEntry
	{
		public eLocalZoneIndex ZoneIndex { get; set; }

		public LG_LayerType LayerType { get; set; }

		public eDimensionIndex DimensionIndex { get; set; }

		public eDimensionIndex TargetDimension { get; set; }

		public eLocalZoneIndex TargetZoneIndex { get; set; }

		public uint PortalChainedPuzzleId { get; set; }

		public bool CreateTeamScanAsLast { get; set; }

		public PortalEntry()
		{
			ZoneIndex = (eLocalZoneIndex)0;
			LayerType = (LG_LayerType)0;
			DimensionIndex = (eDimensionIndex)0;
			TargetDimension = (eDimensionIndex)1;
			TargetZoneIndex = (eLocalZoneIndex)0;
			PortalChainedPuzzleId = 4u;
			CreateTeamScanAsLast = false;
		}
	}
}

plugins/ProjectEternal/net6/PrequelCore.dll

Decompiled 4 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.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.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using ChainedPuzzles;
using EOSExt.Reactor.Managers;
using Enemies;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.ExtendedWardenEvents;
using ExtraObjectiveSetup.Instances;
using GTFO.API;
using GTFO.API.JSON.Converters;
using GTFO.API.Utilities;
using GameData;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LEGACY.ExtraEvents;
using LEGACY.LegacyOverride;
using LEGACY.LegacyOverride.DimensionPortal;
using LEGACY.LegacyOverride.ElevatorCargo;
using LEGACY.LegacyOverride.EnemyTagger;
using LEGACY.LegacyOverride.ExtraExpeditionSettings;
using LEGACY.LegacyOverride.FogBeacon;
using LEGACY.LegacyOverride.SecDoorIntText;
using LEGACY.Utils;
using LevelGeneration;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using ScanPosOverride.Managers;
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("PrequelCore")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("PrequelCore")]
[assembly: AssemblyTitle("PrequelCore")]
[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;
		}
	}
}
[HarmonyPatch(typeof(PUI_Watermark), "UpdateWatermark")]
internal static class Patch_WatermarkUpdateWatermark
{
	private static void Postfix(PUI_Watermark __instance)
	{
		string text = "4.6.1+gitf831086-dirty-main".Remove("x.x.x".Length);
		((TMP_Text)__instance.m_watermarkText).SetText("<color=red>MODDED</color> <color=orange>" + text + "</color>\n<color=#FF6781>criscriscris</color>", true);
	}
}
namespace LEGACY
{
	[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("Inas07.PREQUELCore", "PREQUELCore", "2.0.3")]
	[BepInIncompatibility("Inas.LEGACY")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas07";

		public const string RUNDOWN_NAME = "PREQUELCore";

		public const string VERSION = "2.0.3";

		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("LEGACY");
			m_Harmony.PatchAll();
			LegacyOverrideManagers.Init();
			LegacyExtraEvents.Init();
		}
	}
}
namespace LEGACY.Reactor
{
	[HarmonyPatch]
	internal class Patch_ReactorShutdown
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateChange")]
		private static void Post_OnStateChange(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState)
		{
			//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_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_0026: 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_0053: Invalid comparison between Unknown and I4
			//IL_0060: 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_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_0068: 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: Expected I4, but got Unknown
			//IL_007e: 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_0086: 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_0099: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || oldState.status == newState.status)
			{
				return;
			}
			WardenObjectiveDataBlock val = null;
			if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref val) || val == null)
			{
				LegacyLogger.Error("Patch_ReactorShutdown: ");
				LegacyLogger.Error("Failed to get warden objective");
			}
			else if ((int)val.Type == 2 && !val.OnActivateOnSolveItem)
			{
				eWardenObjectiveEventTrigger val2 = (eWardenObjectiveEventTrigger)0;
				eReactorStatus status = newState.status;
				switch (status - 7)
				{
				default:
					return;
				case 0:
					val2 = (eWardenObjectiveEventTrigger)1;
					break;
				case 1:
					val2 = (eWardenObjectiveEventTrigger)2;
					break;
				case 2:
					val2 = (eWardenObjectiveEventTrigger)3;
					break;
				}
				_ = __instance.SpawnNode.LayerType;
				WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(val.EventsOnActivate, val2, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnBuildDone")]
		private static void Pre_OnBuildDone_ChainedPuzzleMidObjectiveFix(LG_WardenObjective_Reactor __instance)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			WardenObjectiveDataBlock val = null;
			if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref val) || val == null)
			{
				LegacyLogger.Error("Patch_ReactorShutdown: Failed to get warden objective");
			}
			else if (val.ChainedPuzzleMidObjective != 0)
			{
				__instance.m_chainedPuzzleAlignMidObjective = __instance.m_chainedPuzzleAlign;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "Update")]
		private static bool Pre_Update(LG_WardenObjective_Reactor __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_000c: Invalid comparison between Unknown and I4
			if ((int)__instance.m_currentState.status != 7)
			{
				return true;
			}
			if (!__instance.m_currentWaveData.HasVerificationTerminal)
			{
				return true;
			}
			__instance.SetGUIMessage(true, Text.Format(3000u, (Object[])(object)new Object[1] { Object.op_Implicit("<color=orange>" + __instance.m_currentWaveData.VerificationTerminalSerial + "</color>") }), (ePUIMessageStyle)3, false, "", "");
			return false;
		}
	}
	[HarmonyPatch]
	internal class Patch_ReactorStartup_ExtraEventsExecution
	{
		[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);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateChange")]
		private static void Post_ExecuteOnNoneEventsOnDefenseStart(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState)
		{
			//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_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_0016: Invalid comparison between Unknown and I4
			if (oldState.status != newState.status && (int)newState.status == 3)
			{
				WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)0, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnBuildDone")]
		private static void Post_OnBuildDone(LG_WardenObjective_Reactor __instance)
		{
			//IL_0011: 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: Invalid comparison between Unknown and I4
			WardenObjectiveDataBlock db = default(WardenObjectiveDataBlock);
			if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref db) || db == null)
			{
				LegacyLogger.Error("Patch_ReactorStartup_ExtraEventsExecution: ");
				LegacyLogger.Error("Failed to get warden objective");
			}
			else if ((int)db.Type == 1 && !db.OnActivateOnSolveItem)
			{
				ChainedPuzzleInstance chainedPuzzleToStartSequence = __instance.m_chainedPuzzleToStartSequence;
				chainedPuzzleToStartSequence.OnPuzzleSolved += Action.op_Implicit((Action)delegate
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(db.EventsOnActivate, (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
				});
			}
		}
	}
}
namespace LEGACY.VanillaFix
{
	[HarmonyPatch]
	internal 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_007f: Expected I4, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Invalid comparison between Unknown and I4
			TERM_Command val = cmd;
			switch (val - 1)
			{
			default:
				if ((int)val != 43)
				{
					break;
				}
				goto case 0;
			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:
				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:
				break;
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_FixScoutFreeze
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(ES_ScoutScream), "CommonUpdate")]
		private static bool Prefix_Debug(ES_ScoutScream __instance)
		{
			if (((AgentAI)((ES_Base)__instance).m_ai).Target == null)
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal class Patch_LG_SecurityDoor_Fix_EventsOnUnlockDoor_Powergenerator
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_SecurityDoor), "OnSyncDoorStatusChange")]
		private static void Pre_OnSyncDoorStatusChange(LG_SecurityDoor __instance, pDoorState state, bool isRecall)
		{
			//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_000b: Invalid comparison between Unknown and I4
			//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_001e: Invalid comparison between Unknown and I4
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			eDoorStatus status = state.status;
			if ((status - 4 <= 1 || (int)status == 9) && (int)__instance.m_lastState.status == 6)
			{
				WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.LinkedToZoneData.EventsOnUnlockDoor, (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_LockSecurityDoor_FixCustomText
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_SecurityDoor_Locks), "Setup", new Type[] { typeof(LG_SecurityDoor) })]
		private static void Post_LG_SecurityDoor_Locks_Setup(LG_SecurityDoor door, LG_SecurityDoor_Locks __instance)
		{
			LocalizedText customText = door.LinkedToZoneData.ProgressionPuzzleToEnter.CustomText;
			__instance.m_lockedWithNoKeyInteractionText = customText;
		}
	}
	[HarmonyPatch]
	[HarmonyWrapSafe]
	internal class Patch_RepeatableCommandEventFix
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "SetupCommandEvents")]
		private static void Post_ResetupChainedPuzzleAfterExecution(LG_ComputerTerminalCommandInterpreter __instance)
		{
			//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_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected I4, but got Unknown
			//IL_00e5: 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_0170: 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_0196: Invalid comparison between Unknown and I4
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Invalid comparison between Unknown and I4
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Invalid comparison between Unknown and I4
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Invalid comparison between Unknown and I4
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Invalid comparison between Unknown and I4
			uint num = 0u;
			if ((Object)(object)__instance.m_terminal.ConnectedReactor != (Object)null)
			{
				return;
			}
			if (__instance.m_terminal.SpawnNode.m_dimension.IsMainDimension)
			{
				LG_LayerType layerType = __instance.m_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:
					LegacyLogger.Error("Unimplemented layer type.");
					return;
				}
			}
			else
			{
				num = __instance.m_terminal.SpawnNode.m_dimension.DimensionData.LevelLayoutData;
			}
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(num);
			List<CustomTerminalCommand> val = null;
			int num2 = __instance.m_terminal.SpawnNode.m_zone.TerminalsSpawnedInZone.IndexOf(__instance.m_terminal);
			ExpeditionZoneData val2 = null;
			Enumerator<ExpeditionZoneData> enumerator = block.Zones.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ExpeditionZoneData current = enumerator.Current;
				if (current.LocalIndex == __instance.m_terminal.SpawnNode.m_zone.LocalIndex)
				{
					val2 = current;
					break;
				}
			}
			if (val2 == null)
			{
				LegacyLogger.Error("Cannot find target zone data.");
				return;
			}
			if (num2 >= val2.TerminalPlacements.Count)
			{
				LegacyLogger.Debug("RepeatableCommand: TerminalDataIndex >= TargetZoneData.TerminalPlacements.Count: found sec-door terminal, skipping");
				return;
			}
			val = val2.TerminalPlacements[num2].UniqueCommands;
			if (val.Count == 0)
			{
				return;
			}
			Enumerator<CustomTerminalCommand> enumerator2 = val.GetEnumerator();
			TERM_Command val3 = default(TERM_Command);
			string text = default(string);
			string text2 = default(string);
			while (enumerator2.MoveNext())
			{
				CustomTerminalCommand current2 = enumerator2.Current;
				if ((int)current2.SpecialCommandRule != 0 || !__instance.TryGetCommand(current2.Command, ref val3, ref text, ref text2) || ((int)val3 != 38 && (int)val3 != 39 && (int)val3 != 40 && (int)val3 != 41 && (int)val3 != 42))
				{
					continue;
				}
				ChainedPuzzleInstance OldCPInstance = null;
				List<WardenObjectiveEventData> commandEvents = current2.CommandEvents;
				for (int i = 0; i < commandEvents.Count && (commandEvents[i].ChainPuzzle == 0 || !__instance.m_terminal.TryGetChainPuzzleForCommand(val3, i, ref OldCPInstance) || !((Object)(object)OldCPInstance != (Object)null)); i++)
				{
				}
				if (!((Object)(object)OldCPInstance == (Object)null))
				{
					ChainedPuzzleInstance obj = OldCPInstance;
					obj.OnPuzzleSolved += Action.op_Implicit((Action)delegate
					{
						Helper.ResetChainedPuzzle(OldCPInstance);
					});
				}
			}
		}
	}
}
namespace LEGACY.Utils
{
	public static class Helper
	{
		private static void ResetChild(iChainedPuzzleCore ICore)
		{
			CP_Bioscan_Core val = ((Il2CppObjectBase)ICore).TryCast<CP_Bioscan_Core>();
			if ((Object)(object)val != (Object)null)
			{
				((Il2CppObjectBase)val.m_spline).Cast<CP_Holopath_Spline>().SetSplineProgress(0f);
				((Il2CppObjectBase)val.PlayerScanner).Cast<CP_PlayerScanner>().ResetScanProgression(0f);
				return;
			}
			CP_Cluster_Core val2 = ((Il2CppObjectBase)ICore).TryCast<CP_Cluster_Core>();
			if ((Object)(object)val2 == (Object)null)
			{
				LegacyLogger.Error("ResetChild: found iChainedPuzzleCore that is neither CP_Bioscan_Core nor CP_Cluster_Core...");
				return;
			}
			((Il2CppObjectBase)val2.m_spline).Cast<CP_Holopath_Spline>().SetSplineProgress(0f);
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)val2.m_childCores)
			{
				ResetChild(item);
			}
		}

		public static void ResetChainedPuzzle(ChainedPuzzleInstance chainedPuzzleInstance)
		{
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)chainedPuzzleInstance.m_chainedPuzzleCores)
			{
				ResetChild(item);
			}
			if (SNet.IsMaster)
			{
				chainedPuzzleInstance.AttemptInteract((eChainedPuzzleInteraction)2);
			}
		}

		public static LG_WardenObjective_Reactor FindReactor(LG_LayerType layer)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			LG_WardenObjective_Reactor val = null;
			Enumerator<LayerChainIndex, iWardenObjectiveItem> enumerator = WardenObjectiveManager.Current.m_wardenObjectiveItem.GetEnumerator();
			while (enumerator.MoveNext())
			{
				KeyValuePair<LayerChainIndex, iWardenObjectiveItem> current = enumerator.Current;
				if (current.Key.Layer == layer)
				{
					val = ((Il2CppObjectBase)current.Value).TryCast<LG_WardenObjective_Reactor>();
					if (!((Object)(object)val == (Object)null))
					{
						break;
					}
				}
			}
			return val;
		}

		public static bool TryGetComponent<T>(this GameObject obj, out T comp)
		{
			comp = obj.GetComponent<T>();
			return comp != null;
		}

		public static bool IsPlayerInLevel(PlayerAgent player)
		{
			//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: Invalid comparison between Unknown and I4
			return (int)player.Owner.Load<pGameState>().gameState == 10;
		}

		public static ChainedPuzzleInstance GetChainedPuzzleForCommandOnTerminal(LG_ComputerTerminal terminal, string command)
		{
			//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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected I4, but got Unknown
			//IL_00bc: 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_0133: 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)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Invalid comparison between Unknown and I4
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Invalid comparison between Unknown and I4
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Invalid comparison between Unknown and I4
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Invalid comparison between Unknown and I4
			//IL_01d2: 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_01b5: Invalid comparison between Unknown and I4
			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:
					LegacyLogger.Error("Unimplemented layer type.");
					return null;
				}
			}
			else
			{
				num = terminal.SpawnNode.m_dimension.DimensionData.LevelLayoutData;
			}
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(num);
			List<CustomTerminalCommand> val = null;
			List<LG_ComputerTerminal> terminalsSpawnedInZone = terminal.SpawnNode.m_zone.TerminalsSpawnedInZone;
			int num2 = terminalsSpawnedInZone.IndexOf(terminal);
			ExpeditionZoneData val2 = null;
			Enumerator<ExpeditionZoneData> enumerator = block.Zones.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ExpeditionZoneData current = enumerator.Current;
				if (current.LocalIndex == terminal.SpawnNode.m_zone.LocalIndex)
				{
					val2 = current;
					break;
				}
			}
			if (val2 == null)
			{
				LegacyLogger.Error("Cannot find target zone data.");
				return null;
			}
			if (val2.TerminalPlacements.Count != terminalsSpawnedInZone.Count)
			{
				LegacyLogger.Error("The numbers of terminal placement and spawn, skipped for the zone terminal.");
				return null;
			}
			val = val2.TerminalPlacements[num2].UniqueCommands;
			if (val.Count == 0)
			{
				return null;
			}
			List<WardenObjectiveEventData> val3 = null;
			TERM_Command val4 = (TERM_Command)0;
			Enumerator<CustomTerminalCommand> enumerator2 = val.GetEnumerator();
			string text = default(string);
			string text2 = default(string);
			while (enumerator2.MoveNext())
			{
				CustomTerminalCommand current2 = enumerator2.Current;
				if (current2.Command == command)
				{
					val3 = current2.CommandEvents;
					if (!terminal.m_command.TryGetCommand(current2.Command, ref val4, ref text, ref text2))
					{
						LegacyLogger.Error("Cannot get TERM_COMMAND for command {0} on the specified terminal.");
					}
					break;
				}
			}
			if (val3 == null || (int)val4 == 0)
			{
				return null;
			}
			if ((int)val4 != 38 && (int)val4 != 39 && (int)val4 != 40 && (int)val4 != 41 && (int)val4 != 42)
			{
				return null;
			}
			ChainedPuzzleInstance val5 = null;
			for (int i = 0; i < val3.Count && (val3[i].ChainPuzzle == 0 || !terminal.TryGetChainPuzzleForCommand(val4, i, ref val5) || !((Object)(object)val5 != (Object)null)); i++)
			{
			}
			return val5;
		}

		public static bool TryGetZoneEntranceSecDoor(LG_Zone zone, out LG_SecurityDoor door)
		{
			if ((Object)(object)zone == (Object)null)
			{
				door = null;
				return false;
			}
			if ((Object)(object)zone.m_sourceGate == (Object)null)
			{
				door = null;
				return false;
			}
			if (zone.m_sourceGate.SpawnedDoor == null)
			{
				door = null;
				return false;
			}
			door = ((Il2CppObjectBase)zone.m_sourceGate.SpawnedDoor).TryCast<LG_SecurityDoor>();
			return (Object)(object)door != (Object)null;
		}

		internal static bool isSecDoorToZoneOpened(LG_Zone zone14)
		{
			//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_0029: Invalid comparison between Unknown and I4
			LG_SecurityDoor door = null;
			if (!TryGetZoneEntranceSecDoor(zone14, out door) || (Object)(object)door == (Object)null)
			{
				return false;
			}
			return (int)door.m_sync.GetCurrentSyncState().status == 10;
		}

		public static List<T> cast<T>(List<T> list)
		{
			List<T> list2 = new List<T>();
			Enumerator<T> enumerator = list.GetEnumerator();
			while (enumerator.MoveNext())
			{
				T current = enumerator.Current;
				list2.Add(current);
			}
			return list2;
		}

		private static eDimensionIndex GetCurrentDimensionIndex()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			if (PlayerManager.PlayerAgentsInLevel.Count <= 0)
			{
				throw new Exception("? You don't have any player agent in level? How could that happen?");
			}
			return ((Agent)PlayerManager.PlayerAgentsInLevel[0]).DimensionIndex;
		}

		public static void GetMinLayerAndLocalIndex(out LG_LayerType MinLayer, out eLocalZoneIndex MinLocalIndex)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Invalid comparison between I4 and Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Invalid comparison between I4 and Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected I4, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected I4, but got Unknown
			MinLayer = (LG_LayerType)2;
			MinLocalIndex = (eLocalZoneIndex)20;
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (IsPlayerInLevel(current))
				{
					if ((int)MinLayer > (int)current.m_courseNode.LayerType)
					{
						MinLayer = (LG_LayerType)(int)current.m_courseNode.LayerType;
						MinLocalIndex = (eLocalZoneIndex)20;
					}
					if ((int)MinLocalIndex >= (int)current.m_courseNode.m_zone.LocalIndex)
					{
						MinLocalIndex = (eLocalZoneIndex)(int)current.m_courseNode.m_zone.LocalIndex;
					}
				}
			}
		}

		public static void GetMaxLayerAndLocalIndex(out LG_LayerType MaxLayer, out eLocalZoneIndex MaxLocalIndex)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Invalid comparison between I4 and Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Invalid comparison between I4 and Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected I4, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected I4, but got Unknown
			MaxLayer = (LG_LayerType)0;
			MaxLocalIndex = (eLocalZoneIndex)0;
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (IsPlayerInLevel(current))
				{
					if ((int)MaxLayer < (int)current.m_courseNode.LayerType)
					{
						MaxLayer = (LG_LayerType)(int)current.m_courseNode.LayerType;
						MaxLocalIndex = (eLocalZoneIndex)0;
					}
					if ((int)MaxLocalIndex < (int)current.m_courseNode.m_zone.LocalIndex)
					{
						MaxLocalIndex = (eLocalZoneIndex)(int)current.m_courseNode.m_zone.LocalIndex;
					}
				}
			}
		}

		public static int GetMinAreaIndex(LG_Zone zone)
		{
			//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_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_001e: 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_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)
			if ((Object)(object)zone == (Object)null)
			{
				return -1;
			}
			LG_LayerType type = zone.m_layer.m_type;
			eLocalZoneIndex localIndex = zone.LocalIndex;
			GetCurrentDimensionIndex();
			int num = zone.m_areas.Count;
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (current.m_courseNode.LayerType != type || current.m_courseNode.m_zone.LocalIndex != localIndex)
				{
					continue;
				}
				int i = 0;
				for (List<LG_Area> areas = zone.m_areas; i < areas.Count; i++)
				{
					if (((Object)((Component)areas[i]).gameObject).GetInstanceID() == ((Object)((Component)current.m_courseNode.m_area).gameObject).GetInstanceID())
					{
						if (num > i)
						{
							num = i;
						}
						break;
					}
				}
			}
			return num;
		}

		public static LG_ComputerTerminal FindTerminal(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, int terminalIndex)
		{
			//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_0034: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = null;
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, localIndex, ref val) || (Object)(object)val == (Object)null)
			{
				LegacyLogger.Error($"FindTerminal: Didn't find LG_Zone {dimensionIndex}, {layerType}, {localIndex}");
				return null;
			}
			if (val.TerminalsSpawnedInZone == null || terminalIndex >= val.TerminalsSpawnedInZone.Count)
			{
				LegacyLogger.Error($"FindTerminal: Invalid terminal index {terminalIndex} - {((val.TerminalsSpawnedInZone != null) ? val.TerminalsSpawnedInZone.Count : 0)} terminals are spawned in {dimensionIndex}, {layerType}, {localIndex}");
				return null;
			}
			if (terminalIndex >= 0)
			{
				return val.TerminalsSpawnedInZone[terminalIndex];
			}
			return null;
		}
	}
	internal static class Json
	{
		private static readonly JsonSerializerOptions _setting;

		static Json()
		{
			//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 = false,
				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);
		}

		public static void Load<T>(string filePath, out T config) where T : new()
		{
			config = Deserialize<T>(File.ReadAllText(filePath));
		}
	}
	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);
		}
	}
	internal static class LegacyLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("LEGACYCore");

		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 class SpawnHibernateEnemiesEvent
	{
		public eWardenObjectiveEventTrigger Trigger { get; set; }

		public int Type { get; set; } = 170;


		public eDimensionIndex DimensionIndex { get; set; }

		public LG_LayerType Layer { get; set; }

		public eLocalZoneIndex LocalIndex { get; set; }

		public string WorldEventObjectFilter { get; set; } = "RANDOM";


		public uint EnemyID { get; set; }

		public int Count { get; set; } = 1;


		public float Delay { get; set; }

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

	}
	public class WeightedAreaSelector
	{
		private static readonly Dictionary<LG_Zone, WeightedAreaSelector> dict;

		private WeightedRandomBag<LG_Area> weightedRandomBag;

		public static WeightedAreaSelector Get(LG_Zone zone)
		{
			//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_003c: 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_0059: Expected I4, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			if (!dict.ContainsKey(zone))
			{
				WeightedAreaSelector weightedAreaSelector = new WeightedAreaSelector();
				Enumerator<LG_Area> enumerator = zone.m_areas.GetEnumerator();
				while (enumerator.MoveNext())
				{
					LG_Area current = enumerator.Current;
					float num = 0f;
					LG_AreaSize size = current.m_size;
					switch (size - 1)
					{
					case 4:
						num = 7f;
						break;
					case 0:
						num = 20f;
						break;
					case 1:
						num = 30f;
						break;
					case 2:
						num = 35f;
						break;
					case 3:
						num = 45f;
						break;
					default:
						LegacyLogger.Error($"Unhandled LG_AreaSize: {current.m_size}. Won't build.");
						return null;
					}
					weightedAreaSelector.AddEntry(current, num);
				}
				dict.Add(zone, weightedAreaSelector);
			}
			return dict[zone];
		}

		public static WeightedAreaSelector Get(eDimensionIndex eDimensionIndex, LG_LayerType layerType, 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);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(eDimensionIndex, layerType, localIndex, ref val) || !Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			return Get(val);
		}

		private WeightedAreaSelector()
		{
			weightedRandomBag = new WeightedRandomBag<LG_Area>();
		}

		private void AddEntry(LG_Area area, float weight)
		{
			weightedRandomBag.AddEntry(area, weight);
		}

		public LG_Area GetRandom()
		{
			return weightedRandomBag.GetRandom();
		}

		private static void OnBuildDone()
		{
		}

		private static void Clear()
		{
			dict.Clear();
		}

		static WeightedAreaSelector()
		{
			dict = new Dictionary<LG_Zone, WeightedAreaSelector>();
			LevelAPI.OnLevelCleanup += dict.Clear;
		}
	}
	public class WeightedRandomBag<T>
	{
		private struct Entry
		{
			public double accumulatedWeight;

			public T item;
		}

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

		private double accumulatedWeight;

		private Random rand = new Random();

		public void AddEntry(T item, double weight)
		{
			if (weight <= 0.0)
			{
				LegacyLogger.Error("AddEntry: no non-positive weight pls.");
				return;
			}
			accumulatedWeight += weight;
			entries.Add(new Entry
			{
				item = item,
				accumulatedWeight = accumulatedWeight
			});
		}

		public T GetRandom()
		{
			double num = rand.NextDouble() * accumulatedWeight;
			foreach (Entry entry in entries)
			{
				if (entry.accumulatedWeight >= num)
				{
					return entry.item;
				}
			}
			return default(T);
		}
	}
}
namespace LEGACY.LegacyOverride
{
	internal static class LegacyOverrideManagers
	{
		internal static readonly string LEGACY_CONFIG_PATH = Path.Combine(MTFOPathAPI.CustomPath, "LegacyOverride");

		internal static void Init()
		{
			ElevatorCargoOverrideManager.Current.Init();
			FogBeaconSettingManager.Current.Init();
			EnemyTaggerSettingManager.Current.Init();
			SecDoorIntTextOverrideManager.Current.Init();
			ExpeditionSettingsManager.Current.Init();
		}
	}
}
namespace LEGACY.LegacyOverride.SecDoorIntText
{
	public class DoorToZone
	{
		public eDimensionIndex DimensionIndex { get; set; }

		public LG_LayerType LayerType { get; set; }

		public eLocalZoneIndex LocalIndex { get; set; }

		public LocalizedText Prefix { get; set; }

		public LocalizedText Postfix { get; set; }

		public LocalizedText TextToReplace { get; set; }
	}
	public class LevelSecDoorIntTextOverride
	{
		public uint MainLevelLayout { get; set; }

		public List<DoorToZone> doorToZones { get; set; } = new List<DoorToZone>
		{
			new DoorToZone()
		};

	}
	internal class SecDoorIntTextOverrideManager
	{
		public static readonly SecDoorIntTextOverrideManager Current;

		private Dictionary<uint, LevelSecDoorIntTextOverride> SecDoorIntTextOverrides = new Dictionary<uint, LevelSecDoorIntTextOverride>();

		private LiveEditListener liveEditListener;

		private static readonly string CONFIG_PATH;

		internal LevelSecDoorIntTextOverride SettingForCurrentLevel { get; private set; }

		private void AddOverride(LevelSecDoorIntTextOverride _override)
		{
			if (_override != null)
			{
				if (SecDoorIntTextOverrides.ContainsKey(_override.MainLevelLayout))
				{
					LegacyLogger.Warning("Replaced MainLevelLayout {0}", _override.MainLevelLayout);
					SecDoorIntTextOverrides[_override.MainLevelLayout] = _override;
				}
				else
				{
					SecDoorIntTextOverrides.Add(_override.MainLevelLayout, _override);
				}
			}
		}

		public void Init()
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Expected O, but got Unknown
			if (!Directory.Exists(CONFIG_PATH))
			{
				Directory.CreateDirectory(CONFIG_PATH);
				StreamWriter streamWriter = File.CreateText(Path.Combine(CONFIG_PATH, "Template.json"));
				streamWriter.WriteLine(Json.Serialize(new LevelSecDoorIntTextOverride()));
				streamWriter.Flush();
				streamWriter.Close();
				return;
			}
			foreach (string item in Directory.EnumerateFiles(CONFIG_PATH, "*.json", SearchOption.AllDirectories))
			{
				Json.Load<LevelSecDoorIntTextOverride>(item, out var config);
				AddOverride(config);
			}
			LevelAPI.OnBuildStart += UpdateSetting;
			liveEditListener = LiveEdit.CreateListener(CONFIG_PATH, "*.json", true);
			liveEditListener.FileChanged += new LiveEditEventHandler(FileChanged);
		}

		private void FileChanged(LiveEditEventArgs e)
		{
			LegacyLogger.Warning("LiveEdit File Changed: " + e.FullPath);
			LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content)
			{
				LevelSecDoorIntTextOverride @override = Json.Deserialize<LevelSecDoorIntTextOverride>(content);
				AddOverride(@override);
				if (GameStateManager.IsInExpedition)
				{
					UpdateSetting();
				}
			});
		}

		private void UpdateSetting()
		{
			uint levelLayoutData = RundownManager.ActiveExpedition.LevelLayoutData;
			SettingForCurrentLevel = (SecDoorIntTextOverrides.ContainsKey(levelLayoutData) ? SecDoorIntTextOverrides[levelLayoutData] : null);
		}

		private SecDoorIntTextOverrideManager()
		{
		}

		static SecDoorIntTextOverrideManager()
		{
			CONFIG_PATH = Path.Combine(LegacyOverrideManagers.LEGACY_CONFIG_PATH, "SecDoorIntText");
			Current = new SecDoorIntTextOverrideManager();
		}
	}
}
namespace LEGACY.LegacyOverride.Patches
{
	[HarmonyPatch]
	internal class DimensionPortal
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_DimensionPortal), "Setup")]
		private static void Pre_DimensionPortal_Setup(LG_DimensionPortal __instance)
		{
			//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_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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			eDimensionIndex dimensionIndex = __instance.SpawnNode.m_dimension.DimensionIndex;
			LG_LayerType layerType = __instance.SpawnNode.LayerType;
			eLocalZoneIndex localIndex = __instance.SpawnNode.m_zone.LocalIndex;
			uint num = ((InstanceManager<LG_DimensionPortal>)DimensionPortalInstanceManager.Current).Register(__instance);
			PortalCustomization definition = ((InstanceDefinitionManager<PortalCustomization>)DimensionPortalDefinitionManager.Current).GetDefinition(dimensionIndex, layerType, localIndex, num);
			if (definition != null)
			{
				LegacyLogger.Debug($"DimensionPortal: found custom setup, {((GlobalZoneIndex)definition).GlobalZoneIndexTuple()}");
				__instance.PortalChainPuzzle = definition.ChainedPuzzleOnPortalActive;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_DimensionPortal), "Setup")]
		private static void Post_DimensionPortal_Setup(LG_DimensionPortal __instance)
		{
			//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_0022: 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_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_0049: Unknown result type (might be due to invalid IL or missing references)
			eDimensionIndex dimensionIndex = __instance.SpawnNode.m_dimension.DimensionIndex;
			LG_LayerType layerType = __instance.SpawnNode.LayerType;
			eLocalZoneIndex localIndex = __instance.SpawnNode.m_zone.LocalIndex;
			uint zoneInstanceIndex = ((InstanceManager<LG_DimensionPortal>)DimensionPortalInstanceManager.Current).GetZoneInstanceIndex(__instance);
			PortalCustomization def = ((InstanceDefinitionManager<PortalCustomization>)DimensionPortalDefinitionManager.Current).GetDefinition(dimensionIndex, layerType, localIndex, zoneInstanceIndex);
			if (def == null)
			{
				return;
			}
			__instance.OnPortalKeyInsertSequenceDone += Action<LG_DimensionPortal>.op_Implicit((Action<LG_DimensionPortal>)delegate
			{
				def.EventsOnScanDone.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			});
			ChainedPuzzleInstance portalChainPuzzleInstance = __instance.m_portalChainPuzzleInstance;
			portalChainPuzzleInstance.OnPuzzleSolved += Action.op_Implicit((Action)delegate
			{
				def.EventsOnScanDone.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			});
		}
	}
	[HarmonyPatch]
	internal class Patch_Customize_SecDoor_Interaction_Text
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_SecurityDoor_Locks), "OnDoorState")]
		private static void Post_Customize_SecDoor_Interaction_Text(pDoorState state, LG_SecurityDoor_Locks __instance)
		{
			//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_0024: Invalid comparison between Unknown and I4
			//IL_0026: 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: Invalid comparison between Unknown and I4
			//IL_0116: 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_0148: Unknown result type (might be due to invalid IL or missing references)
			LevelSecDoorIntTextOverride settingForCurrentLevel = SecDoorIntTextOverrideManager.Current.SettingForCurrentLevel;
			if (settingForCurrentLevel == null || ((int)state.status != 9 && (int)state.status != 5))
			{
				return;
			}
			int num = settingForCurrentLevel.doorToZones.FindIndex((DoorToZone door) => door.DimensionIndex == __instance.m_door.Gate.DimensionIndex && door.LayerType == __instance.m_door.LinksToLayerType && door.LocalIndex == __instance.m_door.LinkedToZoneData.LocalIndex);
			if (num != -1)
			{
				DoorToZone doorToZone = settingForCurrentLevel.doorToZones[num];
				_ = __instance.m_door;
				Interact_Timed intOpenDoor = __instance.m_intOpenDoor;
				string text = LocalizedText.op_Implicit(doorToZone.Prefix);
				string text2 = LocalizedText.op_Implicit(doorToZone.Postfix);
				string text3 = LocalizedText.op_Implicit(doorToZone.TextToReplace);
				if (string.IsNullOrEmpty(text))
				{
					text = string.Empty;
				}
				if (string.IsNullOrEmpty(text2))
				{
					text2 = string.Empty;
				}
				if (string.IsNullOrEmpty(text3))
				{
					text3 = intOpenDoor.InteractionMessage;
				}
				intOpenDoor.InteractionMessage = text + "\n" + text3 + "\n" + text2;
				LegacyLogger.Debug($"SecDoorIntTextOverride: Override IntText. {doorToZone.LocalIndex}, {doorToZone.LayerType}, {doorToZone.DimensionIndex}");
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_ElevatorCargoOverride
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(ElevatorCargoCage), "SpawnObjectiveItemsInLandingArea")]
		private static bool Pre_ElevatorCargoOverride(ElevatorCargoCage __instance)
		{
			LevelElevatorCargo levelElevatorCargoItems = ElevatorCargoOverrideManager.Current.GetLevelElevatorCargoItems(RundownManager.ActiveExpedition.LevelLayoutData);
			if (levelElevatorCargoItems == null)
			{
				return true;
			}
			if (levelElevatorCargoItems.ForceDisable)
			{
				ElevatorRide.Current.m_cargoCageInUse = false;
				return false;
			}
			return true;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ElevatorCargoCage), "SpawnObjectiveItemsInLandingArea")]
		private static void Post_ElevatorCargoOverride(ElevatorCargoCage __instance)
		{
			LevelElevatorCargo levelElevatorCargoItems = ElevatorCargoOverrideManager.Current.GetLevelElevatorCargoItems(RundownManager.ActiveExpedition.LevelLayoutData);
			if (levelElevatorCargoItems == null || levelElevatorCargoItems.ElevatorCargoItems.Count < 1 || levelElevatorCargoItems.ForceDisable)
			{
				return;
			}
			foreach (ElevatorCargoItem elevatorCargoItem in levelElevatorCargoItems.ElevatorCargoItems)
			{
				LG_PickupItem val = LG_PickupItem.SpawnGenericPickupItem(ElevatorShaftLanding.CargoAlign);
				val.SpawnNode = Builder.GetElevatorArea().m_courseNode;
				switch (elevatorCargoItem.ItemType)
				{
				case ItemType.Consumable:
					val.SetupAsConsumable(Random.Range(0, int.MaxValue), elevatorCargoItem.ItemID);
					break;
				case ItemType.BigPickup:
					val.SetupAsBigPickupItem(Random.Range(0, int.MaxValue), elevatorCargoItem.ItemID, false, 0);
					break;
				default:
					LegacyLogger.Error($"Undefined Item Type {elevatorCargoItem.ItemType}");
					continue;
				}
				__instance.m_itemsToMoveToCargo.Add(((Component)val).transform);
				ElevatorRide.Current.m_cargoCageInUse = true;
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_SetupBigPickupItemWithItemId
	{
		private static void SetupAsObserver(LG_PickupItem __instance)
		{
			EnemyTaggerSetting setting = EnemyTaggerSettingManager.Current.SettingForCurrentLevel;
			CarryItemPickup_Core componentInChildren = ((Component)__instance.m_root).GetComponentInChildren<CarryItemPickup_Core>();
			Interact_Pickup_PickupItem interact = ((Il2CppObjectBase)componentInChildren.m_interact).Cast<Interact_Pickup_PickupItem>();
			LG_PickupItem_Sync obj = ((Il2CppObjectBase)componentInChildren.m_sync).Cast<LG_PickupItem_Sync>();
			EnemyTaggerComponent tagger = ((Component)componentInChildren).gameObject.AddComponent<EnemyTaggerComponent>();
			tagger.Parent = componentInChildren;
			((Component)tagger).gameObject.SetActive(true);
			((Interact_Timed)interact).InteractDuration = setting.TimeToPickup;
			tagger.MaxTagPerScan = setting.MaxTagPerScan;
			tagger.TagInterval = setting.TagInterval;
			tagger.TagRadius = setting.TagRadius;
			tagger.WarmupTime = setting.WarmupTime;
			obj.OnSyncStateChange += Action<ePickupItemStatus, pPickupPlacement, PlayerAgent, bool>.op_Implicit((Action<ePickupItemStatus, pPickupPlacement, PlayerAgent, bool>)delegate(ePickupItemStatus status, pPickupPlacement placement, PlayerAgent playerAgent, bool isRecall)
			{
				//IL_0000: 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: Invalid comparison between Unknown and I4
				if ((int)status != 0)
				{
					if ((int)status == 1)
					{
						((Component)tagger).gameObject.SetActive(true);
						tagger.PickedByPlayer = playerAgent;
						tagger.ChangeState((!setting.TagWhenHold) ? eEnemyTaggerState.Inactive : eEnemyTaggerState.Active_Warmup);
						((Interact_Timed)interact).InteractDuration = setting.TimeToPlace;
					}
				}
				else
				{
					tagger.PickedByPlayer = null;
					tagger.ChangeState((!setting.TagWhenPlaced) ? eEnemyTaggerState.Inactive : eEnemyTaggerState.Active_Warmup);
					((Interact_Timed)interact).InteractDuration = setting.TimeToPickup;
				}
			});
		}

		private static void SetupAsFogBeacon(LG_PickupItem __instance)
		{
			//IL_000b: 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_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Expected O, but got Unknown
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Expected O, but got Unknown
			//IL_01a1: 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_01b1: 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_01b6: Unknown result type (might be due to invalid IL or missing references)
			FogRepeller_Sphere val = new GameObject("FogInstance_Beacon_Fake").AddComponent<FogRepeller_Sphere>();
			val.InfiniteDuration = false;
			val.LifeDuration = 99999f;
			val.GrowDuration = 99999f;
			val.ShrinkDuration = 99999f;
			val.Range = 1f;
			FogBeaconSetting setting = FogBeaconSettingManager.Current.SettingForCurrentLevel;
			FogRepeller_Sphere fogRepHold = new GameObject("FogInstance_Beacon_SmallLayer").AddComponent<FogRepeller_Sphere>();
			fogRepHold.InfiniteDuration = setting.RSHold.InfiniteDuration;
			fogRepHold.GrowDuration = setting.RSHold.GrowDuration;
			fogRepHold.ShrinkDuration = setting.RSHold.ShrinkDuration;
			fogRepHold.Range = setting.RSHold.Range;
			fogRepHold.Offset = Vector3.zero;
			FogRepeller_Sphere fogRepPlaced = new GameObject("FogInstance_Beacon_BigLayer").AddComponent<FogRepeller_Sphere>();
			fogRepPlaced.InfiniteDuration = setting.RSPlaced.InfiniteDuration;
			fogRepPlaced.GrowDuration = setting.RSPlaced.GrowDuration;
			fogRepPlaced.ShrinkDuration = setting.RSPlaced.ShrinkDuration;
			fogRepPlaced.Range = setting.RSPlaced.Range;
			fogRepPlaced.Offset = Vector3.zero;
			CarryItemPickup_Core componentInChildren = ((Component)__instance.m_root).GetComponentInChildren<CarryItemPickup_Core>();
			HeavyFogRepellerPickup val2 = ((Il2CppObjectBase)componentInChildren).Cast<HeavyFogRepellerPickup>();
			iCarryItemWithGlobalState val3 = default(iCarryItemWithGlobalState);
			byte byteId = default(byte);
			if (CarryItemWithGlobalStateManager.TryCreateItemInstance((eCarryItemWithGlobalStateType)0, __instance.m_root, ref val3, ref byteId))
			{
				pItemData_Custom customData = ((Item)val2).GetCustomData();
				customData.byteId = byteId;
				pItemData_Custom val4 = customData;
				((Item)val2).SetCustomData(val4, true);
			}
			HeavyFogRepellerGlobalState val5 = ((Il2CppObjectBase)val3).Cast<HeavyFogRepellerGlobalState>();
			((Component)fogRepHold).transform.SetParent(((Component)val5).transform, false);
			((Component)fogRepPlaced).transform.SetParent(((Component)val5).transform, false);
			val5.m_repellerSphere = val;
			fogRepHold.m_sphereAllocator = new FogSphereAllocator();
			fogRepPlaced.m_sphereAllocator = new FogSphereAllocator();
			Interact_Pickup_PickupItem interact = ((Il2CppObjectBase)componentInChildren.m_interact).Cast<Interact_Pickup_PickupItem>();
			((Interact_Timed)interact).InteractDuration = setting.TimeToPickup;
			val5.CallbackOnStateChange += Action<pCarryItemWithGlobalState_State, pCarryItemWithGlobalState_State, bool>.op_Implicit((Action<pCarryItemWithGlobalState_State, pCarryItemWithGlobalState_State, bool>)delegate(pCarryItemWithGlobalState_State oldState, pCarryItemWithGlobalState_State newState, bool isRecall)
			{
				//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_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Invalid comparison between Unknown and I4
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Invalid comparison between Unknown and I4
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				eHeavyFogRepellerStatus val6 = (eHeavyFogRepellerStatus)newState.status;
				if ((int)val6 != 1)
				{
					if ((int)val6 == 2)
					{
						FogRepeller_Sphere obj = fogRepHold;
						if (obj != null)
						{
							obj.StopRepelling();
						}
						FogRepeller_Sphere obj2 = fogRepPlaced;
						if (obj2 != null)
						{
							obj2.StartRepelling();
						}
						((Interact_Timed)interact).InteractDuration = setting.TimeToPickup;
					}
				}
				else
				{
					FogRepeller_Sphere obj3 = fogRepHold;
					if (obj3 != null)
					{
						obj3.StartRepelling();
					}
					if (oldState.status != 0)
					{
						FogRepeller_Sphere obj4 = fogRepPlaced;
						if (obj4 != null)
						{
							obj4.StopRepelling();
						}
					}
					((Interact_Timed)interact).InteractDuration = setting.TimeToPlace;
				}
				if (isRecall)
				{
					FogRepeller_Sphere obj5 = fogRepHold;
					if (obj5 != null)
					{
						obj5.KillRepellerInstantly();
					}
					FogRepeller_Sphere obj6 = fogRepPlaced;
					if (obj6 != null)
					{
						obj6.KillRepellerInstantly();
					}
				}
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PickupItem), "SetupBigPickupItemWithItemId")]
		private static void Post_SetupBigPickupItemWithItemId(LG_PickupItem __instance, uint itemId)
		{
			switch (itemId)
			{
			case 233u:
				SetupAsFogBeacon(__instance);
				break;
			case 234u:
			case 235u:
				SetupAsObserver(__instance);
				break;
			}
		}
	}
}
namespace LEGACY.LegacyOverride.FogBeacon
{
	public class RepellerSphereSetting
	{
		public bool InfiniteDuration { get; set; }

		public float GrowDuration { get; set; } = 10f;


		public float ShrinkDuration { get; set; } = 10f;


		public float Range { get; set; } = 11f;

	}
	public class FogBeaconSetting
	{
		public uint MainLevelLayout { get; set; }

		public float TimeToPickup { get; set; } = 1f;


		public float TimeToPlace { get; set; } = 1f;


		public RepellerSphereSetting RSHold { get; set; } = new RepellerSphereSetting();


		public RepellerSphereSetting RSPlaced { get; set; } = new RepellerSphereSetting();

	}
	internal class FogBeaconSettingManager
	{
		public static readonly FogBeaconSettingManager Current;

		private Dictionary<uint, FogBeaconSetting> fogBeaconSettings = new Dictionary<uint, FogBeaconSetting>();

		private LiveEditListener liveEditListener;

		private static readonly string CONFIG_PATH;

		internal FogBeaconSetting SettingForCurrentLevel { get; private set; }

		private void AddOverride(FogBeaconSetting _override)
		{
			if (_override != null)
			{
				if (fogBeaconSettings.ContainsKey(_override.MainLevelLayout))
				{
					LegacyLogger.Warning("Replaced MainLevelLayout {0}", _override.MainLevelLayout);
					fogBeaconSettings[_override.MainLevelLayout] = _override;
				}
				else
				{
					fogBeaconSettings.Add(_override.MainLevelLayout, _override);
				}
			}
		}

		public void Init()
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Expected O, but got Unknown
			if (!Directory.Exists(CONFIG_PATH))
			{
				Directory.CreateDirectory(CONFIG_PATH);
				StreamWriter streamWriter = File.CreateText(Path.Combine(CONFIG_PATH, "Template.json"));
				streamWriter.WriteLine(Json.Serialize(new FogBeaconSetting()));
				streamWriter.Flush();
				streamWriter.Close();
				return;
			}
			foreach (string item in Directory.EnumerateFiles(CONFIG_PATH, "*.json", SearchOption.AllDirectories))
			{
				Json.Load<FogBeaconSetting>(item, out var config);
				AddOverride(config);
			}
			LevelAPI.OnBuildStart += UpdateSetting;
			liveEditListener = LiveEdit.CreateListener(CONFIG_PATH, "*.json", true);
			liveEditListener.FileChanged += new LiveEditEventHandler(FileChanged);
		}

		private void FileChanged(LiveEditEventArgs e)
		{
			LegacyLogger.Warning("LiveEdit File Changed: " + e.FullPath);
			LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content)
			{
				FogBeaconSetting @override = Json.Deserialize<FogBeaconSetting>(content);
				AddOverride(@override);
				if (GameStateManager.IsInExpedition)
				{
					UpdateSetting();
				}
			});
		}

		private void UpdateSetting()
		{
			uint levelLayoutData = RundownManager.ActiveExpedition.LevelLayoutData;
			SettingForCurrentLevel = (fogBeaconSettings.ContainsKey(levelLayoutData) ? fogBeaconSettings[levelLayoutData] : null);
			LegacyLogger.Debug($"FogBeaconSettingManager: updated setting for level with main level layout id {levelLayoutData}");
		}

		private FogBeaconSettingManager()
		{
		}

		static FogBeaconSettingManager()
		{
			CONFIG_PATH = Path.Combine(LegacyOverrideManagers.LEGACY_CONFIG_PATH, "FogBeaconSetting");
			Current = new FogBeaconSettingManager();
		}
	}
}
namespace LEGACY.LegacyOverride.ExtraExpeditionSettings
{
	public class ExpeditionSettings
	{
		public uint MainLevelLayout { get; set; }
	}
	internal class ExpeditionSettingsManager
	{
		public static ExpeditionSettingsManager Current;

		private Dictionary<uint, ExpeditionSettings> expSettings = new Dictionary<uint, ExpeditionSettings>();

		private LiveEditListener liveEditListener;

		private static readonly string CONFIG_PATH;

		private void AddOverride(ExpeditionSettings _override)
		{
			if (_override != null)
			{
				if (expSettings.ContainsKey(_override.MainLevelLayout))
				{
					LegacyLogger.Warning("Replaced MainLevelLayout {0}", _override.MainLevelLayout);
					expSettings[_override.MainLevelLayout] = _override;
				}
				else
				{
					expSettings.Add(_override.MainLevelLayout, _override);
				}
			}
		}

		public void Init()
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Expected O, but got Unknown
			if (!Directory.Exists(CONFIG_PATH))
			{
				Directory.CreateDirectory(CONFIG_PATH);
				StreamWriter streamWriter = File.CreateText(Path.Combine(CONFIG_PATH, "Template.json"));
				streamWriter.WriteLine(Json.Serialize(new ExpeditionSettings()));
				streamWriter.Flush();
				streamWriter.Close();
				return;
			}
			foreach (string item in Directory.EnumerateFiles(CONFIG_PATH, "*.json", SearchOption.AllDirectories))
			{
				Json.Load<ExpeditionSettings>(item, out var config);
				AddOverride(config);
			}
			liveEditListener = LiveEdit.CreateListener(CONFIG_PATH, "*.json", true);
			liveEditListener.FileChanged += new LiveEditEventHandler(FileChanged);
		}

		private void FileChanged(LiveEditEventArgs e)
		{
			LegacyLogger.Warning("LiveEdit File Changed: " + e.FullPath);
			LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content)
			{
				ExpeditionSettings @override = Json.Deserialize<ExpeditionSettings>(content);
				AddOverride(@override);
			});
		}

		private void OnBuildDone()
		{
			if (expSettings.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData))
			{
				_ = expSettings[RundownManager.ActiveExpedition.LevelLayoutData];
			}
		}

		private void OnBuildStart()
		{
		}

		private void OnLevelCleanup()
		{
		}

		private void OnEnterLevel()
		{
		}

		private ExpeditionSettingsManager()
		{
		}

		static ExpeditionSettingsManager()
		{
			CONFIG_PATH = Path.Combine(LegacyOverrideManagers.LEGACY_CONFIG_PATH, "ExpeditionSettings");
			Current = new ExpeditionSettingsManager();
			LevelAPI.OnBuildStart += Current.OnBuildStart;
			LevelAPI.OnEnterLevel += Current.OnEnterLevel;
			LevelAPI.OnBuildDone += Current.OnBuildDone;
			LevelAPI.OnLevelCleanup += Current.OnLevelCleanup;
		}
	}
}
namespace LEGACY.LegacyOverride.EnemyTagger
{
	public enum eEnemyTaggerState
	{
		Uninitialized,
		Inactive,
		Active_Warmup,
		Active_Tagging
	}
	public class EnemyTaggerComponent : MonoBehaviour
	{
		private const float INACTIVE_SOUND_UPDATE_INTERVAL = 1f;

		internal int MaxTagPerScan = 12;

		internal float TagInterval = 3f;

		internal float TagRadius = 12f;

		internal float WarmupTime = 3f;

		private eEnemyTaggerState CurrentState;

		private CellSoundPlayer m_sound = new CellSoundPlayer();

		private List<EnemyAgent> TaggableEnemies = new List<EnemyAgent>();

		private float UpdateTime;

		internal CarryItemPickup_Core Parent { get; set; }

		internal PlayerAgent PickedByPlayer { get; set; }

		internal Vector3 Position
		{
			get
			{
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)Parent == (Object)null))
				{
					if (!((Object)(object)PickedByPlayer == (Object)null))
					{
						return ((Component)PickedByPlayer).transform.position;
					}
					return ((Component)Parent).transform.position;
				}
				return Vector3.zero;
			}
		}

		public void ChangeState(eEnemyTaggerState newState)
		{
			if (CurrentState == newState)
			{
				return;
			}
			switch (newState)
			{
			case eEnemyTaggerState.Uninitialized:
				LegacyLogger.Error("Enemy Tagger changed to state 'uninitialized'?");
				return;
			case eEnemyTaggerState.Inactive:
				UpdateTime = 0f;
				TaggableEnemies.Clear();
				m_sound.Post(EVENTS.BULKHEAD_BUTTON_CLOSE, true);
				break;
			case eEnemyTaggerState.Active_Warmup:
				UpdateTime = 0f;
				m_sound.Post(EVENTS.BUTTONGENERICDEACTIVATE, true);
				break;
			case eEnemyTaggerState.Active_Tagging:
				if (CurrentState != eEnemyTaggerState.Active_Warmup)
				{
					UpdateTime = 0f;
				}
				break;
			default:
				LegacyLogger.Error($"Enemy Tagger: Undefined state {CurrentState}");
				return;
			}
			CurrentState = newState;
		}

		private bool UpdateTaggableEnemies()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			TaggableEnemies.Clear();
			bool result = false;
			Enumerator<EnemyAgent> enumerator = AIG_CourseGraph.GetReachableEnemiesInNodes(((Object)(object)PickedByPlayer == (Object)null) ? ((ItemInLevel)Parent).m_courseNode : ((Agent)PickedByPlayer).CourseNode, 2).GetEnumerator();
			while (enumerator.MoveNext())
			{
				EnemyAgent current = enumerator.Current;
				if (!((Agent)current).Alive)
				{
					continue;
				}
				Vector3 val = ((Component)current).transform.position - Position;
				if (!(((Vector3)(ref val)).magnitude > TagRadius))
				{
					result = true;
					if (!current.IsTagged)
					{
						TaggableEnemies.Add(current);
					}
					if (TaggableEnemies.Count >= MaxTagPerScan)
					{
						break;
					}
				}
			}
			return result;
		}

		private void StartTagging()
		{
			if (!(UpdateTime >= TagInterval))
			{
				return;
			}
			if (SNet.IsMaster)
			{
				UpdateTaggableEnemies();
				foreach (EnemyAgent taggableEnemy in TaggableEnemies)
				{
					ToolSyncManager.WantToTagEnemy(taggableEnemy);
				}
			}
			m_sound.Post(EVENTS.MARKERGUNACTIVATE, true);
			UpdateTime = 0f;
		}

		private void StopTagging()
		{
			if (UpdateTime >= 1f)
			{
				m_sound.Post(EVENTS.BUTTONGENERICDEACTIVATE, true);
				UpdateTime = 0f;
			}
		}

		private void Warmup()
		{
			if (UpdateTime >= WarmupTime)
			{
				ChangeState(eEnemyTaggerState.Active_Tagging);
				UpdateTime = TagInterval;
			}
		}

		private void Update()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (CurrentState == eEnemyTaggerState.Uninitialized)
			{
				return;
			}
			if ((Object)(object)Parent == (Object)null)
			{
				LegacyLogger.Error("EnemyTagger: null parent");
				return;
			}
			UpdateTime += Time.deltaTime;
			m_sound.UpdatePosition(Position);
			switch (CurrentState)
			{
			case eEnemyTaggerState.Active_Warmup:
				Warmup();
				break;
			case eEnemyTaggerState.Active_Tagging:
				StartTagging();
				break;
			case eEnemyTaggerState.Inactive:
				StopTagging();
				break;
			}
		}

		private void OnDestroy()
		{
			StopTagging();
			TaggableEnemies.Clear();
			TaggableEnemies = null;
			if (m_sound != null)
			{
				m_sound.Stop();
				m_sound.Recycle();
				m_sound = null;
			}
			Parent = null;
		}
	}
	public class EnemyTaggerSetting
	{
		public uint MainLevelLayout { get; set; }

		public float TimeToPickup { get; set; } = 1f;


		public float TimeToPlace { get; set; } = 1f;


		public float WarmupTime { get; set; } = 5f;


		public int MaxTagPerScan { get; set; } = 12;


		public float TagInterval { get; set; } = 3f;


		public float TagRadius { get; set; } = 12f;


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


		public bool TagWhenHold { get; set; }
	}
	internal class EnemyTaggerSettingManager
	{
		public static readonly EnemyTaggerSettingManager Current;

		private Dictionary<uint, EnemyTaggerSetting> enemyTaggerSettingSettings = new Dictionary<uint, EnemyTaggerSetting>();

		private LiveEditListener liveEditListener;

		private static readonly string CONFIG_PATH;

		private static readonly EnemyTaggerSetting DEFAULT;

		internal EnemyTaggerSetting SettingForCurrentLevel { get; private set; } = DEFAULT;


		private void AddOverride(EnemyTaggerSetting _override)
		{
			if (_override != null)
			{
				if (enemyTaggerSettingSettings.ContainsKey(_override.MainLevelLayout))
				{
					LegacyLogger.Warning("Replaced MainLevelLayout {0}", _override.MainLevelLayout);
					enemyTaggerSettingSettings[_override.MainLevelLayout] = _override;
				}
				else
				{
					enemyTaggerSettingSettings.Add(_override.MainLevelLayout, _override);
				}
			}
		}

		public void Init()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Expected O, but got Unknown
			if (!Directory.Exists(CONFIG_PATH))
			{
				Directory.CreateDirectory(CONFIG_PATH);
				StreamWriter streamWriter = File.CreateText(Path.Combine(CONFIG_PATH, "Template.json"));
				streamWriter.WriteLine(Json.Serialize(new EnemyTaggerSetting()));
				streamWriter.Flush();
				streamWriter.Close();
				return;
			}
			foreach (string item in Directory.EnumerateFiles(CONFIG_PATH, "*.json", SearchOption.AllDirectories))
			{
				Json.Load<EnemyTaggerSetting>(item, out var config);
				AddOverride(config);
			}
			LevelAPI.OnBuildStart += UpdateSetting;
			ClassInjector.RegisterTypeInIl2Cpp<EnemyTaggerComponent>();
			liveEditListener = LiveEdit.CreateListener(CONFIG_PATH, "*.json", true);
			liveEditListener.FileChanged += new LiveEditEventHandler(FileChanged);
		}

		private void FileChanged(LiveEditEventArgs e)
		{
			LegacyLogger.Warning("LiveEdit File Changed: " + e.FullPath);
			LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content)
			{
				EnemyTaggerSetting @override = Json.Deserialize<EnemyTaggerSetting>(content);
				AddOverride(@override);
				if (GameStateManager.IsInExpedition)
				{
					UpdateSetting();
				}
			});
		}

		private void UpdateSetting()
		{
			uint levelLayoutData = RundownManager.ActiveExpedition.LevelLayoutData;
			SettingForCurrentLevel = (enemyTaggerSettingSettings.ContainsKey(levelLayoutData) ? enemyTaggerSettingSettings[levelLayoutData] : DEFAULT);
			LegacyLogger.Debug($"EnemyTaggerSettingManager: updated setting for level with main level layout id {levelLayoutData}");
		}

		private EnemyTaggerSettingManager()
		{
		}

		static EnemyTaggerSettingManager()
		{
			CONFIG_PATH = Path.Combine(LegacyOverrideManagers.LEGACY_CONFIG_PATH, "EnemyTaggerSetting");
			DEFAULT = new EnemyTaggerSetting();
			Current = new EnemyTaggerSettingManager();
		}
	}
}
namespace LEGACY.LegacyOverride.ElevatorCargo
{
	internal class ElevatorCargoOverrideManager
	{
		public static readonly ElevatorCargoOverrideManager Current;

		private Dictionary<uint, LevelElevatorCargo> elevatorCargos = new Dictionary<uint, LevelElevatorCargo>();

		private LiveEditListener liveEditListener;

		private static readonly string CONFIG_PATH;

		private void AddOverride(LevelElevatorCargo _override)
		{
			if (_override != null)
			{
				if (elevatorCargos.ContainsKey(_override.MainLevelLayout))
				{
					LegacyLogger.Warning("Replaced MainLevelLayout {0}", _override.MainLevelLayout);
					elevatorCargos[_override.MainLevelLayout] = _override;
				}
				else
				{
					elevatorCargos.Add(_override.MainLevelLayout, _override);
				}
			}
		}

		public void Init()
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Expected O, but got Unknown
			if (!Directory.Exists(CONFIG_PATH))
			{
				Directory.CreateDirectory(CONFIG_PATH);
				StreamWriter streamWriter = File.CreateText(Path.Combine(CONFIG_PATH, "Template.json"));
				streamWriter.WriteLine(Json.Serialize(new LevelElevatorCargo()));
				streamWriter.Flush();
				streamWriter.Close();
				return;
			}
			foreach (string item in Directory.EnumerateFiles(CONFIG_PATH, "*.json", SearchOption.AllDirectories))
			{
				Json.Load<LevelElevatorCargo>(item, out var config);
				AddOverride(config);
			}
			liveEditListener = LiveEdit.CreateListener(CONFIG_PATH, "*.json", true);
			liveEditListener.FileChanged += new LiveEditEventHandler(FileChanged);
		}

		private void FileChanged(LiveEditEventArgs e)
		{
			LegacyLogger.Warning("LiveEdit File Changed: " + e.FullPath);
			LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content)
			{
				LevelElevatorCargo @override = Json.Deserialize<LevelElevatorCargo>(content);
				AddOverride(@override);
			});
		}

		internal LevelElevatorCargo GetLevelElevatorCargoItems(uint MainLevelLayout)
		{
			if (!elevatorCargos.ContainsKey(MainLevelLayout))
			{
				return null;
			}
			return elevatorCargos[MainLevelLayout];
		}

		private ElevatorCargoOverrideManager()
		{
		}

		static ElevatorCargoOverrideManager()
		{
			CONFIG_PATH = Path.Combine(LegacyOverrideManagers.LEGACY_CONFIG_PATH, "ElevatorCargoOverride");
			Current = new ElevatorCargoOverrideManager();
		}
	}
	public enum ItemType
	{
		Consumable,
		BigPickup
	}
	public class ElevatorCargoItem
	{
		public uint ItemID { get; set; }

		public ItemType ItemType { get; set; }
	}
	public class LevelElevatorCargo
	{
		public uint MainLevelLayout { get; set; }

		public bool ForceDisable { get; set; }

		public List<ElevatorCargoItem> ElevatorCargoItems { get; set; } = new List<ElevatorCargoItem>();

	}
}
namespace LEGACY.LegacyOverride.DimensionPortal
{
	public class DimensionPortalInstanceManager : InstanceManager<LG_DimensionPortal>
	{
		public static DimensionPortalInstanceManager Current { get; private set; }

		public override (eDimensionIndex dim, LG_LayerType layer, eLocalZoneIndex zone) GetGlobalZoneIndex(LG_DimensionPortal 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);
		}

		private DimensionPortalInstanceManager()
		{
		}

		static DimensionPortalInstanceManager()
		{
			Current = new DimensionPortalInstanceManager();
		}
	}
	public class DimensionPortalDefinitionManager : InstanceDefinitionManager<PortalCustomization>
	{
		public static DimensionPortalDefinitionManager Current { get; private set; }

		protected override string DEFINITION_NAME => "DimensionPortal";

		private DimensionPortalDefinitionManager()
		{
		}

		static DimensionPortalDefinitionManager()
		{
			Current = new DimensionPortalDefinitionManager();
		}
	}
	public class PortalCustomization : BaseInstanceDefinition
	{
		public uint ChainedPuzzleOnPortalActive { get; set; } = 4u;


		public List<WardenObjectiveEventData> EventsOnScanActive { get; set; } = new List<WardenObjectiveEventData>();


		public List<WardenObjectiveEventData> EventsOnScanDone { get; set; } = new List<WardenObjectiveEventData>();

	}
}
namespace LEGACY.ExtraEvents
{
	internal static class LegacyExtraEvents
	{
		private static bool initialized;

		private static void AlertEnemiesInArea(LG_Area area)
		{
			//IL_00c1: 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_0102: 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_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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			AIG_CourseNode courseNode = area.m_courseNode;
			if (courseNode.m_enemiesInNode.Count > 0)
			{
				EnemyAgent obj = courseNode.m_enemiesInNode[0];
				PlayerAgent val = null;
				if (PlayerManager.TryGetClosestAlivePlayerAgent(((Agent)obj).CourseNode, ref val) && (Object)(object)val != (Object)null)
				{
					Vector3 position = courseNode.m_enemiesInNode[0].Position;
					NoiseManager.MakeNoise(new NM_NoiseData
					{
						noiseMaker = null,
						position = position,
						radiusMin = 50f,
						radiusMax = 120f,
						yScale = 1f,
						node = courseNode,
						type = (NM_NoiseType)0,
						includeToNeightbourAreas = true,
						raycastFirstNode = false
					});
				}
				else
				{
					LegacyLogger.Error($"AlertEnemies: failed to alert enemies in area in Zone_{area.m_zone.LocalIndex}, {area.m_zone.m_layer.m_type}, {area.m_zone.DimensionIndex}");
				}
			}
		}

		private static void AlertEnemiesInZone(WardenObjectiveEventData e)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: 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_009c: 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)
			LG_Zone val = default(LG_Zone);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(e.DimensionIndex, e.Layer, e.LocalIndex, ref val) || (Object)(object)val == (Object)null)
			{
				LegacyLogger.Error($"AlertEnemiesInZone: zone not found, {(e.DimensionIndex, e.Layer, e.LocalIndex)}");
				return;
			}
			LegacyLogger.Debug($"AlertEnemiesInZone: {e.LocalIndex}, {e.Layer}, {e.DimensionIndex}");
			Enumerator<LG_Area> enumerator = val.m_areas.GetEnumerator();
			while (enumerator.MoveNext())
			{
				AlertEnemiesInArea(enumerator.Current);
			}
		}

		private static void AlertEnemiesInArea(WardenObjectiveEventData e)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = default(LG_Zone);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(e.DimensionIndex, e.Layer, e.LocalIndex, ref val) || (Object)(object)val == (Object)null)
			{
				LegacyLogger.Error($"AlertEnemiesInArea: zone not found, {(e.DimensionIndex, e.Layer, e.LocalIndex)}");
			}
			else if (e.Count >= val.m_areas.Count && e.Count < 0)
			{
				LegacyLogger.Error($"AlertEnemiesInArea: invalid area index {e.Count} (specified by 'Count')");
			}
			else
			{
				AlertEnemiesInArea(val.m_areas[e.Count]);
			}
		}

		private static void ActivateChainedPuzzle(WardenObjectiveEventData e)
		{
			//IL_00f9: 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)
			uint chainPuzzle = e.ChainPuzzle;
			CP_Bioscan_Core bioscanCore = PuzzleOverrideManager.Current.GetBioscanCore(chainPuzzle);
			CP_Cluster_Core clusterCore = PuzzleOverrideManager.Current.GetClusterCore(chainPuzzle);
			iChainedPuzzleOwner val;
			if ((Object)(object)bioscanCore != (Object)null)
			{
				val = PuzzleOverrideManager.Current.ChainedPuzzleInstanceOwner(bioscanCore);
			}
			else
			{
				if (!((Object)(object)clusterCore != (Object)null))
				{
					LegacyLogger.Error($"ActivateChainedPuzzle: Cannot find puzzle with puzzle override index {chainPuzzle}!");
					return;
				}
				val = clusterCore.m_owner;
			}
			ChainedPuzzleInstance val2 = ((Il2CppObjectBase)val).TryCast<ChainedPuzzleInstance>();
			if ((Object)(object)val2 == (Object)null)
			{
				LegacyLogger.Error("ActivateChainedPuzzle: Cannot find ChainedPuzzleInstance!");
				return;
			}
			if (SNet.IsMaster)
			{
				val2.AttemptInteract((eChainedPuzzleInteraction)0);
			}
			LegacyLogger.Debug($"ActivateChainedPuzzle: puzzle override index: {chainPuzzle}");
			LegacyLogger.Debug($"ChainedPuzzleZone: Dim {val2.m_sourceArea.m_zone.DimensionIndex}, {val2.m_sourceArea.m_zone.m_layer.m_type}, Zone {val2.m_sourceArea.m_zone.Alias}");
			LegacyLogger.Debug("ChainedPuzzle Alarm name: " + val2.Data.PublicAlarmName);
		}

		internal static IEnumerator AddReqItem(WardenObjectiveEventData e, float currentDuration)
		{
			uint puzzleOverrideIndex = e.ChainPuzzle;
			int count = e.Count;
			CarryItemPickup_Core itemToAdd = PuzzleReqItemManager.Current.GetBigPickupItem(count);
			if ((Object)(object)itemToAdd == (Object)null)
			{
				LegacyLogger.Error($"AddReqItem: Cannot find BigPickup Item with index {count}");
				yield break;
			}
			CP_Bioscan_Core bioscanCore = PuzzleOverrideManager.Current.GetBioscanCore(puzzleOverrideIndex);
			CP_Cluster_Core clusterCore = PuzzleOverrideManager.Current.GetClusterCore(puzzleOverrideIndex);
			if ((Object)(object)bioscanCore != (Object)null)
			{
				float num = Mathf.Max(e.Delay - currentDuration, 0f);
				if (num > 0f)
				{
					yield return (object)new WaitForSeconds(num);
				}
				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);
					}
				}
				if ((double)e.Duration > 0.0 && (double)e.Duration < 1.0)
				{
					float duration = e.Duration;
					CP_PlayerScanner scanner = ((Il2CppObjectBase)bioscanCore.m_playerScanner).TryCast<CP_PlayerScanner>();
					if ((Object)(object)scanner != (Object)null)
					{
						float CheckInterval = (((double)e.FogTransitionDuration > 0.0) ? e.FogTransitionDuration : 0.5f);
						LegacyLogger.Debug($"AddReqItem: item would be added on scan progression: {duration}, progression check interval: {CheckInterval} (seconds)");
						while (scanner.m_scanProgression < e.Duration)
						{
							yield return (object)new WaitForSeconds(CheckInterval);
						}
					}
					else
					{
						LegacyLogger.Error("AddReqItem: Failed to get scanner for the CP_Bioscan_Core");
					}
				}
				bioscanCore.AddRequiredItems(Il2CppReferenceArray<iWardenObjectiveItem>.op_Implicit((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
				{
					new iWardenObjectiveItem(((Il2CppObjectBase)itemToAdd).Pointer)
				}));
				LegacyLogger.Debug($"AddReqItem: puzzle override index: {puzzleOverrideIndex}");
				LegacyLogger.Debug("Item name: " + ((Item)itemToAdd).ItemDataBlock.publicName);
			}
			else if ((Object)(object)clusterCore != (Object)null)
			{
				float num2 = Mathf.Max(e.Delay - currentDuration, 0f);
				if (num2 > 0f)
				{
					yield return (object)new WaitForSeconds(num2);
				}
				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 text2 = ((Object)e.SoundSubtitle).ToString();
					if (!string.IsNullOrWhiteSpace(text2))
					{
						GuiManager.PlayerLayer.ShowMultiLineSubtitle(text2);
					}
				}
				iWardenObjectiveItem[] array = (iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
				{
					new iWardenObjectiveItem(((Il2CppObjectBase)itemToAdd).Pointer)
				};
				foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)clusterCore.m_childCores)
				{
					item.AddRequiredItems(Il2CppReferenceArray<iWardenObjectiveItem>.op_Implicit(array));
				}
				LegacyLogger.Debug($"AddReqItem: puzzle override index: {puzzleOverrideIndex}");
				LegacyLogger.Debug("Item name: " + ((Item)itemToAdd).ItemDataBlock.publicName);
			}
			else
			{
				LegacyLogger.Error($"AddReqItem: cannot find puzzle core with index {puzzleOverrideIndex}");
			}
		}

		internal static IEnumerator RemoveReqItem(WardenObjectiveEventData e, float currentDuration)
		{
			uint puzzleOverrideIndex = e.ChainPuzzle;
			int count = e.Count;
			CarryItemPickup_Core itemToRemove = PuzzleReqItemManager.Current.GetBigPickupItem(count);
			if ((Object)(object)itemToRemove == (Object)null)
			{
				LegacyLogger.Error($"RemoveReqItem: Cannot find BigPickup Item with index {count}");
				yield break;
			}
			CP_Bioscan_Core bioscanCore = PuzzleOverrideManager.Current.GetBioscanCore(puzzleOverrideIndex);
			CP_Cluster_Core clusterCore = PuzzleOverrideManager.Current.GetClusterCore(puzzleOverrideIndex);
			if ((Object)(object)bioscanCore != (Object)null)
			{
				float num = Mathf.Max(e.Delay - currentDuration, 0f);
				if (num > 0f)
				{
					yield return (object)new WaitForSeconds(num);
				}
				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);
					}
				}
				if ((double)e.Duration > 0.0 && (double)e.Duration < 1.0)
				{
					float duration = e.Duration;
					CP_PlayerScanner scanner = ((Il2CppObjectBase)bioscanCore.m_playerScanner).TryCast<CP_PlayerScanner>();
					if ((Object)(object)scanner != (Object)null)
					{
						float CheckInterval = (((double)e.FogTransitionDuration > 0.0) ? e.FogTransitionDuration : 0.5f);
						LegacyLogger.Debug($"RemoveReqItem: item would be added on scan progression: {duration}, progression check interval: {CheckInterval} (seconds)");
						while (scanner.m_scanProgression < e.Duration)
						{
							yield return (object)new WaitForSeconds(CheckInterval);
						}
					}
					else
					{
						LegacyLogger.Error("RemoveReqItem: Failed to get scanner for the CP_Bioscan_Core");
					}
				}
				bioscanCore.RemoveRequiredItems((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
				{
					new iWardenObjectiveItem(((Il2CppObjectBase)itemToRemove).Pointer)
				});
				LegacyLogger.Debug($"RemoveReqItem: puzzle override index: {puzzleOverrideIndex}");
				LegacyLogger.Debug("Removed Item name: " + ((Item)itemToRemove).ItemDataBlock.publicName);
			}
			else if ((Object)(object)clusterCore != (Object)null)
			{
				float num2 = Mathf.Max(e.Delay - currentDuration, 0f);
				if (num2 > 0f)
				{
					yield return (object)new WaitForSeconds(num2);
				}
				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 text2 = ((Object)e.SoundSubtitle).ToString();
					if (!string.IsNullOrWhiteSpace(text2))
					{
						GuiManager.PlayerLayer.ShowMultiLineSubtitle(text2);
					}
				}
				iWardenObjectiveItem[] array = (iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
				{
					new iWardenObjectiveItem(((Il2CppObjectBase)itemToRemove).Pointer)
				};
				foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)clusterCore.m_childCores)
				{
					item.RemoveRequiredItems(array);
				}
				LegacyLogger.Debug($"RemoveReqItem: puzzle override index: {puzzleOverrideIndex}");
				LegacyLogger.Debug("Removed Item name: " + ((Item)itemToRemove).ItemDataBlock.publicName);
			}
			else
			{
				LegacyLogger.Error($"RemoveReqItem: cannot find puzzle core with index {puzzleOverrideIndex}");
			}
		}

		internal static void Init()
		{
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			if (!initialized)
			{
				LegacyLogger.Log("Adding Legacy warden event definitions...");
				EOSWardenEventManager.Current.AddEventDefinition(EventType.CloseSecurityDoor_Custom.ToString(), 100u, (Action<WardenObjectiveEventData>)CloseSecurityDoor);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.SetTimerTitle.ToString(), 102u, (Action<WardenObjectiveEventData>)SetTimerTitle);
				EOSWardenEventManager current = EOSWardenEventManager.Current;
				eWardenObjectiveEventType val = (eWardenObjectiveEventType)21;
				current.AddEventDefinition(((object)(eWardenObjectiveEventType)(ref val)).ToString(), 21u, (Action<WardenObjectiveEventData>)SetTerminalCommand_Custom);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.AlertEnemiesInArea.ToString(), 108u, (Action<WardenObjectiveEventData>)AlertEnemiesInArea);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.AlertEnemiesInZone.ToString(), 107u, (Action<WardenObjectiveEventData>)AlertEnemiesInZone);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.KillEnemiesInArea.ToString(), 140u, (Action<WardenObjectiveEventData>)KillEnemiesInArea);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.KillEnemiesInZone.ToString(), 141u, (Action<WardenObjectiveEventData>)KillEnemiesInZone);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.KillEnemiesInDimension.ToString(), 142u, (Action<WardenObjectiveEventData>)KillEnemiesInDimension);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.SpawnHibernate.ToString(), 170u, (Action<WardenObjectiveEventData>)SpawnHibernate);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.Info_ZoneHibernate.ToString(), 250u, (Action<WardenObjectiveEventData>)Info_ZoneHibernate);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.Info_LevelHibernate.ToString(), 251u, (Action<WardenObjectiveEventData>)Info_LevelEnemies);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.Output_LevelHibernateSpawnEvent.ToString(), 252u, (Action<WardenObjectiveEventData>)Output_LevelHibernateSpawnEvent);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.PlayGCEndSequence.ToString(), 180u, (Action<WardenObjectiveEventData>)PlayGCEndSequence);
				EOSWardenEventManager current2 = EOSWardenEventManager.Current;
				val = (eWardenObjectiveEventType)22;
				current2.AddEventDefinition(((object)(eWardenObjectiveEventType)(ref val)).ToString(), 22u, (Action<WardenObjectiveEventData>)ActivateChainedPuzzle);
				EOSWardenEventManager.Current.AddEventDefinition(EventType.Terminal_ShowTerminalInfoInZone.ToString(), 130u, (Action<WardenObjectiveEventData>)ShowTerminalInfoInZone);
				LegacyLogger.Log("Legacy warden event definitions setup completed");
				initialized = true;
			}
		}

		private static IEnumerator Play(WardenObjectiveEventData e)
		{
			List<LG_PowerGenerator_Core> gcInZone = ((InstanceManager<LG_PowerGenerator_Core>)(object)PowerGeneratorInstanceManager.Current).GetInstancesInZone(e.DimensionIndex, e.Layer, e.LocalIndex);
			yield return (object)new WaitForSeconds(4f);
			CellSound.Post(EVENTS.DISTANT_EXPLOSION_SEQUENCE);
			yield return (object)new WaitForSeconds(2f);
			EnvironmentStateManager.AttemptSetExpeditionLightMode(false);
			CellSound.Post(EVENTS.LIGHTS_OFF_GLOBAL);
			yield return (object)new WaitForSeconds(3f);
			int g = 0;
			while (g < gcInZone.Count)
			{
				gcInZone[g].TriggerPowerFailureSequence();
				yield return (object)new WaitForSeconds(Random.Range(0.3f, 1f));
				int num = g + 1;
				g = num;
			}
			yield return (object)new WaitForSeconds(4f);
			EnvironmentStateManager.AttemptSetExpeditionLightMode(true);
		}

		private static void PlayGCEndSequence(WardenObjectiveEventData e)
		{
			Coroutine val = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(Play(e)), (Action)null);
			WorldEventManager.m_worldEventEventCoroutines.Add(val);
		}

		private static void KillEnemiesInArea(LG_Area area)
		{
			//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 (EnemyAgent item in area.m_courseNode.m_enemiesInNode.ToArray())
			{
				if ((Object)(object)item != (Object)null && (Object)(object)item.Damage != (Object)null)
				{
					item.Damage.MeleeDamage(float.MaxValue, (Agent)null, Vector3.zero, Vector3.up, 0, 1f, 1f, 1f, 1f, false, (DamageNoiseLevel)0, 0u);
				}
			}
		}

		private static void KillEnemiesInArea(WardenObjectiveEventData e)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = default(LG_Zone);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(e.DimensionIndex, e.Layer, e.LocalIndex, ref val) || (Object)(object)val == (Object)null)
			{
				LegacyLogger.Error($"KillEnemiesInArea - Failed to find {(e.DimensionIndex, e.Layer, e.LocalIndex)}");
			}
			else if (e.Count < 0 || e.Count >= val.m_areas.Count)
			{
				LegacyLogger.Error($"KillEnemiesInArea - invalid area index {e.Count} (specified by 'Count')");
			}
			else
			{
				KillEnemiesInArea(val.m_areas[e.Count]);
			}
		}

		private static void KillEnemiesInZone(WardenObjectiveEventData e)
		{
			//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)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (!SNet.IsMaster)
			{
				return;
			}
			LG_Zone val = default(LG_Zone);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(e.DimensionIndex, e.Layer, e.LocalIndex, ref val) || (Object)(object)val == (Object)null)
			{
				LegacyLogger.Error($"KillEnemiesInArea - Failed to find {(e.DimensionIndex, e.Layer, e.LocalIndex)}");
			}
			else
			{
				Enumerator<LG_Area> enumerator = val.m_areas.GetEnumerator();
				while (enumerator.MoveNext())
				{
					KillEnemiesInArea(enumerator.Current);
				}
			}
		}

		private static void KillEnemiesInDimension(WardenObjectiveEventData e)
		{
			//IL_0009: 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_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_009a: Invalid comparison between Unknown and I4
			if (!SNet.IsMaster)
			{
				return;
			}
			Dimension val = default(Dimension);
			if (!Dimension.GetDimension(e.DimensionIndex, ref val))
			{
				LegacyLogger.Error($"KillEnemiesInDimension: invalid dimension index {e.DimensionIndex}");
				return;
			}
			for (int i = 0; i < val.Layers.Count; i++)
			{
				LG_Layer val2 = val.Layers[i];
				for (int j = 0; j < val2.m_zones.Count; j++)
				{
					LG_Zone val3 = val2.m_zones[j];
					Helper.TryGetZoneEntranceSecDoor(val3, out var door);
					if (j == 0 || ((Object)(object)door != (Object)null && (int)door.m_sync.GetCurrentSyncState().status == 10))
					{
						Enumerator<LG_Area> enumerator = val3.m_areas.GetEnumerator();
						while (enumerator.MoveNext())
						{
							KillEnemiesInArea(enumerator.Current);
						}
					}
				}
			}
		}

		private static void CloseSecurityDoor(WardenObjectiveEventData e)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: 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_0047: 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_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_0092: Unknown result type (might be due to invalid IL or missing

plugins/ProjectEternal/net6/ProgressionGear_test.dll

Decompiled 4 months 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.Text.Json;
using System.Text.Json.Serialization;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CellMenu;
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 LocalProgression;
using LocalProgression.Data;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using ProgressionGear.Dependencies;
using ProgressionGear.JSON;
using ProgressionGear.Patches;
using ProgressionGear.ProgressionLock;
using ProgressionGear.Utils;
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("ProgressionGear")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+ca1861130430234dd6a79de88815d55a4a5edbd0")]
[assembly: AssemblyProduct("ProgressionGear")]
[assembly: AssemblyTitle("ProgressionGear")]
[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 ProgressionGear
{
	internal static class Configuration
	{
		private static readonly ConfigFile _configFile;

		public static bool DisableProgression { get; set; }

		static Configuration()
		{
			//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, "ProgressionGear.cfg"), true);
			BindAll(_configFile);
		}

		public 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, "ProgressionGear.cfg", false).FileChanged += new LiveEditEventHandler(OnFileChanged);
		}

		private static void OnFileChanged(LiveEditEventArgs _)
		{
			_configFile.Reload();
			DisableProgression = (bool)_configFile["Override", "Disable Progression Locks"].BoxedValue;
		}

		private static void BindAll(ConfigFile config)
		{
			DisableProgression = config.Bind<bool>("Override", "Disable Progression Locks", DisableProgression, "Disables progression-locking for weapons.").Value;
		}
	}
	[BepInPlugin("Dinorush.ProgressionGear", "ProgressionGear", "1.1.2")]
	[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 = "ProgressionGear";

		public override void Load()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			PWLogger.Log("Loading ProgressionGear");
			Harmony val = new Harmony("ProgressionGear");
			val.PatchAll();
			if (!LocalProgressionWrapper.HasLocalProgression)
			{
				val.PatchAll(typeof(PageRundownPatches_NoLP));
			}
			if (EOSWrapper.HasEOS)
			{
				val.PatchAll(typeof(RundownManagerPatches_EOS));
			}
			Configuration.Init();
			GearToggleManager.Current.Init();
			ProgressionLockManager.Current.Init();
			PWLogger.Log("Loaded ProgressionGear");
		}
	}
}
namespace ProgressionGear.Utils
{
	internal class DictListEnumerator<T> : IEnumerator<T>, IDisposable, IEnumerator
	{
		private readonly IEnumerator<List<T>> _valueEnumerator;

		private List<T>? _curList;

		private int _index;

		private T? _current;

		public T Current => _current;

		object IEnumerator.Current => Current;

		internal DictListEnumerator(Dictionary<string, List<T>> data)
		{
			_valueEnumerator = data.Values.GetEnumerator();
			if (_valueEnumerator.MoveNext())
			{
				_curList = _valueEnumerator.Current;
			}
			_index = -1;
		}

		public void Dispose()
		{
		}

		public bool MoveNext()
		{
			if (_curList == null || ++_index >= _curList.Count)
			{
				if (!_valueEnumerator.MoveNext())
				{
					return false;
				}
				_curList = _valueEnumerator.Current;
				_index = 0;
			}
			_current = _curList[_index];
			return true;
		}

		public void Reset()
		{
			_valueEnumerator.Reset();
			if (_valueEnumerator.MoveNext())
			{
				_curList = _valueEnumerator.Current;
			}
			_index = -1;
		}
	}
	internal static class GearIDRangeExtensions
	{
		public static uint GetOfflineID(this GearIDRange gearIDRange)
		{
			string playfabItemInstanceId = gearIDRange.PlayfabItemInstanceId;
			if (!playfabItemInstanceId.Contains("OfflineGear_ID_"))
			{
				PWLogger.Error("Find PlayfabItemInstanceId without substring 'OfflineGear_ID_'! " + playfabItemInstanceId);
				return 0u;
			}
			try
			{
				return uint.Parse(playfabItemInstanceId.Substring("OfflineGear_ID_".Length));
			}
			catch
			{
				PWLogger.Error("Caught exception while trying to parse persistentID of PlayerOfflineGearDB from GearIDRange, which means itemInstanceId could be ill-formated");
				return 0u;
			}
		}
	}
	internal 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)
			{
				PWLogger.Log($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}");
			}
		}
	}
	internal static class PWLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("ProgressionGear");

		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 ProgressionGear.Patches
{
	[HarmonyPatch]
	internal static class GearManagerPatches
	{
		[HarmonyPatch(typeof(GearManager), "SetupGearInOfflineMode")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_SetupGearInOfflineMode()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected I4, but got Unknown
			GearLockManager.Current.VanillaGearManager = GearManager.Current;
			foreach (var gearSlot in GearLockManager.Current.GearSlots)
			{
				InventorySlot item = gearSlot.inventorySlot;
				Dictionary<uint, GearIDRange> item2 = gearSlot.loadedGears;
				Enumerator<GearIDRange> enumerator2 = ((Il2CppArrayBase<List<GearIDRange>>)(object)GearManager.Current.m_gearPerSlot)[(int)item].GetEnumerator();
				while (enumerator2.MoveNext())
				{
					GearIDRange current2 = enumerator2.Current;
					uint offlineID = current2.GetOfflineID();
					item2.TryAdd(offlineID, current2);
				}
			}
			GearToggleManager.Current.ResetRelatedIDs();
		}
	}
	[HarmonyPatch]
	internal static class PageRundownPatches
	{
		[HarmonyPatch(typeof(CM_PageRundown_New), "PlaceRundown")]
		[HarmonyPatch(typeof(CM_PageRundown_New), "OnEnable")]
		[HarmonyAfter(new string[] { "Inas.LocalProgression" })]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_RundownUpdate()
		{
			GearLockManager.Current.SetupAllowedGearsForActiveRundown();
		}
	}
	internal static class PageRundownPatches_NoLP
	{
		[HarmonyPatch(typeof(CM_PageRundown_New), "SetIconStatus")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_IconUpdate(CM_ExpeditionIcon_New icon, string mainFinishCount, string secondFinishCount, string thirdFinishCount, string allFinishedCount)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			ProgressionData progressionData = new ProgressionData();
			if (mainFinishCount != "-")
			{
				progressionData.MainCompletionCount = int.Parse(mainFinishCount);
			}
			if (secondFinishCount != "-")
			{
				progressionData.SecondaryCompletionCount = int.Parse(secondFinishCount);
			}
			if (thirdFinishCount != "-")
			{
				progressionData.ThirdCompletionCount = int.Parse(thirdFinishCount);
			}
			if (allFinishedCount != "-")
			{
				progressionData.AllCompletionCount = int.Parse(allFinishedCount);
			}
			ProgressionWrapper.UpdateNativeProgression(icon.Tier, icon.ExpIndex, progressionData);
		}
	}
	[HarmonyPatch]
	internal static class PlayerLobbyBarPatches
	{
		public static GameObject? SwapButton;

		private static CM_InventorySlotItem? _cachedItem;

		[HarmonyPatch(typeof(CM_PlayerLobbyBar), "UpdateWeaponWindowInfo")]
		[HarmonyPrefix]
		private static void Pre_LoadoutHeaderSelected(CM_PlayerLobbyBar __instance)
		{
			_cachedItem = __instance.selectedWeaponSlotItem;
		}

		[HarmonyPatch(typeof(CM_PlayerLobbyBar), "UpdateWeaponWindowInfo")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_LoadoutHeaderSelected(CM_PlayerLobbyBar __instance, InventorySlot slot)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			BackpackItem val = default(BackpackItem);
			if ((Object)(object)_cachedItem != (Object)(object)__instance.selectedWeaponSlotItem || !PlayerBackpackManager.TryGetItem(__instance.m_player, slot, ref val) || val.GearIDRange == null)
			{
				return;
			}
			uint offlineID = val.GearIDRange.GetOfflineID();
			if (!GearToggleManager.Current.TryGetRelatedIDs(offlineID, out List<uint> relatedIDs))
			{
				return;
			}
			foreach (iScrollWindowContent item in (Il2CppArrayBase<iScrollWindowContent>)(object)__instance.m_popupScrollWindow.ContentItems)
			{
				CM_InventorySlotItem val2 = ((Il2CppObjectBase)item).TryCast<CM_InventorySlotItem>();
				if (relatedIDs.Contains(val2.m_gearID.GetOfflineID()))
				{
					val2.IsPicked = true;
					val2.LoadData(val.GearIDRange, true, true);
					__instance.OnWeaponSlotItemSelected(val2);
					_cachedItem = __instance.selectedWeaponSlotItem;
					break;
				}
			}
		}

		[HarmonyPatch(typeof(CM_PlayerLobbyBar), "ShowWeaponSelectionPopup")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_LoadoutMenuOpened(CM_PlayerLobbyBar __instance)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			CM_PlayerLobbyBar __instance2 = __instance;
			CM_ScrollWindowInfoBox infoBox = __instance2.m_popupScrollWindow.InfoBox;
			SwapButton = Object.Instantiate<GameObject>(((Component)CM_PageLoadout.Current.m_copyLobbyIdButton).gameObject, ((Component)infoBox).transform);
			CM_Item component = SwapButton.GetComponent<CM_Item>();
			((TMP_Text)((Il2CppArrayBase<TextMeshPro>)(object)component.m_texts)[0]).SetText("Switch Gear", true);
			((Component)component).transform.localPosition = new Vector3(-300f, -320f, -1f);
			component.OnBtnPressCallback = null;
			component.OnBtnPressCallback += Action<int>.op_Implicit((Action<int>)delegate
			{
				CM_InventorySlotItem val = __instance2.selectedWeaponSlotItem ?? _cachedItem;
				if (!((Object)(object)val == (Object)null))
				{
					uint offlineID = val.m_gearID.GetOfflineID();
					List<uint> relatedIDs = GearToggleManager.Current.GetRelatedIDs(offlineID);
					uint value = relatedIDs[(relatedIDs.IndexOf(offlineID) + 1) % relatedIDs.Count];
					GearIDRange val2 = default(GearIDRange);
					if (GearManager.TryGetGear("OfflineGear_ID_" + value, ref val2))
					{
						val.LoadData(val2, true, true);
						__instance2.OnWeaponSlotItemSelected(val);
					}
					else
					{
						PWLogger.Error($"Couldn't swap to next weapon ({value}) in toggle list!");
					}
				}
			});
			if ((Object)(object)__instance2.selectedWeaponSlotItem != (Object)null)
			{
				Post_LoadoutItemSelected(__instance2.selectedWeaponSlotItem);
			}
		}

		[HarmonyPatch(typeof(CM_PlayerLobbyBar), "OnWeaponSlotItemSelected")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_LoadoutItemSelected(CM_InventorySlotItem slotItem)
		{
			if (!((Object)(object)SwapButton == (Object)null))
			{
				uint offlineID = slotItem.m_gearID.GetOfflineID();
				SwapButton.SetActive(GearToggleManager.Current.HasRelatedIDs(offlineID));
			}
		}
	}
	internal static class RundownManagerPatches_EOS
	{
		[HarmonyPatch(typeof(RundownManager), "SetActiveExpedition")]
		[HarmonyAfter(new string[] { "Inas.ExtraObjectiveSetup" })]
		[HarmonyPostfix]
		private static void Post_RundownManager_SetActiveExpedition(pActiveExpedition expPackage)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)expPackage.tier != 99)
			{
				GearLockManager.Current.LockGearForActiveRundown();
			}
		}
	}
}
namespace ProgressionGear.JSON
{
	public static class PWJson
	{
		private static readonly JsonSerializerOptions _setting;

		static PWJson()
		{
			//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 ProgressionGear.ProgressionLock
{
	public sealed class GearToggleData
	{
		public List<uint> OfflineIDs { get; set; } = new List<uint>();


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

	}
	public sealed class GearToggleManager
	{
		public static readonly GearToggleManager Current = new GearToggleManager();

		private readonly Dictionary<string, List<GearToggleData>> _fileToData = new Dictionary<string, List<GearToggleData>>();

		private readonly Dictionary<uint, List<uint>> _relatedIDs = new Dictionary<uint, List<uint>>();

		private readonly LiveEditListener _liveEditListener;

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

		private void FileDeleted(LiveEditEventArgs e)
		{
			PWLogger.Warning("LiveEdit File Removed: " + e.FullPath);
			_fileToData.Remove(e.FullPath);
			ResetRelatedIDs();
		}

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

		private void ReadFileContent(string file, string content)
		{
			_fileToData.Remove(file);
			List<GearToggleData> list = null;
			try
			{
				list = PWJson.Deserialize<List<GearToggleData>>(content);
			}
			catch (JsonException ex)
			{
				PWLogger.Error("Error parsing progression lock json " + file);
				PWLogger.Error(ex.Message);
			}
			if (list != null)
			{
				_fileToData[file] = list;
				ResetRelatedIDs();
			}
		}

		private GearToggleManager()
		{
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Expected O, but got Unknown
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Expected O, but got Unknown
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			string text = Path.Combine(MTFOPathAPI.CustomPath, "ProgressionGear", "GearToggle");
			if (!Directory.Exists(text))
			{
				PWLogger.Log("No directory detected. Creating " + text + "/Template.json");
				Directory.CreateDirectory(text);
				StreamWriter streamWriter = File.CreateText(Path.Combine(text, "Template.json"));
				streamWriter.WriteLine(PWJson.Serialize(new List<GearToggleData>
				{
					new GearToggleData()
				}));
				streamWriter.Flush();
				streamWriter.Close();
			}
			else
			{
				PWLogger.Log("Directory detected. " + text);
			}
			foreach (string item in Directory.EnumerateFiles(text, "*.json", SearchOption.AllDirectories))
			{
				string content = File.ReadAllText(item);
				ReadFileContent(item, content);
			}
			_liveEditListener = LiveEdit.CreateListener(text, "*.json", true);
			_liveEditListener.FileCreated += new LiveEditEventHandler(FileCreated);
			_liveEditListener.FileChanged += new LiveEditEventHandler(FileChanged);
			_liveEditListener.FileDeleted += new LiveEditEventHandler(FileDeleted);
		}

		internal void Init()
		{
		}

		public bool IsVisibleID(uint id)
		{
			if (_relatedIDs.TryGetValue(id, out List<uint> value))
			{
				return value[0] == id;
			}
			return true;
		}

		public bool HasRelatedIDs(uint id)
		{
			return _relatedIDs.ContainsKey(id);
		}

		public List<uint>? GetRelatedIDs(uint id)
		{
			return _relatedIDs.GetValueOrDefault(id);
		}

		public bool TryGetRelatedIDs(uint id, [MaybeNullWhen(false)] out List<uint> relatedIDs)
		{
			return _relatedIDs.TryGetValue(id, out relatedIDs);
		}

		public List<GearToggleData> GetData()
		{
			List<GearToggleData> list2 = new List<GearToggleData>(_fileToData.Values.Sum((List<GearToggleData> list) => list.Count));
			IEnumerator<GearToggleData> enumerator = GetEnumerator();
			while (enumerator.MoveNext())
			{
				list2.Add(enumerator.Current);
			}
			return list2;
		}

		public IEnumerator<GearToggleData> GetEnumerator()
		{
			return new DictListEnumerator<GearToggleData>(_fileToData);
		}

		public void RemoveFromRelatedIDs(uint id)
		{
			if (_relatedIDs.TryGetValue(id, out List<uint> value))
			{
				value.Remove(id);
				if (value.Count == 1)
				{
					_relatedIDs.Remove(value[0]);
				}
				_relatedIDs.Remove(id);
			}
		}

		public void ResetRelatedIDs()
		{
			_relatedIDs.Clear();
			HashSet<uint> hashSet = new HashSet<uint>();
			IEnumerator<GearToggleData> enumerator = GetEnumerator();
			while (enumerator.MoveNext())
			{
				GearToggleData current = enumerator.Current;
				if (current.OfflineIDs.Count <= 1)
				{
					continue;
				}
				List<uint> list = new List<uint>(current.OfflineIDs.Count);
				foreach (uint offlineID in current.OfflineIDs)
				{
					if (hashSet.Add(offlineID))
					{
						list.Add(offlineID);
						continue;
					}
					PWLogger.Warning($"Duplicate ID {offlineID} detected in toggle data. Removed from {current.Name}");
				}
				if (list.Count <= 1)
				{
					continue;
				}
				RemoveInvalidGear(list, current.Name);
				if (list.Count <= 1)
				{
					continue;
				}
				foreach (uint item in list)
				{
					_relatedIDs[item] = list;
				}
			}
		}

		private void RemoveInvalidGear(List<uint> relatedIDs, string name)
		{
			//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_00ad: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)GearLockManager.Current.VanillaGearManager == (Object)null)
			{
				return;
			}
			foreach (var (value, dictionary) in GearLockManager.Current.GearSlots)
			{
				if (!dictionary.ContainsKey(relatedIDs[0]))
				{
					continue;
				}
				for (int num = relatedIDs.Count - 1; num >= 1; num--)
				{
					uint num2 = relatedIDs[num];
					if (!dictionary.ContainsKey(num2))
					{
						PWLogger.Warning($"ID {num2} removed from toggle data {name} since it is not of type {value}");
						relatedIDs.RemoveAt(num);
					}
				}
			}
		}
	}
	public sealed class GearLockManager
	{
		private struct PriorityLockData
		{
			public int priority;

			public bool locked;

			public bool explicitLock;
		}

		private readonly HashSet<uint> _lockedGearIds = new HashSet<uint>();

		internal readonly List<(InventorySlot inventorySlot, Dictionary<uint, GearIDRange> loadedGears)> GearSlots = new List<(InventorySlot, Dictionary<uint, GearIDRange>)>
		{
			((InventorySlot)1, new Dictionary<uint, GearIDRange>()),
			((InventorySlot)2, new Dictionary<uint, GearIDRange>()),
			((InventorySlot)10, new Dictionary<uint, GearIDRange>()),
			((InventorySlot)3, new Dictionary<uint, GearIDRange>())
		};

		public static GearLockManager Current { get; private set; } = new GearLockManager();


		public GearManager? VanillaGearManager { get; internal set; }

		private void ConfigRundownGears()
		{
			if (Configuration.DisableProgression)
			{
				return;
			}
			_lockedGearIds.Clear();
			GearToggleManager.Current.ResetRelatedIDs();
			IEnumerator<ProgressionLockData> enumerator = ProgressionLockManager.Current.GetEnumerator();
			Dictionary<uint, PriorityLockData> dictionary = new Dictionary<uint, PriorityLockData>();
			while (enumerator.MoveNext())
			{
				ProgressionLockData current = enumerator.Current;
				foreach (uint offlineID in current.OfflineIDs)
				{
					PriorityLockData priorityLockData = default(PriorityLockData);
					priorityLockData.priority = current.Priority;
					priorityLockData.locked = IsGearLocked(current);
					priorityLockData.explicitLock = IsLockExplicit(current);
					PriorityLockData value = priorityLockData;
					if (!dictionary.TryGetValue(offlineID, out var value2) || ((!value2.explicitLock || value.explicitLock) && value2.priority <= value.priority))
					{
						dictionary.Add(offlineID, value);
					}
				}
			}
			foreach (KeyValuePair<uint, PriorityLockData> item in dictionary.Where((KeyValuePair<uint, PriorityLockData> kv) => kv.Value.locked))
			{
				_lockedGearIds.Add(item.Key);
				GearToggleManager.Current.RemoveFromRelatedIDs(item.Key);
			}
		}

		private void ClearLoadedGears()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected I4, but got Unknown
			foreach (var gearSlot in GearSlots)
			{
				((Il2CppArrayBase<List<GearIDRange>>)(object)VanillaGearManager.m_gearPerSlot)[(int)gearSlot.inventorySlot].Clear();
			}
		}

		public bool IsGearAllowed(uint id)
		{
			return !_lockedGearIds.Contains(id);
		}

		private void AddGearForCurrentRundown()
		{
			//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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected I4, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			foreach (var gearSlot in GearSlots)
			{
				InventorySlot item = gearSlot.inventorySlot;
				Dictionary<uint, GearIDRange> item2 = gearSlot.loadedGears;
				List<GearIDRange> val = ((Il2CppArrayBase<List<GearIDRange>>)(object)VanillaGearManager.m_gearPerSlot)[(int)item];
				if (item2.Count == 0)
				{
					PWLogger.Debug($"No gear has been loaded for {item}.");
					continue;
				}
				foreach (uint key in item2.Keys)
				{
					if (IsGearAllowed(key))
					{
						val.Add(item2[key]);
					}
				}
				if (val.Count == 0)
				{
					PWLogger.Error($"No gear is allowed for {item}, there must be at least 1 allowed gear!");
					val.Add(item2.First().Value);
				}
			}
		}

		private void ResetPlayerSelectedGears()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected I4, but got Unknown
			VanillaGearManager.RescanFavorites();
			foreach (var gearSlot in GearSlots)
			{
				int num = (int)gearSlot.inventorySlot;
				if (((Il2CppArrayBase<GearIDRange>)(object)VanillaGearManager.m_lastEquippedGearPerSlot)[num] != null)
				{
					PlayerBackpackManager.EquipLocalGear(((Il2CppArrayBase<GearIDRange>)(object)VanillaGearManager.m_lastEquippedGearPerSlot)[num]);
				}
				else if (((Il2CppArrayBase<List<GearIDRange>>)(object)VanillaGearManager.m_favoriteGearPerSlot)[num].Count > 0)
				{
					PlayerBackpackManager.EquipLocalGear(((Il2CppArrayBase<List<GearIDRange>>)(object)VanillaGearManager.m_favoriteGearPerSlot)[num][0]);
				}
				else if (((Il2CppArrayBase<List<GearIDRange>>)(object)VanillaGearManager.m_gearPerSlot)[num].Count > 0)
				{
					PlayerBackpackManager.EquipLocalGear(((Il2CppArrayBase<List<GearIDRange>>)(object)VanillaGearManager.m_gearPerSlot)[num][0]);
				}
			}
		}

		private void RemoveToggleGears()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected I4, but got Unknown
			foreach (var gearSlot in GearSlots)
			{
				List<GearIDRange> val = ((Il2CppArrayBase<List<GearIDRange>>)(object)VanillaGearManager.m_gearPerSlot)[(int)gearSlot.inventorySlot];
				for (int num = val.Count - 1; num >= 0; num--)
				{
					if (!GearToggleManager.Current.IsVisibleID(val[num].GetOfflineID()))
					{
						val.RemoveAt(num);
					}
				}
			}
		}

		internal void SetupAllowedGearsForActiveRundown()
		{
			if (ProgressionWrapper.UpdateReferences())
			{
				ConfigRundownGears();
				ClearLoadedGears();
				AddGearForCurrentRundown();
				ResetPlayerSelectedGears();
				RemoveToggleGears();
			}
		}

		internal void LockGearForActiveRundown()
		{
			if (ProgressionWrapper.UpdateReferences())
			{
				ReapplyGearLocks();
				ResetPlayerSelectedGears();
				RemoveToggleGears();
			}
		}

		private void ReapplyGearLocks()
		{
			//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_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected I4, but got Unknown
			foreach (var gearSlot in GearSlots)
			{
				InventorySlot item = gearSlot.inventorySlot;
				Dictionary<uint, GearIDRange> item2 = gearSlot.loadedGears;
				List<GearIDRange> val = ((Il2CppArrayBase<List<GearIDRange>>)(object)VanillaGearManager.m_gearPerSlot)[(int)item];
				HashSet<uint> hashSet = new HashSet<uint>(item2.Keys);
				for (int num = val.Count - 1; num >= 0; num--)
				{
					uint offlineID = val[num].GetOfflineID();
					if (!IsGearAllowed(offlineID))
					{
						val.RemoveAt(num);
					}
					hashSet.Remove(offlineID);
				}
				foreach (uint item3 in hashSet)
				{
					GearToggleManager.Current.RemoveFromRelatedIDs(item3);
				}
			}
		}

		private static bool IsGearLocked(ProgressionLockData data)
		{
			if ((!data.UnlockLayoutIDs.Any() || data.UnlockLayoutIDs.All(LayoutComplete)) && (!data.UnlockTiers.Any() || data.UnlockTiers.All(TierComplete)))
			{
				if ((data.LockLayoutIDs.Any() || data.LockTiers.Any()) && data.LockLayoutIDs.All(LayoutComplete))
				{
					return data.LockTiers.All(TierComplete);
				}
				return false;
			}
			return true;
		}

		private static bool IsLockExplicit(ProgressionLockData data)
		{
			if (!data.UnlockLayoutIDs.All(LayoutComplete) || !data.UnlockTiers.All(TierComplete))
			{
				if ((data.LockLayoutIDs.Any() || data.LockTiers.Any()) && data.LockLayoutIDs.All(LayoutComplete))
				{
					return data.LockTiers.All(TierComplete);
				}
				return false;
			}
			return true;
		}

		private static bool LayoutComplete(uint id)
		{
			return ProgressionWrapper.LayoutComplete(id);
		}

		private static bool TierComplete(eRundownTier tier)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return ProgressionWrapper.TierComplete(tier);
		}
	}
	internal class ProgressionData
	{
		public string ExpeditionKey { get; set; } = string.Empty;


		public int MainCompletionCount { get; set; }

		public int SecondaryCompletionCount { get; set; }

		public int ThirdCompletionCount { get; set; }

		public int AllCompletionCount { get; set; }

		public int NoBoosterAllClearCount { get; set; }

		public ProgressionData()
		{
		}

		public ProgressionData(string key, int main, int secondary, int third, int all, int noBooster)
		{
			ExpeditionKey = key;
			MainCompletionCount = main;
			SecondaryCompletionCount = secondary;
			ThirdCompletionCount = third;
			AllCompletionCount = all;
			NoBoosterAllClearCount = noBooster;
		}
	}
	public sealed class ProgressionLockData
	{
		public List<uint> UnlockLayoutIDs { get; set; } = new List<uint>();


		public List<eRundownTier> UnlockTiers { get; set; } = new List<eRundownTier>();


		public List<uint> LockLayoutIDs { get; set; } = new List<uint>();


		public List<eRundownTier> LockTiers { get; set; } = new List<eRundownTier>();


		public List<uint> OfflineIDs { get; set; } = new List<uint>();


		public int Priority { get; set; }

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

	}
	public sealed class ProgressionLockManager
	{
		public static readonly ProgressionLockManager Current = new ProgressionLockManager();

		private readonly Dictionary<string, List<ProgressionLockData>> _fileToData = new Dictionary<string, List<ProgressionLockData>>();

		private readonly LiveEditListener _liveEditListener;

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

		private void FileDeleted(LiveEditEventArgs e)
		{
			PWLogger.Warning("LiveEdit File Removed: " + e.FullPath);
			_fileToData.Remove(e.FullPath);
		}

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

		private void ReadFileContent(string file, string content)
		{
			_fileToData.Remove(file);
			List<ProgressionLockData> list = null;
			try
			{
				list = PWJson.Deserialize<List<ProgressionLockData>>(content);
			}
			catch (JsonException ex)
			{
				PWLogger.Error("Error parsing progression lock json " + file);
				PWLogger.Error(ex.Message);
			}
			if (list != null)
			{
				_fileToData[file] = list;
			}
		}

		private ProgressionLockManager()
		{
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Expected O, but got Unknown
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Expected O, but got Unknown
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Expected O, but got Unknown
			string text = Path.Combine(MTFOPathAPI.CustomPath, "ProgressionGear", "ProgressionLocks");
			if (!Directory.Exists(text))
			{
				PWLogger.Log("No directory detected. Creating " + text + "/Template.json");
				Directory.CreateDirectory(text);
				StreamWriter streamWriter = File.CreateText(Path.Combine(text, "Template.json"));
				streamWriter.WriteLine(PWJson.Serialize(new List<ProgressionLockData>
				{
					new ProgressionLockData()
				}));
				streamWriter.Flush();
				streamWriter.Close();
			}
			else
			{
				PWLogger.Log("Directory detected. " + text);
			}
			foreach (string item in Directory.EnumerateFiles(text, "*.json", SearchOption.AllDirectories))
			{
				string content = File.ReadAllText(item);
				ReadFileContent(item, content);
			}
			_liveEditListener = LiveEdit.CreateListener(text, "*.json", true);
			_liveEditListener.FileCreated += new LiveEditEventHandler(FileCreated);
			_liveEditListener.FileChanged += new LiveEditEventHandler(FileChanged);
			_liveEditListener.FileDeleted += new LiveEditEventHandler(FileDeleted);
		}

		internal void Init()
		{
		}

		public List<ProgressionLockData> GetLockData()
		{
			List<ProgressionLockData> list2 = new List<ProgressionLockData>(_fileToData.Values.Sum((List<ProgressionLockData> list) => list.Count));
			IEnumerator<ProgressionLockData> enumerator = GetEnumerator();
			while (enumerator.MoveNext())
			{
				list2.Add(enumerator.Current);
			}
			return list2;
		}

		public IEnumerator<ProgressionLockData> GetEnumerator()
		{
			return new DictListEnumerator<ProgressionLockData>(_fileToData);
		}
	}
	public static class ProgressionWrapper
	{
		private struct ExpeditionKey
		{
			public eRundownTier tier;

			public int expIndex;
		}

		private static readonly Dictionary<uint, ExpeditionKey> _layoutToExpedition;

		private static readonly Dictionary<eRundownTier, List<ExpeditionKey>> _tierExpeditionKeys;

		private static readonly Dictionary<eRundownTier, List<ProgressionData>> _nativeProgression;

		public static uint CurrentRundownID { get; private set; }

		static ProgressionWrapper()
		{
			_layoutToExpedition = new Dictionary<uint, ExpeditionKey>();
			_tierExpeditionKeys = new Dictionary<eRundownTier, List<ExpeditionKey>>
			{
				{
					(eRundownTier)1,
					new List<ExpeditionKey>()
				},
				{
					(eRundownTier)2,
					new List<ExpeditionKey>()
				},
				{
					(eRundownTier)3,
					new List<ExpeditionKey>()
				},
				{
					(eRundownTier)4,
					new List<ExpeditionKey>()
				},
				{
					(eRundownTier)5,
					new List<ExpeditionKey>()
				}
			};
			_nativeProgression = new Dictionary<eRundownTier, List<ProgressionData>>();
			CurrentRundownID = 0u;
		}

		private static uint ActiveRundownID()
		{
			string activeRundownKey = RundownManager.ActiveRundownKey;
			uint result = default(uint);
			if (!RundownManager.RundownProgressionReady || !RundownManager.TryGetIdFromLocalRundownKey(activeRundownKey, ref result))
			{
				return 0u;
			}
			return result;
		}

		public static bool UpdateReferences()
		{
			uint num = ActiveRundownID();
			if (num == 0)
			{
				return false;
			}
			if (CurrentRundownID == num)
			{
				return true;
			}
			CurrentRundownID = num;
			_layoutToExpedition.Clear();
			RundownDataBlock block = GameDataBlockBase<RundownDataBlock>.GetBlock(CurrentRundownID);
			AddTierLayouts((eRundownTier)1, block.TierA);
			AddTierLayouts((eRundownTier)2, block.TierB);
			AddTierLayouts((eRundownTier)3, block.TierC);
			AddTierLayouts((eRundownTier)4, block.TierD);
			AddTierLayouts((eRundownTier)5, block.TierE);
			return true;
		}

		internal static void UpdateNativeProgression(eRundownTier tier, int expIndex, ProgressionData data)
		{
			//IL_000b: 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_0018: Unknown result type (might be due to invalid IL or missing references)
			UpdateReferences();
			if (!_nativeProgression.ContainsKey(tier))
			{
				_nativeProgression[tier] = new List<ProgressionData>(5);
			}
			List<ProgressionData> list = _nativeProgression[tier];
			if (list.Count <= expIndex)
			{
				list.EnsureCapacity(expIndex + 1);
				for (int i = list.Count; i <= expIndex; i++)
				{
					list.Add(new ProgressionData());
				}
			}
			list[expIndex] = data;
		}

		private static void AddTierLayouts(eRundownTier tier, List<ExpeditionInTierData> dataList)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			_tierExpeditionKeys[tier].Clear();
			for (int i = 0; i < dataList.Count; i++)
			{
				ExpeditionInTierData val = dataList[i];
				if (val.Enabled)
				{
					ExpeditionKey expeditionKey = default(ExpeditionKey);
					expeditionKey.tier = tier;
					expeditionKey.expIndex = i;
					ExpeditionKey expeditionKey2 = expeditionKey;
					_layoutToExpedition.Add(val.LevelLayoutData, expeditionKey2);
					_tierExpeditionKeys[tier].Add(expeditionKey2);
				}
			}
		}

		private static ProgressionData GetProgressionData(uint id, eRundownTier tier, int index)
		{
			//IL_0008: 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 (LocalProgressionWrapper.HasLocalProgression)
			{
				return LocalProgressionWrapper.GetProgressionDataLP(id, tier, index);
			}
			if (_nativeProgression.Count == 0)
			{
				return new ProgressionData();
			}
			return _nativeProgression[tier][index];
		}

		private static bool ExpeditionComplete(ProgressionData data)
		{
			if (data.MainCompletionCount <= 0 && data.SecondaryCompletionCount <= 0)
			{
				return data.ThirdCompletionCount > 0;
			}
			return true;
		}

		public static bool LayoutComplete(uint layoutID)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			UpdateReferences();
			if (!_layoutToExpedition.ContainsKey(layoutID))
			{
				return true;
			}
			ExpeditionKey expeditionKey = _layoutToExpedition[layoutID];
			return ExpeditionComplete(GetProgressionData(CurrentRundownID, expeditionKey.tier, expeditionKey.expIndex));
		}

		public static bool TierComplete(eRundownTier tier)
		{
			//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)
			UpdateReferences();
			foreach (ExpeditionKey item in _tierExpeditionKeys[tier])
			{
				if (!ExpeditionComplete(GetProgressionData(CurrentRundownID, item.tier, item.expIndex)))
				{
					return false;
				}
			}
			return true;
		}
	}
}
namespace ProgressionGear.Dependencies
{
	internal static class EOSWrapper
	{
		public const string GUID = "Inas.ExtraObjectiveSetup";

		public static bool HasEOS { get; private set; }

		static EOSWrapper()
		{
			HasEOS = ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.ContainsKey("Inas.ExtraObjectiveSetup");
		}
	}
	internal static class LocalProgressionWrapper
	{
		public const string GUID = "Inas.LocalProgression";

		public static bool HasLocalProgression { get; private set; }

		static LocalProgressionWrapper()
		{
			HasLocalProgression = ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.ContainsKey("Inas.LocalProgression");
		}

		public static ProgressionData GetProgressionDataLP(uint id, eRundownTier tier, int index)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (!HasLocalProgression)
			{
				return new ProgressionData();
			}
			ExpeditionProgressionData expeditionLP = LocalProgressionManager.Current.GetExpeditionLP(id, tier, index);
			return new ProgressionData(expeditionLP.ExpeditionKey, expeditionLP.MainCompletionCount, expeditionLP.SecondaryCompletionCount, expeditionLP.ThirdCompletionCount, expeditionLP.AllClearCount, expeditionLP.NoBoosterAllClearCount);
		}
	}
}