Decompiled source of Survival v1.9.3

plugins/XiaoTian-SURVIVAL/SURVIVAL/Custom/net6/AddEvents.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using Agents;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using ExtraObjectiveSetup;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.ExtendedWardenEvents;
using ExtraObjectiveSetup.JSON;
using FloLib.Networks.Replications;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppSystem.Collections.Generic;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("AddEvents")]
[assembly: AssemblyProduct("AddEvents")]
[assembly: AssemblyFileVersion("1.1.3.0")]
[assembly: AssemblyInformationalVersion("1.1.3")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.3.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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]
	[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 AddEvents
{
	internal static class LaserRoomConfigResolver
	{
		internal static bool TryResolveMainLevelLayoutForExternalConfig(JsonElement element, out uint mainLevelLayout, out string resolvedBy)
		{
			mainLevelLayout = 0u;
			resolvedBy = string.Empty;
			try
			{
				if (element.ValueKind == JsonValueKind.Number && element.TryGetUInt32(out var value))
				{
					mainLevelLayout = value;
					resolvedBy = "numeric";
					return value != 0;
				}
				if (element.ValueKind != JsonValueKind.String)
				{
					return false;
				}
				string text = element.GetString()?.Trim() ?? string.Empty;
				if (string.IsNullOrWhiteSpace(text))
				{
					return false;
				}
				if (uint.TryParse(text, out var result))
				{
					mainLevelLayout = result;
					resolvedBy = "numeric string";
					return result != 0;
				}
				if (MTFOPartialDataIdResolver.TryResolve(text, out var id) && id != 0)
				{
					mainLevelLayout = id;
					resolvedBy = "MTFO PartialData:" + text;
					return true;
				}
				if (GameDataBlockBase<LevelLayoutDataBlock>.HasBlock(text))
				{
					uint blockID = GameDataBlockBase<LevelLayoutDataBlock>.GetBlockID(text);
					if (blockID != 0)
					{
						mainLevelLayout = blockID;
						resolvedBy = "LevelLayoutDataBlock:" + text;
						return true;
					}
				}
			}
			catch (Exception ex)
			{
				AddEventsRuntime.LogThrottled("LaserRoom MainLevelLayout resolver failed: " + ex.Message);
			}
			return false;
		}
	}
	internal static class MTFOPartialDataIdResolver
	{
		private const string PartialDataPluginGuid = "MTFO.Extension.PartialBlocks";

		private const string IdFileName = "_persistentID.json";

		private static readonly object Sync = new object();

		private static Dictionary<string, uint>? _guidToId;

		private static bool _loadAttempted;

		internal static bool TryResolve(string guid, out uint id)
		{
			id = 0u;
			if (string.IsNullOrWhiteSpace(guid))
			{
				return false;
			}
			EnsureLoaded();
			lock (Sync)
			{
				return _guidToId != null && _guidToId.TryGetValue(guid.Trim(), out id);
			}
		}

		private static void EnsureLoaded()
		{
			lock (Sync)
			{
				if (_loadAttempted)
				{
					return;
				}
				_loadAttempted = true;
				try
				{
					string text = TryGetPartialDataPathFromPlugin();
					if (string.IsNullOrWhiteSpace(text))
					{
						return;
					}
					string text2 = Path.Combine(text, "_persistentID.json");
					if (File.Exists(text2))
					{
						Dictionary<string, uint> dictionary = ReadPersistentIdFile(text2);
						if (dictionary.Count > 0)
						{
							_guidToId = dictionary;
						}
					}
				}
				catch (Exception ex)
				{
					AddEventsRuntime.LogThrottled("MTFO PartialData persistentID resolver failed: " + ex.Message);
				}
			}
		}

		private static string TryGetPartialDataPathFromPlugin()
		{
			try
			{
				if (((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value))
				{
					Assembly assembly = ((value == null) ? null : value.Instance?.GetType()?.Assembly);
					if (assembly != null && (assembly.GetTypes().FirstOrDefault((Type t) => string.Equals(t.Name, "PartialDataManager", StringComparison.Ordinal))?.GetProperty("PartialDataPath", BindingFlags.Static | BindingFlags.Public))?.GetValue(null) is string text && !string.IsNullOrWhiteSpace(text))
					{
						return text;
					}
				}
			}
			catch
			{
			}
			return DiscoverPartialDataPathFromFileSystem();
		}

		private static string DiscoverPartialDataPathFromFileSystem()
		{
			try
			{
				foreach (string item in Directory.EnumerateFiles(Paths.PluginPath, "_persistentID.json", SearchOption.AllDirectories))
				{
					string directoryName = Path.GetDirectoryName(item);
					if (!string.IsNullOrWhiteSpace(directoryName))
					{
						return directoryName;
					}
				}
			}
			catch
			{
			}
			return string.Empty;
		}

		private static Dictionary<string, uint> ReadPersistentIdFile(string idFilePath)
		{
			Dictionary<string, uint> dictionary = new Dictionary<string, uint>(StringComparer.OrdinalIgnoreCase);
			string text = File.ReadAllText(idFilePath);
			try
			{
				using JsonDocument jsonDocument = JsonDocument.Parse(text, new JsonDocumentOptions
				{
					CommentHandling = JsonCommentHandling.Skip,
					AllowTrailingCommas = true
				});
				if (jsonDocument.RootElement.ValueKind == JsonValueKind.Array)
				{
					foreach (JsonElement item in jsonDocument.RootElement.EnumerateArray())
					{
						if (TryReadGuidEntry(item, out string guid, out uint id))
						{
							dictionary[guid] = id;
						}
					}
				}
				else if (jsonDocument.RootElement.ValueKind == JsonValueKind.Object)
				{
					foreach (JsonProperty item2 in jsonDocument.RootElement.EnumerateObject())
					{
						if (TryReadUIntElement(item2.Value, out var id2) && !string.IsNullOrWhiteSpace(item2.Name))
						{
							dictionary[item2.Name.Trim()] = id2;
						}
					}
				}
			}
			catch
			{
				foreach (Match item3 in Regex.Matches(text, "\\{[^{}]*\\\"GUID\\\"\\s*:\\s*\\\"(?<guid>(?:\\\\.|[^\\\"])*)\\\"[^{}]*\\\"ID\\\"\\s*:\\s*(?<id>\\d+)[^{}]*\\}", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant))
				{
					string text2 = Regex.Unescape(item3.Groups["guid"].Value).Trim();
					if (!string.IsNullOrWhiteSpace(text2) && uint.TryParse(item3.Groups["id"].Value, out var result))
					{
						dictionary[text2] = result;
					}
				}
			}
			return dictionary;
		}

		private static bool TryReadGuidEntry(JsonElement entry, out string guid, out uint id)
		{
			guid = string.Empty;
			id = 0u;
			if (entry.ValueKind != JsonValueKind.Object)
			{
				return false;
			}
			foreach (JsonProperty item in entry.EnumerateObject())
			{
				if (string.Equals(item.Name, "GUID", StringComparison.OrdinalIgnoreCase) || string.Equals(item.Name, "Guid", StringComparison.OrdinalIgnoreCase) || string.Equals(item.Name, "persistentID", StringComparison.OrdinalIgnoreCase))
				{
					guid = ((item.Value.ValueKind == JsonValueKind.String) ? (item.Value.GetString() ?? string.Empty).Trim() : item.Value.ToString().Trim());
				}
				else if (string.Equals(item.Name, "ID", StringComparison.OrdinalIgnoreCase) || string.Equals(item.Name, "Id", StringComparison.OrdinalIgnoreCase))
				{
					TryReadUIntElement(item.Value, out id);
				}
			}
			if (!string.IsNullOrWhiteSpace(guid))
			{
				return id != 0;
			}
			return false;
		}

		private static bool TryReadUIntElement(JsonElement element, out uint id)
		{
			id = 0u;
			if (element.ValueKind == JsonValueKind.Number && element.TryGetUInt32(out var value))
			{
				id = value;
				return true;
			}
			if (element.ValueKind == JsonValueKind.String && uint.TryParse(element.GetString(), out var result))
			{
				id = result;
				return true;
			}
			return false;
		}
	}
	internal sealed class AddEventsType2004EventData
	{
		internal int Count { get; set; }

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

		internal bool HasEnabled { get; set; }

		internal Vector3 Position { get; set; }

		internal bool HasPosition { get; set; }

		internal float FogTransitionDuration { get; set; }

		internal bool HasFogTransitionDuration { get; set; }

		internal List<WardenObjectiveEventData> Events { get; set; } = new List<WardenObjectiveEventData>();
	}
	internal readonly struct AddEventsType2004Signature : IEquatable<AddEventsType2004Signature>
	{
		private readonly int _count;

		private readonly bool _enabled;

		private readonly int _radius1000;

		private readonly int _x1000;

		private readonly int _y1000;

		private readonly int _z1000;

		internal AddEventsType2004Signature(int count, bool enabled, float radius, Vector3 position)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			_count = count;
			_enabled = enabled;
			_radius1000 = Quantize(radius);
			_x1000 = Quantize(position.x);
			_y1000 = Quantize(position.y);
			_z1000 = Quantize(position.z);
		}

		internal static AddEventsType2004Signature FromEvent(WardenObjectiveEventData e)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			return new AddEventsType2004Signature(e.Count, e.Enabled, e.FogTransitionDuration, e.Position);
		}

		public bool Equals(AddEventsType2004Signature other)
		{
			if (_count == other._count && _enabled == other._enabled && _radius1000 == other._radius1000 && _x1000 == other._x1000 && _y1000 == other._y1000)
			{
				return _z1000 == other._z1000;
			}
			return false;
		}

		public override bool Equals(object? obj)
		{
			if (obj is AddEventsType2004Signature other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return HashCode.Combine(_count, _enabled, _radius1000, _x1000, _y1000, _z1000);
		}

		private static int Quantize(float value)
		{
			if (float.IsNaN(value) || float.IsInfinity(value))
			{
				return 0;
			}
			return (int)Math.Round(value * 1000f);
		}
	}
	internal static class AddEventsType2004SidecarStore
	{
		private static readonly Dictionary<IntPtr, AddEventsType2004EventData> ByEventPointer = new Dictionary<IntPtr, AddEventsType2004EventData>();

		private static readonly Dictionary<AddEventsType2004Signature, List<AddEventsType2004EventData>> ByLooseSignature = new Dictionary<AddEventsType2004Signature, List<AddEventsType2004EventData>>();

		private static readonly List<AddEventsType2004EventData> LooseFallback = new List<AddEventsType2004EventData>();

		private static readonly HashSet<string> RegisteredLooseFingerprints = new HashSet<string>(StringComparer.Ordinal);

		private static readonly HashSet<AddEventsType2004Signature> AmbiguousWarningPrinted = new HashSet<AddEventsType2004Signature>();

		private static bool _isDeserializingSidecarEvents;

		private static bool _diskScanned;

		internal static bool TryGet(WardenObjectiveEventData eventData, out AddEventsType2004EventData data)
		{
			if (eventData != null && ByEventPointer.TryGetValue(((Il2CppObjectBase)eventData).Pointer, out data))
			{
				return true;
			}
			if (eventData != null)
			{
				AddEventsType2004Signature addEventsType2004Signature = AddEventsType2004Signature.FromEvent(eventData);
				if (ByLooseSignature.TryGetValue(addEventsType2004Signature, out List<AddEventsType2004EventData> value) && value.Count > 0)
				{
					data = value[0];
					if (value.Count > 1 && AmbiguousWarningPrinted.Add(addEventsType2004Signature))
					{
						ManualLogSource? log = AddEventsRuntime.Log;
						if (log != null)
						{
							log.LogWarning((object)"AddEvents Type 2004 sidecar fallback matched multiple definitions with the same vanilla signature. Using the first match. Make Count/Position/FogTransitionDuration/Enabled unique if this is not intended.");
						}
					}
					ByEventPointer[((Il2CppObjectBase)eventData).Pointer] = data;
					return true;
				}
			}
			if (LooseFallback.Count == 1)
			{
				data = LooseFallback[0];
				if (eventData != null)
				{
					ByEventPointer[((Il2CppObjectBase)eventData).Pointer] = data;
				}
				return true;
			}
			data = null;
			return false;
		}

		internal static void ScanDiskForDefinitions()
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Expected O, but got Unknown
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Expected O, but got Unknown
			if (_diskScanned)
			{
				return;
			}
			_diskScanned = true;
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			bool flag = default(bool);
			ManualLogSource log;
			try
			{
				foreach (string item in EnumerateCandidateJsonFiles())
				{
					num++;
					string text;
					try
					{
						text = File.ReadAllText(item);
					}
					catch
					{
						continue;
					}
					if (text.IndexOf("2004", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						List<AddEventsType2004EventData> list = ParseType2004Nodes(text);
						if (list.Count != 0)
						{
							num2++;
							num3 += list.Count;
							RegisterLoose(list);
						}
					}
				}
			}
			catch (Exception ex)
			{
				log = AddEventsRuntime.Log;
				if (log != null)
				{
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(48, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2004 disk sidecar scan failed: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetType().Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					}
					log.LogWarning(val);
				}
			}
			if (num3 > 0)
			{
				log = AddEventsRuntime.Log;
				if (log != null)
				{
					BepInExMessageLogInterpolatedStringHandler val2 = new BepInExMessageLogInterpolatedStringHandler(96, 3, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("AddEvents Type 2004 disk sidecar scan complete. FilesScanned=");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", FilesWithType2004=");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num2);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", Definitions=");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num3);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(".");
					}
					log.LogMessage(val2);
				}
				return;
			}
			log = AddEventsRuntime.Log;
			if (log != null)
			{
				BepInExDebugLogInterpolatedStringHandler val3 = new BepInExDebugLogInterpolatedStringHandler(77, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("AddEvents Type 2004 disk sidecar scan complete. FilesScanned=");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<int>(num);
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(", Definitions=0.");
				}
				log.LogDebug(val3);
			}
		}

		internal static void Capture(string json, object? result)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Invalid comparison between Unknown and I4
			if (_isDeserializingSidecarEvents || string.IsNullOrWhiteSpace(json) || json.IndexOf("2004", StringComparison.OrdinalIgnoreCase) < 0)
			{
				return;
			}
			List<AddEventsType2004EventData> list = ParseType2004Nodes(json);
			if (list.Count == 0)
			{
				return;
			}
			RegisterLoose(list);
			if (result == null)
			{
				return;
			}
			List<WardenObjectiveEventData> list2 = new List<WardenObjectiveEventData>();
			CollectEvents(result, list2, new HashSet<object>(ReferenceEqualityComparer.Instance), 0);
			if (list2.Count == 0)
			{
				return;
			}
			Dictionary<AddEventsType2004Signature, Queue<AddEventsType2004EventData>> dictionary = new Dictionary<AddEventsType2004Signature, Queue<AddEventsType2004EventData>>();
			foreach (AddEventsType2004EventData item in list)
			{
				AddEventsType2004Signature key = new AddEventsType2004Signature(item.Count, item.Enabled, item.FogTransitionDuration, item.Position);
				if (!dictionary.TryGetValue(key, out var value))
				{
					value = (dictionary[key] = new Queue<AddEventsType2004EventData>());
				}
				value.Enqueue(item);
			}
			Queue<AddEventsType2004EventData> queue2 = new Queue<AddEventsType2004EventData>(list);
			foreach (WardenObjectiveEventData item2 in list2)
			{
				if ((int)item2.Type == 2004)
				{
					AddEventsType2004EventData addEventsType2004EventData = null;
					AddEventsType2004Signature key2 = AddEventsType2004Signature.FromEvent(item2);
					if (dictionary.TryGetValue(key2, out var value2) && value2.Count > 0)
					{
						addEventsType2004EventData = value2.Dequeue();
					}
					else if (queue2.Count > 0)
					{
						addEventsType2004EventData = queue2.Dequeue();
					}
					if (addEventsType2004EventData != null)
					{
						ByEventPointer[((Il2CppObjectBase)item2).Pointer] = addEventsType2004EventData;
					}
				}
			}
		}

		private static void RegisterLoose(IEnumerable<AddEventsType2004EventData> parsed)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			foreach (AddEventsType2004EventData item in parsed)
			{
				string looseFingerprint = GetLooseFingerprint(item);
				if (RegisteredLooseFingerprints.Add(looseFingerprint))
				{
					AddEventsType2004Signature key = new AddEventsType2004Signature(item.Count, item.Enabled, item.FogTransitionDuration, item.Position);
					if (!ByLooseSignature.TryGetValue(key, out List<AddEventsType2004EventData> value))
					{
						value = new List<AddEventsType2004EventData>(1);
						ByLooseSignature[key] = value;
					}
					value.Add(item);
					LooseFallback.Add(item);
				}
			}
		}

		private static string GetLooseFingerprint(AddEventsType2004EventData data)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected I4, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: 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_012e: Unknown result type (might be due to invalid IL or missing references)
			int num = 17;
			foreach (WardenObjectiveEventData @event in data.Events)
			{
				num = num * 31 + @event.Type;
				num = num * 31 + @event.Count;
				num = num * 31 + ((object)@event.LocalIndex/*cast due to .constrained prefix*/).GetHashCode();
				num = num * 31 + ((object)@event.Layer/*cast due to .constrained prefix*/).GetHashCode();
				num = num * 31 + ((object)@event.DimensionIndex/*cast due to .constrained prefix*/).GetHashCode();
				num = num * 31 + ((object)@event.Position/*cast due to .constrained prefix*/).GetHashCode();
				num = num * 31 + @event.FogTransitionDuration.GetHashCode();
			}
			return string.Join("|", data.Count, data.Enabled, data.FogTransitionDuration, data.Position.x, data.Position.y, data.Position.z, data.Events.Count, num);
		}

		private static IEnumerable<string> EnumerateCandidateJsonFiles()
		{
			HashSet<string> roots = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			AddRoot(Paths.PluginPath);
			AddRoot(Path.Combine(Paths.BepInExRootPath, "GameData"));
			AddRoot(Path.Combine(Paths.BepInExRootPath, "Custom"));
			foreach (string item in roots)
			{
				IEnumerable<string> enumerable;
				try
				{
					enumerable = Directory.EnumerateFiles(item, "*.json", SearchOption.AllDirectories).ToArray();
				}
				catch
				{
					continue;
				}
				foreach (string item2 in enumerable)
				{
					yield return item2;
				}
			}
			void AddRoot(string? root)
			{
				if (!string.IsNullOrWhiteSpace(root) && Directory.Exists(root))
				{
					roots.Add(Path.GetFullPath(root));
				}
			}
		}

		private static List<AddEventsType2004EventData> ParseType2004Nodes(string json)
		{
			List<AddEventsType2004EventData> list = new List<AddEventsType2004EventData>();
			try
			{
				JsonNode jsonNode = JsonNode.Parse(json, new JsonNodeOptions
				{
					PropertyNameCaseInsensitive = true
				}, new JsonDocumentOptions
				{
					AllowTrailingCommas = true,
					CommentHandling = JsonCommentHandling.Skip
				});
				if (jsonNode != null)
				{
					TraverseJson(jsonNode, list);
				}
			}
			catch
			{
			}
			return list;
		}

		private static void TraverseJson(JsonNode node, List<AddEventsType2004EventData> output)
		{
			if (node is JsonObject jsonObject)
			{
				if (IsType2004Object(jsonObject))
				{
					output.Add(ParseEventData(jsonObject));
				}
				{
					foreach (KeyValuePair<string, JsonNode> item in jsonObject)
					{
						if (item.Value != null)
						{
							TraverseJson(item.Value, output);
						}
					}
					return;
				}
			}
			if (!(node is JsonArray jsonArray))
			{
				return;
			}
			foreach (JsonNode item2 in jsonArray)
			{
				if (item2 != null)
				{
					TraverseJson(item2, output);
				}
			}
		}

		private static bool IsType2004Object(JsonObject obj)
		{
			if (!obj.TryGetPropertyValue("Type", out JsonNode jsonNode))
			{
				return false;
			}
			if (jsonNode is JsonValue jsonValue)
			{
				if (jsonValue.TryGetValue<int>(out var value))
				{
					return value == 2004;
				}
				if (jsonValue.TryGetValue<string>(out string value2))
				{
					if (!string.Equals(value2, "2004", StringComparison.OrdinalIgnoreCase))
					{
						return string.Equals(value2, "AddPlayersToDeathEventGroup", StringComparison.OrdinalIgnoreCase);
					}
					return true;
				}
			}
			return false;
		}

		private static AddEventsType2004EventData ParseEventData(JsonObject obj)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			JsonNode jsonNode;
			AddEventsType2004EventData addEventsType2004EventData = new AddEventsType2004EventData
			{
				Count = ReadInt(obj, "Count", 0),
				HasEnabled = obj.ContainsKey("Enabled"),
				Enabled = ReadBool(obj, "Enabled", fallback: true),
				HasPosition = obj.ContainsKey("Position"),
				Position = ReadVector3(obj.TryGetPropertyValue("Position", out jsonNode) ? jsonNode : null),
				HasFogTransitionDuration = obj.ContainsKey("FogTransitionDuration"),
				FogTransitionDuration = ReadFloat(obj, "FogTransitionDuration", 0f)
			};
			if (obj.TryGetPropertyValue("Events", out JsonNode jsonNode2) && jsonNode2 != null)
			{
				addEventsType2004EventData.Events = DeserializeEvents(jsonNode2.ToJsonString());
			}
			return addEventsType2004EventData;
		}

		private static List<WardenObjectiveEventData> DeserializeEvents(string json)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			try
			{
				_isDeserializingSidecarEvents = true;
				return EOSJson.Deserialize<List<WardenObjectiveEventData>>(json) ?? new List<WardenObjectiveEventData>();
			}
			catch (Exception ex)
			{
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					bool flag = default(bool);
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(59, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2004 could not deserialize nested Events: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetType().Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					}
					log.LogWarning(val);
				}
				return new List<WardenObjectiveEventData>();
			}
			finally
			{
				_isDeserializingSidecarEvents = false;
			}
		}

		private static void CollectEvents(object obj, List<WardenObjectiveEventData> output, HashSet<object> visited, int depth)
		{
			if (obj == null || depth > 12 || !visited.Add(obj))
			{
				return;
			}
			WardenObjectiveEventData val = (WardenObjectiveEventData)((obj is WardenObjectiveEventData) ? obj : null);
			if (val != null)
			{
				output.Add(val);
				return;
			}
			if (obj is IEnumerable enumerable && !(obj is string))
			{
				foreach (object item in enumerable)
				{
					if (item != null)
					{
						CollectEvents(item, output, visited, depth + 1);
					}
				}
				return;
			}
			Type type = obj.GetType();
			if (type.IsPrimitive || type.IsEnum || type == typeof(string))
			{
				return;
			}
			PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (PropertyInfo propertyInfo in properties)
			{
				if (propertyInfo.GetIndexParameters().Length != 0)
				{
					continue;
				}
				try
				{
					object value = propertyInfo.GetValue(obj);
					if (value != null)
					{
						CollectEvents(value, output, visited, depth + 1);
					}
				}
				catch
				{
				}
			}
			FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (FieldInfo fieldInfo in fields)
			{
				try
				{
					object value2 = fieldInfo.GetValue(obj);
					if (value2 != null)
					{
						CollectEvents(value2, output, visited, depth + 1);
					}
				}
				catch
				{
				}
			}
		}

		private static int ReadInt(JsonObject node, string name, int fallback)
		{
			try
			{
				if (node.TryGetPropertyValue(name, out JsonNode jsonNode) && jsonNode is JsonValue jsonValue)
				{
					if (jsonValue.TryGetValue<int>(out var value))
					{
						return value;
					}
					if (jsonValue.TryGetValue<string>(out string value2) && int.TryParse(value2, out value))
					{
						return value;
					}
				}
			}
			catch
			{
			}
			return fallback;
		}

		private static float ReadFloat(JsonObject node, string name, float fallback)
		{
			try
			{
				if (node.TryGetPropertyValue(name, out JsonNode jsonNode) && jsonNode is JsonValue jsonValue)
				{
					if (jsonValue.TryGetValue<float>(out var value))
					{
						return value;
					}
					if (jsonValue.TryGetValue<double>(out var value2))
					{
						return (float)value2;
					}
					if (jsonValue.TryGetValue<string>(out string value3) && float.TryParse(value3, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
					{
						return value;
					}
				}
			}
			catch
			{
			}
			return fallback;
		}

		private static bool ReadBool(JsonObject node, string name, bool fallback)
		{
			try
			{
				if (node.TryGetPropertyValue(name, out JsonNode jsonNode) && jsonNode is JsonValue jsonValue)
				{
					if (jsonValue.TryGetValue<bool>(out var value))
					{
						return value;
					}
					if (jsonValue.TryGetValue<string>(out string value2) && bool.TryParse(value2, out value))
					{
						return value;
					}
				}
			}
			catch
			{
			}
			return fallback;
		}

		private static Vector3 ReadVector3(JsonNode? node)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if (!(node is JsonObject node2))
			{
				return Vector3.zero;
			}
			return new Vector3(ReadFloat(node2, "x", 0f), ReadFloat(node2, "y", 0f), ReadFloat(node2, "z", 0f));
		}
	}
	internal static class AddEventsDeathEventGroupEvents
	{
		internal static void AddPlayersToDeathEventGroup(WardenObjectiveEventData eventData)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			if (!AddEventsNetworkEventProxy.EnsureHostExecution(AddEventsCustomEventType.AddPlayersToDeathEventGroup, eventData))
			{
				return;
			}
			if (!AddEventsType2004SidecarStore.TryGet(eventData, out AddEventsType2004EventData data))
			{
				data = new AddEventsType2004EventData
				{
					Count = eventData.Count,
					Enabled = eventData.Enabled,
					Position = eventData.Position,
					HasPosition = true,
					FogTransitionDuration = eventData.FogTransitionDuration,
					HasFogTransitionDuration = (eventData.FogTransitionDuration > 0f),
					Events = new List<WardenObjectiveEventData>()
				};
			}
			bool flag = default(bool);
			ManualLogSource log;
			if (!data.Enabled)
			{
				AddEventsDeathEventGroupManager.Current.SetGroupEnabled(data.Count, enabled: false);
				log = AddEventsRuntime.Log;
				if (log != null)
				{
					BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(60, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2004 death event group ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(data.Count);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" disabled and cleared.");
					}
					log.LogDebug(val);
				}
				return;
			}
			List<PlayerAgent> list = ResolvePlayers(eventData, data);
			int num = AddEventsDeathEventGroupManager.Current.AddPlayersToGroup(data.Count, list, data.Events);
			log = AddEventsRuntime.Log;
			if (log != null)
			{
				BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(67, 4, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2004 death event group ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(data.Count);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": added ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("/");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(list.Count);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" player(s), Events=");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(data.Events.Count);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
				}
				log.LogDebug(val);
			}
		}

		private static List<PlayerAgent> ResolvePlayers(WardenObjectiveEventData eventData, AddEventsType2004EventData data)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			float num = (data.HasFogTransitionDuration ? data.FogTransitionDuration : eventData.FogTransitionDuration);
			Vector3 origin = (data.HasPosition ? data.Position : eventData.Position);
			if (num > 0f)
			{
				return GetPlayersInRadius(origin, num);
			}
			return GetAllPlayers();
		}

		private static List<PlayerAgent> GetPlayersInRadius(Vector3 origin, float radius)
		{
			//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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			float num = radius * radius;
			List<PlayerAgent> list = new List<PlayerAgent>();
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (!((Object)(object)current == (Object)null) && ((Agent)current).Alive)
				{
					Vector3 val = ((Agent)current).Position - origin;
					if (((Vector3)(ref val)).sqrMagnitude <= num)
					{
						list.Add(current);
					}
				}
			}
			return list;
		}

		private static List<PlayerAgent> GetAllPlayers()
		{
			List<PlayerAgent> list = new List<PlayerAgent>();
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if ((Object)(object)current != (Object)null && ((Agent)current).Alive)
				{
					list.Add(current);
				}
			}
			return list;
		}
	}
	public struct AddEventsDeathEventGroupReplicationState
	{
		public bool enabled;

		public bool checkP1;

		public bool checkP2;

		public bool checkP3;

		public bool checkP4;
	}
	internal sealed class AddEventsDeathEventGroup
	{
		internal const int MaxPlayers = 4;

		private readonly bool[] _slots = new bool[4];

		private readonly Dictionary<int, int> _lastDeathFrameBySlot = new Dictionary<int, int>();

		private StateReplicator<AddEventsDeathEventGroupReplicationState>? _stateReplicator;

		internal bool Enabled { get; private set; }

		internal List<WardenObjectiveEventData> Events { get; set; } = new List<WardenObjectiveEventData>();

		internal int Count
		{
			get
			{
				int num = 0;
				for (int i = 0; i < _slots.Length; i++)
				{
					if (_slots[i])
					{
						num++;
					}
				}
				return num;
			}
		}

		internal bool SetPlayerInGroup(int slot, bool inGroup)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (!IsValidPlayerSlot(slot))
			{
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(63, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2004 invalid player slot index ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(slot);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; expected [0, ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(4);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(").");
					}
					log.LogError(val);
				}
				return false;
			}
			if (_slots[slot] == inGroup)
			{
				return false;
			}
			int count = Count;
			_slots[slot] = inGroup;
			if (inGroup)
			{
				_lastDeathFrameBySlot.Remove(slot);
			}
			int count2 = Count;
			if (count == 0 && count2 > 0)
			{
				Enabled = true;
			}
			else if (count > 0 && count2 == 0)
			{
				Enabled = false;
			}
			Sync();
			return true;
		}

		internal void Toggle(bool enabled)
		{
			if (!enabled)
			{
				ClearAndDisable();
			}
			else if (!Enabled)
			{
				Enabled = true;
				Sync();
			}
		}

		internal void ClearAndDisable()
		{
			bool flag = Enabled || Count > 0 || Events.Count > 0 || _lastDeathFrameBySlot.Count > 0;
			Enabled = false;
			for (int i = 0; i < _slots.Length; i++)
			{
				_slots[i] = false;
			}
			_lastDeathFrameBySlot.Clear();
			Events = new List<WardenObjectiveEventData>();
			if (flag)
			{
				Sync();
			}
		}

		internal bool ContainsSlot(int slot)
		{
			if (IsValidPlayerSlot(slot))
			{
				return _slots[slot];
			}
			return false;
		}

		internal bool TryMarkDeathFrame(int slot, int frame)
		{
			if (_lastDeathFrameBySlot.TryGetValue(slot, out var value) && value == frame)
			{
				return false;
			}
			_lastDeathFrameBySlot[slot] = frame;
			return true;
		}

		internal void ResetSynced()
		{
			Reset();
			Sync();
		}

		internal void ResetUnsynced()
		{
			Reset();
			_stateReplicator?.SetStateUnsynced(GetSyncState());
		}

		private void Reset()
		{
			Enabled = false;
			for (int i = 0; i < _slots.Length; i++)
			{
				_slots[i] = false;
			}
			_lastDeathFrameBySlot.Clear();
			Events = new List<WardenObjectiveEventData>();
		}

		private void Sync()
		{
			if (!SNet.IsMaster)
			{
				ManualLogSource? log = AddEventsRuntime.Log;
				if (log != null)
				{
					log.LogWarning((object)"AddEvents Type 2004 death event group sync blocked on client; state changes must be executed by host.");
				}
			}
			else
			{
				_stateReplicator?.SetState(GetSyncState());
			}
		}

		private void OnStateChanged(AddEventsDeathEventGroupReplicationState oldState, AddEventsDeathEventGroupReplicationState newState, bool isRecall)
		{
			if (isRecall)
			{
				Enabled = newState.enabled;
				_slots[0] = newState.checkP1;
				_slots[1] = newState.checkP2;
				_slots[2] = newState.checkP3;
				_slots[3] = newState.checkP4;
			}
		}

		private AddEventsDeathEventGroupReplicationState GetSyncState()
		{
			return new AddEventsDeathEventGroupReplicationState
			{
				enabled = Enabled,
				checkP1 = _slots[0],
				checkP2 = _slots[1],
				checkP3 = _slots[2],
				checkP4 = _slots[3]
			};
		}

		internal static AddEventsDeathEventGroup? Instantiate()
		{
			uint num = EOSNetworking.AllotForeverReplicatorID();
			if (num == 0)
			{
				ManualLogSource? log = AddEventsRuntime.Log;
				if (log != null)
				{
					log.LogError((object)"AddEvents Type 2004 could not allocate a network replicator id.");
				}
				return null;
			}
			AddEventsDeathEventGroup addEventsDeathEventGroup = new AddEventsDeathEventGroup();
			addEventsDeathEventGroup._stateReplicator = AddEventsStateReplicatorCompat.Create(num, default(AddEventsDeathEventGroupReplicationState), (LifeTimeType)0, "AddEvents Type 2004");
			if (addEventsDeathEventGroup._stateReplicator == null)
			{
				return null;
			}
			addEventsDeathEventGroup._stateReplicator.OnStateChanged += addEventsDeathEventGroup.OnStateChanged;
			addEventsDeathEventGroup.ResetUnsynced();
			return addEventsDeathEventGroup;
		}

		private static bool IsValidPlayerSlot(int slot)
		{
			if (slot >= 0)
			{
				return slot < 4;
			}
			return false;
		}

		private AddEventsDeathEventGroup()
		{
		}
	}
	internal sealed class AddEventsDeathEventGroupManager
	{
		internal const int MaxGroups = 4;

		private readonly List<AddEventsDeathEventGroup> _groups = new List<AddEventsDeathEventGroup>();

		private bool _initialized;

		internal static AddEventsDeathEventGroupManager Current { get; } = new AddEventsDeathEventGroupManager();

		internal void Init()
		{
			if (!_initialized)
			{
				_initialized = true;
				EventAPI.OnManagersSetup += SetupGroups;
				LevelAPI.OnBuildStart += ResetUnsynced;
				LevelAPI.OnLevelCleanup += ResetUnsynced;
			}
		}

		internal int AddPlayersToGroup(int groupIndex, IEnumerable<PlayerAgent> players, List<WardenObjectiveEventData> events)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			EnsureGroupsReady();
			if (!TryGetGroup(groupIndex, out AddEventsDeathEventGroup group))
			{
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(61, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2004 group index must be between 0 and ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_groups.Count - 1);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; got ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(groupIndex);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
					}
					log.LogError(val);
				}
				return 0;
			}
			if (events.Count > 0)
			{
				group.Events = events;
			}
			int num = 0;
			foreach (PlayerAgent player in players)
			{
				try
				{
					if (group.SetPlayerInGroup(player.PlayerSlotIndex, inGroup: true))
					{
						num++;
					}
				}
				catch
				{
				}
			}
			return num;
		}

		internal void SetGroupEnabled(int groupIndex, bool enabled)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			EnsureGroupsReady();
			if (!TryGetGroup(groupIndex, out AddEventsDeathEventGroup group))
			{
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(61, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2004 group index must be between 0 and ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_groups.Count - 1);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; got ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(groupIndex);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
					}
					log.LogError(val);
				}
			}
			else
			{
				group.Toggle(enabled);
			}
		}

		internal void ResetSynced()
		{
			foreach (AddEventsDeathEventGroup group in _groups)
			{
				group.ResetSynced();
			}
		}

		internal void ResetUnsynced()
		{
			foreach (AddEventsDeathEventGroup group in _groups)
			{
				group.ResetUnsynced();
			}
		}

		internal void OnPlayerDied(PlayerAgent? player)
		{
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			if ((Object)(object)player == (Object)null || !SNet.IsMaster)
			{
				return;
			}
			int playerSlotIndex;
			try
			{
				playerSlotIndex = player.PlayerSlotIndex;
			}
			catch
			{
				return;
			}
			int frameCount = Time.frameCount;
			bool flag = default(bool);
			for (int i = 0; i < _groups.Count; i++)
			{
				AddEventsDeathEventGroup addEventsDeathEventGroup = _groups[i];
				if (!addEventsDeathEventGroup.Enabled || !addEventsDeathEventGroup.ContainsSlot(playerSlotIndex) || !addEventsDeathEventGroup.TryMarkDeathFrame(playerSlotIndex, frameCount))
				{
					continue;
				}
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(79, 3, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2004 death event group ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(i);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": player slot ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(playerSlotIndex);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" died; executing ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(addEventsDeathEventGroup.Events.Count);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" event(s).");
					}
					log.LogDebug(val);
				}
				foreach (WardenObjectiveEventData @event in addEventsDeathEventGroup.Events)
				{
					try
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(@event, (eWardenObjectiveEventTrigger)0, true, 0f);
					}
					catch (Exception ex)
					{
						log = AddEventsRuntime.Log;
						if (log != null)
						{
							BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(43, 2, ref flag);
							if (flag)
							{
								((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("AddEvents Type 2004 nested event failed: ");
								((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.GetType().Name);
								((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": ");
								((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
							}
							log.LogWarning(val2);
						}
					}
				}
			}
		}

		private void SetupGroups()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			if (_groups.Count > 0)
			{
				return;
			}
			bool flag = default(bool);
			for (int i = 0; i < 4; i++)
			{
				AddEventsDeathEventGroup addEventsDeathEventGroup = AddEventsDeathEventGroup.Instantiate();
				if (addEventsDeathEventGroup == null)
				{
					ManualLogSource log = AddEventsRuntime.Log;
					if (log != null)
					{
						BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(58, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2004 instantiated death event group count: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_groups.Count);
						}
						log.LogError(val);
					}
					break;
				}
				_groups.Add(addEventsDeathEventGroup);
			}
		}

		private void EnsureGroupsReady()
		{
			if (_groups.Count == 0)
			{
				SetupGroups();
			}
		}

		private bool TryGetGroup(int groupIndex, out AddEventsDeathEventGroup? group)
		{
			if (groupIndex < 0 || groupIndex >= _groups.Count)
			{
				group = null;
				return false;
			}
			group = _groups[groupIndex];
			return true;
		}

		private AddEventsDeathEventGroupManager()
		{
		}
	}
	[HarmonyPatch(typeof(Dam_PlayerDamageBase), "ReceiveSetDead")]
	internal static class AddEventsDeathEvent_DamPlayerDamageBaseReceiveSetDeadPatch
	{
		private static void Postfix(Dam_PlayerDamageBase __instance)
		{
			AddEventsDeathEventGroupManager.Current.OnPlayerDied(TryGetOwner(__instance));
		}

		internal static PlayerAgent? TryGetOwner(Dam_PlayerDamageBase? damageBase)
		{
			if ((Object)(object)damageBase == (Object)null)
			{
				return null;
			}
			try
			{
				return damageBase.Owner;
			}
			catch
			{
				return null;
			}
		}
	}
	[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveSetDead")]
	internal static class AddEventsDeathEvent_DamPlayerDamageLocalReceiveSetDeadPatch
	{
		private static void Postfix(Dam_PlayerDamageLocal __instance)
		{
			AddEventsDeathEventGroupManager.Current.OnPlayerDied(AddEventsDeathEvent_DamPlayerDamageBaseReceiveSetDeadPatch.TryGetOwner((Dam_PlayerDamageBase?)(object)__instance));
		}
	}
	internal sealed class AddEventsType2005EventData
	{
		internal int Count { get; set; }

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

		internal bool HasEnabled { get; set; }

		internal Vector3 Position { get; set; }

		internal bool HasPosition { get; set; }

		internal float FogTransitionDuration { get; set; }

		internal bool HasFogTransitionDuration { get; set; }

		internal List<WardenObjectiveEventData> Events { get; set; } = new List<WardenObjectiveEventData>();
	}
	internal readonly struct AddEventsType2005Signature : IEquatable<AddEventsType2005Signature>
	{
		private readonly int _count;

		private readonly bool _enabled;

		private readonly int _radius1000;

		private readonly int _x1000;

		private readonly int _y1000;

		private readonly int _z1000;

		internal AddEventsType2005Signature(int count, bool enabled, float radius, Vector3 position)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			_count = count;
			_enabled = enabled;
			_radius1000 = Quantize(radius);
			_x1000 = Quantize(position.x);
			_y1000 = Quantize(position.y);
			_z1000 = Quantize(position.z);
		}

		internal static AddEventsType2005Signature FromEvent(WardenObjectiveEventData e)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			return new AddEventsType2005Signature(e.Count, e.Enabled, e.FogTransitionDuration, e.Position);
		}

		public bool Equals(AddEventsType2005Signature other)
		{
			if (_count == other._count && _enabled == other._enabled && _radius1000 == other._radius1000 && _x1000 == other._x1000 && _y1000 == other._y1000)
			{
				return _z1000 == other._z1000;
			}
			return false;
		}

		public override bool Equals(object? obj)
		{
			if (obj is AddEventsType2005Signature other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return HashCode.Combine(_count, _enabled, _radius1000, _x1000, _y1000, _z1000);
		}

		private static int Quantize(float value)
		{
			if (float.IsNaN(value) || float.IsInfinity(value))
			{
				return 0;
			}
			return (int)Math.Round(value * 1000f);
		}
	}
	internal static class AddEventsType2005SidecarStore
	{
		private static readonly Dictionary<IntPtr, AddEventsType2005EventData> ByEventPointer = new Dictionary<IntPtr, AddEventsType2005EventData>();

		private static readonly Dictionary<AddEventsType2005Signature, List<AddEventsType2005EventData>> ByLooseSignature = new Dictionary<AddEventsType2005Signature, List<AddEventsType2005EventData>>();

		private static readonly List<AddEventsType2005EventData> LooseFallback = new List<AddEventsType2005EventData>();

		private static readonly HashSet<string> RegisteredLooseFingerprints = new HashSet<string>(StringComparer.Ordinal);

		private static readonly HashSet<AddEventsType2005Signature> AmbiguousWarningPrinted = new HashSet<AddEventsType2005Signature>();

		private static bool _isDeserializingSidecarEvents;

		private static bool _diskScanned;

		internal static bool TryGet(WardenObjectiveEventData eventData, out AddEventsType2005EventData data)
		{
			if (eventData != null && ByEventPointer.TryGetValue(((Il2CppObjectBase)eventData).Pointer, out data))
			{
				return true;
			}
			if (eventData != null)
			{
				AddEventsType2005Signature addEventsType2005Signature = AddEventsType2005Signature.FromEvent(eventData);
				if (ByLooseSignature.TryGetValue(addEventsType2005Signature, out List<AddEventsType2005EventData> value) && value.Count > 0)
				{
					data = value[0];
					if (value.Count > 1 && AmbiguousWarningPrinted.Add(addEventsType2005Signature))
					{
						ManualLogSource? log = AddEventsRuntime.Log;
						if (log != null)
						{
							log.LogWarning((object)"AddEvents Type 2005 sidecar fallback matched multiple definitions with the same vanilla signature. Using the first match. Make Count/Position/FogTransitionDuration/Enabled unique if this is not intended.");
						}
					}
					ByEventPointer[((Il2CppObjectBase)eventData).Pointer] = data;
					return true;
				}
			}
			if (LooseFallback.Count == 1)
			{
				data = LooseFallback[0];
				if (eventData != null)
				{
					ByEventPointer[((Il2CppObjectBase)eventData).Pointer] = data;
				}
				return true;
			}
			data = null;
			return false;
		}

		internal static void ScanDiskForDefinitions()
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Expected O, but got Unknown
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Expected O, but got Unknown
			if (_diskScanned)
			{
				return;
			}
			_diskScanned = true;
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			bool flag = default(bool);
			ManualLogSource log;
			try
			{
				foreach (string item in EnumerateCandidateJsonFiles())
				{
					num++;
					string text;
					try
					{
						text = File.ReadAllText(item);
					}
					catch
					{
						continue;
					}
					if (text.IndexOf("2005", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						List<AddEventsType2005EventData> list = ParseType2005Nodes(text);
						if (list.Count != 0)
						{
							num2++;
							num3 += list.Count;
							RegisterLoose(list);
						}
					}
				}
			}
			catch (Exception ex)
			{
				log = AddEventsRuntime.Log;
				if (log != null)
				{
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(48, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2005 disk sidecar scan failed: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetType().Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					}
					log.LogWarning(val);
				}
			}
			if (num3 > 0)
			{
				log = AddEventsRuntime.Log;
				if (log != null)
				{
					BepInExMessageLogInterpolatedStringHandler val2 = new BepInExMessageLogInterpolatedStringHandler(96, 3, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("AddEvents Type 2005 disk sidecar scan complete. FilesScanned=");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", FilesWithType2005=");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num2);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", Definitions=");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num3);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(".");
					}
					log.LogMessage(val2);
				}
				return;
			}
			log = AddEventsRuntime.Log;
			if (log != null)
			{
				BepInExDebugLogInterpolatedStringHandler val3 = new BepInExDebugLogInterpolatedStringHandler(77, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("AddEvents Type 2005 disk sidecar scan complete. FilesScanned=");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<int>(num);
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(", Definitions=0.");
				}
				log.LogDebug(val3);
			}
		}

		internal static void Capture(string json, object? result)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Invalid comparison between Unknown and I4
			if (_isDeserializingSidecarEvents || string.IsNullOrWhiteSpace(json) || json.IndexOf("2005", StringComparison.OrdinalIgnoreCase) < 0)
			{
				return;
			}
			List<AddEventsType2005EventData> list = ParseType2005Nodes(json);
			if (list.Count == 0)
			{
				return;
			}
			RegisterLoose(list);
			if (result == null)
			{
				return;
			}
			List<WardenObjectiveEventData> list2 = new List<WardenObjectiveEventData>();
			CollectEvents(result, list2, new HashSet<object>(ReferenceEqualityComparer.Instance), 0);
			if (list2.Count == 0)
			{
				return;
			}
			Dictionary<AddEventsType2005Signature, Queue<AddEventsType2005EventData>> dictionary = new Dictionary<AddEventsType2005Signature, Queue<AddEventsType2005EventData>>();
			foreach (AddEventsType2005EventData item in list)
			{
				AddEventsType2005Signature key = new AddEventsType2005Signature(item.Count, item.Enabled, item.FogTransitionDuration, item.Position);
				if (!dictionary.TryGetValue(key, out var value))
				{
					value = (dictionary[key] = new Queue<AddEventsType2005EventData>());
				}
				value.Enqueue(item);
			}
			Queue<AddEventsType2005EventData> queue2 = new Queue<AddEventsType2005EventData>(list);
			foreach (WardenObjectiveEventData item2 in list2)
			{
				if ((int)item2.Type == 2005)
				{
					AddEventsType2005EventData addEventsType2005EventData = null;
					AddEventsType2005Signature key2 = AddEventsType2005Signature.FromEvent(item2);
					if (dictionary.TryGetValue(key2, out var value2) && value2.Count > 0)
					{
						addEventsType2005EventData = value2.Dequeue();
					}
					else if (queue2.Count > 0)
					{
						addEventsType2005EventData = queue2.Dequeue();
					}
					if (addEventsType2005EventData != null)
					{
						ByEventPointer[((Il2CppObjectBase)item2).Pointer] = addEventsType2005EventData;
					}
				}
			}
		}

		private static void RegisterLoose(IEnumerable<AddEventsType2005EventData> parsed)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			foreach (AddEventsType2005EventData item in parsed)
			{
				string looseFingerprint = GetLooseFingerprint(item);
				if (RegisteredLooseFingerprints.Add(looseFingerprint))
				{
					AddEventsType2005Signature key = new AddEventsType2005Signature(item.Count, item.Enabled, item.FogTransitionDuration, item.Position);
					if (!ByLooseSignature.TryGetValue(key, out List<AddEventsType2005EventData> value))
					{
						value = new List<AddEventsType2005EventData>(1);
						ByLooseSignature[key] = value;
					}
					value.Add(item);
					LooseFallback.Add(item);
				}
			}
		}

		private static string GetLooseFingerprint(AddEventsType2005EventData data)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected I4, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: 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_012e: Unknown result type (might be due to invalid IL or missing references)
			int num = 17;
			foreach (WardenObjectiveEventData @event in data.Events)
			{
				num = num * 31 + @event.Type;
				num = num * 31 + @event.Count;
				num = num * 31 + ((object)@event.LocalIndex/*cast due to .constrained prefix*/).GetHashCode();
				num = num * 31 + ((object)@event.Layer/*cast due to .constrained prefix*/).GetHashCode();
				num = num * 31 + ((object)@event.DimensionIndex/*cast due to .constrained prefix*/).GetHashCode();
				num = num * 31 + ((object)@event.Position/*cast due to .constrained prefix*/).GetHashCode();
				num = num * 31 + @event.FogTransitionDuration.GetHashCode();
			}
			return string.Join("|", data.Count, data.Enabled, data.FogTransitionDuration, data.Position.x, data.Position.y, data.Position.z, data.Events.Count, num);
		}

		private static IEnumerable<string> EnumerateCandidateJsonFiles()
		{
			HashSet<string> roots = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			AddRoot(Paths.PluginPath);
			AddRoot(Path.Combine(Paths.BepInExRootPath, "GameData"));
			AddRoot(Path.Combine(Paths.BepInExRootPath, "Custom"));
			foreach (string item in roots)
			{
				IEnumerable<string> enumerable;
				try
				{
					enumerable = Directory.EnumerateFiles(item, "*.json", SearchOption.AllDirectories).ToArray();
				}
				catch
				{
					continue;
				}
				foreach (string item2 in enumerable)
				{
					yield return item2;
				}
			}
			void AddRoot(string? root)
			{
				if (!string.IsNullOrWhiteSpace(root) && Directory.Exists(root))
				{
					roots.Add(Path.GetFullPath(root));
				}
			}
		}

		private static List<AddEventsType2005EventData> ParseType2005Nodes(string json)
		{
			List<AddEventsType2005EventData> list = new List<AddEventsType2005EventData>();
			try
			{
				JsonNode jsonNode = JsonNode.Parse(json, new JsonNodeOptions
				{
					PropertyNameCaseInsensitive = true
				}, new JsonDocumentOptions
				{
					AllowTrailingCommas = true,
					CommentHandling = JsonCommentHandling.Skip
				});
				if (jsonNode != null)
				{
					TraverseJson(jsonNode, list);
				}
			}
			catch
			{
			}
			return list;
		}

		private static void TraverseJson(JsonNode node, List<AddEventsType2005EventData> output)
		{
			if (node is JsonObject jsonObject)
			{
				if (IsType2005Object(jsonObject))
				{
					output.Add(ParseEventData(jsonObject));
				}
				{
					foreach (KeyValuePair<string, JsonNode> item in jsonObject)
					{
						if (item.Value != null)
						{
							TraverseJson(item.Value, output);
						}
					}
					return;
				}
			}
			if (!(node is JsonArray jsonArray))
			{
				return;
			}
			foreach (JsonNode item2 in jsonArray)
			{
				if (item2 != null)
				{
					TraverseJson(item2, output);
				}
			}
		}

		private static bool IsType2005Object(JsonObject obj)
		{
			if (!obj.TryGetPropertyValue("Type", out JsonNode jsonNode))
			{
				return false;
			}
			if (jsonNode is JsonValue jsonValue)
			{
				if (jsonValue.TryGetValue<int>(out var value))
				{
					return value == 2005;
				}
				if (jsonValue.TryGetValue<string>(out string value2))
				{
					if (!string.Equals(value2, "2005", StringComparison.OrdinalIgnoreCase))
					{
						return string.Equals(value2, "AddPlayersToAllDownEventGroup", StringComparison.OrdinalIgnoreCase);
					}
					return true;
				}
			}
			return false;
		}

		private static AddEventsType2005EventData ParseEventData(JsonObject obj)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			JsonNode jsonNode;
			AddEventsType2005EventData addEventsType2005EventData = new AddEventsType2005EventData
			{
				Count = ReadInt(obj, "Count", 0),
				HasEnabled = obj.ContainsKey("Enabled"),
				Enabled = ReadBool(obj, "Enabled", fallback: true),
				HasPosition = obj.ContainsKey("Position"),
				Position = ReadVector3(obj.TryGetPropertyValue("Position", out jsonNode) ? jsonNode : null),
				HasFogTransitionDuration = obj.ContainsKey("FogTransitionDuration"),
				FogTransitionDuration = ReadFloat(obj, "FogTransitionDuration", 0f)
			};
			if (obj.TryGetPropertyValue("Events", out JsonNode jsonNode2) && jsonNode2 != null)
			{
				addEventsType2005EventData.Events = DeserializeEvents(jsonNode2.ToJsonString());
			}
			return addEventsType2005EventData;
		}

		private static List<WardenObjectiveEventData> DeserializeEvents(string json)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			try
			{
				_isDeserializingSidecarEvents = true;
				return EOSJson.Deserialize<List<WardenObjectiveEventData>>(json) ?? new List<WardenObjectiveEventData>();
			}
			catch (Exception ex)
			{
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					bool flag = default(bool);
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(59, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2005 could not deserialize nested Events: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetType().Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					}
					log.LogWarning(val);
				}
				return new List<WardenObjectiveEventData>();
			}
			finally
			{
				_isDeserializingSidecarEvents = false;
			}
		}

		private static void CollectEvents(object obj, List<WardenObjectiveEventData> output, HashSet<object> visited, int depth)
		{
			if (obj == null || depth > 12 || !visited.Add(obj))
			{
				return;
			}
			WardenObjectiveEventData val = (WardenObjectiveEventData)((obj is WardenObjectiveEventData) ? obj : null);
			if (val != null)
			{
				output.Add(val);
				return;
			}
			if (obj is IEnumerable enumerable && !(obj is string))
			{
				foreach (object item in enumerable)
				{
					if (item != null)
					{
						CollectEvents(item, output, visited, depth + 1);
					}
				}
				return;
			}
			Type type = obj.GetType();
			if (type.IsPrimitive || type.IsEnum || type == typeof(string))
			{
				return;
			}
			PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (PropertyInfo propertyInfo in properties)
			{
				if (propertyInfo.GetIndexParameters().Length != 0)
				{
					continue;
				}
				try
				{
					object value = propertyInfo.GetValue(obj);
					if (value != null)
					{
						CollectEvents(value, output, visited, depth + 1);
					}
				}
				catch
				{
				}
			}
			FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (FieldInfo fieldInfo in fields)
			{
				try
				{
					object value2 = fieldInfo.GetValue(obj);
					if (value2 != null)
					{
						CollectEvents(value2, output, visited, depth + 1);
					}
				}
				catch
				{
				}
			}
		}

		private static int ReadInt(JsonObject node, string name, int fallback)
		{
			try
			{
				if (node.TryGetPropertyValue(name, out JsonNode jsonNode) && jsonNode is JsonValue jsonValue)
				{
					if (jsonValue.TryGetValue<int>(out var value))
					{
						return value;
					}
					if (jsonValue.TryGetValue<string>(out string value2) && int.TryParse(value2, out value))
					{
						return value;
					}
				}
			}
			catch
			{
			}
			return fallback;
		}

		private static float ReadFloat(JsonObject node, string name, float fallback)
		{
			try
			{
				if (node.TryGetPropertyValue(name, out JsonNode jsonNode) && jsonNode is JsonValue jsonValue)
				{
					if (jsonValue.TryGetValue<float>(out var value))
					{
						return value;
					}
					if (jsonValue.TryGetValue<double>(out var value2))
					{
						return (float)value2;
					}
					if (jsonValue.TryGetValue<string>(out string value3) && float.TryParse(value3, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
					{
						return value;
					}
				}
			}
			catch
			{
			}
			return fallback;
		}

		private static bool ReadBool(JsonObject node, string name, bool fallback)
		{
			try
			{
				if (node.TryGetPropertyValue(name, out JsonNode jsonNode) && jsonNode is JsonValue jsonValue)
				{
					if (jsonValue.TryGetValue<bool>(out var value))
					{
						return value;
					}
					if (jsonValue.TryGetValue<string>(out string value2) && bool.TryParse(value2, out value))
					{
						return value;
					}
				}
			}
			catch
			{
			}
			return fallback;
		}

		private static Vector3 ReadVector3(JsonNode? node)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if (!(node is JsonObject node2))
			{
				return Vector3.zero;
			}
			return new Vector3(ReadFloat(node2, "x", 0f), ReadFloat(node2, "y", 0f), ReadFloat(node2, "z", 0f));
		}
	}
	internal static class AddEventsAllDownEventGroupEvents
	{
		internal static void AddPlayersToAllDownEventGroup(WardenObjectiveEventData eventData)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			if (!AddEventsNetworkEventProxy.EnsureHostExecution(AddEventsCustomEventType.AddPlayersToAllDownEventGroup, eventData))
			{
				return;
			}
			if (!AddEventsType2005SidecarStore.TryGet(eventData, out AddEventsType2005EventData data))
			{
				data = new AddEventsType2005EventData
				{
					Count = eventData.Count,
					Enabled = eventData.Enabled,
					Position = eventData.Position,
					HasPosition = true,
					FogTransitionDuration = eventData.FogTransitionDuration,
					HasFogTransitionDuration = (eventData.FogTransitionDuration > 0f),
					Events = new List<WardenObjectiveEventData>()
				};
			}
			bool flag = default(bool);
			ManualLogSource log;
			if (!data.Enabled)
			{
				AddEventsAllDownEventGroupManager.Current.SetGroupEnabled(data.Count, enabled: false);
				log = AddEventsRuntime.Log;
				if (log != null)
				{
					BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(63, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2005 all-down event group ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(data.Count);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" disabled and cleared.");
					}
					log.LogDebug(val);
				}
				return;
			}
			List<PlayerAgent> list = ResolvePlayers(eventData, data);
			int num = AddEventsAllDownEventGroupManager.Current.AddPlayersToGroup(data.Count, list, data.Events);
			log = AddEventsRuntime.Log;
			if (log != null)
			{
				BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(70, 4, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2005 all-down event group ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(data.Count);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": added ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("/");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(list.Count);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" player(s), Events=");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(data.Events.Count);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
				}
				log.LogDebug(val);
			}
		}

		private static List<PlayerAgent> ResolvePlayers(WardenObjectiveEventData eventData, AddEventsType2005EventData data)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			float num = (data.HasFogTransitionDuration ? data.FogTransitionDuration : eventData.FogTransitionDuration);
			Vector3 origin = (data.HasPosition ? data.Position : eventData.Position);
			if (num > 0f)
			{
				return GetPlayersInRadius(origin, num);
			}
			return GetAllPlayers();
		}

		private static List<PlayerAgent> GetPlayersInRadius(Vector3 origin, float radius)
		{
			//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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			float num = radius * radius;
			List<PlayerAgent> list = new List<PlayerAgent>();
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (!((Object)(object)current == (Object)null) && ((Agent)current).Alive)
				{
					Vector3 val = ((Agent)current).Position - origin;
					if (((Vector3)(ref val)).sqrMagnitude <= num)
					{
						list.Add(current);
					}
				}
			}
			return list;
		}

		private static List<PlayerAgent> GetAllPlayers()
		{
			List<PlayerAgent> list = new List<PlayerAgent>();
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if ((Object)(object)current != (Object)null && ((Agent)current).Alive)
				{
					list.Add(current);
				}
			}
			return list;
		}
	}
	public struct AddEventsAllDownEventGroupReplicationState
	{
		public bool enabled;

		public bool checkP1;

		public bool checkP2;

		public bool checkP3;

		public bool checkP4;
	}
	internal sealed class AddEventsAllDownEventGroup
	{
		internal const int MaxPlayers = 4;

		private readonly bool[] _slots = new bool[4];

		private readonly bool[] _downSlots = new bool[4];

		private readonly Dictionary<int, int> _lastDeathFrameBySlot = new Dictionary<int, int>();

		private bool _hasTriggered;

		private StateReplicator<AddEventsAllDownEventGroupReplicationState>? _stateReplicator;

		internal bool Enabled { get; private set; }

		internal List<WardenObjectiveEventData> Events { get; set; } = new List<WardenObjectiveEventData>();

		internal int Count
		{
			get
			{
				int num = 0;
				for (int i = 0; i < _slots.Length; i++)
				{
					if (_slots[i])
					{
						num++;
					}
				}
				return num;
			}
		}

		internal bool SetPlayerInGroup(int slot, bool inGroup)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			if (!IsValidPlayerSlot(slot))
			{
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(63, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2005 invalid player slot index ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(slot);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; expected [0, ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(4);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(").");
					}
					log.LogError(val);
				}
				return false;
			}
			if (_slots[slot] == inGroup)
			{
				return false;
			}
			int count = Count;
			_slots[slot] = inGroup;
			_downSlots[slot] = false;
			_lastDeathFrameBySlot.Remove(slot);
			if (inGroup)
			{
				_hasTriggered = false;
			}
			int count2 = Count;
			if (count == 0 && count2 > 0)
			{
				Enabled = true;
			}
			else if (count > 0 && count2 == 0)
			{
				Enabled = false;
			}
			Sync();
			return true;
		}

		internal void Toggle(bool enabled)
		{
			if (!enabled)
			{
				ClearAndDisable();
			}
			else if (!Enabled)
			{
				Enabled = true;
				Sync();
			}
		}

		internal void ClearAndDisable()
		{
			bool flag = Enabled || Count > 0 || Events.Count > 0 || _lastDeathFrameBySlot.Count > 0 || _hasTriggered;
			Enabled = false;
			for (int i = 0; i < _slots.Length; i++)
			{
				_slots[i] = false;
				_downSlots[i] = false;
			}
			_lastDeathFrameBySlot.Clear();
			_hasTriggered = false;
			Events = new List<WardenObjectiveEventData>();
			if (flag)
			{
				Sync();
			}
		}

		internal bool ContainsSlot(int slot)
		{
			if (IsValidPlayerSlot(slot))
			{
				return _slots[slot];
			}
			return false;
		}

		internal bool TryMarkPlayerDownAndCheckAll(int slot, int frame, out int markedCount, out int downCount)
		{
			markedCount = Count;
			downCount = GetDownCount();
			if (!IsValidPlayerSlot(slot) || !_slots[slot] || _hasTriggered)
			{
				return false;
			}
			if (_lastDeathFrameBySlot.TryGetValue(slot, out var value) && value == frame)
			{
				return false;
			}
			_lastDeathFrameBySlot[slot] = frame;
			_downSlots[slot] = true;
			downCount = GetDownCount();
			markedCount = Count;
			if (markedCount <= 0 || downCount < markedCount)
			{
				return false;
			}
			_hasTriggered = true;
			return true;
		}

		internal void Rearm(List<WardenObjectiveEventData> events)
		{
			_hasTriggered = false;
			_lastDeathFrameBySlot.Clear();
			for (int i = 0; i < _downSlots.Length; i++)
			{
				_downSlots[i] = false;
			}
			if (events.Count > 0)
			{
				Events = events;
			}
		}

		private int GetDownCount()
		{
			int num = 0;
			for (int i = 0; i < _slots.Length; i++)
			{
				if (_slots[i] && _downSlots[i])
				{
					num++;
				}
			}
			return num;
		}

		internal void ResetSynced()
		{
			Reset();
			Sync();
		}

		internal void ResetUnsynced()
		{
			Reset();
			_stateReplicator?.SetStateUnsynced(GetSyncState());
		}

		private void Reset()
		{
			Enabled = false;
			for (int i = 0; i < _slots.Length; i++)
			{
				_slots[i] = false;
				_downSlots[i] = false;
			}
			_lastDeathFrameBySlot.Clear();
			_hasTriggered = false;
			Events = new List<WardenObjectiveEventData>();
		}

		private void Sync()
		{
			if (!SNet.IsMaster)
			{
				ManualLogSource? log = AddEventsRuntime.Log;
				if (log != null)
				{
					log.LogWarning((object)"AddEvents Type 2005 all-down event group sync blocked on client; state changes must be executed by host.");
				}
			}
			else
			{
				_stateReplicator?.SetState(GetSyncState());
			}
		}

		private void OnStateChanged(AddEventsAllDownEventGroupReplicationState oldState, AddEventsAllDownEventGroupReplicationState newState, bool isRecall)
		{
			if (isRecall)
			{
				Enabled = newState.enabled;
				_slots[0] = newState.checkP1;
				_slots[1] = newState.checkP2;
				_slots[2] = newState.checkP3;
				_slots[3] = newState.checkP4;
			}
		}

		private AddEventsAllDownEventGroupReplicationState GetSyncState()
		{
			return new AddEventsAllDownEventGroupReplicationState
			{
				enabled = Enabled,
				checkP1 = _slots[0],
				checkP2 = _slots[1],
				checkP3 = _slots[2],
				checkP4 = _slots[3]
			};
		}

		internal static AddEventsAllDownEventGroup? Instantiate()
		{
			uint num = EOSNetworking.AllotForeverReplicatorID();
			if (num == 0)
			{
				ManualLogSource? log = AddEventsRuntime.Log;
				if (log != null)
				{
					log.LogError((object)"AddEvents Type 2005 could not allocate a network replicator id.");
				}
				return null;
			}
			AddEventsAllDownEventGroup addEventsAllDownEventGroup = new AddEventsAllDownEventGroup();
			addEventsAllDownEventGroup._stateReplicator = AddEventsStateReplicatorCompat.Create(num, default(AddEventsAllDownEventGroupReplicationState), (LifeTimeType)0, "AddEvents Type 2005");
			if (addEventsAllDownEventGroup._stateReplicator == null)
			{
				return null;
			}
			addEventsAllDownEventGroup._stateReplicator.OnStateChanged += addEventsAllDownEventGroup.OnStateChanged;
			addEventsAllDownEventGroup.ResetUnsynced();
			return addEventsAllDownEventGroup;
		}

		private static bool IsValidPlayerSlot(int slot)
		{
			if (slot >= 0)
			{
				return slot < 4;
			}
			return false;
		}

		private AddEventsAllDownEventGroup()
		{
		}
	}
	internal sealed class AddEventsAllDownEventGroupManager
	{
		internal const int MaxGroups = 4;

		private readonly List<AddEventsAllDownEventGroup> _groups = new List<AddEventsAllDownEventGroup>();

		private bool _initialized;

		internal static AddEventsAllDownEventGroupManager Current { get; } = new AddEventsAllDownEventGroupManager();

		internal void Init()
		{
			if (!_initialized)
			{
				_initialized = true;
				EventAPI.OnManagersSetup += SetupGroups;
				LevelAPI.OnBuildStart += ResetUnsynced;
				LevelAPI.OnLevelCleanup += ResetUnsynced;
			}
		}

		internal int AddPlayersToGroup(int groupIndex, IEnumerable<PlayerAgent> players, List<WardenObjectiveEventData> events)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			EnsureGroupsReady();
			if (!TryGetGroup(groupIndex, out AddEventsAllDownEventGroup group))
			{
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(61, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2005 group index must be between 0 and ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_groups.Count - 1);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; got ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(groupIndex);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
					}
					log.LogError(val);
				}
				return 0;
			}
			group.Rearm(events);
			int num = 0;
			foreach (PlayerAgent player in players)
			{
				try
				{
					if (group.SetPlayerInGroup(player.PlayerSlotIndex, inGroup: true))
					{
						num++;
					}
				}
				catch
				{
				}
			}
			return num;
		}

		internal void SetGroupEnabled(int groupIndex, bool enabled)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			EnsureGroupsReady();
			if (!TryGetGroup(groupIndex, out AddEventsAllDownEventGroup group))
			{
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(61, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2005 group index must be between 0 and ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_groups.Count - 1);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; got ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(groupIndex);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
					}
					log.LogError(val);
				}
			}
			else
			{
				group.Toggle(enabled);
			}
		}

		internal void ResetSynced()
		{
			foreach (AddEventsAllDownEventGroup group in _groups)
			{
				group.ResetSynced();
			}
		}

		internal void ResetUnsynced()
		{
			foreach (AddEventsAllDownEventGroup group in _groups)
			{
				group.ResetUnsynced();
			}
		}

		internal void OnPlayerDied(PlayerAgent? player)
		{
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Expected O, but got Unknown
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Expected O, but got Unknown
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			if ((Object)(object)player == (Object)null || !SNet.IsMaster)
			{
				return;
			}
			int playerSlotIndex;
			try
			{
				playerSlotIndex = player.PlayerSlotIndex;
			}
			catch
			{
				return;
			}
			int frameCount = Time.frameCount;
			bool flag = default(bool);
			for (int i = 0; i < _groups.Count; i++)
			{
				AddEventsAllDownEventGroup addEventsAllDownEventGroup = _groups[i];
				if (!addEventsAllDownEventGroup.Enabled || !addEventsAllDownEventGroup.ContainsSlot(playerSlotIndex))
				{
					continue;
				}
				ManualLogSource log;
				if (!addEventsAllDownEventGroup.TryMarkPlayerDownAndCheckAll(playerSlotIndex, frameCount, out var markedCount, out var downCount))
				{
					log = AddEventsRuntime.Log;
					if (log != null)
					{
						BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(99, 4, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2005 all-down event group ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(i);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": player slot ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(playerSlotIndex);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" downed (");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(downCount);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("/");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(markedCount);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("); waiting for all marked players.");
						}
						log.LogDebug(val);
					}
					continue;
				}
				log = AddEventsRuntime.Log;
				if (log != null)
				{
					BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(94, 4, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2005 all-down event group ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(i);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": all marked players downed (");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(downCount);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("/");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(markedCount);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("); executing ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(addEventsAllDownEventGroup.Events.Count);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" event(s).");
					}
					log.LogDebug(val);
				}
				foreach (WardenObjectiveEventData @event in addEventsAllDownEventGroup.Events)
				{
					try
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(@event, (eWardenObjectiveEventTrigger)0, true, 0f);
					}
					catch (Exception ex)
					{
						log = AddEventsRuntime.Log;
						if (log != null)
						{
							BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(43, 2, ref flag);
							if (flag)
							{
								((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("AddEvents Type 2005 nested event failed: ");
								((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.GetType().Name);
								((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": ");
								((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
							}
							log.LogWarning(val2);
						}
					}
				}
			}
		}

		private void SetupGroups()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			if (_groups.Count > 0)
			{
				return;
			}
			bool flag = default(bool);
			for (int i = 0; i < 4; i++)
			{
				AddEventsAllDownEventGroup addEventsAllDownEventGroup = AddEventsAllDownEventGroup.Instantiate();
				if (addEventsAllDownEventGroup == null)
				{
					ManualLogSource log = AddEventsRuntime.Log;
					if (log != null)
					{
						BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(61, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents Type 2005 instantiated all-down event group count: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_groups.Count);
						}
						log.LogError(val);
					}
					break;
				}
				_groups.Add(addEventsAllDownEventGroup);
			}
		}

		private void EnsureGroupsReady()
		{
			if (_groups.Count == 0)
			{
				SetupGroups();
			}
		}

		private bool TryGetGroup(int groupIndex, out AddEventsAllDownEventGroup? group)
		{
			if (groupIndex < 0 || groupIndex >= _groups.Count)
			{
				group = null;
				return false;
			}
			group = _groups[groupIndex];
			return true;
		}

		private AddEventsAllDownEventGroupManager()
		{
		}
	}
	[HarmonyPatch(typeof(Dam_PlayerDamageBase), "ReceiveSetDead")]
	internal static class AddEventsAllDownEvent_DamPlayerDamageBaseReceiveSetDeadPatch
	{
		private static void Postfix(Dam_PlayerDamageBase __instance)
		{
			AddEventsAllDownEventGroupManager.Current.OnPlayerDied(TryGetOwner(__instance));
		}

		internal static PlayerAgent? TryGetOwner(Dam_PlayerDamageBase? damageBase)
		{
			if ((Object)(object)damageBase == (Object)null)
			{
				return null;
			}
			try
			{
				return damageBase.Owner;
			}
			catch
			{
				return null;
			}
		}
	}
	[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveSetDead")]
	internal static class AddEventsAllDownEvent_DamPlayerDamageLocalReceiveSetDeadPatch
	{
		private static void Postfix(Dam_PlayerDamageLocal __instance)
		{
			AddEventsAllDownEventGroupManager.Current.OnPlayerDied(AddEventsAllDownEvent_DamPlayerDamageBaseReceiveSetDeadPatch.TryGetOwner((Dam_PlayerDamageBase?)(object)__instance));
		}
	}
	internal delegate void AddEventsCustomEventHandler(WardenObjectiveEventData eventData);
	internal enum AddEventsCustomEventType
	{
		AddPlayersToDeathEventGroup = 2004,
		AddPlayersToAllDownEventGroup = 2005,
		ToggleLaserRoom = 2010
	}
	internal static class AddEventsCustomEventRegistry
	{
		private static bool _registered;

		private static readonly Dictionary<AddEventsCustomEventType, AddEventsCustomEventHandler> Handlers = new Dictionary<AddEventsCustomEventType, AddEventsCustomEventHandler>();

		internal static void RegisterDefaults()
		{
			if (!_registered)
			{
				Register(AddEventsCustomEventType.AddPlayersToDeathEventGroup, AddEventsDeathEventGroupEvents.AddPlayersToDeathEventGroup);
				Register(AddEventsCustomEventType.AddPlayersToAllDownEventGroup, AddEventsAllDownEventGroupEvents.AddPlayersToAllDownEventGroup);
				Register(AddEventsCustomEventType.ToggleLaserRoom, LaserRoomEvents.ToggleLaserRoom);
				_registered = true;
				ManualLogSource? log = AddEventsRuntime.Log;
				if (log != null)
				{
					log.LogMessage((object)"AddEvents custom event registry initialized with numeric Type 2004, 2005 and 2010.");
				}
			}
		}

		private static void Register(AddEventsCustomEventType eventType, AddEventsCustomEventHandler handler)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			Handlers[eventType] = handler;
			string text = eventType.ToString();
			uint num = (uint)eventType;
			if (EOSWardenEventManager.Current.AddEventDefinition(text, num, (Action<WardenObjectiveEventData>)delegate(WardenObjectiveEventData e)
			{
				handler(e);
			}))
			{
				return;
			}
			ManualLogSource log = AddEventsRuntime.Log;
			if (log != null)
			{
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(113, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents custom event Type=");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(num);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" Name=");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" could not be registered. Another plugin may already own this event name or id.");
				}
				log.LogWarning(val);
			}
		}

		internal static void Execute(AddEventsCustomEventType eventType, WardenObjectiveEventData eventData)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			if (Handlers.TryGetValue(eventType, out AddEventsCustomEventHandler value))
			{
				value(eventData);
				return;
			}
			ManualLogSource log = AddEventsRuntime.Log;
			if (log != null)
			{
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(52, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents custom event '");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<AddEventsCustomEventType>(eventType);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' has no registered handler.");
				}
				log.LogWarning(val);
			}
		}

		internal static bool IsAddEventsEvent(eWardenObjectiveEventType type, out AddEventsCustomEventType eventType)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Expected I4, but got Unknown
			int num = (int)type;
			if (Enum.IsDefined(typeof(AddEventsCustomEventType), num))
			{
				eventType = (AddEventsCustomEventType)num;
				return true;
			}
			eventType = (AddEventsCustomEventType)0;
			return false;
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 1)]
	internal struct AddEventsEventRequestPacket
	{
		public int EventType;

		public byte Enabled;

		public int Count;

		public float PosX;

		public float PosY;

		public float PosZ;
	}
	internal static class AddEventsNetworkEventProxy
	{
		private const string EventName = "AddEvents.EventRequest.v1";

		private static bool _registered;

		private static bool _executingHostRequest;

		private static bool _registrationFailed;

		internal static void Init()
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			if (_registered)
			{
				return;
			}
			bool flag = default(bool);
			try
			{
				if (!NetworkAPI.IsEventRegistered("AddEvents.EventRequest.v1"))
				{
					NetworkAPI.RegisterEvent<AddEventsEventRequestPacket>("AddEvents.EventRequest.v1", (Action<ulong, AddEventsEventRequestPacket>)OnReceiveEventRequest);
					ManualLogSource? log = AddEventsRuntime.Log;
					if (log != null)
					{
						log.LogMessage((object)"AddEvents network event proxy registered.");
					}
				}
				else
				{
					ManualLogSource log2 = AddEventsRuntime.Log;
					if (log2 != null)
					{
						BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(61, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents network event proxy event '");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("AddEvents.EventRequest.v1");
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' is already registered.");
						}
						log2.LogWarning(val);
					}
				}
				_registered = true;
				_registrationFailed = false;
			}
			catch (Exception ex)
			{
				_registered = false;
				_registrationFailed = true;
				ManualLogSource log2 = AddEventsRuntime.Log;
				if (log2 != null)
				{
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(98, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents network event proxy disabled because GTFO-API NetworkAPI is not ready or unavailable: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetType().Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					}
					log2.LogWarning(val);
				}
			}
		}

		internal static bool EnsureHostExecution(AddEventsCustomEventType eventType, WardenObjectiveEventData eventData)
		{
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			if (_executingHostRequest || SNet.IsMaster)
			{
				return true;
			}
			bool flag = default(bool);
			if (!SNet.HasMaster || (Object)(object)SNet.Master == (Object)null)
			{
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(73, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents event '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<AddEventsCustomEventType>(eventType);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' ignored on client because no SNet master is available.");
					}
					log.LogWarning(val);
				}
				return false;
			}
			if (!_registered)
			{
				Init();
				if (!_registered)
				{
					string text = (_registrationFailed ? "network proxy registration is unavailable" : "network proxy is not registered");
					ManualLogSource log = AddEventsRuntime.Log;
					if (log != null)
					{
						BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(54, 2, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("AddEvents event '");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<AddEventsCustomEventType>(eventType);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' was not forwarded to host because ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
						}
						log.LogWarning(val);
					}
					return false;
				}
			}
			try
			{
				AddEventsEventRequestPacket addEventsEventRequestPacket = BuildPacket(eventType, eventData);
				NetworkAPI.InvokeEvent<AddEventsEventRequestPacket>("AddEvents.EventRequest.v1", addEventsEventRequestPacket, SNet.Master, (SNet_ChannelType)4);
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					BepInExMessageLogInterpolatedStringHandler val2 = new BepInExMessageLogInterpolatedStringHandler(65, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("AddEvents event '");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<AddEventsCustomEventType>(eventType);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("' forwarded to host for authoritative execution.");
					}
					log.LogMessage(val2);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = AddEventsRuntime.Log;
				if (log != null)
				{
					BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(42, 3, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("AddEvents event '");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<AddEventsCustomEventType>(eventType);
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("' host-forward failed: ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(ex.GetType().Name);
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(": ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(ex.Message);
					}
					log.LogError(val3);
				}
			}
			return false;
		}

		private static AddEventsEventRequestPacket BuildPacket(AddEventsCustomEventType eventType, WardenObjectiveEventData eventData)
		{
			//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_0039: 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_0053: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = eventData.Position;
			return new AddEventsEventRequestPacket
			{
				EventType = (int)eventType,
				Enabled = (byte)(eventData.Enabled ? 1 : 0),
				Count = eventData.Count,
				PosX = position.x,
				PosY = position.y,
				PosZ = position.z
			};
		}

		private static void OnReceiveEventRequest(ulong sender, AddEventsEventRequestPacket packet)
		{
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Expected O, but got Unknown
			//IL_0084: Unknown result 

plugins/XiaoTian-SURVIVAL/SURVIVAL/Custom/net6/BigPickupCarryOnBack.dll

Decompiled 2 weeks 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.Unity.IL2CPP;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using LevelGeneration;
using Microsoft.CodeAnalysis;
using Player;
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("BigPickupCarryOnBack")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("BigPickupCarryOnBack")]
[assembly: AssemblyTitle("BigPickupCarryOnBack")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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]
	[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 BigPickupCarryOnBack_Patches
{
	internal static class BigPickupUtil
	{
		internal static readonly HashSet<uint> TargetIds;

		private static HashSet<uint> EnabledLevels;

		internal static bool IsTargetCarried(out BackpackItem carryItem)
		{
			carryItem = null;
			return PlayerBackpackManager.TryGetItem(SNet.LocalPlayer, (InventorySlot)8, ref carryItem) && carryItem != null && TargetIds.Contains(carryItem.ItemID);
		}

		internal static bool IsTargetCarried()
		{
			BackpackItem carryItem;
			return IsTargetCarried(out carryItem);
		}

		internal static bool EnableOverride()
		{
			return EnabledLevels.Contains(RundownManager.ActiveExpedition.LevelLayoutData);
		}

		static BigPickupUtil()
		{
			TargetIds = new HashSet<uint> { 131u, 173u, 2002u };
			EnabledLevels = new HashSet<uint>();
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock("SR.E_LevelLayou");
			if (block != null)
			{
				EnabledLevels.Add(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID);
			}
			block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock("LAYOUT_FX.6_L1");
			if (block != null)
			{
				EnabledLevels.Add(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID);
			}
		}
	}
	[HarmonyPatch(typeof(LG_PickupItem))]
	internal class SetupBigPickupItemWithItemId
	{
		[HarmonyPatch("SetupBigPickupItemWithItemId")]
		[HarmonyPostfix]
		private static void LG_PickupItem__SetupBigPickupItemWithItemId__Postfix(LG_PickupItem __instance, uint itemId)
		{
			if (BigPickupUtil.EnableOverride() && BigPickupUtil.IsTargetCarried())
			{
				CarryItemPickup_Core componentInChildren = ((Component)__instance.m_root).GetComponentInChildren<CarryItemPickup_Core>();
				Interact_Pickup_PickupItem val = ((Il2CppObjectBase)componentInChildren.m_interact).Cast<Interact_Pickup_PickupItem>();
				((Interact_Timed)val).InteractDuration = 1.5f;
			}
		}
	}
	[HarmonyPatch(typeof(FirstPersonItemHolder))]
	internal class Patch_FirstPersonItemHolder
	{
		[HarmonyPatch("ItemCanMoveQuick")]
		[HarmonyPrefix]
		private static bool FirstPersonItemHolder__ItemCanMoveQuick__Prefix(ref bool __result)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			if (!BigPickupUtil.EnableOverride())
			{
				return true;
			}
			if (PlayerBackpackManager.LocalBackpack.HasBackpackItem((InventorySlot)8) && (int)PlayerManager.GetLocalPlayerAgent().Inventory.WieldedSlot != 8)
			{
				__result = false;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerBackpackManager))]
	internal class Patch_PlayerBackpackManager
	{
		[HarmonyPatch("HasItem_Local")]
		[HarmonyPrefix]
		private static bool PlayerBackpackManager__HasItem_Local__Prefix(InventorySlot slot, ref bool __result)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			if (!BigPickupUtil.EnableOverride())
			{
				return true;
			}
			if ((int)slot != 8)
			{
				return true;
			}
			__result = false;
			return false;
		}
	}
	[HarmonyPatch(typeof(PlayerInventoryLocal))]
	internal class Patch_PlayerInventoryLocal
	{
		private static void ForceWieldSlot(PlayerInventoryLocal inv, InventorySlot slot)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			((PlayerInventoryBase)inv).Owner.Sync.WantsToWieldSlot(slot, false);
			pInventoryStatus syncedInventoryStatus = ((PlayerInventoryBase)inv).Owner.Sync.m_syncedInventoryStatus;
			syncedInventoryStatus.wieldedSlot = slot;
			((PlayerInventoryBase)inv).Owner.Sync.m_syncedInventoryStatus = syncedInventoryStatus;
			((PlayerInventoryBase)inv).Owner.Sync.LastWantedSlot = syncedInventoryStatus.wieldedSlot;
			((PlayerInventoryBase)inv).Owner.Sync.m_inventoryStatusPacket.Send(syncedInventoryStatus, (SNet_ChannelType)4);
			((PlayerInventoryBase)inv).Owner.Sync.DoInventoryWield(syncedInventoryStatus);
		}

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void PlayerInventoryLocal__Awake__Postfix(PlayerInventoryLocal __instance)
		{
			if (BigPickupUtil.EnableOverride() && !__instance.m_allowedScrollSlots.Contains((InventorySlot)8))
			{
				__instance.m_allowedScrollSlots.Add((InventorySlot)8);
			}
		}

		[HarmonyPatch("CheckInput")]
		[HarmonyPrefix]
		private static bool PlayerInventoryLocal__CheckInput__Prefix(PlayerInventoryLocal __instance)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Invalid comparison between Unknown and I4
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Invalid comparison between Unknown and I4
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			if (!BigPickupUtil.EnableOverride())
			{
				return true;
			}
			if ((int)((PlayerInventoryBase)__instance).WieldedSlot != 8)
			{
				return true;
			}
			if (!BigPickupUtil.IsTargetCarried())
			{
				return true;
			}
			if (InputMapper.GetButtonDownKeyMouseGamepad((InputAction)32, (eFocusState)0))
			{
				((PlayerInventoryBase)__instance).Owner.Sync.WantsToSetFlashlightEnabled(!((PlayerInventoryBase)__instance).WantsFlashlightEnabled, false);
			}
			if (((PlayerInventoryBase)__instance).Owner.FPItemHolder.ItemHiddenTrigger)
			{
				return false;
			}
			InventorySlot? val = null;
			if (InputMapper.GetButtonDownKeyMouseGamepad((InputAction)23, (eFocusState)0))
			{
				val = (InventorySlot)1;
			}
			else if (InputMapper.GetButtonDownKeyMouseGamepad((InputAction)24, (eFocusState)0))
			{
				val = (InventorySlot)2;
			}
			else if (InputMapper.GetButtonDownKeyMouseGamepad((InputAction)25, (eFocusState)0))
			{
				val = (InventorySlot)3;
			}
			else if (InputMapper.GetButtonDownKeyMouseGamepad((InputAction)27, (eFocusState)0))
			{
				val = (InventorySlot)4;
			}
			else if (InputMapper.GetButtonDownKeyMouseGamepad((InputAction)28, (eFocusState)0))
			{
				val = (InventorySlot)5;
			}
			else if (InputMapper.GetButtonDownKeyMouseGamepad((InputAction)26, (eFocusState)0))
			{
				val = (InventorySlot)10;
			}
			else if (InputMapper.GetButtonDownKeyMouseGamepad((InputAction)29, (eFocusState)0))
			{
				val = (InventorySlot)11;
			}
			if (val.HasValue && val.Value != ((PlayerInventoryBase)__instance).WieldedSlot)
			{
				BackpackItem val2 = default(BackpackItem);
				if (!PlayerBackpackManager.TryGetItem(SNet.LocalPlayer, val.Value, ref val2) || val2 == null)
				{
					return false;
				}
				bool flag = (int)((PlayerInventoryBase)__instance).WieldedSlot == 8 && BigPickupUtil.IsTargetCarried();
				_ = val2.Status;
				if (!flag)
				{
					return false;
				}
				ItemEquippable val3 = ((Il2CppObjectBase)val2.Instance).TryCast<ItemEquippable>();
				if ((Object)(object)val3 != (Object)null && val3.CanWield)
				{
					ForceWieldSlot(__instance, val.Value);
					__instance.m_itemScrollTimer = Clock.Time + 0.1f;
				}
			}
			if ((int)FocusStateManager.CurrentState != 6 && !__instance.CheckWieldingKeys() && (Object)(object)((PlayerInventoryBase)__instance).m_wieldedItem != (Object)null)
			{
				float axisKeyMouse = InputMapper.GetAxisKeyMouse((InputAction)30, (eFocusState)0);
				bool buttonDownKeyMouseGamepad = InputMapper.GetButtonDownKeyMouseGamepad((InputAction)31, (eFocusState)0);
				if ((((PlayerInventoryBase)__instance).AllowScrollInput && ((PlayerInventoryBase)__instance).m_wieldedItem.WeaponSwitchAllowed && Mathf.Abs(axisKeyMouse) > 0f && Clock.Time > __instance.m_itemScrollTimer) || buttonDownKeyMouseGamepad)
				{
					int num = ((axisKeyMouse > 0f) ? __instance.GetNextSlot(((PlayerInventoryBase)__instance).WieldedSlot, -1) : __instance.GetNextSlot(((PlayerInventoryBase)__instance).WieldedSlot, 1));
					if (num > -1)
					{
						ForceWieldSlot(__instance, (InventorySlot)(byte)num);
						__instance.m_itemScrollTimer = Clock.Time + 0.1f;
					}
				}
			}
			if (__instance.m_FPItemHolder.ItemIsBusy)
			{
				return false;
			}
			if (InputMapper.GetButtonDownKeyMouseGamepad((InputAction)11, (eFocusState)0) && ((PlayerInventoryBase)__instance).CanReloadCurrent())
			{
				((PlayerInventoryBase)__instance).TriggerReload();
			}
			return false;
		}

		[HarmonyPatch("CheckInput")]
		[HarmonyPostfix]
		private static void CheckInput_Postfix(PlayerInventoryLocal __instance)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Invalid comparison between Unknown and I4
			if (BigPickupUtil.EnableOverride() && !((PlayerInventoryBase)__instance).Owner.FPItemHolder.ItemHiddenTrigger && (int)FocusStateManager.CurrentState != 6 && (int)((PlayerInventoryBase)__instance).WieldedSlot != 8 && BigPickupUtil.IsTargetCarried() && (Input.GetKeyDown((KeyCode)56) || Input.GetKeyDown((KeyCode)264)) && Clock.Time > __instance.m_itemScrollTimer)
			{
				ForceWieldSlot(__instance, (InventorySlot)8);
				__instance.m_itemScrollTimer = Clock.Time + 0.1f;
			}
		}
	}
	[HarmonyPatch(typeof(PLOC_Base))]
	internal class Patch_PLOC_State
	{
		[HarmonyPatch("GetHorizontalVelocityFromInput")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void PLOC_Base__GetHorizontalVelocityFromInput__Postfix(PLOC_Base __instance, ref Vector3 __result)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Invalid comparison between Unknown and I4
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (BigPickupUtil.EnableOverride() && __instance.m_owner.Owner.IsLocal && BigPickupUtil.IsTargetCarried() && (int)__instance.m_owner.Inventory.WieldedSlot != 8)
			{
				__result *= 0.7f;
			}
		}
	}
}
namespace BigPickupCarryOnBack
{
	[BepInPlugin("BigPickupCarryOnBack", "BigPickupCarryOnBack", "1.0.0")]
	internal class EntryPoint : BasePlugin
	{
		public static EntryPoint Instance;

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			Instance = this;
			m_Harmony = new Harmony("BigPickupCarryOnBack");
			m_Harmony.PatchAll();
		}
	}
}

plugins/XiaoTian-SURVIVAL/SURVIVAL/Custom/net6/Endlessinferno.plugins.dll

Decompiled 2 weeks ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using GameData;
using Gear;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Player;

[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("weapon")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("weapon")]
[assembly: AssemblyTitle("weapon")]
[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 Interference_Weapon
{
	[HarmonyPatch(typeof(BulletWeapon))]
	internal static class Inject_BulletWeapon
	{
		[HarmonyPostfix]
		[HarmonyPatch("UpdateAmmoStatus")]
		private static void Post_UpdateAmmoStatus(BulletWeapon __instance)
		{
			DoReload(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("OnWield")]
		private static void Post_Wield(BulletWeapon __instance)
		{
			DoReload(__instance);
		}

		private static void DoReload(BulletWeapon weapon)
		{
			if (weapon.m_clip == 0 && (((GameDataBlockBase<ItemDataBlock>)(object)((Item)weapon).ItemDataBlock).persistentID == 5001 || ((GameDataBlockBase<ItemDataBlock>)(object)((Item)weapon).ItemDataBlock).persistentID == 5005))
			{
				((Item)weapon).Owner.Inventory.DoReload();
			}
			else if (weapon.m_clip == 0 && (((GameDataBlockBase<ItemDataBlock>)(object)((Item)weapon).ItemDataBlock).persistentID == 5002 || ((GameDataBlockBase<ItemDataBlock>)(object)((Item)weapon).ItemDataBlock).persistentID == 5003) && ((PlayerInventoryBase)((Weapon)weapon).m_inventory).CanReloadCurrent())
			{
				((ItemEquippable)weapon).TryTriggerReloadAnimationSequence();
				if (((Item)weapon).Owner.Locomotion.IsRunning)
				{
					((Item)weapon).Owner.Locomotion.ChangeState((PLOC_State)0, false);
				}
			}
		}
	}
	[BepInPlugin("Yoake.Endlessinferno-Weapon", "Plugin for Endlessinferno Weaponpack", "1.1.0.0")]
	[BepInProcess("GTFO.exe")]
	public class EntryPoint : BasePlugin
	{
		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			new Harmony("Interference.Weapon.Harmony").PatchAll();
		}
	}
}

plugins/XiaoTian-SURVIVAL/SURVIVAL/Custom/net6/Inas07.ExtraObjectiveSetup.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using AIGraph;
using AK;
using Agents;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using ChainedPuzzles;
using Enemies;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.BaseClasses.CustomTerminalDefinition;
using ExtraObjectiveSetup.Expedition;
using ExtraObjectiveSetup.Expedition.Gears;
using ExtraObjectiveSetup.Expedition.IndividualGeneratorGroup;
using ExtraObjectiveSetup.ExtendedWardenEvents;
using ExtraObjectiveSetup.Instances;
using ExtraObjectiveSetup.Instances.ChainedPuzzle;
using ExtraObjectiveSetup.JSON;
using ExtraObjectiveSetup.JSON.Extensions;
using ExtraObjectiveSetup.JSON.MTFOPartialData;
using ExtraObjectiveSetup.JSON.PData;
using ExtraObjectiveSetup.Objectives.ActivateSmallHSU;
using ExtraObjectiveSetup.Objectives.GeneratorCluster;
using ExtraObjectiveSetup.Objectives.IndividualGenerator;
using ExtraObjectiveSetup.Objectives.ObjectiveCounter;
using ExtraObjectiveSetup.Objectives.TerminalUplink;
using ExtraObjectiveSetup.Tweaks.BossEvents;
using ExtraObjectiveSetup.Tweaks.Scout;
using ExtraObjectiveSetup.Tweaks.TerminalPosition;
using ExtraObjectiveSetup.Tweaks.TerminalTweak;
using ExtraObjectiveSetup.Utils;
using FloLib.Networks.Replications;
using GTFO.API;
using GTFO.API.Extensions;
using GTFO.API.JSON.Converters;
using GTFO.API.Utilities;
using GameData;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using StateMachines;
using UnityEngine;

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

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ExtraObjectiveSetup
{
	public static class EOSNetworking
	{
		public const uint INVALID_ID = 0u;

		public const uint FOREVER_REPLICATOR_ID_START = 1000u;

		public const uint REPLICATOR_ID_START = 10000u;

		private static uint currentForeverID;

		private static uint currentID;

		private static HashSet<uint> foreverUsedIDs;

		private static HashSet<uint> usedIDs;

		public static uint AllotReplicatorID()
		{
			while (currentID >= 10000 && usedIDs.Contains(currentID))
			{
				currentID++;
			}
			if (currentID < 10000)
			{
				EOSLogger.Error("Replicator ID depleted. How?");
				return 0u;
			}
			uint num = currentID;
			usedIDs.Add(num);
			currentID++;
			return num;
		}

		public static bool TryAllotID(uint id)
		{
			return usedIDs.Add(id);
		}

		public static uint AllotForeverReplicatorID()
		{
			while (currentForeverID < 10000 && foreverUsedIDs.Contains(currentForeverID))
			{
				currentForeverID++;
			}
			if (currentForeverID >= 10000)
			{
				EOSLogger.Error("Forever Replicator ID depleted.");
				return 0u;
			}
			uint num = currentForeverID;
			foreverUsedIDs.Add(num);
			currentForeverID++;
			return num;
		}

		private static void Clear()
		{
			usedIDs.Clear();
			currentID = 10000u;
		}

		public static void ClearForever()
		{
			foreverUsedIDs.Clear();
			currentForeverID = 1000u;
		}

		static EOSNetworking()
		{
			currentForeverID = 1000u;
			currentID = 10000u;
			foreverUsedIDs = new HashSet<uint>();
			usedIDs = new HashSet<uint>();
			LevelAPI.OnBuildStart += Clear;
			LevelAPI.OnLevelCleanup += Clear;
		}
	}
	public sealed class BatchBuildManager
	{
		private Dictionary<BatchName, Action> OnBatchStart = new Dictionary<BatchName, Action>();

		private Dictionary<BatchName, Action> OnBatchDone = new Dictionary<BatchName, Action>();

		public static BatchBuildManager Current { get; private set; }

		public void Init()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			if (OnBatchStart.Count < 1)
			{
				foreach (object value in Enum.GetValues(typeof(BatchName)))
				{
					OnBatchStart[(BatchName)value] = null;
				}
			}
			if (OnBatchDone.Count >= 1)
			{
				return;
			}
			foreach (object value2 in Enum.GetValues(typeof(BatchName)))
			{
				OnBatchDone[(BatchName)value2] = null;
			}
		}

		public void Add_OnBatchDone(BatchName batchName, Action action)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<BatchName, Action> onBatchDone = OnBatchDone;
			onBatchDone[batchName] = (Action)Delegate.Combine(onBatchDone[batchName], action);
		}

		public void Remove_OnBatchDone(BatchName batchName, Action action)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<BatchName, Action> onBatchDone = OnBatchDone;
			onBatchDone[batchName] = (Action)Delegate.Remove(onBatchDone[batchName], action);
		}

		public Action Get_OnBatchDone(BatchName batchName)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return OnBatchDone[batchName];
		}

		public void Add_OnBatchStart(BatchName batchName, Action action)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<BatchName, Action> onBatchStart = OnBatchStart;
			onBatchStart[batchName] = (Action)Delegate.Combine(onBatchStart[batchName], action);
		}

		public void Remove_OnBatchStart(BatchName batchName, Action action)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<BatchName, Action> onBatchStart = OnBatchStart;
			onBatchStart[batchName] = (Action)Delegate.Remove(onBatchStart[batchName], action);
		}

		public Action Get_OnBatchStart(BatchName batchName)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return OnBatchStart[batchName];
		}

		private BatchBuildManager()
		{
		}

		static BatchBuildManager()
		{
			Current = new BatchBuildManager();
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Inas.ExtraObjectiveSetup", "ExtraObjectiveSetup", "100.0.0")]
	[BepInIncompatibility("Amor.ExcellentObjectiveSetup")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas";

		public const string PLUGIN_NAME = "ExtraObjectiveSetup";

		public const string VERSION = "100.0.0";

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			m_Harmony = new Harmony("ExtraObjectiveSetup");
			m_Harmony.PatchAll();
			SetupManagers();
		}

		private void SetupManagers()
		{
			BatchBuildManager.Current.Init();
			IndividualGeneratorObjectiveManager.Current.Init();
			GeneratorClusterObjectiveManager.Current.Init();
			HSUActivatorObjectiveManager.Current.Init();
			UplinkObjectiveManager.Current.Init();
			TerminalPositionOverrideManager.Current.Init();
			ScoutScreamEventManager.Current.Init();
			BossDeathEventManager.Current.Init();
			ExpeditionDefinitionManager.Current.Init();
			ExpeditionGearManager.Current.Init();
			ExpeditionIGGroupManager.Current.Init();
			GeneratorClusterInstanceManager.Current.Init();
			HSUActivatorInstanceManager.Current.Init();
			PowerGeneratorInstanceManager.Current.Init();
			TerminalInstanceManager.Current.Init();
			ObjectiveCounterManager.Current.Init();
		}
	}
}
namespace ExtraObjectiveSetup.Utils
{
	public static class EOSTerminalUtils
	{
		public static List<LG_ComputerTerminal> FindTerminal(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, Predicate<LG_ComputerTerminal> predicate)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = default(LG_Zone);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, localIndex, ref val) || (Object)(object)val == (Object)null)
			{
				EOSLogger.Error($"SelectTerminal: Could NOT find zone {(dimensionIndex, layerType, localIndex)}");
				return null;
			}
			if (val.TerminalsSpawnedInZone.Count <= 0)
			{
				EOSLogger.Error($"SelectTerminal: Could not find any terminals in zone {(dimensionIndex, layerType, localIndex)}");
				return null;
			}
			List<LG_ComputerTerminal> list = new List<LG_ComputerTerminal>();
			Enumerator<LG_ComputerTerminal> enumerator = val.TerminalsSpawnedInZone.GetEnumerator();
			while (enumerator.MoveNext())
			{
				LG_ComputerTerminal current = enumerator.Current;
				if (predicate != null)
				{
					if (predicate(current))
					{
						list.Add(current);
					}
				}
				else
				{
					list.Add(current);
				}
			}
			return list;
		}

		public static TerminalLogFileData GetLocalLog(this LG_ComputerTerminal terminal, string logName)
		{
			Dictionary<string, TerminalLogFileData> localLogs = terminal.GetLocalLogs();
			logName = logName.ToUpperInvariant();
			return localLogs.ContainsKey(logName) ? localLogs[logName] : null;
		}

		public static void ResetInitialOutput(this LG_ComputerTerminal terminal)
		{
			terminal.m_command.ClearOutputQueueAndScreenBuffer();
			terminal.m_command.AddInitialTerminalOutput();
			if (terminal.IsPasswordProtected)
			{
				terminal.m_command.AddPasswordProtectedOutput((Il2CppStringArray)null);
			}
		}

		public static List<WardenObjectiveEventData> GetUniqueCommandEvents(this LG_ComputerTerminal terminal, string command)
		{
			List<WardenObjectiveEventData> result = new List<WardenObjectiveEventData>();
			if ((Object)(object)terminal.ConnectedReactor != (Object)null)
			{
				return result;
			}
			List<LG_ComputerTerminal> terminalsSpawnedInZone = terminal.SpawnNode.m_zone.TerminalsSpawnedInZone;
			int num = terminalsSpawnedInZone.IndexOf(terminal);
			AIG_CourseNode spawnNode = terminal.SpawnNode;
			ExpeditionZoneData val = ((spawnNode != null) ? spawnNode.m_zone.m_settings.m_zoneData : null) ?? null;
			if (val == null)
			{
				EOSLogger.Error("GetCommandEvents: Cannot find target zone data.");
				return result;
			}
			if (num < 0 || num >= val.TerminalPlacements.Count)
			{
				EOSLogger.Debug($"GetCommandEvents: TerminalDataIndex({num}), TargetZoneData.TerminalPlacements.Count == ({val.TerminalPlacements.Count}) - maybe a custom terminal, skipped");
				return result;
			}
			List<CustomTerminalCommand> uniqueCommands = val.TerminalPlacements[num].UniqueCommands;
			Enumerator<CustomTerminalCommand> enumerator = uniqueCommands.GetEnumerator();
			while (enumerator.MoveNext())
			{
				CustomTerminalCommand current = enumerator.Current;
				if (current.Command.ToLower().Equals(command.ToLower()))
				{
					return current.CommandEvents.ToManaged<WardenObjectiveEventData>();
				}
			}
			EOSLogger.Error("GetCommandEvents: command '" + command + "' not found on " + terminal.ItemKey);
			return result;
		}

		public static LG_ComputerTerminal SelectPasswordTerminal(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, eSeedType seedType, int staticSeed = 1)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Expected I4, but got Unknown
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			if ((int)seedType == 0)
			{
				EOSLogger.Error($"SelectTerminal: unsupported seed type {seedType}");
				return null;
			}
			List<LG_ComputerTerminal> list = FindTerminal(dimensionIndex, layerType, localIndex, (LG_ComputerTerminal x) => !x.HasPasswordPart);
			if (list == null)
			{
				EOSLogger.Error($"SelectTerminal: Could not find zone {(dimensionIndex, layerType, localIndex)}!");
				return null;
			}
			if (list.Count <= 0)
			{
				EOSLogger.Error($"SelectTerminal: Could not find any terminals without a password part in zone {(dimensionIndex, layerType, localIndex)}, putting the password on random (session) already used terminal.");
				LG_Zone val = default(LG_Zone);
				Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, localIndex, ref val);
				return val.TerminalsSpawnedInZone[Builder.SessionSeedRandom.Range(0, val.TerminalsSpawnedInZone.Count, "NO_TAG")];
			}
			switch (seedType - 1)
			{
			case 0:
				return list[Builder.SessionSeedRandom.Range(0, list.Count, "NO_TAG")];
			case 1:
				return list[Builder.BuildSeedRandom.Range(0, list.Count, "NO_TAG")];
			case 2:
				Random.InitState(staticSeed);
				return list[Random.Range(0, list.Count)];
			default:
				EOSLogger.Error("SelectTerminal: did not have a valid SeedType!!");
				return null;
			}
		}

		public static void BuildPassword(LG_ComputerTerminal terminal, TerminalPasswordData data)
		{
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Invalid comparison between Unknown and I4
			//IL_0350: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_035e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04da: Unknown result type (might be due to invalid IL or missing references)
			//IL_054d: Unknown result type (might be due to invalid IL or missing references)
			//IL_054e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0553: Unknown result type (might be due to invalid IL or missing references)
			//IL_0576: Unknown result type (might be due to invalid IL or missing references)
			//IL_0583: Expected O, but got Unknown
			//IL_0586: Expected O, but got Unknown
			if (!data.PasswordProtected)
			{
				return;
			}
			if (terminal.IsPasswordProtected)
			{
				EOSLogger.Error("EOSTerminalUtils.BuildPassword: " + terminal.PublicName + " is already password-protected!");
				return;
			}
			if (!data.GeneratePassword)
			{
				terminal.LockWithPassword(data.Password, new string[1] { data.PasswordHintText });
				return;
			}
			if (data.TerminalZoneSelectionDatas.Count <= 0)
			{
				EOSLogger.Error($"Tried to generate a password for terminal {terminal.PublicName} with no {typeof(TerminalZoneSelectionData).Name}!! This is not allowed.");
				return;
			}
			string codeWord = SerialGenerator.GetCodeWord();
			string passwordHintText = data.PasswordHintText;
			string text = "<b>[Forgot your password?]</b> Backup security key(s) located in logs on ";
			int num = data.PasswordPartCount;
			if (codeWord.Length % num != 0)
			{
				EOSLogger.Error($"Build() password.Length ({codeWord.Length}) not divisible by passwordParts ({num}). Defaulting to 1.");
				num = 1;
			}
			string[] array = ((num > 1) ? Il2CppArrayBase<string>.op_Implicit((Il2CppArrayBase<string>)(object)StringUtils.SplitIntoChunksArray(codeWord, codeWord.Length / num)) : new string[1] { codeWord });
			string text2 = "";
			if (data.ShowPasswordPartPositions)
			{
				for (int i = 0; i < array[0].Length; i++)
				{
					text2 += "-";
				}
			}
			HashSet<LG_ComputerTerminal> hashSet = new HashSet<LG_ComputerTerminal>();
			LG_Zone val = default(LG_Zone);
			for (int j = 0; j < num; j++)
			{
				int index = j % data.TerminalZoneSelectionDatas.Count;
				List<CustomTerminalZoneSelectionData> list = data.TerminalZoneSelectionDatas[index];
				int index2 = Builder.SessionSeedRandom.Range(0, list.Count, "NO_TAG");
				CustomTerminalZoneSelectionData customTerminalZoneSelectionData = list[index2];
				LG_ComputerTerminal val2;
				if ((int)customTerminalZoneSelectionData.SeedType == 0)
				{
					if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(customTerminalZoneSelectionData.DimensionIndex, customTerminalZoneSelectionData.LayerType, customTerminalZoneSelectionData.LocalIndex, ref val) || (Object)(object)val == (Object)null)
					{
						EOSLogger.Error($"BuildPassword: seedType {0} specified but cannot find zone {customTerminalZoneSelectionData.GlobalZoneIndexTuple()}");
					}
					if (val.TerminalsSpawnedInZone.Count <= 0)
					{
						EOSLogger.Error($"BuildPassword: seedType {0} specified but cannot find terminal zone {customTerminalZoneSelectionData.GlobalZoneIndexTuple()}");
					}
					val2 = val.TerminalsSpawnedInZone[customTerminalZoneSelectionData.TerminalIndex];
				}
				else
				{
					val2 = SelectPasswordTerminal(customTerminalZoneSelectionData.DimensionIndex, customTerminalZoneSelectionData.LayerType, customTerminalZoneSelectionData.LocalIndex, customTerminalZoneSelectionData.SeedType);
				}
				if ((Object)(object)val2 == (Object)null)
				{
					EOSLogger.Error($"BuildPassword: CRITICAL ERROR, could not get a LG_ComputerTerminal for password part ({j + 1}/{num}) for {terminal.PublicName} backup log.");
					continue;
				}
				string text3 = "";
				string text4;
				if (data.ShowPasswordPartPositions)
				{
					for (int k = 0; k < j; k++)
					{
						text3 += text2;
					}
					text4 = text3 + array[j];
					for (int l = j; l < num - 1; l++)
					{
						text4 += text2;
					}
				}
				else
				{
					text4 = array[j];
				}
				string value = (data.ShowPasswordPartPositions ? $"0{j + 1}" : $"0{Builder.SessionSeedRandom.Range(0, 9, "NO_TAG")}");
				TerminalLogFileData val3 = new TerminalLogFileData
				{
					FileName = $"key{value}_{LG_TerminalPasswordLinkerJob.GetTerminalNumber(terminal)}{(val2.HasPasswordPart ? "_1" : "")}.LOG",
					FileContent = new LocalizedText
					{
						UntranslatedText = string.Format(Text.Get((num > 1) ? 1431221909u : 2260297836u), text4),
						Id = 0u
					}
				};
				val2.AddLocalLog(val3, true);
				if (!hashSet.Contains(val2))
				{
					if (j > 0)
					{
						text += ", ";
					}
					text = text + val2.PublicName + " in " + val2.SpawnNode.m_zone.AliasName;
				}
				hashSet.Add(val2);
				val2.HasPasswordPart = true;
			}
			string text5 = text + ".";
			if (data.ShowPasswordLength)
			{
				terminal.LockWithPassword(codeWord, new string[3]
				{
					passwordHintText,
					text5,
					"Char[" + codeWord.Length + "]"
				});
			}
			else
			{
				terminal.LockWithPassword(codeWord, new string[2] { passwordHintText, text5 });
			}
		}

		public static void AddUniqueCommand(LG_ComputerTerminal terminal, CustomCommand cmd)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			if (terminal.m_command.m_commandsPerString.ContainsKey(cmd.Command))
			{
				EOSLogger.Error("Duplicate command name: '" + cmd.Command + "', cannot add command");
				return;
			}
			TERM_Command val = default(TERM_Command);
			if (!terminal.m_command.TryGetUniqueCommandSlot(ref val))
			{
				EOSLogger.Error("Cannot get more unique command slot, max: 5");
				return;
			}
			terminal.m_command.AddCommand(val, cmd.Command, cmd.CommandDesc, cmd.SpecialCommandRule, ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(cmd.CommandEvents), ListExtensions.ToIl2Cpp<TerminalOutput>(cmd.PostCommandOutputs));
			for (int i = 0; i < cmd.CommandEvents.Count; i++)
			{
				WardenObjectiveEventData val2 = cmd.CommandEvents[i];
				if (val2.ChainPuzzle == 0)
				{
					continue;
				}
				ChainedPuzzleDataBlock block = GameDataBlockBase<ChainedPuzzleDataBlock>.GetBlock(val2.ChainPuzzle);
				if (block == null)
				{
					continue;
				}
				LG_Area val3;
				Transform val4;
				if (terminal.SpawnNode != null)
				{
					val3 = terminal.SpawnNode.m_area;
					val4 = terminal.m_wardenObjectiveSecurityScanAlign;
				}
				else
				{
					LG_WardenObjective_Reactor connectedReactor = terminal.ConnectedReactor;
					object obj;
					if (connectedReactor == null)
					{
						obj = null;
					}
					else
					{
						AIG_CourseNode spawnNode = connectedReactor.SpawnNode;
						obj = ((spawnNode != null) ? spawnNode.m_area : null);
					}
					if (obj == null)
					{
						obj = null;
					}
					val3 = (LG_Area)obj;
					LG_WardenObjective_Reactor connectedReactor2 = terminal.ConnectedReactor;
					val4 = ((connectedReactor2 != null) ? connectedReactor2.m_chainedPuzzleAlign : null) ?? null;
				}
				if ((Object)(object)val3 == (Object)null)
				{
					EOSLogger.Error("Terminal Source Area is not found! Cannot create chained puzzle for command " + cmd.Command + "!");
					continue;
				}
				ChainedPuzzleInstance val5 = ChainedPuzzleManager.CreatePuzzleInstance(block, val3, val4.position, val4, val2.UseStaticBioscanPoints);
				List<WardenObjectiveEventData> events = ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(cmd.CommandEvents.GetRange(i, cmd.CommandEvents.Count - i));
				val5.OnPuzzleSolved += Action.op_Implicit((Action)delegate
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(events, (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
				});
				terminal.SetChainPuzzleForCommand(val, i, val5);
			}
		}
	}
	public static class EOSUtils
	{
		public static List<T> ToManaged<T>(this List<T> il2cppList)
		{
			List<T> list = new List<T>();
			Enumerator<T> enumerator = il2cppList.GetEnumerator();
			while (enumerator.MoveNext())
			{
				T current = enumerator.Current;
				list.Add(current);
			}
			return list;
		}

		public static void ResetProgress(this ChainedPuzzleInstance chainedPuzzle)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: 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_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			if (chainedPuzzle.Data.DisableSurvivalWaveOnComplete)
			{
				chainedPuzzle.m_sound = new CellSoundPlayer(chainedPuzzle.m_parent.position);
			}
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)chainedPuzzle.m_chainedPuzzleCores)
			{
				ResetChild(item);
			}
			if (SNet.IsMaster)
			{
				pChainedPuzzleState state = chainedPuzzle.m_stateReplicator.State;
				pChainedPuzzleState val = default(pChainedPuzzleState);
				val.status = (eChainedPuzzleStatus)0;
				val.currentSurvivalWave_EventID = state.currentSurvivalWave_EventID;
				val.isSolved = false;
				val.isActive = false;
				pChainedPuzzleState val2 = val;
				chainedPuzzle.m_stateReplicator.InteractWithState(val2, new pChainedPuzzleInteraction
				{
					type = (eChainedPuzzleInteraction)2
				});
			}
			static void ResetChild(iChainedPuzzleCore ICore)
			{
				CP_Bioscan_Core val3 = ((Il2CppObjectBase)ICore).TryCast<CP_Bioscan_Core>();
				if ((Object)(object)val3 != (Object)null)
				{
					CP_Holopath_Spline val4 = ((Il2CppObjectBase)val3.m_spline).Cast<CP_Holopath_Spline>();
					CP_PlayerScanner val5 = ((Il2CppObjectBase)val3.PlayerScanner).Cast<CP_PlayerScanner>();
					val5.ResetScanProgression(0f);
					val3.Deactivate();
				}
				else
				{
					CP_Cluster_Core val6 = ((Il2CppObjectBase)ICore).TryCast<CP_Cluster_Core>();
					if ((Object)(object)val6 == (Object)null)
					{
						EOSLogger.Error("ResetChild: found iChainedPuzzleCore that is neither CP_Bioscan_Core nor CP_Cluster_Core...");
					}
					else
					{
						CP_Holopath_Spline val7 = ((Il2CppObjectBase)val6.m_spline).Cast<CP_Holopath_Spline>();
						foreach (iChainedPuzzleCore item2 in (Il2CppArrayBase<iChainedPuzzleCore>)(object)val6.m_childCores)
						{
							ResetChild(item2);
						}
						val6.Deactivate();
					}
				}
			}
		}
	}
	public class EOSColor
	{
		public float r { get; set; }

		public float g { get; set; }

		public float b { get; set; }

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


		public Color ToUnityColor()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			return new Color(r, g, b, a);
		}
	}
	public static class VanillaTMPPros
	{
		public const string VANILLA_CP_PREFAB_PATH = "Assets/AssetPrefabs/Complex/Generic/ChainedPuzzles/CP_Bioscan_sustained_RequireAll.prefab";

		public static GameObject Instantiate(GameObject parent = null)
		{
			GameObject loadedAsset = AssetAPI.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/Complex/Generic/ChainedPuzzles/CP_Bioscan_sustained_RequireAll.prefab");
			if ((Object)(object)loadedAsset == (Object)null)
			{
				EOSLogger.Error("VanillaTMPPros.Instantiate: Cannot find TMPPro from vanilla CP!");
				return null;
			}
			GameObject gameObject = ((Component)loadedAsset.transform.GetChild(0).GetChild(1).GetChild(0)).gameObject;
			return ((Object)(object)parent != (Object)null) ? Object.Instantiate<GameObject>(gameObject.gameObject, parent.transform) : Object.Instantiate<GameObject>(gameObject.gameObject);
		}
	}
	public class Vec4 : Vec3
	{
		[JsonPropertyOrder(-9)]
		public float w { get; set; } = 0f;


		public Vector4 ToVector4()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			return new Vector4(base.x, base.y, base.z, w);
		}
	}
	public class Vec3
	{
		[JsonPropertyOrder(-10)]
		public float x { get; set; }

		[JsonPropertyOrder(-10)]
		public float y { get; set; }

		[JsonPropertyOrder(-10)]
		public float z { get; set; }

		public Vector3 ToVector3()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(x, y, z);
		}

		public Quaternion ToQuaternion()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return Quaternion.Euler(x, y, z);
		}
	}
	public static class EOSLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("ExtraObjectiveSetup");

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

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

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

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

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

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

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

		public static void Debug(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)32, (object)str);
			}
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.TerminalTweak
{
	public struct TerminalState
	{
		public bool Enabled;

		public TerminalState()
		{
			Enabled = true;
		}

		public TerminalState(bool Enabled)
		{
			this.Enabled = true;
			this.Enabled = Enabled;
		}

		public TerminalState(TerminalState o)
		{
			Enabled = true;
			Enabled = o.Enabled;
		}
	}
	public class TerminalWrapper
	{
		public LG_ComputerTerminal lgTerminal { get; private set; }

		public StateReplicator<TerminalState> stateReplicator { get; private set; }

		private void ChangeStateUnsynced(bool enabled)
		{
			EOSLogger.Debug($"{lgTerminal.ItemKey} state, enabled: {enabled}");
			lgTerminal.OnProximityExit();
			Interact_ComputerTerminal componentInChildren = ((Component)lgTerminal).GetComponentInChildren<Interact_ComputerTerminal>(true);
			bool flag = enabled;
			if ((Object)(object)componentInChildren != (Object)null)
			{
				((Behaviour)componentInChildren).enabled = flag;
				((Interact_Base)componentInChildren).SetActive(flag);
			}
			lgTerminal.m_interfaceScreen.SetActive(flag);
			lgTerminal.m_loginScreen.SetActive(flag);
			if ((Object)(object)lgTerminal.m_text != (Object)null)
			{
				((Behaviour)lgTerminal.m_text).enabled = flag;
			}
			if (!flag)
			{
				PlayerAgent localInteractionSource = lgTerminal.m_localInteractionSource;
				if ((Object)(object)localInteractionSource != (Object)null && localInteractionSource.FPItemHolder.InTerminalTrigger)
				{
					lgTerminal.ExitFPSView();
				}
			}
		}

		public void ChangeState(bool enabled)
		{
			ChangeStateUnsynced(enabled);
			if (SNet.IsMaster)
			{
				stateReplicator.SetState(new TerminalState
				{
					Enabled = enabled
				});
			}
		}

		private void OnStateChanged(TerminalState oldState, TerminalState newState, bool isRecall)
		{
			if (isRecall)
			{
				ChangeStateUnsynced(newState.Enabled);
			}
		}

		public static TerminalWrapper Instantiate(LG_ComputerTerminal lgTerminal, uint replicatorID)
		{
			if ((Object)(object)lgTerminal == (Object)null || replicatorID == 0)
			{
				return null;
			}
			TerminalWrapper terminalWrapper = new TerminalWrapper();
			terminalWrapper.lgTerminal = lgTerminal;
			terminalWrapper.stateReplicator = StateReplicator<TerminalState>.Create(replicatorID, new TerminalState
			{
				Enabled = true
			}, (LifeTimeType)1, (IStateReplicatorHolder<TerminalState>)null);
			terminalWrapper.stateReplicator.OnStateChanged += terminalWrapper.OnStateChanged;
			return terminalWrapper;
		}

		private TerminalWrapper()
		{
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.TerminalPosition
{
	public class TerminalPosition : BaseInstanceDefinition
	{
		public Vec3 Position { get; set; } = new Vec3();


		public Vec3 Rotation { get; set; } = new Vec3();

	}
	internal class TerminalPositionOverrideManager : InstanceDefinitionManager<TerminalPosition>
	{
		public static TerminalPositionOverrideManager Current;

		protected override string DEFINITION_NAME => "TerminalPosition";

		private TerminalPositionOverrideManager()
		{
		}

		static TerminalPositionOverrideManager()
		{
			Current = new TerminalPositionOverrideManager();
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.Scout
{
	public class EventsOnZoneScoutScream : GlobalZoneIndex
	{
		public bool SuppressVanillaScoutWave { get; set; } = false;


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

	}
	internal class ScoutScreamEventManager : ZoneDefinitionManager<EventsOnZoneScoutScream>
	{
		public static ScoutScreamEventManager Current;

		protected override string DEFINITION_NAME => "EventsOnScoutScream";

		private ScoutScreamEventManager()
		{
		}

		static ScoutScreamEventManager()
		{
			Current = new ScoutScreamEventManager();
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.BossEvents
{
	public struct FiniteBDEState
	{
		public int ApplyToHibernateCount;

		public int ApplyToWaveCount;

		public FiniteBDEState()
		{
			ApplyToHibernateCount = int.MaxValue;
			ApplyToWaveCount = int.MaxValue;
		}

		public FiniteBDEState(FiniteBDEState other)
		{
			ApplyToHibernateCount = int.MaxValue;
			ApplyToWaveCount = int.MaxValue;
			ApplyToHibernateCount = other.ApplyToHibernateCount;
			ApplyToHibernateCount = other.ApplyToWaveCount;
		}

		public FiniteBDEState(int ApplyToHibernateCount, int ApplyToWaveCount)
		{
			this.ApplyToHibernateCount = int.MaxValue;
			this.ApplyToWaveCount = int.MaxValue;
			this.ApplyToHibernateCount = ApplyToHibernateCount;
			this.ApplyToWaveCount = ApplyToWaveCount;
		}
	}
	public class EventsOnZoneBossDeath : GlobalZoneIndex
	{
		public bool ApplyToHibernate { get; set; } = true;


		public int ApplyToHibernateCount { get; set; } = int.MaxValue;


		public bool ApplyToWave { get; set; } = false;


		public int ApplyToWaveCount { get; set; } = int.MaxValue;


		public List<uint> BossIDs { get; set; } = new List<uint> { 29u, 36u, 37u };


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


		[JsonIgnore]
		public StateReplicator<FiniteBDEState> FiniteBDEStateReplicator { get; private set; } = null;


		[JsonIgnore]
		public int RemainingWaveBDE => (FiniteBDEStateReplicator != null) ? FiniteBDEStateReplicator.State.ApplyToWaveCount : ApplyToWaveCount;

		[JsonIgnore]
		public int RemainingHibernateBDE => (FiniteBDEStateReplicator != null) ? FiniteBDEStateReplicator.State.ApplyToHibernateCount : ApplyToHibernateCount;

		public void SetupReplicator(uint replicatorID)
		{
			if (ApplyToHibernateCount != int.MaxValue || ApplyToWaveCount != int.MaxValue)
			{
				FiniteBDEStateReplicator = StateReplicator<FiniteBDEState>.Create(replicatorID, new FiniteBDEState
				{
					ApplyToHibernateCount = ApplyToHibernateCount,
					ApplyToWaveCount = ApplyToWaveCount
				}, (LifeTimeType)1, (IStateReplicatorHolder<FiniteBDEState>)null);
				FiniteBDEStateReplicator.OnStateChanged += OnStateChanged;
			}
		}

		private void OnStateChanged(FiniteBDEState oldState, FiniteBDEState newState, bool isRecall)
		{
		}

		internal void Destroy()
		{
			FiniteBDEStateReplicator = null;
		}
	}
	internal class BossDeathEventManager : ZoneDefinitionManager<EventsOnZoneBossDeath>
	{
		public enum Mode
		{
			HIBERNATE,
			WAVE
		}

		public static BossDeathEventManager Current;

		public const int UNLIMITED_COUNT = int.MaxValue;

		private ConcurrentDictionary<(eDimensionIndex, LG_LayerType, eLocalZoneIndex), EventsOnZoneBossDeath> LevelBDEs { get; } = new ConcurrentDictionary<(eDimensionIndex, LG_LayerType, eLocalZoneIndex), EventsOnZoneBossDeath>();


		protected override string DEFINITION_NAME => "EventsOnBossDeath";

		public bool TryConsumeBDEventsExecutionTimes(EventsOnZoneBossDeath def, Mode mode)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			return TryConsumeBDEventsExecutionTimes(def.DimensionIndex, def.LayerType, def.LocalIndex, mode);
		}

		public bool TryConsumeBDEventsExecutionTimes(eDimensionIndex dimensionIndex, LG_LayerType layer, eLocalZoneIndex localIndex, Mode mode)
		{
			//IL_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_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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (!LevelBDEs.ContainsKey((dimensionIndex, layer, localIndex)))
			{
				EOSLogger.Error($"BossDeathEventManager: got an unregistered entry: {(dimensionIndex, layer, localIndex, mode)}");
				return false;
			}
			EventsOnZoneBossDeath eventsOnZoneBossDeath = LevelBDEs[(dimensionIndex, layer, localIndex)];
			int num = ((mode == Mode.HIBERNATE) ? eventsOnZoneBossDeath.RemainingHibernateBDE : eventsOnZoneBossDeath.RemainingWaveBDE);
			if (num == int.MaxValue)
			{
				return true;
			}
			if (num > 0)
			{
				FiniteBDEState state = eventsOnZoneBossDeath.FiniteBDEStateReplicator.State;
				if (SNet.IsMaster)
				{
					eventsOnZoneBossDeath.FiniteBDEStateReplicator.SetState(new FiniteBDEState
					{
						ApplyToHibernateCount = ((mode == Mode.HIBERNATE) ? (num - 1) : state.ApplyToHibernateCount),
						ApplyToWaveCount = ((mode == Mode.WAVE) ? (num - 1) : state.ApplyToWaveCount)
					});
				}
				return true;
			}
			return false;
		}

		private void Clear()
		{
			foreach (EventsOnZoneBossDeath value in LevelBDEs.Values)
			{
				value.Destroy();
			}
			LevelBDEs.Clear();
		}

		private void SetupForCurrentExpedition()
		{
			if (!definitions.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData))
			{
				return;
			}
			foreach (EventsOnZoneBossDeath definition in definitions[RundownManager.ActiveExpedition.LevelLayoutData].Definitions)
			{
				if (LevelBDEs.ContainsKey(definition.GlobalZoneIndexTuple()))
				{
					EOSLogger.Error($"BossDeathEvent: found duplicate setup for zone {definition.GlobalZoneIndexTuple()}, will overwrite!");
				}
				if (definition.ApplyToHibernateCount != int.MaxValue || definition.ApplyToWaveCount != int.MaxValue)
				{
					uint num = EOSNetworking.AllotReplicatorID();
					if (num != 0)
					{
						definition.SetupReplicator(num);
					}
					else
					{
						EOSLogger.Error("BossDeathEvent: replicator ID depleted, cannot setup replicator!");
					}
				}
				LevelBDEs[definition.GlobalZoneIndexTuple()] = definition;
			}
		}

		private BossDeathEventManager()
		{
			LevelAPI.OnBuildStart += delegate
			{
				Clear();
				SetupForCurrentExpedition();
			};
			LevelAPI.OnLevelCleanup += Clear;
		}

		static BossDeathEventManager()
		{
			Current = new BossDeathEventManager();
		}
	}
}
namespace ExtraObjectiveSetup.Patches
{
	[HarmonyPatch]
	internal class Patch_CheckAndExecuteEventsOnTrigger
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(WardenObjectiveManager), "CheckAndExecuteEventsOnTrigger", new Type[]
		{
			typeof(WardenObjectiveEventData),
			typeof(eWardenObjectiveEventTrigger),
			typeof(bool),
			typeof(float)
		})]
		private static bool Pre_CheckAndExecuteEventsOnTrigger(WardenObjectiveEventData eventToTrigger, eWardenObjectiveEventTrigger trigger, bool ignoreTrigger, float currentDuration)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected I4, but got Unknown
			if (eventToTrigger == null || (!ignoreTrigger && eventToTrigger.Trigger != trigger) || ((double)currentDuration != 0.0 && eventToTrigger.Delay <= currentDuration))
			{
				return true;
			}
			uint num = (uint)(int)eventToTrigger.Type;
			if (!EOSWardenEventManager.Current.HasEventDefinition(num))
			{
				return true;
			}
			string value = (EOSWardenEventManager.Current.IsVanillaEventID(num) ? "overriding vanilla event implementation..." : "executing...");
			EOSLogger.Debug($"WardenEvent: found definition for event ID {num}, {value}");
			EOSWardenEventManager.Current.ExecuteEvent(eventToTrigger, currentDuration);
			return false;
		}
	}
	[HarmonyPatch]
	internal class Patch_EventsOnBossDeath
	{
		private static HashSet<ushort> ExecutedForInstances;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemySync), "OnSpawn")]
		private static void Post_SpawnEnemy(EnemySync __instance, pEnemySpawnData spawnData)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Invalid comparison between Unknown and I4
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Invalid comparison between Unknown and I4
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Invalid comparison between Unknown and I4
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Invalid comparison between Unknown and I4
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			AIG_CourseNode val = default(AIG_CourseNode);
			if (!((pCourseNode)(ref spawnData.courseNode)).TryGet(ref val) || val == null)
			{
				EOSLogger.Error("Failed to get spawnnode for a boss! Skipped EventsOnBossDeath for it");
				return;
			}
			LG_Zone zone = val.m_zone;
			EventsOnZoneBossDeath def = BossDeathEventManager.Current.GetDefinition(zone.DimensionIndex, zone.Layer.m_type, zone.LocalIndex);
			if (def == null)
			{
				return;
			}
			EnemyAgent enemy = __instance.m_agent;
			if (!def.BossIDs.Contains(((GameDataBlockBase<EnemyDataBlock>)(object)enemy.EnemyData).persistentID) || ((((int)spawnData.mode != 4 && (int)spawnData.mode != 3) || !def.ApplyToHibernate) && ((int)spawnData.mode != 1 || !def.ApplyToWave)))
			{
				return;
			}
			BossDeathEventManager.Mode mode = (((int)spawnData.mode != 4) ? BossDeathEventManager.Mode.WAVE : BossDeathEventManager.Mode.HIBERNATE);
			enemy.OnDeadCallback += Action.op_Implicit((Action)delegate
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Invalid comparison between Unknown and I4
				if ((int)GameStateManager.CurrentStateName == 10)
				{
					if (!BossDeathEventManager.Current.TryConsumeBDEventsExecutionTimes(def, mode))
					{
						EOSLogger.Debug($"EventsOnBossDeath: execution times depleted for {def.GlobalZoneIndexTuple()}, {mode}");
					}
					else
					{
						ushort globalID = ((Agent)enemy).GlobalID;
						if (ExecutedForInstances.Contains(globalID))
						{
							ExecutedForInstances.Remove(globalID);
						}
						else
						{
							def.EventsOnBossDeath.ForEach(delegate(WardenObjectiveEventData e)
							{
								WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
							});
							ExecutedForInstances.Add(globalID);
						}
					}
				}
			});
			EOSLogger.Debug($"EventsOnBossDeath: added for enemy with id  {((GameDataBlockBase<EnemyDataBlock>)(object)enemy.EnemyData).persistentID}, mode: {spawnData.mode}");
		}

		static Patch_EventsOnBossDeath()
		{
			ExecutedForInstances = new HashSet<ushort>();
			LevelAPI.OnLevelCleanup += ExecutedForInstances.Clear;
		}
	}
	[HarmonyPatch]
	internal class Patch_EventsOnZoneScoutScream
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(ES_ScoutScream), "CommonUpdate")]
		private static bool Pre_ES_ScoutScream_CommonUpdate(ES_ScoutScream __instance)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Invalid comparison between Unknown and I4
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			EnemyAgent enemyAgent = ((ES_Base)__instance).m_enemyAgent;
			AIG_CourseNode courseNode = ((Agent)enemyAgent).CourseNode;
			EventsOnZoneScoutScream definition = ScoutScreamEventManager.Current.GetDefinition(courseNode.m_dimension.DimensionIndex, courseNode.LayerType, courseNode.m_zone.LocalIndex);
			if (definition == null)
			{
				return true;
			}
			if ((int)__instance.m_state != 3 || __instance.m_stateDoneTimer >= Clock.Time)
			{
				return true;
			}
			if (definition.EventsOnScoutScream != null && definition.EventsOnScoutScream.Count > 0)
			{
				EOSLogger.Debug($"EventsOnZoneScoutScream: found config for {definition.GlobalZoneIndexTuple()}, executing events.");
				definition.EventsOnScoutScream.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
			if (!definition.SuppressVanillaScoutWave)
			{
				if (SNet.IsMaster && ((Agent)((ES_Base)__instance).m_enemyAgent).CourseNode != null)
				{
					if (RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings != 0 && RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation != 0)
					{
						ushort num = default(ushort);
						Mastermind.Current.TriggerSurvivalWave(((Agent)((ES_Base)__instance).m_enemyAgent).CourseNode, RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings, RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation, ref num, (SurvivalWaveSpawnType)0, 0f, 2f, true, false, default(Vector3), "");
					}
					else
					{
						Debug.LogError(Object.op_Implicit("ES_ScoutScream, a scout is screaming but we can't spawn a wave because the the scout settings are not set for this expedition! ScoutWaveSettings: " + RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings + " ScoutWavePopulation: " + RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation));
					}
				}
			}
			else
			{
				EOSLogger.Debug("Vanilla scout wave suppressed.");
			}
			if (SNet.IsMaster)
			{
				((ES_Base)__instance).m_enemyAgent.AI.m_behaviour.ChangeState((EB_States)5);
			}
			((MachineState<ES_Base>)(object)__instance).m_machine.ChangeState(2);
			__instance.m_state = (ScoutScreamState)4;
			return false;
		}
	}
}
namespace ExtraObjectiveSetup.Patches.Uplink
{
	[HarmonyPatch]
	internal static class CorruptedUplinkConfirm
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalCorruptedUplinkConfirm")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalCorruptedUplinkConfirm(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result)
		{
			LG_ComputerTerminal receiver = __instance.m_terminal;
			LG_ComputerTerminal sender = __instance.m_terminal.CorruptedUplinkReceiver;
			if ((Object)(object)sender == (Object)null)
			{
				EOSLogger.Error("TerminalCorruptedUplinkConfirm() critical failure because terminal does not have a CorruptedUplinkReceiver (sender).");
				__result = false;
				return false;
			}
			if (sender.m_isWardenObjective)
			{
				return true;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(sender);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(sender);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			receiver.m_command.AddOutput((TerminalLineType)0, string.Format(Text.Get(2816126705u), sender.PublicName), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
			if ((Object)(object)sender.ChainedPuzzleForWardenObjective != (Object)null)
			{
				ChainedPuzzleInstance chainedPuzzleForWardenObjective = sender.ChainedPuzzleForWardenObjective;
				chainedPuzzleForWardenObjective.OnPuzzleSolved += Action.op_Implicit((Action)delegate
				{
					receiver.m_command.StartTerminalUplinkSequence(string.Empty, true);
					UplinkObjectiveManager.Current.ChangeState(sender, new UplinkState
					{
						Status = UplinkStatus.InProgress,
						CurrentRoundIndex = 0
					});
				});
				sender.m_command.AddOutput("", true);
				sender.m_command.AddOutput(Text.Get(3268596368u), true);
				sender.m_command.AddOutput(Text.Get(2277987284u), true);
				receiver.m_command.AddOutput("", true);
				receiver.m_command.AddOutput(Text.Get(3268596368u), true);
				receiver.m_command.AddOutput(Text.Get(2277987284u), true);
				if (SNet.IsMaster)
				{
					sender.ChainedPuzzleForWardenObjective.AttemptInteract((eChainedPuzzleInteraction)0);
				}
			}
			else
			{
				receiver.m_command.StartTerminalUplinkSequence(string.Empty, true);
				UplinkObjectiveManager.Current.ChangeState(sender, new UplinkState
				{
					Status = UplinkStatus.InProgress,
					CurrentRoundIndex = 0
				});
			}
			__result = true;
			return false;
		}
	}
	[HarmonyPatch]
	internal static class CorruptedUplinkConnect
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalCorruptedUplinkConnect")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalCorruptedUplinkConnect(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result)
		{
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Expected O, but got Unknown
			LG_ComputerTerminal terminal = __instance.m_terminal;
			if (terminal.m_isWardenObjective)
			{
				return true;
			}
			__result = false;
			LG_ComputerTerminal corruptedUplinkReceiver = terminal.CorruptedUplinkReceiver;
			if ((Object)(object)corruptedUplinkReceiver == (Object)null)
			{
				EOSLogger.Error("TerminalCorruptedUplinkConnect() critical failure because terminal does not have a CorruptedUplinkReceiver.");
				return false;
			}
			if (LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != 0 && LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != terminal.SyncID)
			{
				__instance.AddOngoingUplinkOutput();
				__result = false;
				return false;
			}
			LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = terminal.SyncID;
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (definition.UseUplinkAddress)
			{
				param1 = param1.ToUpper();
				EOSLogger.Debug("TerminalCorruptedUplinkConnect, param1: " + param1 + ", TerminalUplink: " + ((Object)terminal.UplinkPuzzle).ToString());
			}
			else
			{
				param1 = terminal.UplinkPuzzle.TerminalUplinkIP.ToUpper();
				EOSLogger.Debug("TerminalCorruptedUplinkConnect, not using uplink address, TerminalUplink: " + ((Object)terminal.UplinkPuzzle).ToString());
			}
			if (!definition.UseUplinkAddress || param1 == terminal.UplinkPuzzle.TerminalUplinkIP)
			{
				if (corruptedUplinkReceiver.m_command.HasRegisteredCommand((TERM_Command)27))
				{
					terminal.m_command.AddUplinkCorruptedOutput();
				}
				else
				{
					terminal.m_command.AddUplinkCorruptedOutput();
					terminal.m_command.AddOutput("", true);
					terminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(3492863045u), corruptedUplinkReceiver.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
					terminal.m_command.AddOutput((TerminalLineType)0, Text.Get(2761366063u), 0.6f, (TerminalSoundType)0, (TerminalSoundType)0);
					terminal.m_command.AddOutput("", true);
					terminal.m_command.AddOutput((TerminalLineType)0, Text.Get(3435969025u), 0.8f, (TerminalSoundType)0, (TerminalSoundType)0);
					corruptedUplinkReceiver.m_command.AddCommand((TERM_Command)27, "UPLINK_CONFIRM", new LocalizedText
					{
						UntranslatedText = Text.Get(112719254u),
						Id = 0u
					}, (TERM_CommandRule)2);
					corruptedUplinkReceiver.m_command.AddOutput((TerminalLineType)0, string.Format(Text.Get(1173595354u), terminal.PublicName), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
				}
			}
			else
			{
				terminal.m_command.AddUplinkWrongAddressError(param1);
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class StartTerminalUplinkSequence
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "StartTerminalUplinkSequence")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_StartTerminalUplinkSequence(LG_ComputerTerminalCommandInterpreter __instance, string uplinkIp, bool corrupted)
		{
			if (!corrupted)
			{
				LG_ComputerTerminal uplinkTerminal = __instance.m_terminal;
				if (uplinkTerminal.m_isWardenObjective)
				{
					return true;
				}
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(uplinkTerminal);
				uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(uplinkTerminal);
				UplinkDefinition uplinkConfig2 = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
				uplinkTerminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2583360288u), uplinkIp), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
				__instance.TerminalUplinkSequenceOutputs(uplinkTerminal, false);
				uplinkTerminal.m_command.OnEndOfQueue = Action.op_Implicit((Action)delegate
				{
					EOSLogger.Debug("UPLINK CONNECTION DONE!");
					uplinkTerminal.UplinkPuzzle.Connected = true;
					uplinkTerminal.UplinkPuzzle.CurrentRound.ShowGui = true;
					uplinkTerminal.UplinkPuzzle.OnStartSequence();
					uplinkConfig2.EventsOnCommence.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
					});
					int num2 = uplinkConfig2.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == 0);
					((num2 != -1) ? uplinkConfig2.RoundOverrides[num2] : null)?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
					});
				});
			}
			else
			{
				LG_ComputerTerminal terminal = __instance.m_terminal;
				LG_ComputerTerminal sender = __instance.m_terminal.CorruptedUplinkReceiver;
				if (sender.m_isWardenObjective)
				{
					return true;
				}
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex2 = TerminalInstanceManager.Current.GetGlobalZoneIndex(sender);
				uint zoneInstanceIndex2 = TerminalInstanceManager.Current.GetZoneInstanceIndex(sender);
				UplinkDefinition uplinkConfig = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex2, zoneInstanceIndex2);
				sender.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2056072887u), sender.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
				sender.m_command.AddOutput("", true);
				terminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2056072887u), sender.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
				terminal.m_command.AddOutput("", true);
				terminal.m_command.TerminalUplinkSequenceOutputs(sender, false);
				terminal.m_command.TerminalUplinkSequenceOutputs(terminal, true);
				terminal.m_command.OnEndOfQueue = Action.op_Implicit((Action)delegate
				{
					EOSLogger.Debug("UPLINK CONNECTION DONE!");
					sender.UplinkPuzzle.Connected = true;
					sender.UplinkPuzzle.CurrentRound.ShowGui = true;
					sender.UplinkPuzzle.OnStartSequence();
					uplinkConfig.EventsOnCommence.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
					});
					int num = uplinkConfig.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == 0);
					((num != -1) ? uplinkConfig.RoundOverrides[num] : null)?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
					});
				});
			}
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "StartTerminalUplinkSequence")]
		private static void Post_LG_ComputerTerminalCommandInterpreter_StartTerminalUplinkSequence(LG_ComputerTerminalCommandInterpreter __instance, bool corrupted)
		{
			if (!corrupted)
			{
				LG_ComputerTerminal terminal = __instance.m_terminal;
				if (!terminal.m_isWardenObjective)
				{
					return;
				}
				UplinkDefinition uplinkConfig = UplinkObjectiveManager.Current.GetWardenDefinition(__instance.m_terminal);
				if (uplinkConfig == null)
				{
					return;
				}
				LG_ComputerTerminalCommandInterpreter command = terminal.m_command;
				command.OnEndOfQueue += Action.op_Implicit((Action)delegate
				{
					uplinkConfig.EventsOnCommence.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
					});
					int num2 = uplinkConfig.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == 0);
					((num2 != -1) ? uplinkConfig.RoundOverrides[num2] : null)?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
					});
				});
				return;
			}
			LG_ComputerTerminal terminal2 = __instance.m_terminal;
			LG_ComputerTerminal corruptedUplinkReceiver = __instance.m_terminal.CorruptedUplinkReceiver;
			if (!corruptedUplinkReceiver.m_isWardenObjective)
			{
				return;
			}
			UplinkDefinition uplinkConfig2 = UplinkObjectiveManager.Current.GetWardenDefinition(corruptedUplinkReceiver);
			if (uplinkConfig2 == null)
			{
				return;
			}
			LG_ComputerTerminalCommandInterpreter command2 = terminal2.m_command;
			command2.OnEndOfQueue += Action.op_Implicit((Action)delegate
			{
				uplinkConfig2.EventsOnCommence.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
				int num = uplinkConfig2.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == 0);
				((num != -1) ? uplinkConfig2.RoundOverrides[num] : null)?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
				});
			});
		}
	}
	[HarmonyPatch]
	internal static class TerminalUplinkConnect
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkConnect")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkConnect(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result)
		{
			LG_ComputerTerminal terminal = __instance.m_terminal;
			if (terminal.m_isWardenObjective)
			{
				return true;
			}
			if (LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != 0 && LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != terminal.SyncID)
			{
				__instance.AddOngoingUplinkOutput();
				return false;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance.m_terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (!definition.UseUplinkAddress)
			{
				param1 = __instance.m_terminal.UplinkPuzzle.TerminalUplinkIP;
			}
			if (!definition.UseUplinkAddress || param1 == __instance.m_terminal.UplinkPuzzle.TerminalUplinkIP)
			{
				__instance.m_terminal.TrySyncSetCommandRule((TERM_Command)25, (TERM_CommandRule)1);
				if ((Object)(object)__instance.m_terminal.ChainedPuzzleForWardenObjective != (Object)null)
				{
					ChainedPuzzleInstance chainedPuzzleForWardenObjective = __instance.m_terminal.ChainedPuzzleForWardenObjective;
					chainedPuzzleForWardenObjective.OnPuzzleSolved += Action.op_Implicit((Action)delegate
					{
						__instance.StartTerminalUplinkSequence(param1, false);
					});
					__instance.AddOutput("", true);
					__instance.AddOutput(Text.Get(3268596368u), true);
					__instance.AddOutput(Text.Get(3041541194u), true);
					if (SNet.IsMaster)
					{
						__instance.m_terminal.ChainedPuzzleForWardenObjective.AttemptInteract((eChainedPuzzleInteraction)0);
					}
				}
				else
				{
					__instance.StartTerminalUplinkSequence(param1, false);
				}
				__result = true;
			}
			else
			{
				__instance.AddUplinkWrongAddressError(param1);
				__result = false;
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class TerminalUplinkSequenceOutput
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkSequenceOutputs")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkSequenceOutputs(LG_ComputerTerminal terminal, bool corrupted)
		{
			if (terminal.m_isWardenObjective)
			{
				return true;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (definition == null)
			{
				if (!((Object)(object)terminal.CorruptedUplinkReceiver != (Object)null))
				{
					return true;
				}
				LG_ComputerTerminal corruptedUplinkReceiver = terminal.CorruptedUplinkReceiver;
				globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(corruptedUplinkReceiver);
				zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(corruptedUplinkReceiver);
				definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
				if (definition == null || definition.DisplayUplinkWarning)
				{
					return true;
				}
			}
			terminal.m_command.AddOutput((TerminalLineType)3, Text.Get(3418104670u), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
			terminal.m_command.AddOutput("", true);
			if (!corrupted)
			{
				terminal.m_command.AddOutput(string.Format(Text.Get(947485599u), terminal.UplinkPuzzle.CurrentRound.CorrectPrefix), true);
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class TerminalUplinkVerify
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkVerify")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkVerify(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result, out List<WardenObjectiveEventData> __state)
		{
			__state = null;
			if (__instance.m_terminal.m_isWardenObjective)
			{
				UplinkDefinition wardenDefinition = UplinkObjectiveManager.Current.GetWardenDefinition(__instance.m_terminal);
				if (wardenDefinition == null)
				{
					return true;
				}
				TerminalUplinkPuzzle puzzle = __instance.m_terminal.UplinkPuzzle;
				if (puzzle.Connected && !puzzle.Solved && puzzle.CurrentRound.CorrectCode.ToUpper() == param1.ToUpper())
				{
					__state = wardenDefinition.RoundOverrides.Find((UplinkRound round) => round.RoundIndex == puzzle.m_roundIndex + 1)?.EventsOnRound;
					wardenDefinition.RoundOverrides.Find((UplinkRound round) => round.RoundIndex == puzzle.m_roundIndex)?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)2, false, 0f);
					});
				}
				return true;
			}
			TerminalUplinkPuzzle uplinkPuzzle = __instance.m_terminal.UplinkPuzzle;
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance.m_terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(__instance.m_terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			int CurrentRoundIndex = uplinkPuzzle.m_roundIndex;
			int num = definition.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == CurrentRoundIndex);
			UplinkRound roundOverride = ((num != -1) ? definition.RoundOverrides[num] : null);
			TimeSettings timeSettings = ((num != -1) ? roundOverride.OverrideTimeSettings : definition.DefaultTimeSettings);
			float num2 = ((timeSettings.TimeToStartVerify >= 0f) ? timeSettings.TimeToStartVerify : definition.DefaultTimeSettings.TimeToStartVerify);
			float timeToCompleteVerify = ((timeSettings.TimeToCompleteVerify >= 0f) ? timeSettings.TimeToCompleteVerify : definition.DefaultTimeSettings.TimeToCompleteVerify);
			float num3 = ((timeSettings.TimeToRestoreFromFail >= 0f) ? timeSettings.TimeToRestoreFromFail : definition.DefaultTimeSettings.TimeToRestoreFromFail);
			if (uplinkPuzzle.Connected)
			{
				__instance.AddOutput((TerminalLineType)3, Text.Get(2734004688u), num2, (TerminalSoundType)0, (TerminalSoundType)0);
				if (!uplinkPuzzle.Solved && uplinkPuzzle.CurrentRound.CorrectCode.ToUpper() == param1.ToUpper())
				{
					__instance.AddOutput(string.Format(Text.Get(1221800228u), uplinkPuzzle.CurrentProgress), true);
					if (uplinkPuzzle.TryGoToNextRound())
					{
						int newRoundIndex = uplinkPuzzle.m_roundIndex;
						int num4 = definition.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == newRoundIndex);
						UplinkRound newRoundOverride = ((num4 != -1) ? definition.RoundOverrides[num4] : null);
						roundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
						{
							WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)2, false, 0f);
						});
						if (roundOverride != null && (Object)(object)roundOverride.ChainedPuzzleToEndRoundInstance != (Object)null)
						{
							TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.UplinkTerminal.ScanRequiredToProgress");
							if (block != null)
							{
								__instance.AddOutput((TerminalLineType)4, Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
							}
							ChainedPuzzleInstance chainedPuzzleToEndRoundInstance = roundOverride.ChainedPuzzleToEndRoundInstance;
							chainedPuzzleToEndRoundInstance.OnPuzzleSolved += Action.op_Implicit((Action)delegate
							{
								__instance.AddOutput((TerminalLineType)4, Text.Get(27959760u), timeToCompleteVerify, (TerminalSoundType)0, (TerminalSoundType)0);
								__instance.AddOutput("", true);
								__instance.AddOutput(string.Format(Text.Get(4269617288u), uplinkPuzzle.CurrentProgress, uplinkPuzzle.CurrentRound.CorrectPrefix), true);
								__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
								{
									EOSLogger.Log("UPLINK VERIFICATION GO TO NEXT ROUND!");
									uplinkPuzzle.CurrentRound.ShowGui = true;
									newRoundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
									{
										WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
									});
									UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
									{
										Status = UplinkStatus.InProgress,
										CurrentRoundIndex = uplinkPuzzle.m_roundIndex
									});
								});
							});
							if (SNet.IsMaster)
							{
								roundOverride.ChainedPuzzleToEndRoundInstance.AttemptInteract((eChainedPuzzleInteraction)0);
							}
						}
						else
						{
							__instance.AddOutput((TerminalLineType)4, Text.Get(27959760u), timeToCompleteVerify, (TerminalSoundType)0, (TerminalSoundType)0);
							__instance.AddOutput("", true);
							__instance.AddOutput(string.Format(Text.Get(4269617288u), uplinkPuzzle.CurrentProgress, uplinkPuzzle.CurrentRound.CorrectPrefix), true);
							__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
							{
								EOSLogger.Log("UPLINK VERIFICATION GO TO NEXT ROUND!");
								uplinkPuzzle.CurrentRound.ShowGui = true;
								newRoundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
								{
									WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
								});
								UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
								{
									Status = UplinkStatus.InProgress,
									CurrentRoundIndex = uplinkPuzzle.m_roundIndex
								});
							});
						}
					}
					else
					{
						__instance.AddOutput((TerminalLineType)3, Text.Get(1780488547u), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
						__instance.AddOutput("", true);
						__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
						{
							roundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
							{
								WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)2, false, 0f);
							});
							uplinkPuzzle.CurrentRound.ShowGui = false;
							if (roundOverride != null && (Object)(object)roundOverride.ChainedPuzzleToEndRoundInstance != (Object)null)
							{
								ChainedPuzzleInstance chainedPuzzleToEndRoundInstance2 = roundOverride.ChainedPuzzleToEndRoundInstance;
								chainedPuzzleToEndRoundInstance2.OnPuzzleSolved += Action.op_Implicit((Action)delegate
								{
									__instance.AddOutput((TerminalLineType)0, string.Format(Text.Get(3928683780u), uplinkPuzzle.TerminalUplinkIP), 2f, (TerminalSoundType)0, (TerminalSoundType)0);
									__instance.AddOutput("", true);
									__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
									{
										EOSLogger.Error("UPLINK VERIFICATION SEQUENCE DONE!");
										LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = 0u;
										uplinkPuzzle.Solved = true;
										Action onPuzzleSolved2 = uplinkPuzzle.OnPuzzleSolved;
										if (onPuzzleSolved2 != null)
										{
											onPuzzleSolved2.Invoke();
										}
										UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
										{
											Status = UplinkStatus.Finished,
											CurrentRoundIndex = uplinkPuzzle.m_roundIndex
										});
									});
								});
								if (SNet.IsMaster)
								{
									roundOverride.ChainedPuzzleToEndRoundInstance.AttemptInteract((eChainedPuzzleInteraction)0);
								}
							}
							else
							{
								__instance.AddOutput((TerminalLineType)0, string.Format(Text.Get(3928683780u), uplinkPuzzle.TerminalUplinkIP), 2f, (TerminalSoundType)0, (TerminalSoundType)0);
								__instance.AddOutput("", true);
								EOSLogger.Error("UPLINK VERIFICATION SEQUENCE DONE!");
								LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = 0u;
								uplinkPuzzle.Solved = true;
								Action onPuzzleSolved = uplinkPuzzle.OnPuzzleSolved;
								if (onPuzzleSolved != null)
								{
									onPuzzleSolved.Invoke();
								}
								UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
								{
									Status = UplinkStatus.Finished,
									CurrentRoundIndex = uplinkPuzzle.m_roundIndex
								});
							}
						});
					}
				}
				else if (uplinkPuzzle.Solved)
				{
					__instance.AddOutput("", true);
					__instance.AddOutput((TerminalLineType)1, Text.Get(4080876165u), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
					__instance.AddOutput((TerminalLineType)0, Text.Get(4104839742u), 6f, (TerminalSoundType)0, (TerminalSoundType)0);
				}
				else
				{
					__instance.AddOutput("", true);
					__instance.AddOutput((TerminalLineType)1, string.Format(Text.Get(507647514u), uplinkPuzzle.CurrentRound.CorrectPrefix), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
					__instance.AddOutput((TerminalLineType)0, Text.Get(4104839742u), num3, (TerminalSoundType)0, (TerminalSoundType)0);
				}
			}
			else
			{
				__instance.AddOutput("", true);
				__instance.AddOutput(Text.Get(403360908u), true);
			}
			__result = false;
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkVerify")]
		private static void Post_LG_ComputerTerminalCommandInterpreter_TerminalUplinkVerify(LG_ComputerTerminalCommandInterpreter __instance, List<WardenObjectiveEventData> __state)
		{
			if (__state == null)
			{
				return;
			}
			__instance.OnEndOfQueue += Action.op_Implicit((Action)delegate
			{
				__state.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
				});
			});
		}
	}
	[HarmonyPatch]
	internal static class UplinkGUI_Update
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminal), "Update")]
		private static void Post_LG_ComputerTerminal_Update(LG_ComputerTerminal __instance)
		{
			if (!__instance.m_isWardenObjective && __instance.UplinkPuzzle != null)
			{
				__instance.UplinkPuzzle.UpdateGUI(false);
			}
		}
	}
}
namespace ExtraObjectiveSetup.Patches.PowerGenerator
{
	[HarmonyPatch]
	internal static class Patch_LG_PowerGeneratorCluster
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGeneratorCluster), "Setup")]
		private static void Post_PowerGeneratorCluster_Setup(LG_PowerGeneratorCluster __instance)
		{
			uint instanceIndex = GeneratorClusterInstanceManager.Current.Register(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = GeneratorClusterInstanceManager.Current.GetGlobalZoneIndex(__instance);
			GeneratorClusterDefinition definition = GeneratorClusterObjectiveManager.Current.GetDefinition(globalZoneIndex, instanceIndex);
			if (definition == null)
			{
				return;
			}
			EOSLogger.Debug("Found LG_PowerGeneratorCluster and its definition! Building this Generator cluster...");
			__instance.m_serialNumber = SerialGenerator.GetUniqueSerialNo();
			__instance.m_itemKey = "GENERATOR_CLUSTER_" + __instance.m_serialNumber;
			__instance.m_terminalItem = GOUtil.GetInterfaceFromComp<iTerminalItem>(__instance.m_terminalItemComp);
			__instance.m_terminalItem.Setup(__instance.m_itemKey, (AIG_CourseNode)null);
			__instance.m_terminalItem.FloorItemStatus = (eFloorInventoryObjectStatus)4;
			if (__instance.SpawnNode != null)
			{
				__instance.m_terminalItem.FloorItemLocation = __instance.SpawnNode.m_zone.NavInfo.GetFormattedText((LG_NavInfoFormat)7);
			}
			List<Transform> list = new List<Transform>((IEnumerable<Transform>)__instance.m_generatorAligns);
			uint numberOfGenerators = definition.NumberOfGenerators;
			__instance.m_generators = Il2CppReferenceArray<LG_PowerGenerator_Core>.op_Implicit((LG_PowerGenerator_Core[])(object)new LG_PowerGenerator_Core[numberOfGenerators]);
			if (list.Count >= numberOfGenerators)
			{
				for (int i = 0; i < numberOfGenerators; i++)
				{
					int index = Builder.BuildSeedRandom.Range(0, list.Count, "NO_TAG");
					LG_PowerGenerator_Core val = GOUtil.SpawnChildAndGetComp<LG_PowerGenerator_Core>(__instance.m_generatorPrefab, list[index]);
					((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)__instance.m_generators)[i] = val;
					val.SpawnNode = __instance.SpawnNode;
					PowerGeneratorInstanceManager.Current.MarkAsGCGenerator(__instance, val);
					val.Setup();
					val.SetCanTakePowerCell(true);
					Debug.Log(Object.op_Implicit("Spawning generator at alignIndex: " + index));
					list.RemoveAt(index);
				}
			}
			else
			{
				Debug.LogError(Object.op_Implicit("LG_PowerGeneratorCluster does NOT have enough generator aligns to support the warden objective! Has " + list.Count + " needs " + numberOfGenerators));
			}
			__instance.ObjectiveItemSolved = true;
			if (definition.EndSequenceChainedPuzzle != 0)
			{
				GeneratorClusterObjectiveManager.Current.RegisterForChainedPuzzleBuild(__instance, definition);
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_LG_PowerGenerator_Core_SyncStatusChanged
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGenerator_Core), "SyncStatusChanged")]
		private static void Post_SyncStatusChanged(LG_PowerGenerator_Core __instance, pPowerGeneratorState state, bool isDropinState)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Invalid comparison between Unknown and I4
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Invalid comparison between Unknown and I4
			//IL_036a: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0375: Invalid comparison between Unknown and I4
			uint zoneInstanceIndex = PowerGeneratorInstanceManager.Current.GetZoneInstanceIndex(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance);
			LG_PowerGeneratorCluster parentGeneratorCluster = PowerGeneratorInstanceManager.Current.GetParentGeneratorCluster(__instance);
			GeneratorClusterDefinition generatorClusterDefinition = null;
			if ((Object)(object)parentGeneratorCluster != (Object)null)
			{
				uint zoneInstanceIndex2 = GeneratorClusterInstanceManager.Current.GetZoneInstanceIndex(parentGeneratorCluster);
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex2 = GeneratorClusterInstanceManager.Current.GetGlobalZoneIndex(parentGeneratorCluster);
				generatorClusterDefinition = GeneratorClusterObjectiveManager.Current.GetDefinition(globalZoneIndex2, zoneInstanceIndex2);
			}
			ePowerGeneratorStatus status = state.status;
			if (generatorClusterDefinition != null)
			{
				EOSLogger.Log($"LG_PowerGeneratorCluster.powerGenerator.OnSyncStatusChanged! status: {status}, isDropinState: {isDropinState}");
				if ((int)status == 0)
				{
					uint num = 0u;
					for (int i = 0; i < ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Length; i++)
					{
						if ((int)((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators)[i].m_stateReplicator.State.status == 0)
						{
							num++;
						}
					}
					EOSLogger.Log($"Generator Cluster PowerCell inserted ({num} / {((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count})");
					List<List<WardenObjectiveEventData>> eventsOnInsertCell = generatorClusterDefinition.EventsOnInsertCell;
					int num2 = (int)(num - 1);
					if (!isDropinState)
					{
						if (num2 >= 0 && num2 < eventsOnInsertCell.Count)
						{
							EOSLogger.Log($"Executing events ({num} / {((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count}). Event count: {eventsOnInsertCell[num2].Count}");
							eventsOnInsertCell[num2].ForEach(delegate(WardenObjectiveEventData e)
							{
								WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
							});
						}
						if (num == ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count && !parentGeneratorCluster.m_endSequenceTriggered)
						{
							EOSLogger.Log("All generators powered, executing end sequence");
							((MonoBehaviour)__instance).StartCoroutine(parentGeneratorCluster.ObjectiveEndSequence());
							parentGeneratorCluster.m_endSequenceTriggered = true;
						}
					}
					else if (num != ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count)
					{
						parentGeneratorCluster.m_endSequenceTriggered = false;
					}
				}
				else if (isDropinState)
				{
					parentGeneratorCluster.m_endSequenceTriggered = false;
				}
			}
			IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (definition != null && definition.EventsOnInsertCell != null && (int)status == 0 && !isDropinState)
			{
				definition.EventsOnInsertCell.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
			ExpeditionIGGroup expeditionIGGroup = ExpeditionIGGroupManager.Current.FindGroupDefOf(__instance);
			if (expeditionIGGroup == null)
			{
				return;
			}
			int num3 = 0;
			foreach (LG_PowerGenerator_Core generatorInstance in expeditionIGGroup.GeneratorInstances)
			{
				if ((int)generatorInstance.m_stateReplicator.State.status == 0)
				{
					num3++;
				}
			}
			if (isDropinState)
			{
				return;
			}
			if (num3 == expeditionIGGroup.GeneratorInstances.Count && expeditionIGGroup.PlayEndSequenceOnGroupComplete)
			{
				Coroutine val = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(ExpeditionIGGroupManager.PlayGroupEndSequence(expeditionIGGroup)), (Action)null);
				WorldEventManager.m_worldEventEventCoroutines.Add(val);
				return;
			}
			int num4 = num3 - 1;
			if (num4 >= 0 && num4 < expeditionIGGroup.EventsOnInsertCell.Count)
			{
				expeditionIGGroup.EventsOnInsertCell[num4].ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_LG_PowerGenerator_Core_Setup
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGenerator_Core), "Setup")]
		private static void Post_PowerGenerator_Setup(LG_PowerGenerator_Core __instance)
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			iCarryItemInteractionTarget powerCellInteraction = __instance.m_powerCellInteraction;
			powerCellInteraction.AttemptCarryItemInsert += Action<SNet_Player, Item>.op_Implicit((Action<SNet_Player, Item>)delegate(SNet_Player p, Item item)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				Item val2 = default(Item);
				if (PlayerBackpackManager.TryGetItemInLevelFromItemData(item.Get_pItemData(), ref val2))
				{
					ItemInLevel val3 = ((Il2CppObjectBase)val2).Cast<ItemInLevel>();
					val3.CanWarp = false;
				}
				else
				{
					EOSLogger.Error($"Inserting sth other than PowerCell ({item.PublicName}) into {__instance.m_itemKey}, how?");
				}
			});
			if (PowerGeneratorInstanceManager.Current.IsGCGenerator(__instance))
			{
				return;
			}
			uint num = PowerGeneratorInstanceManager.Current.Register(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance);
			IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, num);
			if (definition != null)
			{
				Vector3 val = definition.Position.ToVector3();
				Quaternion rotation = definition.Rotation.ToQuaternion();
				if (val != Vector3.zero)
				{
					((Component)__instance).transform.position = val;
					((Component)__instance).transform.rotation = rotation;
					__instance.m_sound.UpdatePosition(val);
					EOSLogger.Debug("LG_PowerGenerator_Core: modified position / rotation");
				}
				if (definition.ForceAllowPowerCellInsertion)
				{
					__instance.SetCanTakePowerCell(true);
				}
				EOSLogger.Debug($"LG_PowerGenerator_Core: overriden, instance {num} in {globalZoneIndex}");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGenerator_Core), "SyncStatusChanged")]
		private static void Post_SyncStatusChanged(LG_PowerGenerator_Core __instance, pPowerGeneratorState state, bool isDropinState)
		{
			//IL_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_0038: Invalid comparison between Unknown and I4
			uint zoneInstanceIndex = PowerGeneratorInstanceManager.Current.GetZoneInstanceIndex(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance);
			IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (!(definition == null || definition.EventsOnInsertCell == null || (int)state.status > 0 || isDropinState) && definition.EventsOnInsertCell.Count > 0)
			{
				definition.EventsOnInsertCell.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
		}
	}
}
namespace ExtraObjectiveSetup.Patches.Terminal
{
	[HarmonyPatch]
	internal static class Patch_FixHiddenCommandExecution
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReceiveCommand")]
		private static void Pre_TerminalInterpreter_ReceiveCommand(LG_ComputerTerminalCommandInterpreter __instance, ref TERM_Command cmd)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00ba: Expected I4, but got Unknown
			TERM_Command val = cmd;
			TERM_Command val2 = val;
			switch (val2 - 1)
			{
			case 0:
			case 1:
			case 2:
			case 3:
			case 11:
			case 13:
			case 14:
			case 17:
			case 18:
			case 19:
			case 20:
			case 21:
			case 22:
			case 23:
			case 24:
			case 25:
			case 26:
			case 27:
			case 28:
			case 31:
			case 32:
			case 33:
			case 42:
				if (__instance.m_terminal.CommandIsHidden(cmd))
				{
					cmd = (TERM_Command)10;
				}
				break;
			case 4:
			case 5:
			case 6:
			case 7:
			case 8:
			case 9:
			case 10:
			case 12:
			case 15:
			case 16:
			case 29:
			case 30:
			case 34:
			case 35:
			case 36:
			case 37:
			case 38:
			case 39:
			case 40:
			case 41:
				break;
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_FixReactorTerminalNullSpawnNode
	{
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		private static bool Pre(LG_ComputerTerminal __instance, ref AIG_CourseNode __result)
		{
			if ((Object)(object)__instance.ConnectedReactor != (Object)null && __instance.m_terminalItem.SpawnNode == null)
			{
				__result = __instance.ConnectedReactor.SpawnNode;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class Patch_FixRepeatablePuzzleBugs
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(CP_Cluster_Core), "OnSyncStateChange")]
		private static bool Pre_CheckEventsOnPuzzleSolved(CP_Cluster_Core __instance, eClusterStatus newStatus, bool isDropinState)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Invalid comparison between Unknown and I4
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Invalid comparison between Unknown and I4
			pClusterState currentState = __instance.m_sync.GetCurrentState();
			if (isDropinState && (int)newStatus == 3)
			{
				__instance.m_spline.SetVisible(false);
				for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Length; i++)
				{
					((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores)[i].Deactivate();
				}
				return false;
			}
			if (!isDropinState && (int)currentState.status == 3 && (int)newStatus == 1)
			{
				__instance.m_spline.Reveal(0f);
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class Patch_LG_ComputerTerminal_Setup
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminal), "Setup")]
		private static void Post_LG_ComputerTerminal_Setup(LG_ComputerTerminal __instance)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			uint instanceIndex = TerminalInstanceManager.Current.Register(__instance);
			TerminalInstanceManager.Current.SetupTerminalWrapper(__instance);
			if (__instance.SpawnNode == null)
			{
				return;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance);
			TerminalPosition definition = TerminalPositionOverrideManager.Current.GetDefinition(globalZoneIndex, instanceIndex);
			if (definition != null)
			{
				if (definition.Position.ToVector3() != Vector3.zeroVector)
				{
					((Component)__instance).transform.position = definition.Position.ToVector3();
					((Component)__instance).transform.rotation = definition.Rotation.ToQuaternion();
				}
				EOSLogger.Debug($"TerminalPositionOverride: {definition.LocalIndex}, {definition.LayerType}, {definition.DimensionIndex}, TerminalIndex {definition.InstanceIndex}");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminal), "SetupAsWardenObjectiveTerminalUplink")]
		[HarmonyPatch(typeof(LG_ComputerTerminal), "SetupAsWardenObjectiveCorruptedTerminalUplink")]
		private static void Post_LG_ComputerTerminal_UplinkSetup(LG_ComputerTerminal __instance)
		{
			TerminalInstanceManager.Current.RegisterWardenUplink(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(TerminalUplinkPuzzle), "Setup")]
		private static void Post_LG_ComputerTerminal_SyncedPuzzle(TerminalUplinkPuzzle __instance, LG_ComputerTerminal terminal)
		{
			if (!terminal.m_isWardenObjective)
			{
				return;
			}
			UplinkDefinition def = UplinkObjectiveManager.Current.GetWardenDefinition(terminal);
			if (def == null)
			{
				return;
			}
			__instance.OnPuzzleSolved += Action.op_Implicit((Action)delegate
			{
				def.EventsOnComplete?.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			});
		}
	}
	[HarmonyPatch]
	internal static class Patch_RepeatableCommandEventFix
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "SetupCommandEvents")]
		private static void Post_ResetRepeatableUniqueCommandChainedPuzzle(LG_ComputerTerminalCommandInterpreter __instance)
		{
			//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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Invalid comparison between Unknown and I4
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			LG_ComputerTerminal terminal = __instance.m_terminal;
			ChainedPuzzleInstance val = default(ChainedPuzzleInstance);
			foreach (TERM_Command uNIQUE_CMD in TerminalInstanceManager.UNIQUE_CMDS)
			{
				if (!__instance.m_commandsPerEnum.ContainsKey(uNIQUE_CMD))
				{
					continue;
				}
				string text = __instance.m_commandsPerEnum[uNIQUE_CMD];
				if ((int)__instance.m_terminal.GetCommandRule(uNIQUE_CMD) > 0)
				{
					continue;
				}
				List<WardenObjectiveEventData> uniqueCommandEvents = __instance.m_terminal.GetUniqueCommandEvents(text);
				for (int i = 0; i < uniqueCommandEvents.Count; i++)
				{
					if (uniqueCommandEvents[i].ChainPuzzle != 0)
					{
						if (__instance.m_terminal.TryGetChainPuzzleForCommand(uNIQUE_CMD, i, ref val) && (Object)(object)val != (Object)null)
						{
							ChainedPuzzleInstance obj = val;
							obj.OnPuzzleSolved += Action.op_Implicit((Action)val.ResetProgress);
						}
						EOSLogger.Debug($"TerminalTweak: {terminal.ItemKey}, command {text} set to be repeatable!");
					}
				}
			}
		}
	}
}
namespace ExtraObjectiveSetup.Patches.LGFactory
{
	[HarmonyPatch]
	internal class Patch_LG_Factory_NextBatch
	{
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(LG_Factory), "NextBatch")]
		private static void Prefix(LG_Factory __instance)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.m_batchStep > -1)
			{
				BatchName currentBatchName = __instance.m_currentBatchName;
				BatchBuildManager.Current.Get_OnBatchDone(currentBatchName)?.Invoke();
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(LG_Factory), "NextBatch")]
		private static void Postfix(LG_Factory __instance)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			BatchBuildManager.Current.Get_OnBatchStart(__instance.m_currentBatchName)?.Invoke();
		}
	}
}
namespace ExtraObjectiveSetup.Patches.HSUActivator
{
	[HarmonyPatch]
	internal class SetupFromCustomGeomorph
	{
		[HarmonyPostfi

plugins/XiaoTian-SURVIVAL/SURVIVAL/Custom/net6/Inas07.ThermalSights.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Json.Serialization;
using AssetShards;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using ChainedPuzzles;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.Expedition.Gears;
using ExtraObjectiveSetup.Utils;
using FirstPersonItem;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Microsoft.CodeAnalysis;
using ThermalSights.Definition;
using UnityEngine;

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

		public const string PLUGIN_NAME = "ThermalSights";

		public const string VERSION = "1.0.0";

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			SetupManagers();
			m_Harmony = new Harmony("ThermalSights");
			m_Harmony.PatchAll();
			EOSLogger.Log("ThermalSights loaded.");
		}

		private void SetupManagers()
		{
			AssetShardManager.OnStartupAssetsLoaded += Action.op_Implicit((Action)delegate
			{
				((GenericDefinitionManager<TSADefinition>)TSAManager.Current).Init();
			});
		}
	}
	public class TSAManager : GenericDefinitionManager<TSADefinition>
	{
		public class PuzzleVisualWrapper
		{
			public GameObject GO { get; set; }

			public Renderer Renderer { get; set; }

			public float Intensity { get; set; }

			public float BehindWallIntensity { get; set; }

			public void SetIntensity(float t)
			{
				if (GO.active)
				{
					if (Intensity > 0f)
					{
						Renderer.material.SetFloat("_Intensity", Intensity * t);
					}
					if (BehindWallIntensity > 0f)
					{
						Renderer.material.SetFloat("_BehindWallIntensity", BehindWallIntensity * t);
					}
				}
			}
		}

		private const bool OUTPUT_THERMAL_SHADER_SETTINGS_ON_WIELD = false;

		public static TSAManager Current { get; }

		protected override string DEFINITION_NAME => "ThermalSight";

		private Dictionary<uint, Renderer[]> InLevelGearThermals { get; } = new Dictionary<uint, Renderer[]>();


		private HashSet<uint> ModifiedInLevelGearThermals { get; } = new HashSet<uint>();


		private HashSet<uint> ThermalOfflineGears { get; } = new HashSet<uint>();


		public uint CurrentGearPID { get; private set; }

		private List<PuzzleVisualWrapper> PuzzleVisuals { get; } = new List<PuzzleVisualWrapper>();


		protected override void FileChanged(LiveEditEventArgs e)
		{
			base.FileChanged(e);
			InitThermalOfflineGears();
			CleanupInLevelGearThermals(keepCurrentGear: true);
			TrySetThermalSightRenderer(CurrentGearPID);
		}

		public override void Init()
		{
			InitThermalOfflineGears();
		}

		private void InitThermalOfflineGears()
		{
			ThermalOfflineGears.Clear();
			foreach (PlayerOfflineGearDataBlock allBlock in GameDataBlockBase<PlayerOfflineGearDataBlock>.GetAllBlocks())
			{
				if (((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)allBlock).name.ToLowerInvariant().EndsWith("_t"))
				{
					ThermalOfflineGears.Add(((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)allBlock).persistentID);
				}
			}
			EOSLogger.Debug($"Found OfflineGear with thermal sight, count: {ThermalOfflineGears.Count}");
		}

		private bool TryGetInLevelGearThermalRenderersFromItem(ItemEquippable item, uint gearPID, out Renderer[] renderers)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			renderers = null;
			if (item.GearIDRange == null)
			{
				return false;
			}
			if (gearPID == 0)
			{
				gearPID = ExpeditionGearManager.GetOfflineGearPID(item.GearIDRange);
			}
			if (gearPID == 0 || !IsGearWithThermal(gearPID))
			{
				return false;
			}
			bool flag = false;
			if (!InLevelGearThermals.ContainsKey(gearPID))
			{
				flag = true;
			}
			else
			{
				try
				{
					_ = ((Component)InLevelGearThermals[gearPID][0]).gameObject.transform.position;
					flag = false;
				}
				catch
				{
					ModifiedInLevelGearThermals.Remove(gearPID);
					flag = true;
				}
			}
			if (flag)
			{
				renderers = (from x in ((IEnumerable<Renderer>)((Component)item).GetComponentsInChildren<Renderer>(true))?.Where((Renderer x) => (Object)(object)x.sharedMaterial != (Object)null && (Object)(object)x.sharedMaterial.shader != (Object)null)
					where ((Object)x.sharedMaterial.shader).name.ToLower().Contains("Thermal".ToLower())
					select x).ToArray() ?? null;
				if (renderers != null)
				{
					if (renderers.Length != 1)
					{
						EOSLogger.Warning(((Item)item).PublicName + " contains more than 1 thermal renderers!");
					}
					InLevelGearThermals[gearPID] = renderers;
					return true;
				}
				EOSLogger.Debug(((Item)item).PublicName + ": thermal renderer not found");
				return false;
			}
			renderers = InLevelGearThermals[gearPID];
			return true;
		}

		internal bool TrySetThermalSightRenderer(uint gearPID = 0u)
		{
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0110: 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_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Expected O, but got Unknown
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			if (gearPID == 0)
			{
				gearPID = CurrentGearPID;
			}
			if (!IsGearWithThermal(gearPID))
			{
				return false;
			}
			if (ModifiedInLevelGearThermals.Contains(gearPID))
			{
				return true;
			}
			if (base.definitions.TryGetValue(gearPID, out var value) && InLevelGearThermals.TryGetValue(gearPID, out var value2))
			{
				TSShader shader = value.Definition.Shader;
				Renderer[] array = value2;
				foreach (Renderer val in array)
				{
					PropertyInfo[] properties = shader.GetType().GetProperties();
					foreach (PropertyInfo propertyInfo in properties)
					{
						Type type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
						string text = "_" + propertyInfo.Name;
						if (type == typeof(float))
						{
							val.material.SetFloat(text, (float)propertyInfo.GetValue(shader));
						}
						else if (type == typeof(EOSColor))
						{
							EOSColor val2 = (EOSColor)propertyInfo.GetValue(shader);
							val.material.SetVector(text, Color.op_Implicit(val2.ToUnityColor()));
						}
						else if (type == typeof(bool))
						{
							bool flag = (bool)propertyInfo.GetValue(shader);
							val.material.SetFloat(text, flag ? 1f : 0f);
						}
						else if (type == typeof(Vec4))
						{
							Vec4 val3 = (Vec4)propertyInfo.GetValue(shader);
							val.material.SetVector(text, val3.ToVector4());
						}
					}
				}
				ModifiedInLevelGearThermals.Add(gearPID);
				return true;
			}
			return false;
		}

		internal void OnPlayerItemWielded(FirstPersonItemHolder fpsItemHolder, ItemEquippable item)
		{
			if (item.GearIDRange == null)
			{
				CurrentGearPID = 0u;
				return;
			}
			CurrentGearPID = ExpeditionGearManager.GetOfflineGearPID(item.GearIDRange);
			TryGetInLevelGearThermalRenderersFromItem(item, CurrentGearPID, out var _);
			TrySetThermalSightRenderer(CurrentGearPID);
		}

		public bool IsGearWithThermal(uint gearPID)
		{
			return ThermalOfflineGears.Contains(gearPID);
		}

		private void CleanupInLevelGearThermals(bool keepCurrentGear = false)
		{
			if (!keepCurrentGear || !InLevelGearThermals.ContainsKey(CurrentGearPID))
			{
				InLevelGearThermals.Clear();
			}
			else
			{
				Renderer[] value = InLevelGearThermals[CurrentGearPID];
				InLevelGearThermals.Clear();
				InLevelGearThermals[CurrentGearPID] = value;
			}
			ModifiedInLevelGearThermals.Clear();
		}

		internal void SetCurrentThermalSightSettings(float t)
		{
			if (InLevelGearThermals.TryGetValue(CurrentGearPID, out var value) && base.definitions.TryGetValue(CurrentGearPID, out var value2))
			{
				Renderer[] array = value;
				foreach (Renderer obj in array)
				{
					float zoom = value2.Definition.Shader.Zoom;
					float offAimPixelZoom = value2.Definition.OffAimPixelZoom;
					float num = Mathf.Lerp(zoom, offAimPixelZoom, t);
					obj.material.SetFloat("_Zoom", num);
				}
			}
		}

		private void Clear()
		{
			CurrentGearPID = 0u;
			CleanupInLevelGearThermals();
			CleanupPuzzleVisuals();
		}

		private TSAManager()
		{
			LevelAPI.OnBuildStart += Clear;
			LevelAPI.OnLevelCleanup += Clear;
		}

		static TSAManager()
		{
			Current = new TSAManager();
		}

		public void RegisterPuzzleVisual(CP_Bioscan_Core core)
		{
			Il2CppArrayBase<Renderer> componentsInChildren = ((Component)core).gameObject.GetComponentsInChildren<Renderer>(true);
			if (componentsInChildren == null)
			{
				return;
			}
			foreach (Renderer item2 in ((IEnumerable<Renderer>)componentsInChildren).Where((Renderer comp) => ((Object)((Component)comp).gameObject).name.Equals("Zone")).ToList())
			{
				GameObject gameObject = ((Component)item2).gameObject;
				float @float = item2.material.GetFloat("_Intensity");
				float float2 = item2.material.GetFloat("_BehindWallIntensity");
				PuzzleVisualWrapper item = new PuzzleVisualWrapper
				{
					GO = gameObject,
					Renderer = item2,
					Intensity = @float,
					BehindWallIntensity = float2
				};
				PuzzleVisuals.Add(item);
			}
		}

		public void RegisterPuzzleVisual(PuzzleVisualWrapper wrapper)
		{
			PuzzleVisuals.Add(wrapper);
		}

		internal void SetPuzzleVisualsIntensity(float t)
		{
			PuzzleVisuals.ForEach(delegate(PuzzleVisualWrapper v)
			{
				v.SetIntensity(t);
			});
		}

		private void CleanupPuzzleVisuals()
		{
			PuzzleVisuals.Clear();
		}
	}
}
namespace ThermalSights.Patches
{
	internal static class CP_Bioscan_Core_Setup
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Bioscan_Core), "Setup")]
		private static void Post_CaptureBioscanVisual(CP_Bioscan_Core __instance)
		{
			TSAManager.Current.RegisterPuzzleVisual(__instance);
		}
	}
	[HarmonyPatch]
	internal static class FirstPersonItemHolder_SetWieldedItem
	{
		public static event Action<FirstPersonItemHolder, ItemEquippable> OnItemWielded;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FirstPersonItemHolder), "SetWieldedItem")]
		private static void Post_SetWieldedItem(FirstPersonItemHolder __instance, ItemEquippable item)
		{
			TSAManager.Current.OnPlayerItemWielded(__instance, item);
			TSAManager.Current.SetPuzzleVisualsIntensity(1f);
			TSAManager.Current.SetCurrentThermalSightSettings(1f);
			FirstPersonItemHolder_SetWieldedItem.OnItemWielded?.Invoke(__instance, item);
		}
	}
	[HarmonyPatch]
	internal static class FPIS_Aim_Update
	{
		public static event Action<FPIS_Aim, float> OnAimUpdate;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FPIS_Aim), "Update")]
		private static void Post_Aim_Update(FPIS_Aim __instance)
		{
			if (!((Object)(object)((FPItemState)__instance).Holder.WieldedItem == (Object)null))
			{
				float num = 1f - FirstPersonItemHolder.m_transitionDelta;
				if (!TSAManager.Current.IsGearWithThermal(TSAManager.Current.CurrentGearPID))
				{
					num = Math.Max(0.05f, num);
				}
				else
				{
					TSAManager.Current.SetCurrentThermalSightSettings(num);
				}
				TSAManager.Current.SetPuzzleVisualsIntensity(num);
				FPIS_Aim_Update.OnAimUpdate?.Invoke(__instance, num);
			}
		}
	}
}
namespace ThermalSights.Definition
{
	public class TSADefinition
	{
		public float OffAimPixelZoom { get; set; } = 1f;


		public TSShader Shader { get; set; } = new TSShader();

	}
	public class TSShader
	{
		[JsonPropertyName("DistanceFalloff")]
		[Range(0.0, 1.0)]
		public float HeatFalloff { get; set; } = 0.01f;


		[Range(0.0, 1.0)]
		public float FogFalloff { get; set; } = 0.1f;


		[JsonPropertyName("PixelZoom")]
		[Range(0.0, 1.0)]
		public float Zoom { get; set; } = 0.8f;


		[JsonPropertyName("AspectRatioAdjust")]
		[Range(0.0, 2.0)]
		public float RatioAdjust { get; set; } = 1f;


		[Range(0.0, 1.0)]
		public float DistortionCenter { get; set; } = 0.5f;


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


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


		public float DistortionSignalSpeed { get; set; } = 0.025f;


		[Range(0.0, 1.0)]
		public float DistortionMin { get; set; } = 0.01f;


		[Range(0.0, 1.0)]
		public float DistortionMax { get; set; } = 0.4f;


		[JsonPropertyName("AmbientTemperature")]
		[Range(0.0, 1.0)]
		public float AmbientTemp { get; set; } = 0.15f;


		[JsonPropertyName("BackgroundTemperature")]
		[Range(0.0, 1.0)]
		public float BackgroundTemp { get; set; } = 0.05f;


		[Range(0.0, 10.0)]
		public float AlbedoColorFactor { get; set; } = 0.5f;


		[Range(0.0, 10.0)]
		public float AmbientColorFactor { get; set; } = 5f;


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


		public float BodyOcclusionHeat { get; set; } = 2.5f;


		[Range(0.0, 1.0)]
		public float ScreenIntensity { get; set; } = 0.2f;


		[Range(0.0, 1.0)]
		public float OffAngleFade { get; set; } = 0.95f;


		[Range(0.0, 1.0)]
		public float Noise { get; set; } = 0.1f;


		[JsonPropertyName("MinShadowEnemyDistortion")]
		[Range(0.0, 1.0)]
		public float DistortionMinShadowEnemies { get; set; } = 0.2f;


		[JsonPropertyName("MaxShadowEnemyDistortion")]
		[Range(0.0, 1.0)]
		public float DistortionMaxShadowEnemies { get; set; } = 1f;


		[Range(0.0, 1.0)]
		public float DistortionSignalSpeedShadowEnemies { get; set; } = 1f;


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


		[Range(0.0, 1.0)]
		public float ShadowEnemyHeat { get; set; } = 0.1f;


		public EOSColor ReticuleColorA { get; set; } = new EOSColor
		{
			r = 1f,
			g = 1f,
			b = 1f,
			a = 1f
		};


		public EOSColor ReticuleColorB { get; set; } = new EOSColor
		{
			r = 1f,
			g = 1f,
			b = 1f,
			a = 1f
		};


		public EOSColor ReticuleColorC { get; set; } = new EOSColor
		{
			r = 1f,
			g = 1f,
			b = 1f,
			a = 1f
		};


		[Range(0.0, 20.0)]
		public float SightDirt { get; set; }

		public bool LitGlass { get; set; }

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


		public Vec4 AxisX { get; set; } = new Vec4();


		public Vec4 AxisY { get; set; } = new Vec4();


		public Vec4 AxisZ { get; set; } = new Vec4();


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


		[JsonPropertyName("Distance1")]
		[Range(0.0, 100.0)]
		public float ProjDist1 { get; set; } = 100f;


		[JsonPropertyName("Distance2")]
		[Range(0.0, 100.0)]
		public float ProjDist2 { get; set; } = 66f;


		[JsonPropertyName("Distance3")]
		[Range(0.0, 100.0)]
		public float ProjDist3 { get; set; } = 33f;


		[JsonPropertyName("Size1")]
		[Range(0.0, 3.0)]
		public float ProjSize1 { get; set; } = 1f;


		[JsonPropertyName("Size2")]
		[Range(0.0, 3.0)]
		public float ProjSize2 { get; set; } = 1f;


		[JsonPropertyName("Size3")]
		[Range(0.0, 3.0)]
		public float ProjSize3 { get; set; } = 1f;


		[JsonPropertyName("Zeroing")]
		[Range(-1.0, 1.0)]
		public float ZeroOffset { get; set; }
	}
}

plugins/XiaoTian-SURVIVAL/SURVIVAL/Custom/net6/LEGACY.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using AIGraph;
using AK;
using Agents;
using AssetShards;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using BoosterImplants;
using CellMenu;
using ChainedPuzzles;
using EOSExt.Reactor.Managers;
using Enemies;
using ExtraObjectiveSetup;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.ExtendedWardenEvents;
using ExtraObjectiveSetup.Instances;
using ExtraObjectiveSetup.JSON;
using ExtraObjectiveSetup.Utils;
using FloLib.Infos;
using FloLib.Networks.Replications;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using GameEvent;
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.ExtraEvents.Patches;
using LEGACY.LegacyOverride;
using LEGACY.LegacyOverride.DummyVisual;
using LEGACY.LegacyOverride.DummyVisual.VisualGOAnimation;
using LEGACY.LegacyOverride.DummyVisual.VisualGOAnimation.AnimationConfig;
using LEGACY.LegacyOverride.DummyVisual.VisualSequenceType;
using LEGACY.LegacyOverride.ElevatorCargo;
using LEGACY.LegacyOverride.EnemyTagger;
using LEGACY.LegacyOverride.EventScan;
using LEGACY.LegacyOverride.ExpeditionIntelNotification;
using LEGACY.LegacyOverride.ExpeditionSuccessPage;
using LEGACY.LegacyOverride.FogBeacon;
using LEGACY.LegacyOverride.ForceFail;
using LEGACY.LegacyOverride.Music;
using LEGACY.LegacyOverride.ResourceStations;
using LEGACY.LegacyOverride.Restart;
using LEGACY.Utils;
using LEGACY.VanillaFix;
using LevelGeneration;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using ScanPosOverride.Managers;
using TMPro;
using ThermalSights;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("LEGACY")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LEGACY")]
[assembly: AssemblyTitle("LEGACY")]
[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.2+git44e73d7-dirty-main".Remove("x.x.x".Length);
		((TMP_Text)__instance.m_watermarkText).SetText("<color=red>MODDED</color> <color=orange>" + text + "</color>\n<color=#33ff99>SURVIVAL</color>", true);
	}
}
namespace LEGACY
{
	internal static class Assets
	{
		public static GameObject CircleSensor { get; private set; }

		public static GameObject MovableSensor { get; private set; }

		public static GameObject OBSVisual { get; private set; }

		public static GameObject ObjectiveMarker { get; private set; }

		public static GameObject EventScan { get; private set; }

		internal static GameObject DummyScan { get; private set; }

		internal static GameObject DummySensor { get; private set; }

		internal static GameObject AmmoStation { get; private set; }

		internal static GameObject MediStation { get; private set; }

		internal static GameObject ToolStation { get; private set; }

		internal static GameObject RestartPage { get; private set; }

		public static void Init()
		{
			CircleSensor = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/CircleSensor.prefab");
			MovableSensor = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/MovableSensor.prefab");
			OBSVisual = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/OBSVisual.prefab");
			ObjectiveMarker = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/ObjectiveMarker.prefab");
			EventScan = AssetAPI.GetLoadedAsset<GameObject>("Assets/EventObjects/EventScan.prefab");
			DummyScan = AssetAPI.GetLoadedAsset<GameObject>("Assets/DummyVisual/DummyScan.prefab");
			DummySensor = AssetAPI.GetLoadedAsset<GameObject>("Assets/DummyVisual/DummySensor.prefab");
			AmmoStation = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/AmmoStation.prefab");
			MediStation = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/MediStation.prefab");
			ToolStation = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/ToolStation.prefab");
			RestartPage = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/CM_PageRestart_CellUI.prefab");
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Inas.LEGACY", "LEGACY", "4.4.5")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas";

		public const string RUNDOWN_NAME = "LEGACY";

		public const string VERSION = "4.4.5";

		public const bool TESTING = false;

		public const string TEST_STRING = "TESTING";

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			m_Harmony = new Harmony("LEGACY");
			m_Harmony.PatchAll();
			LegacyOverrideManagers.Init();
			LegacyExtraEvents.Init();
			LEGACY.VanillaFix.Debugger.Current.Init();
			AssetAPI.OnAssetBundlesLoaded += Assets.Init;
			EventAPI.OnManagersSetup += delegate
			{
				AssetShardManager.OnStartupAssetsLoaded += Action.op_Implicit((Action)MainMenuGuiLayer.Current.PageRundownNew.SetupCustomTutorialButton);
			};
		}
	}
}
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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Invalid comparison between Unknown and I4
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected I4, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: 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;
				eReactorStatus val3 = status;
				switch (val3 - 7)
				{
				default:
					return;
				case 0:
					val2 = (eWardenObjectiveEventTrigger)1;
					break;
				case 1:
					val2 = (eWardenObjectiveEventTrigger)2;
					break;
				case 2:
					val2 = (eWardenObjectiveEventTrigger)3;
					break;
				}
				LG_LayerType layerType = __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_000e: 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_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: 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), "OnStateChange")]
		private static void Post_ExecuteOnNoneEventsOnDefenseStart(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: 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);
				});
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_ReactorStartup_OverwriteGUIBehaviour
	{
		private static HashSet<uint> ForceDisableLevels;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateChange")]
		private static bool Pre_HideReactorMessageForInfiniteWave(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Invalid comparison between Unknown and I4
			//IL_002c: 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: Invalid comparison between Unknown and I4
			//IL_0053: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected I4, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			if (oldState.status == newState.status)
			{
				return true;
			}
			if ((int)newState.status != 2 && (int)newState.status != 3 && (int)newState.status != 4)
			{
				return true;
			}
			if (ForceDisable())
			{
				if (oldState.stateCount != newState.stateCount)
				{
					__instance.OnStateCountUpdate(newState.stateCount);
				}
				if (oldState.stateProgress != newState.stateProgress)
				{
					__instance.OnStateProgressUpdate(newState.stateProgress);
				}
				__instance.ReadyForVerification = false;
				eReactorStatus status = newState.status;
				eReactorStatus val = status;
				switch (val - 2)
				{
				case 0:
				{
					WardenObjectiveDataBlock val2 = null;
					if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref val2) || val2 == null)
					{
						LegacyLogger.Error("Patch_ReactorStartup_OverwriteGUIBehaviour: ");
						LegacyLogger.Error("Failed to get warden objective datablock");
						break;
					}
					__instance.m_lightCollection.SetMode(val2.LightsOnDuringIntro);
					__instance.m_lightCollection.ResetUpdateValues(true);
					__instance.lcReset = true;
					__instance.m_lightsBlinking = false;
					__instance.m_spawnEnemies = false;
					__instance.m_progressUpdateEnabled = true;
					__instance.m_alarmCountdownPlayed = false;
					__instance.m_currentDuration = ((!newState.verifyFailed) ? __instance.m_currentWaveData.Warmup : __instance.m_currentWaveData.WarmupFail);
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)1, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
					if (__instance.m_currentWaveCount == 1)
					{
						Debug.LogError(Object.op_Implicit("Reactor IDLE START"));
						__instance.m_sound.Post(EVENTS.REACTOR_POWER_LEVEL_1_LOOP, true);
						__instance.m_sound.SetRTPCValue(GAME_PARAMETERS.REACTOR_POWER, 0f);
					}
					else
					{
						Debug.LogError(Object.op_Implicit("Reactor REACTOR_POWER_DOWN"));
						__instance.m_sound.Post(EVENTS.REACTOR_POWER_LEVEL_2_TO_1_TRANSITION, true);
						__instance.m_sound.SetRTPCValue(GAME_PARAMETERS.REACTOR_POWER, 0f);
					}
					break;
				}
				case 1:
					__instance.m_lightCollection.ResetUpdateValues(true);
					__instance.lcReset = true;
					__instance.m_spawnEnemies = true;
					__instance.m_currentEnemyWaveIndex = 0;
					__instance.m_alarmCountdownPlayed = false;
					__instance.m_progressUpdateEnabled = true;
					__instance.m_currentDuration = __instance.m_currentWaveData.Wave;
					__instance.m_sound.Post(EVENTS.REACTOR_POWER_LEVEL_1_TO_3_TRANSITION, true);
					break;
				case 2:
					__instance.m_lightCollection.ResetUpdateValues(false);
					__instance.lcReset = true;
					__instance.m_spawnEnemies = false;
					__instance.m_progressUpdateEnabled = true;
					__instance.ReadyForVerification = true;
					Debug.Log(Object.op_Implicit("Wait for verify! newState.verifyFailed? " + newState.verifyFailed));
					__instance.m_currentDuration = ((!newState.verifyFailed) ? __instance.m_currentWaveData.Verify : __instance.m_currentWaveData.VerifyFail);
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)2, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
					break;
				}
				__instance.m_currentState = newState;
				return false;
			}
			return true;
		}

		private static bool ForceDisable()
		{
			return ForceDisableLevels.Contains(RundownManager.ActiveExpedition.LevelLayoutData);
		}

		static Patch_ReactorStartup_OverwriteGUIBehaviour()
		{
			ForceDisableLevels = new HashSet<uint>();
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock("Legacy_L3E2_L1");
			if (block != null)
			{
				ForceDisableLevels.Add(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID);
			}
			block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock("Legacy_L1E1_L1");
			if (block != null)
			{
				ForceDisableLevels.Add(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID);
			}
		}
	}
}
namespace LEGACY.HardcodedBehaviours
{
	[HarmonyPatch]
	internal class Patch_PickupItem_Hardcoded
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_Distribute_PickupItemsPerZone), "Build")]
		private static void Pre_LG_Distribute_PickupItemsPerZone(LG_Distribute_PickupItemsPerZone __instance)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Invalid comparison between Unknown and I4
			//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)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Invalid comparison between Unknown and I4
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Invalid comparison between Unknown and I4
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock("LAYOUT_O4_1_L1");
			if (block == null || RundownManager.ActiveExpedition.LevelLayoutData != ((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID)
			{
				return;
			}
			eLocalZoneIndex localIndex = __instance.m_zone.LocalIndex;
			eLocalZoneIndex val = localIndex;
			if ((int)val != 1)
			{
				if ((int)val == 5)
				{
					__instance.m_zonePlacementWeights.Start = 0f;
					__instance.m_zonePlacementWeights.Middle = 0f;
					__instance.m_zonePlacementWeights.End = 100000f;
				}
				return;
			}
			ePickupItemType pickupType = __instance.m_pickupType;
			ePickupItemType val2 = pickupType;
			if ((int)val2 == 1)
			{
				__instance.m_zonePlacementWeights.Start = 100000f;
				__instance.m_zonePlacementWeights.Middle = 0f;
				__instance.m_zonePlacementWeights.End = 0f;
			}
		}
	}
}
namespace LEGACY.VanillaFix
{
	[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_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Invalid comparison between Unknown and I4
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			eDoorStatus status = state.status;
			eDoorStatus val = status;
			if ((val - 4 <= 1 || (int)val == 9) && (int)__instance.m_lastState.status == 6 && !isRecall)
			{
				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]
	internal class Debugger
	{
		public static Debugger Current { get; private set; } = new Debugger();


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


		private Debugger()
		{
		}

		internal void Init()
		{
			if (DEBUGGING)
			{
			}
		}

		private void f1(int k, out string v)
		{
			if (k < 2)
			{
				v = "2";
			}
			v = null;
		}

		private void f2(int k, ref string v)
		{
			if (k < 2)
			{
				v = "2";
			}
		}
	}
}
namespace LEGACY.Utils
{
	public delegate float EasingFunction(float t, float b, float c, float d);
	public delegate bool BoolCheck();
	internal static class CoroutineEase
	{
		[CompilerGenerated]
		private sealed class <DoEaseLocalPos>d__1 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public Transform trans;

			public Vector3 sourcePos;

			public Vector3 targetPos;

			public float startTime;

			public float duration;

			public EasingFunction ease;

			public Action onDone;

			public BoolCheck checkAbort;

			private bool <doAbort>5__1;

			private float <t>5__2;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <DoEaseLocalPos>d__1(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_00e2: 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_0086: 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)
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<doAbort>5__1 = false;
					break;
				case 1:
					<>1__state = -1;
					break;
				}
				if (Clock.Time < startTime + duration && !<doAbort>5__1)
				{
					<doAbort>5__1 = checkAbort != null && checkAbort();
					<t>5__2 = ease(Clock.Time - startTime, 0f, 1f, duration);
					trans.localPosition = Vector3.Lerp(sourcePos, targetPos, <t>5__2);
					<>2__current = null;
					<>1__state = 1;
					return true;
				}
				trans.localPosition = targetPos;
				if (!<doAbort>5__1 && onDone != null)
				{
					onDone();
				}
				return false;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		[CompilerGenerated]
		private sealed class <DoEaseLocalRot>d__2 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public Transform trans;

			public Vector3 sourceEuler;

			public Vector3 targetEuler;

			public float startTime;

			public float duration;

			public EasingFunction ease;

			public Action onDone;

			public BoolCheck checkAbort;

			private bool <doAbort>5__1;

			private float <t>5__2;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <DoEaseLocalRot>d__2(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_00e2: 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_0086: 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)
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<doAbort>5__1 = false;
					break;
				case 1:
					<>1__state = -1;
					break;
				}
				if (Clock.Time < startTime + duration && !<doAbort>5__1)
				{
					<doAbort>5__1 = checkAbort != null && checkAbort();
					<t>5__2 = ease(Clock.Time - startTime, 0f, 1f, duration);
					trans.localEulerAngles = Vector3.Lerp(sourceEuler, targetEuler, <t>5__2);
					<>2__current = null;
					<>1__state = 1;
					return true;
				}
				trans.localEulerAngles = targetEuler;
				if (!<doAbort>5__1 && onDone != null)
				{
					onDone();
				}
				return false;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		[CompilerGenerated]
		private sealed class <DoEaseLocalScale>d__0 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public Transform trans;

			public Vector3 startScale;

			public Vector3 targetScale;

			public float startTime;

			public float duration;

			public EasingFunction ease;

			public Action onDone;

			public BoolCheck checkAbort;

			private bool <doAbort>5__1;

			private float <t>5__2;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <DoEaseLocalScale>d__0(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_00e2: 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_0086: 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)
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<doAbort>5__1 = false;
					break;
				case 1:
					<>1__state = -1;
					break;
				}
				if (Clock.Time < startTime + duration && !<doAbort>5__1)
				{
					<doAbort>5__1 = checkAbort != null && checkAbort();
					<t>5__2 = ease(Clock.Time - startTime, 0f, 1f, duration);
					trans.localScale = Vector3.Lerp(startScale, targetScale, <t>5__2);
					<>2__current = null;
					<>1__state = 1;
					return true;
				}
				trans.localScale = targetScale;
				if (!<doAbort>5__1 && onDone != null)
				{
					onDone();
				}
				return false;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		[IteratorStateMachine(typeof(<DoEaseLocalScale>d__0))]
		private static IEnumerator DoEaseLocalScale(Transform trans, Vector3 startScale, Vector3 targetScale, float startTime, float duration, EasingFunction ease, Action onDone, BoolCheck checkAbort)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DoEaseLocalScale>d__0(0)
			{
				trans = trans,
				startScale = startScale,
				targetScale = targetScale,
				startTime = startTime,
				duration = duration,
				ease = ease,
				onDone = onDone,
				checkAbort = checkAbort
			};
		}

		[IteratorStateMachine(typeof(<DoEaseLocalPos>d__1))]
		private static IEnumerator DoEaseLocalPos(Transform trans, Vector3 sourcePos, Vector3 targetPos, float startTime, float duration, EasingFunction ease, Action onDone, BoolCheck checkAbort)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DoEaseLocalPos>d__1(0)
			{
				trans = trans,
				sourcePos = sourcePos,
				targetPos = targetPos,
				startTime = startTime,
				duration = duration,
				ease = ease,
				onDone = onDone,
				checkAbort = checkAbort
			};
		}

		[IteratorStateMachine(typeof(<DoEaseLocalRot>d__2))]
		private static IEnumerator DoEaseLocalRot(Transform trans, Vector3 sourceEuler, Vector3 targetEuler, float startTime, float duration, EasingFunction ease, Action onDone, BoolCheck checkAbort)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DoEaseLocalRot>d__2(0)
			{
				trans = trans,
				sourceEuler = sourceEuler,
				targetEuler = targetEuler,
				startTime = startTime,
				duration = duration,
				ease = ease,
				onDone = onDone,
				checkAbort = checkAbort
			};
		}

		internal static Coroutine EaseLocalScale(Transform trans, Vector3 startScale, Vector3 targetScale, float duration, EasingFunction ease = null, Action onDone = null, BoolCheck checkAbort = null)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			EasingFunction ease2 = ease ?? new EasingFunction(Easing.EaseOutExpo);
			return CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DoEaseLocalScale(trans, startScale, targetScale, Clock.Time, duration, ease2, onDone, checkAbort)), (Action)null);
		}

		internal static Coroutine EaseLocalPos(Transform trans, Vector3 sourcePos, Vector3 targetPos, float duration, EasingFunction ease = null, Action onDone = null, BoolCheck checkAbort = null)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			EasingFunction ease2 = ease ?? new EasingFunction(Easing.EaseOutExpo);
			return CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DoEaseLocalPos(trans, sourcePos, targetPos, Clock.Time, duration, ease2, onDone, checkAbort)), (Action)null);
		}

		internal static Coroutine EaseLocalRot(Transform trans, Vector3 sourceEuler, Vector3 targetEuler, float duration, EasingFunction ease = null, Action onDone = null, BoolCheck checkAbort = null)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			EasingFunction ease2 = ease ?? new EasingFunction(Easing.EaseOutExpo);
			return CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DoEaseLocalRot(trans, sourceEuler, targetEuler, Clock.Time, duration, ease2, onDone, checkAbort)), (Action)null);
		}
	}
	public static class GOExtensions
	{
		public static GameObject GetChild(this GameObject go, string childName, bool substrSearch = false, bool recursiveSearch = true)
		{
			if (((Object)go).name.Equals(childName) || (substrSearch && ((Object)go).name.Contains(childName)))
			{
				return go;
			}
			for (int i = 0; i < go.transform.childCount; i++)
			{
				GameObject gameObject = ((Component)go.transform.GetChild(i)).gameObject;
				GameObject val = null;
				if (recursiveSearch)
				{
					val = gameObject.GetChild(childName, substrSearch);
				}
				else if (((Object)gameObject).name.Equals(childName) || (substrSearch && ((Object)gameObject).name.Contains(childName)))
				{
					val = gameObject;
				}
				if ((Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			return null;
		}
	}
	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)
			{
				CP_Holopath_Spline val2 = ((Il2CppObjectBase)val.m_spline).Cast<CP_Holopath_Spline>();
				CP_PlayerScanner val3 = ((Il2CppObjectBase)val.PlayerScanner).Cast<CP_PlayerScanner>();
				val3.ResetScanProgression(0f);
				val.Deactivate();
				return;
			}
			CP_Cluster_Core val4 = ((Il2CppObjectBase)ICore).TryCast<CP_Cluster_Core>();
			if ((Object)(object)val4 == (Object)null)
			{
				LegacyLogger.Error("ResetChild: found iChainedPuzzleCore that is neither CP_Bioscan_Core nor CP_Cluster_Core...");
				return;
			}
			CP_Holopath_Spline val5 = ((Il2CppObjectBase)val4.m_spline).Cast<CP_Holopath_Spline>();
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)val4.m_childCores)
			{
				ResetChild(item);
			}
			val4.Deactivate();
		}

		public static void ResetChainedPuzzle(ChainedPuzzleInstance chainedPuzzleInstance)
		{
			//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_0027: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: 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_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			if (chainedPuzzleInstance.Data.DisableSurvivalWaveOnComplete)
			{
				chainedPuzzleInstance.m_sound = new CellSoundPlayer(chainedPuzzleInstance.m_parent.position);
			}
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)chainedPuzzleInstance.m_chainedPuzzleCores)
			{
				ResetChild(item);
			}
			if (SNet.IsMaster)
			{
				pChainedPuzzleState state = chainedPuzzleInstance.m_stateReplicator.State;
				pChainedPuzzleState val = default(pChainedPuzzleState);
				val.status = (eChainedPuzzleStatus)0;
				val.currentSurvivalWave_EventID = state.currentSurvivalWave_EventID;
				val.isSolved = false;
				val.isActive = false;
				pChainedPuzzleState val2 = val;
				chainedPuzzleInstance.m_stateReplicator.InteractWithState(val2, new pChainedPuzzleInteraction
				{
					type = (eChainedPuzzleInteraction)2
				});
			}
		}

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

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

		public static bool IsPlayerInLevel(PlayerAgent player)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			return (int)player.Owner.Load<pGameState>().gameState == 10;
		}

		public static ChainedPuzzleInstance GetChainedPuzzleForCommandOnTerminal(LG_ComputerTerminal terminal, string command)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected I4, but got Unknown
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Invalid comparison between Unknown and I4
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Invalid comparison between Unknown and I4
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Invalid comparison between Unknown and I4
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Invalid comparison between Unknown and I4
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Invalid comparison between Unknown and I4
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Invalid comparison between Unknown and I4
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			uint num = 0u;
			if (terminal.SpawnNode.m_dimension.IsMainDimension)
			{
				LG_LayerType layerType = terminal.SpawnNode.LayerType;
				LG_LayerType val = layerType;
				switch ((int)val)
				{
				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> val2 = null;
			List<LG_ComputerTerminal> terminalsSpawnedInZone = terminal.SpawnNode.m_zone.TerminalsSpawnedInZone;
			int num2 = terminalsSpawnedInZone.IndexOf(terminal);
			ExpeditionZoneData val3 = null;
			Enumerator<ExpeditionZoneData> enumerator = block.Zones.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ExpeditionZoneData current = enumerator.Current;
				if (current.LocalIndex == terminal.SpawnNode.m_zone.LocalIndex)
				{
					val3 = current;
					break;
				}
			}
			if (val3 == null)
			{
				LegacyLogger.Error("Cannot find target zone data.");
				return null;
			}
			if (val3.TerminalPlacements.Count != terminalsSpawnedInZone.Count)
			{
				LegacyLogger.Error("The numbers of terminal placement and spawn, skipped for the zone terminal.");
				return null;
			}
			val2 = val3.TerminalPlacements[num2].UniqueCommands;
			if (val2.Count == 0)
			{
				return null;
			}
			List<WardenObjectiveEventData> val4 = null;
			TERM_Command val5 = (TERM_Command)0;
			Enumerator<CustomTerminalCommand> enumerator2 = val2.GetEnumerator();
			string text = default(string);
			string text2 = default(string);
			while (enumerator2.MoveNext())
			{
				CustomTerminalCommand current2 = enumerator2.Current;
				if (current2.Command == command)
				{
					val4 = current2.CommandEvents;
					if (!terminal.m_command.TryGetCommand(current2.Command, ref val5, ref text, ref text2))
					{
						LegacyLogger.Error("Cannot get TERM_COMMAND for command {0} on the specified terminal.");
					}
					break;
				}
			}
			if (val4 == null || (int)val5 == 0)
			{
				return null;
			}
			if ((int)val5 != 38 && (int)val5 != 39 && (int)val5 != 40 && (int)val5 != 41 && (int)val5 != 42)
			{
				return null;
			}
			ChainedPuzzleInstance val6 = null;
			for (int i = 0; i < val4.Count && (val4[i].ChainPuzzle == 0 || !terminal.TryGetChainPuzzleForCommand(val5, i, ref val6) || !((Object)(object)val6 != (Object)null)); i++)
			{
			}
			return val6;
		}

		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_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: 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_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_0034: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Invalid comparison between I4 and Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Invalid comparison between I4 and Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected I4, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Invalid comparison between I4 and Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Invalid comparison between I4 and Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected I4, but got Unknown
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: 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_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_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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			if ((Object)(object)zone == (Object)null)
			{
				return -1;
			}
			LG_LayerType type = zone.m_layer.m_type;
			eLocalZoneIndex localIndex = zone.LocalIndex;
			eDimensionIndex currentDimensionIndex = 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_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: 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;
			}
			return (terminalIndex < 0) ? null : val.TerminalsSpawnedInZone[terminalIndex];
		}

		public static AIG_NodeCluster GetNodeFromDimensionPosition(eDimensionIndex dimensionIndex, Vector3 position)
		{
			//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_0013: 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)
			AIG_GeomorphNodeVolume val = default(AIG_GeomorphNodeVolume);
			AIG_VoxelNodePillar val2 = default(AIG_VoxelNodePillar);
			AIG_INode val3 = default(AIG_INode);
			AIG_NodeCluster result = default(AIG_NodeCluster);
			if (!AIG_GeomorphNodeVolume.TryGetGeomorphVolume(0, dimensionIndex, position, ref val) || !((AIG_NodeVolume)val).m_voxelNodeVolume.TryGetPillar(position, ref val2) || !val2.TryGetVoxelNode(position.y, ref val3) || !AIG_NodeCluster.TryGetNodeCluster(val3.ClusterID, ref result))
			{
				LegacyLogger.Error("TryWarpTo : Position is not valid, try again inside an area.");
				return null;
			}
			return result;
		}
	}
	internal static class Json
	{
		static Json()
		{
		}

		public static T Deserialize<T>(string json)
		{
			return EOSJson.Deserialize<T>(json);
		}

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

		public static string Serialize<T>(T value)
		{
			return EOSJson.Serialize<T>(value);
		}

		public static void Load<T>(string filePath, out T config) where T : new()
		{
			config = Deserialize<T>(File.ReadAllText(filePath));
		}
	}
	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; } = (eWardenObjectiveEventTrigger)0;


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


		public eDimensionIndex DimensionIndex { get; set; } = (eDimensionIndex)0;


		public LG_LayerType Layer { get; set; } = (LG_LayerType)0;


		public eLocalZoneIndex LocalIndex { get; set; } = (eLocalZoneIndex)0;


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


		public uint EnemyID { get; set; }

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


		public float Delay { get; set; } = 0f;


		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_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: 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_004a: 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_0067: Expected I4, but got Unknown
			//IL_00b0: 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;
					LG_AreaSize val = size;
					switch (val - 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_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			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 class NavMarkerManager
	{
		private Dictionary<string, GameObject> markerVisuals = new Dictionary<string, GameObject>();

		private Dictionary<string, NavMarker> navMarkers = new Dictionary<string, NavMarker>();

		private List<GameObject> arbitraryNavMarkers = new List<GameObject>();

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


		private GameObject InstantiateMarkerVisual()
		{
			//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_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)
			GameObject val = Object.Instantiate<GameObject>(Assets.ObjectiveMarker);
			float num = 0.16216217f;
			Transform transform = val.transform;
			transform.localPosition += Vector3.up * num;
			return val;
		}

		public void EnableMarkerAt(string markerName, GameObject target, float scale)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			if (navMarkers.ContainsKey(markerName))
			{
				navMarkers[markerName].SetVisible(true);
			}
			else
			{
				NavMarker val = GuiManager.NavMarkerLayer.PrepareGenericMarker(target);
				if ((Object)(object)val != (Object)null)
				{
					val.SetColor(new Color(0.855f, 0.482f, 0.976f));
					val.SetStyle((eNavMarkerStyle)14);
					val.SetVisible(true);
					navMarkers[markerName] = val;
				}
				else
				{
					LegacyLogger.Error("EnableMarkerAt: got null nav marker");
				}
			}
			GameObject val2 = null;
			if (markerVisuals.ContainsKey(markerName))
			{
				val2 = markerVisuals[markerName];
			}
			else
			{
				val2 = InstantiateMarkerVisual();
				val2.transform.localScale = new Vector3(scale, scale, scale);
				val2.transform.SetPositionAndRotation(target.transform.position, Quaternion.identity);
				markerVisuals[markerName] = val2;
			}
			CoroutineManager.BlinkIn(val2, 0f);
			LegacyLogger.Debug("EnableMarker: marker " + markerName + " enabled");
		}

		public void EnableArbitraryMarkerAt(string markerName, Vector3 Position)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			if (navMarkers.ContainsKey(markerName))
			{
				navMarkers[markerName].SetVisible(true);
			}
			else
			{
				GameObject val = new GameObject(markerName);
				val.transform.SetPositionAndRotation(Position, Quaternion.identity);
				arbitraryNavMarkers.Add(val);
				NavMarker val2 = GuiManager.NavMarkerLayer.PrepareGenericMarker(val);
				if ((Object)(object)val2 != (Object)null)
				{
					val2.SetColor(new Color(0.855f, 0.482f, 0.976f));
					val2.SetStyle((eNavMarkerStyle)14);
					val2.SetVisible(true);
					navMarkers[markerName] = val2;
				}
				else
				{
					LegacyLogger.Error("EnableMarkerAt: got null nav marker");
				}
			}
			LegacyLogger.Debug("EnableMarker: marker " + markerName + " enabled");
		}

		internal (GameObject markerVisual, NavMarker navMakrer) GetMarkerVisuals(string markerName)
		{
			GameObject value;
			NavMarker value2;
			return (markerVisuals.TryGetValue(markerName, out value) && navMarkers.TryGetValue(markerName, out value2)) ? (value, value2) : (null, null);
		}

		public void DisableMakrer(string markerName)
		{
			if (navMarkers.ContainsKey(markerName))
			{
				navMarkers[markerName].SetVisible(false);
			}
			if (markerVisuals.ContainsKey(markerName))
			{
				GameObject val = markerVisuals[markerName];
				if (val.active)
				{
					CoroutineManager.BlinkOut(val, 0f);
				}
				LegacyLogger.Debug("DisableMakrer: marker " + markerName + " disabled");
			}
		}

		public void Clear()
		{
			foreach (GameObject value in markerVisuals.Values)
			{
				Object.Destroy((Object)(object)value);
			}
			arbitraryNavMarkers.ForEach((Action<GameObject>)Object.Destroy);
			markerVisuals.Clear();
			navMarkers.Clear();
			arbitraryNavMarkers.Clear();
		}

		private NavMarkerManager()
		{
			LevelAPI.OnBuildStart += Clear;
			LevelAPI.OnLevelCleanup += Clear;
		}
	}
	internal static class LegacyOverrideManagers
	{
		internal static readonly string LEGACY_CONFIG_PATH = Path.Combine(MTFOPathAPI.CustomPath, "LegacyOverride");

		internal static void Init()
		{
			ElevatorCargoOverrideManager.Current.Init();
			BigPickupFogBeaconSettingManager.Current.Init();
			EnemyTaggerSettingManager.Current.Init();
			ForceFailManager.Current.Init();
			((GenericExpeditionDefinitionManager<ExpeditionIntel>)ExpeditionIntelNotifier.Current).Init();
			((GenericExpeditionDefinitionManager<EventScanDefinition>)EventScanManager.Current).Init();
			((GenericExpeditionDefinitionManager<VisualGroupDefinition>)VisualManager.Current).Init();
			((GenericExpeditionDefinitionManager<MusicOverride>)MusicStateOverrider.Current).Init();
			((ZoneDefinitionManager<LevelSpawnedFogBeaconDefinition>)LevelSpawnedFogBeaconManager.Current).Init();
			((GenericExpeditionDefinitionManager<SuccessPageCustomization>)SuccessPageCustomizationManager.Current).Init();
			((GenericExpeditionDefinitionManager<ResourceStationDefinition>)ResourceStationManager.Current).Init();
		}
	}
}
namespace LEGACY.LegacyOverride.Restart
{
	public static class CM_PageRestart
	{
		internal static TextMeshPro Text { get; private set; }

		internal static GameObject Reconnecting { get; private set; }

		public static GameObject Page { get; private set; }

		internal static void Setup()
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Assets.RestartPage == (Object)null)
			{
				return;
			}
			if ((Object)(object)Page != (Object)null)
			{
				LegacyLogger.Warning("Duplicate setup for CM_PageRestart!");
				try
				{
					Object.Destroy((Object)(object)Page);
				}
				finally
				{
					Page = null;
				}
			}
			Transform transform = ((Component)((GuiLayer)GuiManager.Current.m_mainMenuLayer).GuiLayerBase).transform;
			Page = Object.Instantiate<GameObject>(Assets.RestartPage, transform.position, transform.rotation, transform);
			CM_PageBase component = Page.GetComponent<CM_PageBase>();
			GameObject gameObject = ((Component)component.m_movingContentHolder).gameObject;
			Reconnecting = gameObject.GetChild("Reconnecting");
			GameObject gameObject2 = ((Component)GuiManager.Current.m_mainMenuLayer.PageMap.m_mapDisconnected.transform.GetChild(0)).gameObject;
			gameObject2 = Object.Instantiate<GameObject>(gameObject2, Reconnecting.transform);
			Text = gameObject2.GetComponent<TextMeshPro>();
			((Graphic)Text).color = new Color(0f, 1f, 72f / 85f, 1f);
			((TMP_Text)Text).SetText("RECONNECTING", true);
			((TMP_Text)Text).ForceMeshUpdate(false, false);
			Page.GetComponent<CM_PageBase>().Setup(GuiManager.Current.m_mainMenuLayer);
		}

		public static void SetPageActive(bool active)
		{
			Page.GetComponent<CM_PageBase>().SetPageActive(active);
		}
	}
}
namespace LEGACY.LegacyOverride.ResourceStations
{
	public sealed class ToolStation : ResourceStation
	{
		public override string ItemKey => $"Tool_Station_{base.SerialNumber}";

		protected override void SetupInteraction()
		{
			base.SetupInteraction();
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.InteractionPrompt.ToolStation");
			Interact.InteractionMessage = ((block == null) ? "TOOL STATION" : Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID));
		}

		protected override void Replenish(PlayerAgent player)
		{
			PlayerBackpack backpack = PlayerBackpackManager.GetBackpack(player.Owner);
			PlayerAmmoStorage ammoStorage = backpack.AmmoStorage;
			float num = Math.Max(0f, Math.Min(def.SupplyUplimit.Tool - ammoStorage.ClassAmmo.RelInPack, def.SupplyEfficiency.Tool));
			player.GiveAmmoRel((PlayerAgent)null, 0f, 0f, num);
			player.Sound.Post(EVENTS.AMMOPACK_APPLY, true);
		}

		public static ToolStation Instantiate(ResourceStationDefinition def)
		{
			if (def.StationType != StationType.TOOL)
			{
				LegacyLogger.Error($"Trying to instantiate MediStation with def with 'StationType': {def.StationType}!");
				return null;
			}
			GameObject gO = Object.Instantiate<GameObject>(Assets.ToolStation);
			return new ToolStation(def, gO);
		}

		private ToolStation(ResourceStationDefinition def, GameObject GO)
			: base(def, GO)
		{
		}

		static ToolStation()
		{
		}
	}
	public sealed class MediStation : ResourceStation
	{
		public const float VANILLA_MAX_HEALTH = 25f;

		public override string ItemKey => $"Health_Station_{base.SerialNumber}";

		protected override void SetupInteraction()
		{
			base.SetupInteraction();
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.InteractionPrompt.MediStation");
			Interact.InteractionMessage = ((block == null) ? "HEALTH STATION" : Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID));
		}

		protected override void Replenish(PlayerAgent player)
		{
			float health = ((Dam_SyncedDamageBase)player.Damage).Health;
			float num = def.SupplyUplimit.Medi * 25f;
			if (!(health >= num))
			{
				player.GiveHealth((PlayerAgent)null, Math.Min(def.SupplyEfficiency.Medi, (num - health) / 25f));
				player.Sound.Post(EVENTS.MEDPACK_APPLY, true);
			}
		}

		public static MediStation Instantiate(ResourceStationDefinition def)
		{
			if (def.StationType != 0)
			{
				LegacyLogger.Error($"Trying to instantiate MediStation with def with 'StationType': {def.StationType}!");
				return null;
			}
			GameObject gO = Object.Instantiate<GameObject>(Assets.MediStation);
			return new MediStation(def, gO);
		}

		private MediStation(ResourceStationDefinition def, GameObject GO)
			: base(def, GO)
		{
		}

		static MediStation()
		{
		}
	}
	public abstract class ResourceStation
	{
		[CompilerGenerated]
		private sealed class <BlinkMarker>d__61 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public ResourceStation <>4__this;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <BlinkMarker>d__61(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					break;
				case 1:
					<>1__state = -1;
					break;
				}
				<>4__this.StationMarkerGO.SetActive(!<>4__this.StationMarkerGO.active);
				<>2__current = (object)new WaitForSeconds(0.5f);
				<>1__state = 1;
				return true;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		public const int UNLIMITED_USE_TIME = int.MaxValue;

		private Coroutine m_blinkMarkerCoroutine = null;

		public virtual GameObject GameObject { get; protected set; }

		public GameObject InteractGO
		{
			get
			{
				GameObject gameObject = GameObject;
				return ((gameObject != null) ? ((Component)gameObject.transform.GetChild(3)).gameObject : null) ?? null;
			}
		}

		public GameObject StationMarkerGO
		{
			get
			{
				GameObject gameObject = GameObject;
				return ((gameObject != null) ? ((Component)gameObject.transform.GetChild(2)).gameObject : null) ?? null;
			}
		}

		public virtual Interact_Timed Interact { get; protected set; }

		public virtual ResourceStationDefinition def { get; protected set; }

		public RSTimer Timer { get; protected set; }

		public StateReplicator<RSStateStruct> StateReplicator { get; protected set; }

		public RSStateStruct State => StateReplicator?.State ?? new RSStateStruct();

		public LG_GenericTerminalItem TerminalItem { get; protected set; }

		public AIG_CourseNode SpawnNode
		{
			get
			{
				return TerminalItem.SpawnNode;
			}
			set
			{
				TerminalItem.SpawnNode = value;
			}
		}

		protected int SerialNumber { get; private set; }

		public virtual string ItemKey => $"Resource_Station_{SerialNumber}";

		public bool Enabled => State.Enabled;

		protected virtual bool InCooldown => State.RemainingUseTime <= 0 && State.CurrentCooldownTime > 0f;

		public virtual bool HasUnlimitedUseTime => def.AllowedUseTimePerCooldown == int.MaxValue;

		public virtual void Destroy()
		{
			if (m_blinkMarkerCoroutine != null)
			{
				CoroutineManager.StopCoroutine(m_blinkMarkerCoroutine);
				m_blinkMarkerCoroutine = null;
			}
			Object.Destroy((Object)(object)GameObject);
			StateReplicator?.Unload();
			Interact = null;
			def = null;
			StateReplicator = null;
		}

		protected virtual bool CanInteract()
		{
			return Enabled && !InCooldown;
		}

		protected abstract void Replenish(PlayerAgent player);

		protected virtual void SetInteractionText()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			string text = Text.Format(827u, (Object[])(object)new Object[1] { Object.op_Implicit(InputMapper.GetBindingName(((Interact_Base)Interact).InputAction)) });
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.OnAdditionalInteractionText.ResourceStation");
			string text2 = ((block == null) ? "TO REPLENISH" : Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID));
			string text3 = (HasUnlimitedUseTime ? string.Empty : $"({State.RemainingUseTime}/{def.AllowedUseTimePerCooldown})");
			GuiManager.InteractionLayer.SetInteractPrompt(Interact.InteractionMessage, text + text2 + text3, (ePUIMessageStyle)0);
		}

		protected virtual void OnTriggerInteraction(PlayerAgent player)
		{
			RSStateStruct state = State;
			int num = (HasUnlimitedUseTime ? int.MaxValue : Math.Max(state.RemainingUseTime - 1, 0));
			int num2 = player.Owner.PlayerSlotIndex();
			if (num2 < 0 || num2 >= ((Il2CppArrayBase<SNet_Slot>)(object)SNet.Slots.PlayerSlots).Count)
			{
				LegacyLogger.Error($"ResourceStation_OnTriggerInteraction: player {player.PlayerName} has invalid slot index: {num2}");
			}
			else
			{
				StateReplicator?.SetState(new RSStateStruct
				{
					LastInteractedPlayer = num2,
					RemainingUseTime = num,
					CurrentCooldownTime = ((num == 0) ? def.CooldownTime : 0f),
					Enabled = true
				});
			}
		}

		protected virtual void OnInteractionSelected(PlayerAgent agent, bool selected)
		{
			if (selected)
			{
				SetInteractionText();
			}
		}

		protected virtual void SetupInteraction()
		{
			Interact.InteractDuration = def.InteractDuration;
			Interact_Timed interact = Interact;
			interact.ExternalPlayerCanInteract += Func<PlayerAgent, bool>.op_Implicit((Func<PlayerAgent, bool>)((PlayerAgent _) => CanInteract()));
			Interact_Timed interact2 = Interact;
			interact2.OnInteractionSelected += Action<PlayerAgent, bool>.op_Implicit((Action<PlayerAgent, bool>)OnInteractionSelected);
			Interact_Timed interact3 = Interact;
			interact3.OnInteractionTriggered += Action<PlayerAgent>.op_Implicit((Action<PlayerAgent>)OnTriggerInteraction);
		}

		protected virtual void SetupTerminalItem()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = default(LG_Zone);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(((GlobalZoneIndex)def).DimensionIndex, ((GlobalZoneIndex)def).LayerType, ((GlobalZoneIndex)def).LocalIndex, ref val) || (Object)(object)val == (Object)null)
			{
				LegacyLogger.Error("ResourceStation: Cannot find spawn node!");
				return;
			}
			if (def.AreaIndex < 0 || def.AreaIndex >= val.m_areas.Count)
			{
				LegacyLogger.Error("ResourceStation: Cannot find spawn node - Area index is invalid!");
				return;
			}
			TerminalItem.Setup(ItemKey, val.m_areas[def.AreaIndex].m_courseNode);
			if (SpawnNode != null)
			{
				TerminalItem.FloorItemLocation = SpawnNode.m_zone.NavInfo.GetFormattedText((LG_NavInfoFormat)7);
			}
			TerminalItem.FloorItemStatus = (eFloorInventoryObjectStatus)0;
		}

		protected virtual void OnStateChanged(RSStateStruct oldState, RSStateStruct newState, bool isRecall)
		{
			if (isRecall)
			{
				return;
			}
			int lastInteractedPlayer = newState.LastInteractedPlayer;
			if (lastInteractedPlayer < 0 || lastInteractedPlayer >= ((Il2CppArrayBase<SNet_Slot>)(object)SNet.Slots.PlayerSlots).Count)
			{
				return;
			}
			if (((Interact_Base)Interact).IsSelected)
			{
				SetInteractionText();
			}
			if (!SNet.IsMaster)
			{
				return;
			}
			LegacyLogger.Warning($"ResourceStation OnStateChanged: replenish for player {lastInteractedPlayer}, remaining use time: {newState.RemainingUseTime}");
			if (oldState.RemainingUseTime > 0)
			{
				SNet_Player playerInSlot = SNet.Slots.GetPlayerInSlot(lastInteractedPlayer);
				if ((Object)(object)playerInSlot != (Object)null)
				{
					Replenish(((Il2CppObjectBase)playerInSlot.m_playerAgent).Cast<PlayerAgent>());
				}
				else
				{
					LegacyLogger.Error($"playerSlot_{lastInteractedPlayer} has no player agent!");
				}
			}
			if (newState.RemainingUseTime == 0)
			{
				LegacyLogger.Warning("ResourceStation OnStateChanged: cooldown timer starts!");
				OnCoolDownStart();
			}
		}

		protected virtual void OnCoolDownStart()
		{
			Timer.StartTimer(def.CooldownTime);
			if (m_blinkMarkerCoroutine == null)
			{
				m_blinkMarkerCoroutine = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(BlinkMarker()), (Action)null);
			}
		}

		protected virtual void OnCoolDownTimerProgress(float progress)
		{
		}

		protected virtual void OnCoolDownEnd()
		{
			LegacyLogger.Warning("ResourceStation OnCoolDownEnd");
			if (m_blinkMarkerCoroutine != null)
			{
				CoroutineManager.StopCoroutine(m_blinkMarkerCoroutine);
				m_blinkMarkerCoroutine = null;
				StationMarkerGO.SetActive(true);
			}
			if (SNet.IsMaster)
			{
				LegacyLogger.Warning("ResourceStation OnCoolDownEnd: master reset state!");
				StateReplicator.SetState(new RSStateStruct
				{
					LastInteractedPlayer = -1,
					RemainingUseTime = def.AllowedUseTimePerCooldown,
					CurrentCooldownTime = 0f,
					Enabled = true
				});
			}
		}

		protected virtual void SetupReplicator()
		{
			if (StateReplicator == null)
			{
				uint num = EOSNetworking.AllotReplicatorID();
				if (num == 0)
				{
					LegacyLogger.Error("ResourceStation: replicatorID depleted, cannot setup replicator!");
					return;
				}
				StateReplicator = StateReplicator<RSStateStruct>.Create(num, new RSStateStruct
				{
					RemainingUseTime = def.AllowedUseTimePerCooldown,
					CurrentCooldownTime = -1f,
					Enabled = true
				}, (LifeTimeType)1, (IStateReplicatorHolder<RSStateStruct>)null);
				StateReplicator.OnStateChanged += OnStateChanged;
			}
		}

		protected virtual void SetupRSTimer()
		{
			if ((Object)(object)Timer == (Object)null)
			{
				Timer = RSTimer.Instantiate(OnCoolDownTimerProgress, OnCoolDownEnd);
			}
		}

		[IteratorStateMachine(typeof(<BlinkMarker>d__61))]
		private IEnumerator BlinkMarker()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <BlinkMarker>d__61(0)
			{
				<>4__this = this
			};
		}

		protected ResourceStation(ResourceStationDefinition def, GameObject GO)
		{
			//IL_0030: 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)
			this.def = def;
			GameObject = GO;
			GameObject.transform.SetPositionAndRotation(def.Position.ToVector3(), def.Rotation.ToQuaternion());
			Interact = InteractGO.GetComponent<Interact_Timed>();
			SerialNumber = SerialGenerator.GetUniqueSerialNo();
			if ((Object)(object)Interact == (Object)null)
			{
				LegacyLogger.Error("ResourceStation: Interact Comp not found!");
			}
			else
			{
				SetupInteraction();
			}
			TerminalItem = GO.GetComponent<LG_GenericTerminalItem>();
			if ((Object)(object)TerminalItem == (Object)null)
			{
				LegacyLogger.Error("ResourceStation: TerminalItem not found!");
			}
			else
			{
				SetupTerminalItem();
			}
			SetupReplicator();
			SetupRSTimer();
		}

		static ResourceStation()
		{
		}
	}
	public sealed class AmmoStation : ResourceStation
	{
		public override string ItemKey => $"Ammunition_Station_{base.SerialNumber}";

		protected override void SetupInteraction()
		{
			base.SetupInteraction();
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.InteractionPrompt.AmmoStation");
			Interact.InteractionMessage = ((block == null) ? "AMMUNITION STATION" : Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID));
		}

		public static AmmoStation Instantiate(ResourceStationDefinition def)
		{
			if (def.StationType != StationType.AMMO)
			{
				LegacyLogger.Error($"Trying to instantiate AmmoStation with def with 'StationType': {def.StationType}!");
				return null;
			}
			GameObject gO = Object.Instantiate<GameObject>(Assets.AmmoStation);
			return new AmmoStation(def, gO);
		}

		protected override void Replenish(PlayerAgent player)
		{
			PlayerBackpack backpack = PlayerBackpackManager.GetBackpack(player.Owner);
			PlayerAmmoStorage ammoStorage = backpack.AmmoStorage;
			float num = Math.Max(0f, Math.Min(def.SupplyUplimit.AmmoStandard - ammoStorage.StandardAmmo.RelInPack, def.SupplyEfficiency.AmmoStandard));
			float num2 = Math.Max(0f, Math.Min(def.SupplyUplimit.AmmoSpecial - ammoStorage.SpecialAmmo.RelInPack, def.SupplyEfficiency.AmmoSpecial));
			player.GiveAmmoRel((PlayerAgent)null, num, num2, 0f);
			player.Sound.Post(EVENTS.AMMOPACK_APPLY, true);
		}

		private AmmoStation(ResourceStationDefinition def, GameObject GO)
			: base(def, GO)
		{
		}

		static AmmoStation()
		{
		}
	}
	public enum StationType
	{
		MEDI,
		AMMO,
		TOOL
	}
	public class SupplyUplimit
	{
		public float Medi { get; set; } = 0.6f;


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


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


		public float Tool { get; set; } = 0f;

	}
	public class SupplyEfficiency
	{
		public float Medi { get; set; } = 0.2f;


		public float AmmoStandard { get; set; } = 0.15f;


		public float AmmoSpecial { get; set; } = 0.15f;


		public float Tool { get; set; } = 0f;

	}
	public class ResourceStationDefinition : GlobalZoneIndex
	{
		public int AreaIndex { get; set; } = 0;


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


		public StationType StationType { get; set; } = StationType.AMMO;


		public Vec3 Position { get; set; } = new Vec3();


		public Vec3 Rotation { get; set; } = new Vec3();


		public float InteractDuration { get; set; } = 2.5f;


		public SupplyEfficiency SupplyEfficiency { get; set; } = new SupplyEfficiency();


		public SupplyUplimit SupplyUplimit { get; set; } = new SupplyUplimit();


		public int AllowedUseTimePerCooldown { get; set; } = int.MaxValue;


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

	}
	public class ResourceStationManager : GenericExpeditionDefinitionManager<ResourceStationDefinition>
	{
		public static ResourceStationManager Current { get; private set; }

		protected override string DEFINITION_NAME => "ResourceStation";

		private Dictionary<string, ResourceStation> Stations { get; } = new Dictionary<string, ResourceStation>();


		private void Build(ResourceStationDefinition def)
		{
			if (Stations.ContainsKey(def.WorldEventObjectFilter))
			{
				LegacyLogger.Error("ResourceStationManager: WorldEventObjectFilter '" + def.WorldEventObjectFilter + "' is already used");
				return;
			}
			ResourceStation resourceStation = null;
			switch (def.StationType)
			{
			case StationType.MEDI:
				resourceStation = MediStation.Instantiate(def);
				break;
			case StationType.AMMO:
				resourceStation = AmmoStation.Instantiate(def);
				break;
			case StationType.TOOL:
				resourceStation = ToolStation.Instantiate(def);
				break;
			default:
				LegacyLogger.Error($"ResourceStation {def.StationType} is unimplemented");
				return;
			}
			if (resourceStation != null)
			{
				Stations[def.WorldEventObjectFilter] = resourceStation;
				LegacyLogger.Debug("ResourceStation '" + def.WorldEventObjectFilter + "' instantiated");
			}
		}

		private void BuildStations()
		{
			if (base.definitions.TryGetValue(base.CurrentMainLevelLayout, out var value))
			{
				value.Definitions.ForEach(Build);
			}
		}

		private void Clear()
		{
			foreach (ResourceStation value in Stations.Values)
			{
				value.Destroy();
			}
			Stations.Clear();
		}

		private ResourceStationManager()
		{
			LevelAPI.OnBuildStart += delegate
			{
				Clear();
			};
			LevelAPI.OnLevelCleanup += Clear;
			LevelAPI.OnBuildDone += BuildStations;
		}

		static ResourceStationManager()
		{
			Current = new ResourceStationManager();
		}
	}
	public struct RSStateStruct
	{
		public int LastInteractedPlayer;

		public int RemainingUseTime;

		public float CurrentCooldownTime;

		public bool Enabled;

		public RSStateStruct()
		{
			LastInteractedPlayer = 0;
			RemainingUseTime = 0;
			CurrentCooldownTime = 0f;
			Enabled = false;
		}
	}
	public class RSTimer : MonoBehaviour
	{
		private float startTime = 0f;

		private float endTime = 0f;

		private bool hasOnGoingTimer = false;

		private Action<float> OnProgress;

		private Action OnTimerEnd;

		public float RemainingTime => hasOnGoingTimer ? Math.Max(endTime - Clock.Time, 0f) : 0f;

		private static List<GameObject> TimerGOs { get; }

		private void Update()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)GameStateManager.CurrentStateName == 10 && hasOnGoingTimer)
			{
				float time = Clock.Time;
				if (OnProgress != null)
				{
					OnProgress((time - startTime) / (endTime - startTime));
				}
				if (!(time < endTime))
				{
					endTime = 0f;
					hasOnGoingTimer = false;
					OnTimerEnd?.Invoke();
				}
			}
		}

		public void StartTimer(float time)
		{
			if (time <= 0f)
			{
				LegacyLogger.Error("StartTimer: time is not positive!");
				return;
			}
			if (hasOnGoingTimer)
			{
				LegacyLogger.Error("StartTimer: this timer is yet ended!");
				return;
			}
			startTime = Clock.Time;
			endTime = startTime + time;
			hasOnGoingTimer = true;
		}

		private void OnDestroy()
		{
			endTime = 0f;
			hasOnGoingTimer = false;
			OnTimerEnd = null;
		}

		public static RSTimer Instantiate(Action<float> onProgress, Action actionOnEnd)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			GameObject val = new GameObject();
			RSTimer rSTimer = val.AddComponent<RSTimer>();
			rSTimer.OnProgress = onProgress;
			rSTimer.OnTimerEnd = actionOnEnd;
			TimerGOs.Add(val);
			return rSTimer;
		}

		public static void DestroyAll()
		{
			TimerGOs.ForEach((Action<GameObject>)Object.Destroy);
			TimerGOs.Clear();
		}

		private RSTimer()
		{
		}

		static RSTimer()
		{
			TimerGOs = new List<GameObject>();
			ClassInjector.RegisterTypeInIl2Cpp<RSTimer>();
			LevelAPI.OnBuildStart += DestroyAll;
			LevelAPI.OnLevelCleanup += DestroyAll;
		}
	}
}
namespace LEGACY.LegacyOverride.Patches
{
	[HarmonyPatch]
	internal static class ExpeditionSuccessPage
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_PageExpeditionSuccess), "OnEnable")]
		private static void Post_CM_PageExpeditionSuccess_OnEnable(CM_PageExpeditionSuccess __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				SuccessPageCustomization currentCustomization = SuccessPageCustomizationManager.Current.CurrentCustomization;
				if (currentCustomization != null)
				{
					((TMP_Text)__instance.m_header).SetText(LocalizedText.op_Implicit(currentCustomization.PageHeader), true);
					__instance.m_overrideSuccessMusic = currentCustomization.OverrideSuccessMusic;
					LegacyLogger.Warning("Post_CM_PageExpeditionSuccess_OnEnable: " + ((Object)currentCustomization.PageHeader).ToString());
				}
			}
		}
	}
	[HarmonyPatch]
	internal class GUIManager_RestartPage
	{
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(GuiManager), "Setup")]
		private static void Post_Setup(GuiManager __instance)
		{
			LevelAPI.OnBuildStart += delegate
			{
				CM_PageRestart.Setup();
			};
		}
	}
	[HarmonyPatch]
	internal static class LevelSpawnFogBeacon_BugFix
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeavyFogRepellerGlobalState), "AttemptInteract")]
		private static void Post_HeavyFogRepellerGlobalState_AttemptInteract(HeavyFogRepellerGlobalState __instance)
		{
			LevelSpawnedFogBeaconSettings lSFBDef = LevelSpawnedFogBeaconManager.Current.GetLSFBDef(__instance);
			if (lSFBDef != null)
			{
				__instance.m_repellerSphere.Range = lSFBDef.Range;
			}
		}
	}
	[HarmonyPatch]
	internal class RundownSelectionCustomization
	{
		[CompilerGenerated]
		private sealed class <reverseReveal>d__7 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public CM_PageRundown_New p;

			public bool hosting;

			public Transform guixSurfaceTransform;

			private float <arrowScale>5__1;

			private float <tierMarkerDelay>5__2;

			private int <k>5__3;

			private int <m>5__4;

			private int <l>5__5;

			private int <j>5__6;

			private int <i>5__7;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <reverseReveal>d__7(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_011a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0124: Expected O, but got Unknown
				//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c3: Expected O, but got Unknown
				//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
				//IL_0207: Unknown result type (might be due to invalid IL or missing references)
				//IL_0296: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a0: Expected O, but got Unknown
				//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
				//IL_02db: Unknown result type (might be due to invalid IL or missing references)
				//IL_0356: Unknown result type (might be due to invalid IL or missing references)
				//IL_036a: Unknown result type (might be due to invalid IL or missing references)
				//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_03cd: Expected O, but got Unknown
				//IL_040f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0419: Expected O, but got Unknown
				//IL_0459: Unknown result type (might be due to invalid IL or missing references)
				//IL_046e: Unknown result type (might be due to invalid IL or missing references)
				//IL_015e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0172: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
				//IL_0104: Expected O, but got Unknown
				//IL_023b: Unknown result type (might be due to invalid IL or missing references)
				//IL_024f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0325: Unknown result type (might be due to invalid IL or missing references)
				//IL_032f: Expected O, but got Unknown
				//IL_04ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_04d4: Expected O, but got Unknown
				//IL_05aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_05b4: Expected O, but got Unknown
				//IL_068c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0696: Expected O, but got Unknown
				//IL_076e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0778: Expected O, but got Unknown
				//IL_0850: Unknown result type (might be due to invalid IL or missing references)
				//IL_085a: Expected O, but got Unknown
				//IL_0932: Unknown result type (might be due to invalid IL or missing references)
				//IL_093c: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<arrowScale>5__1 = p.m_tierSpacing * 5f * p.m_tierSpaceToArrowScale;
					if (hosting)
					{
						CoroutineManager.BlinkIn(p.m_buttonConnect, 0f, (Transform)null);
						<>2__current = (object)new WaitForSeconds(0.1f);
						<>1__state = 1;
						return true;
					}
					goto IL_0147;
				case 1:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(0.24f);
					<>1__state = 2;
					return true;
				case 2:
					<>1__state = -1;
					((RectTransformComp)p.m_buttonConnect).SetVisible(false);
					goto IL_0147;
				case 3:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 4;
					return true;
				case 4:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_SURFACE_LEVEL_SHRINK, "");
					CoroutineEase.EaseLocalScale(p.m_textRundownHeader.transform, Vector3.one, new Vector3(0.6f, 0.6f, 0.6f), 0.2f, (EasingFunction)Easing.LinearTween, (Action)null, (BoolCheck)null);
					<>2__current = CoroutineEase.EaseLocalScale(guixSurfaceTransform, Vector3.one, new Vector3(0.2f, 0.2f, 0.2f), 0.2f, (EasingFunction)Easing.LinearTween, (Action)null, (BoolCheck)null);
					<>1__state = 5;
					return true;
				case 5:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 6;
					return true;
				case 6:
					<>1__state = -1;
					CoroutineEase.EaseLocalPos(p.m_textRundownHeader.transform, p.m_textRundownHeader.transform.localPosition, p.m_rundownHeaderPos, 0.2f, (EasingFunction)Easing.LinearTween, (Action)null, (BoolCheck)null);
					CoroutineManager.BlinkIn(p.m_rundownIntelButton, 0f, (Transform)null);
					<>2__current = (object)new WaitForSeconds(0.2f);
					<>1__state = 7;
					return true;
				case 7:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_SURFACE_LEVEL_TURN, "");
					<>2__current = CoroutineEase.EaseLocalRot(guixSurfaceTransform, Vector3.zero, new Vector3(70f, 0f, 0f), 0.3f, (EasingFunction)Easing.LinearTween, (Action)null, (BoolCheck)null);
					<>1__state = 8;
					return true;
				case 8:
					<>1__state = -1;
					p.m_verticalArrow.SetActive(true);
					<>2__current = (object)new WaitForSeconds(0.5f);
					<>1__state = 9;
					return true;
				case 9:
					<>1__state = -1;
					CoroutineManager.BlinkIn(((Component)p.m_tierMarkerSectorSummary).gameObject, 0f);
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_5, "");
					<>2__current = (object)new WaitForSeconds(0.5f);
					<>1__state = 10;
					return true;
				case 10:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_SPINE_START, "");
					CoroutineEase.EaseLocalScale(p.m_verticalArrow.transform, new Vector3(1f, 0f, 1f), new Vector3(1f, <arrowScale>5__1, 1f), 4.3f, (EasingFunction)Easing.LinearTween, (Action)delegate
					{
						CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_SPINE_STOP, "");
					}, (BoolCheck)null);
					<tierMarkerDelay>5__2 = 0.6f;
					<>2__current = (object)new WaitForSeconds(0.2f);
					<>1__state = 11;
					return true;
				case 11:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_3, "");
					((Component)p.m_guix_Tier3).gameObject.SetActive(true);
					<k>5__3 = 0;
					while (<k>5__3 < p.m_expIconsTier3.Count)
					{
						CoroutineManager.BlinkIn(((Component)p.m_expIconsTier3[<k>5__3]).gameObject, (float)<k>5__3 * 0.1f);
						<k>5__3++;
					}
					if (p.m_expIconsTier3.Count > 0)
					{
						p.m_tierMarker3.SetVisible(true, <tierMarkerDelay>5__2);
					}
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 12;
					return true;
				case 12:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_5, "");
					((Component)p.m_guix_Tier5).gameObject.SetActive(true);
					<m>5__4 = 0;
					while (<m>5__4 < p.m_expIconsTier5.Count)
					{
						CoroutineManager.BlinkIn(((Component)p.m_expIconsTier5[<m>5__4]).gameObject, (float)<m>5__4 * 0.1f);
						<m>5__4++;
					}
					if (p.m_expIconsTier5.Count > 0)
					{
						p.m_tierMarker5.SetVisible(true, <tierMarkerDelay>5__2);
					}
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 13;
					return true;
				case 13:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_4, "");
					((Component)p.m_guix_Tier4).gameObject.SetActive(true);
					<l>5__5 = 0;
					while (<l>5__5 < p.m_expIconsTier4.Count)
					{
						CoroutineManager.BlinkIn(((Component)p.m_expIconsTier4[<l>5__5]).gameObject, (float)<l>5__5 * 0.1f);
						<l>5__5++;
					}
					if (p.m_expIconsTier4.Count > 0)
					{
						p.m_tierMarker4.SetVisible(true, <tierMarkerDelay>5__2);
					}
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 14;
					return true;
				case 14:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_2, "");
					((Component)p.m_guix_Tier2).gameObject.SetActive(true);
					<j>5__6 = 0;
					while (<j>5__6 < p.m_expIconsTier2.Count)
					{
						CoroutineManager.BlinkIn(((Component)p.m_expIconsTier2[<j>5__6]).gameObject, (float)<j>5__6 * 0.1f);
						<j>5__6++;
					}
					if (p.m_expIconsTier2.Count > 0)
					{
						p.m_tierMarker2.SetVisible(true, <tierMarkerDelay>5__2);
					}
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 15;
					return true;
				case 15:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_1, "");
					((Component)p.m_guix_Tier1).gameObject.SetActive(true);
					<i>5__7 = 0;
					while (<i>5__7 < p.m_expIconsTier1.Count)
					{
						CoroutineManager.BlinkIn(((Component)p.m_expIconsTier1[<i>5__7]).gameObject, (float)<i>5__7 * 0.1f);
						<i>5__7++;
					}
					if (p.m_expIconsTier1.Count > 0)
					{
						p.m_tierMarker1.SetVisible(true, <tierMarkerDelay>5__2);
					}
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 16;
					return true;
				case 16:
					{
						<>1__state = -1;
						((Component)p.m_joinOnServerIdText).gameObject.SetActive(true);
						Coroutine

plugins/XiaoTian-SURVIVAL/SURVIVAL/Custom/net6/PortalPuzzleChanger.dll

Decompiled 2 weeks 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/XiaoTian-SURVIVAL/SURVIVAL/Custom/x64/Release/netstandard2.1/Oxygen.dll

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