Decompiled source of ModpackFixes v0.1.0

plugins/ModpackFixes.dll

Decompiled 31 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using dev.aqlow.ModpackFixes.Fixes;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ModpackFixes")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Lightweight modular compatibility and bugfix patches for Lethal Company modpacks.")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+82fc096f5d0d3389c867359eae65cfa10bd5b68e")]
[assembly: AssemblyProduct("ModpackFixes")]
[assembly: AssemblyTitle("ModpackFixes")]
[assembly: InternalsVisibleTo("ModpackFixes.Tests")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
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;
		}
	}
	[CompilerGenerated]
	[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 dev.aqlow.ModpackFixes
{
	[BepInPlugin("dev.aqlow.modpackfixes", "ModpackFixes", "0.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "dev.aqlow.modpackfixes";

		public const string PluginName = "ModpackFixes";

		public const string PluginVersion = "0.1.0";

		public const string FixesConfigSection = "Fixes";

		private Harmony? _harmony;

		internal static IReadOnlyList<IFixModule> CreateDefaultModules()
		{
			return new IFixModule[2]
			{
				new DawnEnemyInfoCloneRepairFix(),
				new FacilityMeltdownHostGuardFix()
			};
		}

		private void Awake()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			_harmony = new Harmony("dev.aqlow.modpackfixes");
			IReadOnlyList<IFixModule> readOnlyList = CreateDefaultModules();
			Dictionary<string, ConfigEntry<bool>> configToggles = new Dictionary<string, ConfigEntry<bool>>(readOnlyList.Count);
			foreach (IFixModule item in readOnlyList)
			{
				configToggles[item.Id] = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", item.Id, true, item.ConfigDescription);
			}
			FixModuleRunner.RunModules(readOnlyList, (IFixModule module) => configToggles[module.Id].Value, _harmony, ChainloaderPluginDetector.Instance, ((BaseUnityPlugin)this).Logger);
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "ModpackFixes";

		public const string PLUGIN_NAME = "ModpackFixes";

		public const string PLUGIN_VERSION = "0.1.0";
	}
}
namespace dev.aqlow.ModpackFixes.Fixes
{
	internal sealed class DawnEnemyInfoCloneRepairFix : IFixModule
	{
		public const string DawnLibPluginGuid = "com.github.teamxiaolan.dawnlib";

		public const string ModuleConfigKey = "CopyDawnInfoToClonedEnemyTypes";

		private static DawnInfoCloneRepairEngine? _activeEngine;

		private static ManualLogSource? _logger;

		public string Id => "CopyDawnInfoToClonedEnemyTypes";

		public string ConfigDescription => "Copies DawnLib's DawnEnemyInfo metadata onto runtime-cloned EnemyType assets (such as Mirage's MaskedPlayerEnemy(Clone)) so DawnLib, FacilityMeltdown, and other DawnEnemyInfo consumers do not throw NullReferenceException on the host.";

		public IReadOnlyList<string> RequiredPluginGuids { get; } = new string[1] { "com.github.teamxiaolan.dawnlib" };

		public static bool IsActive => _activeEngine != null;

		internal static void ResetForTesting()
		{
			_activeEngine = null;
			_logger = null;
		}

		public bool TryApply(Harmony harmony, ManualLogSource? logger, IPluginDetector pluginDetector, out string statusMessage)
		{
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Expected O, but got Unknown
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Expected O, but got Unknown
			if (!DawnInfoPropertyAccessor.TryCreate(pluginDetector, out DawnInfoPropertyAccessor accessor, out string failureReason) || accessor == null)
			{
				statusMessage = "could not bind DawnLib IDawnObject.DawnInfo (" + failureReason + ")";
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(TimeOfDay), "Start", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(RoundManager), "LoadNewLevel", new Type[2]
			{
				typeof(int),
				typeof(SelectableLevel)
			}, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(RoundManager), "BeginEnemySpawning", (Type[])null, (Type[])null);
			if (methodInfo == null || methodInfo2 == null || methodInfo3 == null)
			{
				statusMessage = "one or more Lethal Company lifecycle methods (TimeOfDay.Start / RoundManager.LoadNewLevel / RoundManager.BeginEnemySpawning) were not found";
				return false;
			}
			_logger = logger;
			_activeEngine = new DawnInfoCloneRepairEngine(accessor, UnityObjectEquals);
			HarmonyMethod val = new HarmonyMethod(typeof(DawnEnemyInfoCloneRepairFix).GetMethod("TimeOfDayStartPostfix", BindingFlags.Static | BindingFlags.NonPublic))
			{
				priority = 0
			};
			HarmonyMethod val2 = new HarmonyMethod(typeof(DawnEnemyInfoCloneRepairFix).GetMethod("RoundManagerLoadNewLevelPrefix", BindingFlags.Static | BindingFlags.NonPublic))
			{
				priority = 800
			};
			HarmonyMethod val3 = new HarmonyMethod(typeof(DawnEnemyInfoCloneRepairFix).GetMethod("RoundManagerBeginEnemySpawningPrefix", BindingFlags.Static | BindingFlags.NonPublic))
			{
				priority = 800
			};
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo3, val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			statusMessage = "hooked TimeOfDay.Start (with deferred post-MonoMod frame pass), RoundManager.LoadNewLevel, and RoundManager.BeginEnemySpawning.";
			return true;
		}

		public static int RepairClonedEnemyTypes(SelectableLevel? additionalLevel = null)
		{
			DawnInfoCloneRepairEngine activeEngine = _activeEngine;
			if (activeEngine == null)
			{
				return 0;
			}
			try
			{
				List<EnemyTypeCandidate> list = CollectLevelEnemyCandidates(additionalLevel);
				if (list.Count == 0)
				{
					return 0;
				}
				return activeEngine.RepairCandidates(list, CollectAllLoadedEnemyTypes, delegate(string message)
				{
					ManualLogSource? logger2 = _logger;
					if (logger2 != null)
					{
						logger2.LogInfo((object)("[CopyDawnInfoToClonedEnemyTypes] " + message));
					}
				});
			}
			catch (Exception arg)
			{
				ManualLogSource? logger = _logger;
				if (logger != null)
				{
					logger.LogWarning((object)string.Format("[{0}] Unexpected error while scanning cloned EnemyTypes: {1}", "CopyDawnInfoToClonedEnemyTypes", arg));
				}
				return 0;
			}
		}

		private static void TimeOfDayStartPostfix(TimeOfDay __instance)
		{
			RepairClonedEnemyTypes();
			if ((Object)(object)__instance != (Object)null)
			{
				((MonoBehaviour)__instance).StartCoroutine(DeferredTimeOfDayRepair());
			}
		}

		private static IEnumerator DeferredTimeOfDayRepair()
		{
			yield return null;
			RepairClonedEnemyTypes();
		}

		private static void RoundManagerLoadNewLevelPrefix(SelectableLevel newLevel)
		{
			RepairClonedEnemyTypes(newLevel);
		}

		private static void RoundManagerBeginEnemySpawningPrefix()
		{
			RepairClonedEnemyTypes();
		}

		private static List<EnemyTypeCandidate> CollectLevelEnemyCandidates(SelectableLevel? additionalLevel)
		{
			List<EnemyTypeCandidate> list = new List<EnemyTypeCandidate>();
			if ((Object)(object)additionalLevel != (Object)null)
			{
				AddSelectableLevelEnemies(additionalLevel, list);
			}
			RoundManager instance = RoundManager.Instance;
			if ((Object)(object)instance != (Object)null && (Object)(object)instance.currentLevel != (Object)null)
			{
				AddSelectableLevelEnemies(instance.currentLevel, list);
			}
			StartOfRound instance2 = StartOfRound.Instance;
			if ((Object)(object)instance2 != (Object)null && instance2.levels != null)
			{
				SelectableLevel[] levels = instance2.levels;
				foreach (SelectableLevel val in levels)
				{
					if ((Object)(object)val != (Object)null)
					{
						AddSelectableLevelEnemies(val, list);
					}
				}
			}
			return list;
		}

		private static void AddSelectableLevelEnemies(SelectableLevel level, List<EnemyTypeCandidate> destination)
		{
			AddSpawnableList(level.Enemies, destination);
			AddSpawnableList(level.OutsideEnemies, destination);
			AddSpawnableList(level.DaytimeEnemies, destination);
		}

		private static void AddSpawnableList(List<SpawnableEnemyWithRarity>? list, List<EnemyTypeCandidate> destination)
		{
			if (list == null)
			{
				return;
			}
			for (int i = 0; i < list.Count; i++)
			{
				SpawnableEnemyWithRarity val = list[i];
				if (val != null && !((Object)(object)val.enemyType == (Object)null))
				{
					destination.Add(CreateCandidate(val.enemyType));
				}
			}
		}

		private static IReadOnlyList<EnemyTypeCandidate> CollectAllLoadedEnemyTypes()
		{
			EnemyType[] array = Resources.FindObjectsOfTypeAll<EnemyType>();
			if (array == null || array.Length == 0)
			{
				return Array.Empty<EnemyTypeCandidate>();
			}
			List<EnemyTypeCandidate> list = new List<EnemyTypeCandidate>(array.Length);
			foreach (EnemyType val in array)
			{
				if ((Object)(object)val != (Object)null)
				{
					list.Add(CreateCandidate(val));
				}
			}
			return list;
		}

		private static EnemyTypeCandidate CreateCandidate(EnemyType enemyType)
		{
			GameObject val = (((Object)(object)enemyType.enemyPrefab != (Object)null) ? enemyType.enemyPrefab : null);
			EnemyType prefabCanonicalEnemyType = null;
			if ((Object)(object)val != (Object)null)
			{
				EnemyAI component = val.GetComponent<EnemyAI>();
				if ((Object)(object)component != (Object)null && (Object)(object)component.enemyType != (Object)null)
				{
					prefabCanonicalEnemyType = component.enemyType;
				}
			}
			string displayName = ((!string.IsNullOrEmpty(((Object)enemyType).name)) ? ((Object)enemyType).name : (enemyType.enemyName ?? "<unnamed EnemyType>"));
			return new EnemyTypeCandidate(enemyType, displayName, enemyType.enemyName, val, prefabCanonicalEnemyType);
		}

		private static bool UnityObjectEquals(object? left, object? right)
		{
			Object val = (Object)((left is Object) ? left : null);
			if (val != null)
			{
				Object val2 = (Object)((right is Object) ? right : null);
				if (val2 != null)
				{
					return val == val2;
				}
			}
			return left == right;
		}
	}
	internal sealed class DawnInfoPropertyAccessor
	{
		public const string DawnObjectInterfaceFullName = "Dawn.Interfaces.IDawnObject";

		public const string DawnInterfacesAssemblyName = "com.github.teamxiaolan.dawnlib.interfaces";

		public const string DawnInfoPropertyName = "DawnInfo";

		private readonly Type _dawnObjectInterfaceType;

		private readonly MethodInfo _getter;

		private readonly MethodInfo _setter;

		public DawnInfoPropertyAccessor(Type dawnObjectInterfaceType, PropertyInfo dawnInfoProperty)
		{
			_dawnObjectInterfaceType = dawnObjectInterfaceType ?? throw new ArgumentNullException("dawnObjectInterfaceType");
			if (dawnInfoProperty == null)
			{
				throw new ArgumentNullException("dawnInfoProperty");
			}
			_getter = dawnInfoProperty.GetGetMethod(nonPublic: true) ?? throw new ArgumentException("Property '" + dawnInfoProperty.Name + "' has no getter.", "dawnInfoProperty");
			_setter = dawnInfoProperty.GetSetMethod(nonPublic: true) ?? throw new ArgumentException("Property '" + dawnInfoProperty.Name + "' has no setter.", "dawnInfoProperty");
		}

		public static bool TryCreate(IPluginDetector pluginDetector, out DawnInfoPropertyAccessor? accessor, out string failureReason)
		{
			Type type = pluginDetector.FindType("Dawn.Interfaces.IDawnObject", "com.github.teamxiaolan.dawnlib.interfaces");
			if (type == null)
			{
				accessor = null;
				failureReason = "type 'Dawn.Interfaces.IDawnObject' was not found";
				return false;
			}
			return TryCreateFromInterfaceType(type, out accessor, out failureReason);
		}

		public static bool TryCreateFromInterfaceType(Type interfaceType, out DawnInfoPropertyAccessor? accessor, out string failureReason)
		{
			PropertyInfo property = interfaceType.GetProperty("DawnInfo", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property == null || property.GetGetMethod(nonPublic: true) == null || property.GetSetMethod(nonPublic: true) == null)
			{
				accessor = null;
				failureReason = "property 'DawnInfo' with getter/setter was not found on '" + interfaceType.FullName + "'";
				return false;
			}
			accessor = new DawnInfoPropertyAccessor(interfaceType, property);
			failureReason = string.Empty;
			return true;
		}

		public bool IsDawnObject(object? instance)
		{
			if (instance != null)
			{
				return _dawnObjectInterfaceType.IsInstanceOfType(instance);
			}
			return false;
		}

		public object? GetDawnInfo(object instance)
		{
			return _getter.Invoke(instance, null);
		}

		public void SetDawnInfo(object instance, object dawnInfo)
		{
			_setter.Invoke(instance, new object[1] { dawnInfo });
		}
	}
	internal readonly struct EnemyTypeCandidate
	{
		public object EnemyTypeInstance { get; }

		public string DisplayName { get; }

		public string? EnemyName { get; }

		public object? EnemyPrefab { get; }

		public object? PrefabCanonicalEnemyType { get; }

		public EnemyTypeCandidate(object enemyTypeInstance, string displayName, string? enemyName, object? enemyPrefab, object? prefabCanonicalEnemyType)
		{
			EnemyTypeInstance = enemyTypeInstance;
			DisplayName = displayName;
			EnemyName = enemyName;
			EnemyPrefab = enemyPrefab;
			PrefabCanonicalEnemyType = prefabCanonicalEnemyType;
		}
	}
	internal sealed class DawnInfoCloneRepairEngine
	{
		private sealed class RepairedLogMarker
		{
		}

		private readonly struct DonorEntry
		{
			public object EnemyTypeInstance { get; }

			public string? EnemyName { get; }

			public object? EnemyPrefab { get; }

			public object DawnInfo { get; }

			public DonorEntry(object enemyTypeInstance, string? enemyName, object? enemyPrefab, object dawnInfo)
			{
				EnemyTypeInstance = enemyTypeInstance;
				EnemyName = enemyName;
				EnemyPrefab = enemyPrefab;
				DawnInfo = dawnInfo;
			}
		}

		private sealed class ReferenceEqualityComparerInstance : IEqualityComparer<object>
		{
			public static readonly ReferenceEqualityComparerInstance Instance = new ReferenceEqualityComparerInstance();

			public new bool Equals(object? x, object? y)
			{
				return x == y;
			}

			public int GetHashCode(object obj)
			{
				return RuntimeHelpers.GetHashCode(obj);
			}
		}

		private readonly DawnInfoPropertyAccessor _accessor;

		private readonly Func<object?, object?, bool> _prefabEquals;

		private readonly ConditionalWeakTable<object, RepairedLogMarker> _loggedRepairs = new ConditionalWeakTable<object, RepairedLogMarker>();

		public DawnInfoCloneRepairEngine(DawnInfoPropertyAccessor accessor, Func<object?, object?, bool>? prefabEquals = null)
		{
			_accessor = accessor ?? throw new ArgumentNullException("accessor");
			_prefabEquals = prefabEquals ?? new Func<object, object, bool>(object.ReferenceEquals);
		}

		public int RepairCandidates(IEnumerable<EnemyTypeCandidate> candidates, Func<IReadOnlyList<EnemyTypeCandidate>>? fallbackRegistryProvider, Action<string>? logRepairedOnce = null)
		{
			if (candidates == null)
			{
				return 0;
			}
			HashSet<object> hashSet = new HashSet<object>(ReferenceEqualityComparerInstance.Instance);
			IReadOnlyList<DonorEntry> readOnlyList = null;
			bool flag = false;
			int num = 0;
			foreach (EnemyTypeCandidate candidate in candidates)
			{
				object enemyTypeInstance = candidate.EnemyTypeInstance;
				if (enemyTypeInstance == null || !hashSet.Add(enemyTypeInstance) || !_accessor.IsDawnObject(enemyTypeInstance) || _accessor.GetDawnInfo(enemyTypeInstance) != null)
				{
					continue;
				}
				object obj = null;
				string donorSource = string.Empty;
				object prefabCanonicalEnemyType = candidate.PrefabCanonicalEnemyType;
				if (prefabCanonicalEnemyType != null && prefabCanonicalEnemyType != enemyTypeInstance && _accessor.IsDawnObject(prefabCanonicalEnemyType))
				{
					obj = _accessor.GetDawnInfo(prefabCanonicalEnemyType);
					if (obj != null)
					{
						donorSource = "enemyPrefab.EnemyAI.enemyType";
					}
				}
				if (obj == null && fallbackRegistryProvider != null)
				{
					if (!flag)
					{
						flag = true;
						readOnlyList = BuildDonorList(fallbackRegistryProvider());
					}
					if (readOnlyList != null && readOnlyList.Count > 0)
					{
						obj = TryResolveFromFallbackDonors(candidate, readOnlyList, out donorSource);
					}
				}
				if (obj != null)
				{
					_accessor.SetDawnInfo(enemyTypeInstance, obj);
					num++;
					if (logRepairedOnce != null && !_loggedRepairs.TryGetValue(enemyTypeInstance, out RepairedLogMarker _))
					{
						_loggedRepairs.Add(enemyTypeInstance, new RepairedLogMarker());
						logRepairedOnce("Copied DawnEnemyInfo onto cloned EnemyType '" + candidate.DisplayName + "' (enemyName='" + (candidate.EnemyName ?? "<null>") + "', source=" + donorSource + ").");
					}
				}
			}
			return num;
		}

		private IReadOnlyList<DonorEntry> BuildDonorList(IReadOnlyList<EnemyTypeCandidate>? allCandidates)
		{
			if (allCandidates == null || allCandidates.Count == 0)
			{
				return Array.Empty<DonorEntry>();
			}
			List<DonorEntry> list = new List<DonorEntry>();
			HashSet<object> hashSet = new HashSet<object>(ReferenceEqualityComparerInstance.Instance);
			for (int i = 0; i < allCandidates.Count; i++)
			{
				EnemyTypeCandidate enemyTypeCandidate = allCandidates[i];
				if (enemyTypeCandidate.EnemyTypeInstance != null && hashSet.Add(enemyTypeCandidate.EnemyTypeInstance) && _accessor.IsDawnObject(enemyTypeCandidate.EnemyTypeInstance))
				{
					object dawnInfo = _accessor.GetDawnInfo(enemyTypeCandidate.EnemyTypeInstance);
					if (dawnInfo != null)
					{
						list.Add(new DonorEntry(enemyTypeCandidate.EnemyTypeInstance, enemyTypeCandidate.EnemyName, enemyTypeCandidate.EnemyPrefab, dawnInfo));
					}
				}
			}
			return list;
		}

		private object? TryResolveFromFallbackDonors(EnemyTypeCandidate target, IReadOnlyList<DonorEntry> donors, out string donorSource)
		{
			if (target.EnemyPrefab != null)
			{
				object obj = null;
				bool flag = false;
				for (int i = 0; i < donors.Count; i++)
				{
					DonorEntry donorEntry = donors[i];
					if (donorEntry.EnemyTypeInstance != target.EnemyTypeInstance && donorEntry.EnemyPrefab != null && _prefabEquals(donorEntry.EnemyPrefab, target.EnemyPrefab))
					{
						if (obj == null)
						{
							obj = donorEntry.DawnInfo;
						}
						else if (obj != donorEntry.DawnInfo)
						{
							flag = true;
							break;
						}
					}
				}
				if (obj != null && !flag)
				{
					donorSource = "Resources.FindObjectsOfTypeAll(enemyPrefab)";
					return obj;
				}
			}
			if (!string.IsNullOrEmpty(target.EnemyName))
			{
				object obj2 = null;
				bool flag2 = false;
				for (int j = 0; j < donors.Count; j++)
				{
					DonorEntry donorEntry2 = donors[j];
					if (donorEntry2.EnemyTypeInstance != target.EnemyTypeInstance && string.Equals(donorEntry2.EnemyName, target.EnemyName, StringComparison.Ordinal))
					{
						if (obj2 == null)
						{
							obj2 = donorEntry2.DawnInfo;
						}
						else if (obj2 != donorEntry2.DawnInfo)
						{
							flag2 = true;
							break;
						}
					}
				}
				if (obj2 != null && !flag2)
				{
					donorSource = "Resources.FindObjectsOfTypeAll(enemyName)";
					return obj2;
				}
			}
			donorSource = string.Empty;
			return null;
		}
	}
	internal sealed class FacilityMeltdownHostGuardFix : IFixModule
	{
		public const string FacilityMeltdownPluginGuid = "me.loaforc.facilitymeltdown";

		public const string MeltdownAssemblyName = "FacilityMeltdown";

		public const string MeltdownHandlerFullName = "FacilityMeltdown.MeltdownSequence.Behaviours.MeltdownHandler";

		public const string HandleEnemiesMethodName = "HandleEnemies";

		public const string ModuleConfigKey = "GuardFacilityMeltdownHandleEnemies";

		private static Action? _preHandleEnemiesRepair;

		private static ManualLogSource? _logger;

		private static Action<Exception>? _onExceptionSwallowedObserver;

		public string Id => "GuardFacilityMeltdownHandleEnemies";

		public string ConfigDescription => "Repairs cloned EnemyTypes immediately before FacilityMeltdown's MeltdownHandler.HandleEnemies runs and guards HandleEnemies with a Harmony Finalizer so an enemy-spawning exception on the host cannot abort StartMeltdownClientRpc before meltdownStarted = true (preventing the host's ship auto-takeoff timer from desyncing from clients).";

		public IReadOnlyList<string> RequiredPluginGuids { get; } = new string[1] { "me.loaforc.facilitymeltdown" };

		internal static void ResetForTesting()
		{
			_preHandleEnemiesRepair = null;
			_logger = null;
			_onExceptionSwallowedObserver = null;
		}

		public bool TryApply(Harmony harmony, ManualLogSource? logger, IPluginDetector pluginDetector, out string statusMessage)
		{
			Type type = pluginDetector.FindType("FacilityMeltdown.MeltdownSequence.Behaviours.MeltdownHandler", "FacilityMeltdown");
			if (type == null)
			{
				statusMessage = "type 'FacilityMeltdown.MeltdownSequence.Behaviours.MeltdownHandler' was not found in loaded assemblies";
				return false;
			}
			MethodInfo method = type.GetMethod("HandleEnemies", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
			if (method == null)
			{
				statusMessage = "method 'FacilityMeltdown.MeltdownSequence.Behaviours.MeltdownHandler.HandleEnemies()' was not found";
				return false;
			}
			ApplyPatchesToMethod(harmony, method, logger, delegate
			{
				if (DawnEnemyInfoCloneRepairFix.IsActive)
				{
					DawnEnemyInfoCloneRepairFix.RepairClonedEnemyTypes();
				}
			});
			statusMessage = "patched FacilityMeltdown.MeltdownSequence.Behaviours.MeltdownHandler.HandleEnemies() with pre-meltdown DawnInfo repair Prefix and host takeoff Finalizer guard.";
			return true;
		}

		internal static void ApplyPatchesToMethod(Harmony harmony, MethodInfo targetHandleEnemiesMethod, ManualLogSource? logger, Action? preRepairAction, Action<Exception>? onExceptionSwallowedObserver = null)
		{
			//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_003a: 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
			_logger = logger;
			_preHandleEnemiesRepair = preRepairAction;
			_onExceptionSwallowedObserver = onExceptionSwallowedObserver;
			HarmonyMethod val = new HarmonyMethod(typeof(FacilityMeltdownHostGuardFix).GetMethod("HandleEnemiesPrefix", BindingFlags.Static | BindingFlags.NonPublic))
			{
				priority = 800
			};
			HarmonyMethod val2 = new HarmonyMethod(typeof(FacilityMeltdownHostGuardFix).GetMethod("HandleEnemiesFinalizer", BindingFlags.Static | BindingFlags.NonPublic));
			harmony.Patch((MethodBase)targetHandleEnemiesMethod, val, (HarmonyMethod)null, (HarmonyMethod)null, val2, (HarmonyMethod)null);
		}

		private static void HandleEnemiesPrefix()
		{
			try
			{
				_preHandleEnemiesRepair?.Invoke();
			}
			catch (Exception arg)
			{
				ManualLogSource? logger = _logger;
				if (logger != null)
				{
					logger.LogWarning((object)string.Format("[{0}] Pre-meltdown repair callback threw an unexpected error: {1}", "GuardFacilityMeltdownHandleEnemies", arg));
				}
			}
		}

		private static Exception? HandleEnemiesFinalizer(Exception? __exception)
		{
			if (__exception != null)
			{
				ManualLogSource? logger = _logger;
				if (logger != null)
				{
					logger.LogWarning((object)("[GuardFacilityMeltdownHandleEnemies] Caught exception in MeltdownHandler.HandleEnemies so StartMeltdownClientRpc can still set " + $"meltdownStarted = true on the host and keep ship auto-takeoff synchronized: {__exception}"));
				}
				_onExceptionSwallowedObserver?.Invoke(__exception);
			}
			return null;
		}
	}
	internal readonly struct FixModuleResult
	{
		public string ModuleId { get; }

		public bool Activated { get; }

		public string Reason { get; }

		public FixModuleResult(string moduleId, bool activated, string reason)
		{
			ModuleId = moduleId;
			Activated = activated;
			Reason = reason;
		}
	}
	internal static class FixModuleRunner
	{
		public static IReadOnlyList<FixModuleResult> RunModules(IEnumerable<IFixModule> modules, Func<IFixModule, bool> isEnabledInConfig, Harmony harmony, IPluginDetector pluginDetector, ManualLogSource? logger)
		{
			List<FixModuleResult> list = new List<FixModuleResult>();
			foreach (IFixModule module in modules)
			{
				if (!isEnabledInConfig(module))
				{
					list.Add(new FixModuleResult(module.Id, activated: false, "disabled in [Fixes] config"));
					if (logger != null)
					{
						logger.LogInfo((object)("[Fixes] Skipped '" + module.Id + "': disabled in [Fixes] config."));
					}
					continue;
				}
				List<string> list2 = module.RequiredPluginGuids.Where((string guid) => !pluginDetector.IsPluginLoaded(guid)).ToList();
				if (list2.Count > 0)
				{
					string text = "target mod(s) not loaded (" + string.Join(", ", list2) + ")";
					list.Add(new FixModuleResult(module.Id, activated: false, text));
					if (logger != null)
					{
						logger.LogInfo((object)("[Fixes] Skipped '" + module.Id + "': " + text + "."));
					}
					continue;
				}
				try
				{
					string statusMessage;
					bool flag = module.TryApply(harmony, logger, pluginDetector, out statusMessage);
					list.Add(new FixModuleResult(module.Id, flag, statusMessage));
					if (flag)
					{
						if (logger != null)
						{
							logger.LogInfo((object)("[Fixes] Activated '" + module.Id + "': " + statusMessage));
						}
					}
					else if (logger != null)
					{
						logger.LogWarning((object)("[Fixes] Skipped '" + module.Id + "': " + statusMessage));
					}
				}
				catch (Exception ex)
				{
					string reason = "failed during initialization (" + ex.GetType().Name + ": " + ex.Message + ")";
					list.Add(new FixModuleResult(module.Id, activated: false, reason));
					if (logger != null)
					{
						logger.LogWarning((object)$"[Fixes] Failed to activate '{module.Id}': {ex}");
					}
				}
			}
			int num = list.Count((FixModuleResult r) => r.Activated);
			int num2 = list.Count - num;
			if (logger != null)
			{
				logger.LogInfo((object)$"ModpackFixes startup complete: {num} fix module(s) active, {num2} skipped.");
			}
			return list;
		}
	}
	internal interface IFixModule
	{
		string Id { get; }

		string ConfigDescription { get; }

		IReadOnlyList<string> RequiredPluginGuids { get; }

		bool TryApply(Harmony harmony, ManualLogSource? logger, IPluginDetector pluginDetector, out string statusMessage);
	}
	internal interface IPluginDetector
	{
		bool IsPluginLoaded(string pluginGuid);

		Type? FindType(string fullTypeName, string? preferredAssemblyName = null);
	}
	internal sealed class ChainloaderPluginDetector : IPluginDetector
	{
		public static readonly ChainloaderPluginDetector Instance = new ChainloaderPluginDetector();

		public bool IsPluginLoaded(string pluginGuid)
		{
			if (Chainloader.PluginInfos != null)
			{
				return Chainloader.PluginInfos.ContainsKey(pluginGuid);
			}
			return false;
		}

		public Type? FindType(string fullTypeName, string? preferredAssemblyName = null)
		{
			return TypeResolver.FindLoadedType(fullTypeName, preferredAssemblyName);
		}
	}
	internal static class TypeResolver
	{
		public static Type? FindLoadedType(string fullTypeName, string? preferredAssemblyName = null)
		{
			if (string.IsNullOrWhiteSpace(fullTypeName))
			{
				return null;
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			Assembly[] array;
			if (!string.IsNullOrWhiteSpace(preferredAssemblyName))
			{
				array = assemblies;
				foreach (Assembly assembly in array)
				{
					if (string.Equals(assembly.GetName().Name, preferredAssemblyName, StringComparison.OrdinalIgnoreCase))
					{
						Type type = TryGetTypeFromAssembly(assembly, fullTypeName);
						if (type != null)
						{
							return type;
						}
					}
				}
			}
			array = assemblies;
			for (int i = 0; i < array.Length; i++)
			{
				Type type2 = TryGetTypeFromAssembly(array[i], fullTypeName);
				if (type2 != null)
				{
					return type2;
				}
			}
			return null;
		}

		private static Type? TryGetTypeFromAssembly(Assembly assembly, string fullTypeName)
		{
			try
			{
				Type type = assembly.GetType(fullTypeName, throwOnError: false, ignoreCase: false);
				if (type != null)
				{
					return type;
				}
			}
			catch (ReflectionTypeLoadException ex)
			{
				return ex.Types.FirstOrDefault((Type t) => t != null && string.Equals(t.FullName, fullTypeName, StringComparison.Ordinal));
			}
			catch
			{
			}
			return null;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}