Decompiled source of InfernoSkinFix v0.2.1

plugins/InfernoSkinFix.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using EntityStates;
using EntityStates.BrotherMonster;
using EntityStates.MiniMushroom;
using EntityStates.Missions.BrotherEncounter;
using HG;
using Microsoft.CodeAnalysis;
using MonoMod.RuntimeDetour;
using RoR2;
using RoR2.ConVar;
using RoR2.ContentManagement;
using RoR2.Projectile;
using RoR2.UI.MainMenu;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Networking;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("InfernoSkinFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: AssemblyInformationalVersion("0.2.1+149e29ca40fe0488641ec7cd1220f13cda02b4e6-dirty")]
[assembly: AssemblyProduct("InfernoSkinFix")]
[assembly: AssemblyTitle("InfernoSkinFix")]
[assembly: AssemblyVersion("0.2.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 InfernoSkinFix
{
	internal sealed class AccessoryRigSpec
	{
		public readonly InfernoSkin Skin;

		public readonly GameObject ChainPrefab;

		public readonly string ParentBone;

		public readonly int InsertAt;

		public readonly int BaseBoneCount;

		public readonly int ChainLength;

		public readonly object DynamicBoneData;

		public readonly HashSet<Mesh> Meshes;

		private AccessoryRigSpec(InfernoSkin skin, GameObject prefab, string parentBone, int insertAt, int baseBoneCount, int chainLength, object dynamicBoneData, HashSet<Mesh> meshes)
		{
			Skin = skin;
			ChainPrefab = prefab;
			ParentBone = parentBone;
			InsertAt = insertAt;
			BaseBoneCount = baseBoneCount;
			ChainLength = chainLength;
			DynamicBoneData = dynamicBoneData;
			Meshes = meshes;
		}

		public static AccessoryRigSpec TryCreate(InfernoSkin skin, SkinDef bodySkin, ModelSkinController body, out string error)
		{
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			object[] modifications = InfernoDynamicSkins.GetModifications(skin.Token);
			if (modifications.Length != 1)
			{
				error = $"expected 1 DynamicSkins modification for {skin.Token}, found {modifications.Length}";
				return null;
			}
			object owner = modifications[0];
			object field = InfernoDynamicSkins.GetField(owner, "prefab");
			GameObject val = (GameObject)((field is GameObject) ? field : null);
			string text = InfernoDynamicSkins.GetField(owner, "parentname") as string;
			object field2 = InfernoDynamicSkins.GetField(owner, "boneIndex");
			object field3 = InfernoDynamicSkins.GetField(owner, "affectsbasemodel");
			if (!Object.op_Implicit((Object)(object)val) || string.IsNullOrEmpty(text) || !(field2 is int num) || !(field3 is bool) || !(bool)field3)
			{
				error = "unexpected DynamicSkins modification data";
				return null;
			}
			SkinnedMeshRenderer[] array = BaseRenderers(((Component)body).transform);
			int boneCount = ((array.Length != 0) ? array[0].bones.Length : 0);
			if (array.Length == 0 || array.Any((SkinnedMeshRenderer r) => r.bones.Length != boneCount) || num < 0 || num > boneCount)
			{
				error = $"body skinned renderers do not share one bone list (count {boneCount}, insert at {num})";
				return null;
			}
			if (!Object.op_Implicit((Object)(object)FindChild(((Component)body).transform, text)))
			{
				error = "parent bone '" + text + "' not found";
				return null;
			}
			int count = Chain(val.transform).Count;
			HashSet<Mesh> hashSet = new HashSet<Mesh>();
			MeshReplacement[] meshReplacements = bodySkin.meshReplacements;
			foreach (MeshReplacement val2 in meshReplacements)
			{
				if (Object.op_Implicit((Object)(object)val2.mesh) && val2.renderer is SkinnedMeshRenderer && !((Object)(object)((Component)val2.renderer).transform.parent != (Object)(object)((Component)body).transform))
				{
					int num3 = val2.mesh.bindposes.Length;
					if (num3 != boneCount + count)
					{
						error = $"mesh '{((Object)val2.mesh).name}' has {num3} bindposes, expected {boneCount} + {count}";
						return null;
					}
					hashSet.Add(val2.mesh);
				}
			}
			if (hashSet.Count == 0)
			{
				error = "no Inferno mesh needs the extra bones";
				return null;
			}
			error = null;
			return new AccessoryRigSpec(skin, val, text, num, boneCount, count, InfernoDynamicSkins.GetField(owner, "dynamicBoneData"), hashSet);
		}

		internal static SkinnedMeshRenderer[] BaseRenderers(Transform model)
		{
			return (from r in ((Component)model).GetComponentsInChildren<SkinnedMeshRenderer>(true)
				where (Object)(object)((Component)r).transform.parent == (Object)(object)model
				select r).ToArray();
		}

		internal static List<Transform> Chain(Transform root)
		{
			List<Transform> list = new List<Transform>();
			Walk(root);
			return list;
			void Walk(Transform t)
			{
				if (!((Object)t).name.EndsWith("_end", StringComparison.Ordinal))
				{
					list.Add(t);
				}
				for (int i = 0; i < t.childCount; i++)
				{
					Walk(t.GetChild(i));
				}
			}
		}

		internal static Transform FindChild(Transform root, string name)
		{
			if (((Object)root).name == name)
			{
				return root;
			}
			for (int i = 0; i < root.childCount; i++)
			{
				Transform val = FindChild(root.GetChild(i), name);
				if (Object.op_Implicit((Object)(object)val))
				{
					return val;
				}
			}
			return null;
		}
	}
	internal sealed class AccessoryBoneRig : MonoBehaviour
	{
		internal static Action<string> LogError = delegate
		{
		};

		private AccessoryRigSpec spec;

		private SkinnedMeshRenderer[] renderers;

		private Transform[][] originalBones;

		private Mesh[] seenMesh;

		private bool[] extended;

		private bool initialized;

		private GameObject chainRoot;

		private Transform[] chain;

		private readonly List<Component> addedComponents = new List<Component>();

		public static void Ensure(ModelSkinController controller, AccessoryRigSpec spec)
		{
			AccessoryBoneRig accessoryBoneRig = default(AccessoryBoneRig);
			if (((Component)controller).TryGetComponent<AccessoryBoneRig>(ref accessoryBoneRig))
			{
				accessoryBoneRig.Sync();
				return;
			}
			SkinnedMeshRenderer[] array = AccessoryRigSpec.BaseRenderers(((Component)controller).transform);
			if (array.Length == 0 || array.Any((SkinnedMeshRenderer r) => r.bones.Length != spec.BaseBoneCount))
			{
				LogError($"{spec.Skin.Survivor}: '{((Object)controller).name}' does not have the expected {spec.BaseBoneCount}-bone layout; accessory bones not added.");
				return;
			}
			AccessoryBoneRig accessoryBoneRig2 = ((Component)controller).gameObject.AddComponent<AccessoryBoneRig>();
			accessoryBoneRig2.spec = spec;
			accessoryBoneRig2.renderers = array;
			accessoryBoneRig2.originalBones = array.Select((SkinnedMeshRenderer r) => r.bones).ToArray();
			accessoryBoneRig2.seenMesh = (Mesh[])(object)new Mesh[array.Length];
			accessoryBoneRig2.extended = new bool[array.Length];
			accessoryBoneRig2.Sync();
		}

		private void LateUpdate()
		{
			Sync();
		}

		internal void Sync()
		{
			bool flag = false;
			for (int i = 0; i < renderers.Length; i++)
			{
				SkinnedMeshRenderer val = renderers[i];
				if (!Object.op_Implicit((Object)(object)val))
				{
					continue;
				}
				Mesh sharedMesh = val.sharedMesh;
				if (initialized && sharedMesh == seenMesh[i])
				{
					flag |= extended[i];
					continue;
				}
				seenMesh[i] = sharedMesh;
				bool flag2 = Object.op_Implicit((Object)(object)sharedMesh) && spec.Meshes.Contains(sharedMesh);
				if (flag2 != extended[i])
				{
					if (flag2 && !AttachChain())
					{
						flag2 = false;
					}
					val.bones = (flag2 ? Extend(originalBones[i]) : originalBones[i]);
					extended[i] = flag2;
				}
				flag |= extended[i];
			}
			initialized = true;
			if (!flag && Object.op_Implicit((Object)(object)chainRoot))
			{
				DetachChain();
			}
		}

		private Transform[] Extend(Transform[] original)
		{
			List<Transform> list = new List<Transform>(original.Length + chain.Length);
			list.AddRange(original);
			list.InsertRange(spec.InsertAt, chain);
			return list.ToArray();
		}

		private bool AttachChain()
		{
			if (Object.op_Implicit((Object)(object)chainRoot))
			{
				return true;
			}
			try
			{
				Transform val = AccessoryRigSpec.FindChild(((Component)this).transform, spec.ParentBone);
				chainRoot = Object.Instantiate<GameObject>(spec.ChainPrefab, val, false);
				((Object)chainRoot).name = ((Object)spec.ChainPrefab).name;
				chain = AccessoryRigSpec.Chain(chainRoot.transform).ToArray();
				if (spec.DynamicBoneData != null)
				{
					AddDynamicBone();
				}
				return true;
			}
			catch (Exception arg)
			{
				LogError($"{spec.Skin.Survivor}: could not add accessory bones to '{((Object)this).name}': {arg}");
				DetachChain();
				return false;
			}
		}

		private void AddDynamicBone()
		{
			object dynamicBoneData = spec.DynamicBoneData;
			DynamicBone val = chainRoot.AddComponent<DynamicBone>();
			addedComponents.Add((Component)(object)val);
			CopyMatchingFields(dynamicBoneData, val, "m_Root", "m_Colliders", "m_Exclusions");
			val.m_Root = AccessoryRigSpec.FindChild(chainRoot.transform, (InfernoDynamicSkins.GetField(dynamicBoneData, "m_Root") as string) ?? ((Object)chainRoot).name);
			val.m_Exclusions = new List<Transform>();
			if (InfernoDynamicSkins.GetField(dynamicBoneData, "m_Exclusions") is IEnumerable<string> enumerable)
			{
				foreach (string item in enumerable)
				{
					Transform val2 = AccessoryRigSpec.FindChild(val.m_Root, item);
					if (Object.op_Implicit((Object)(object)val2))
					{
						val.m_Exclusions.Add(val2);
					}
				}
			}
			val.m_Colliders = new List<DynamicBoneCollider>();
			if (!(InfernoDynamicSkins.GetField(dynamicBoneData, "m_Colliders") is IEnumerable enumerable2))
			{
				return;
			}
			foreach (object item2 in enumerable2)
			{
				Transform val3 = AccessoryRigSpec.FindChild(((Component)this).transform, (InfernoDynamicSkins.GetField(item2, "m_parent_name") as string) ?? "");
				if (Object.op_Implicit((Object)(object)val3))
				{
					DynamicBoneCollider val4 = ((Component)val3).gameObject.AddComponent<DynamicBoneCollider>();
					CopyMatchingFields(item2, val4, "m_parent_name");
					val.m_Colliders.Add(val4);
					addedComponents.Add((Component)(object)val4);
				}
			}
		}

		private static void CopyMatchingFields(object source, object target, params string[] skip)
		{
			FieldInfo[] fields = source.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public);
			foreach (FieldInfo fieldInfo in fields)
			{
				if (Array.IndexOf(skip, fieldInfo.Name) < 0)
				{
					FieldInfo field = target.GetType().GetField(fieldInfo.Name, BindingFlags.Instance | BindingFlags.Public);
					if (field != null && field.FieldType == fieldInfo.FieldType)
					{
						field.SetValue(target, fieldInfo.GetValue(source));
					}
				}
			}
		}

		private void DetachChain()
		{
			foreach (Component addedComponent in addedComponents)
			{
				if (Object.op_Implicit((Object)(object)addedComponent))
				{
					Object.Destroy((Object)(object)addedComponent);
				}
			}
			addedComponents.Clear();
			if (Object.op_Implicit((Object)(object)chainRoot))
			{
				Object.Destroy((Object)(object)chainRoot);
			}
			chainRoot = null;
			chain = null;
		}
	}
	internal readonly struct IlInstruction
	{
		public readonly int Offset;

		public readonly OpCode OpCode;

		public readonly int Token;

		public bool HasToken
		{
			get
			{
				if (OpCode.OperandType != OperandType.InlineField && OpCode.OperandType != OperandType.InlineMethod && OpCode.OperandType != OperandType.InlineType)
				{
					return OpCode.OperandType == OperandType.InlineTok;
				}
				return true;
			}
		}

		public IlInstruction(int offset, OpCode opCode, int token)
		{
			Offset = offset;
			OpCode = opCode;
			Token = token;
		}
	}
	internal static class IlReader
	{
		private static readonly OpCode[] OneByte;

		private static readonly OpCode[] TwoByte;

		static IlReader()
		{
			OneByte = new OpCode[256];
			TwoByte = new OpCode[256];
			FieldInfo[] fields = typeof(OpCodes).GetFields(BindingFlags.Static | BindingFlags.Public);
			for (int i = 0; i < fields.Length; i++)
			{
				if (fields[i].GetValue(null) is OpCode opCode)
				{
					ushort num = (ushort)opCode.Value;
					if (opCode.Size == 1)
					{
						OneByte[num] = opCode;
					}
					else
					{
						TwoByte[num & 0xFF] = opCode;
					}
				}
			}
		}

		public static List<IlInstruction> Read(MethodBase method)
		{
			byte[] array = method.GetMethodBody()?.GetILAsByteArray() ?? throw new InvalidOperationException(Describe(method) + " has no IL body.");
			List<IlInstruction> list = new List<IlInstruction>();
			int num = 0;
			while (num < array.Length)
			{
				int num2 = num;
				OpCode opCode = ((array[num] == 254 && num + 1 < array.Length) ? TwoByte[array[++num]] : OneByte[array[num]]);
				num++;
				if (opCode.Size == 0)
				{
					throw new InvalidOperationException($"Unknown IL opcode at offset 0x{num2:X4} in {Describe(method)}.");
				}
				int token = 0;
				switch (opCode.OperandType)
				{
				case OperandType.ShortInlineBrTarget:
				case OperandType.ShortInlineI:
				case OperandType.ShortInlineVar:
					num++;
					break;
				case OperandType.InlineVar:
					num += 2;
					break;
				case OperandType.InlineI8:
				case OperandType.InlineR:
					num += 8;
					break;
				case OperandType.InlineSwitch:
					num += 4 + 4 * BitConverter.ToInt32(array, num);
					break;
				default:
					token = BitConverter.ToInt32(array, num);
					num += 4;
					break;
				case OperandType.InlineNone:
					break;
				}
				list.Add(new IlInstruction(num2, opCode, token));
			}
			return list;
		}

		public static string Describe(MethodBase method)
		{
			if (!(method == null))
			{
				return method.DeclaringType?.FullName + "." + method.Name;
			}
			return "null";
		}
	}
	internal static class CompatLog
	{
		public static ManualLogSource Source;

		private const string Prefix = "Inferno compatibility: ";

		public static void Info(string m)
		{
			ManualLogSource source = Source;
			if (source != null)
			{
				source.LogInfo((object)("Inferno compatibility: " + m));
			}
		}

		public static void Debug(string m)
		{
			ManualLogSource source = Source;
			if (source != null)
			{
				source.LogDebug((object)("Inferno compatibility: " + m));
			}
		}

		public static void Warning(string m)
		{
			ManualLogSource source = Source;
			if (source != null)
			{
				source.LogWarning((object)("Inferno compatibility: " + m));
			}
		}

		public static void Error(string m)
		{
			ManualLogSource source = Source;
			if (source != null)
			{
				source.LogError((object)("Inferno compatibility: " + m));
			}
		}
	}
	internal sealed class InfernoBinding
	{
		public const string ExpectedVersion = "1.7.8";

		private const BindingFlags Static = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public Assembly Assembly;

		public string Version;

		public MethodInfo ApplyHooks;

		public MethodInfo UndoHooks;

		public MethodInfo SetUpIcon;

		public MethodInfo JankAsHell;

		public MethodInfo SwapIcons;

		public readonly List<string> Problems = new List<string>();

		private ConfigEntry<bool> enableMithrixChanges;

		private ConfigEntry<bool> infernalEclipse;

		private FieldInfo hasFiredField;

		private FieldInfo bundleField;

		private FieldInfo overlaysField;

		private FieldInfo overlaysEEField;

		public bool MithrixChangesEnabled
		{
			get
			{
				if (enableMithrixChanges != null)
				{
					return enableMithrixChanges.Value;
				}
				return true;
			}
		}

		public bool InfernalEclipseEnabled
		{
			get
			{
				if (infernalEclipse != null)
				{
					return infernalEclipse.Value;
				}
				return true;
			}
		}

		public AssetBundle Bundle
		{
			get
			{
				object? obj = bundleField?.GetValue(null);
				return (AssetBundle)((obj is AssetBundle) ? obj : null);
			}
		}

		public IList LanguageOverlays => overlaysField?.GetValue(null) as IList;

		public IList LanguageOverlaysEE => overlaysEEField?.GetValue(null) as IList;

		public bool ResetWeaponSlamBurst()
		{
			hasFiredField?.SetValue(null, false);
			return hasFiredField != null;
		}

		public static InfernoBinding Bind(PluginInfo inferno)
		{
			InfernoBinding infernoBinding = new InfernoBinding
			{
				Assembly = ((object)inferno.Instance).GetType().Assembly,
				Version = inferno.Metadata.Version.ToString()
			};
			Type owner = infernoBinding.Find("Inferno.Main");
			Type owner2 = infernoBinding.Find("Inferno.Skill_Misc.HookBehavior");
			Type owner3 = infernoBinding.Find("Inferno.Eclipse.InfernalEclipse");
			infernoBinding.ApplyHooks = infernoBinding.Method(owner2, "ApplyHooks", typeof(void));
			infernoBinding.UndoHooks = infernoBinding.Method(owner2, "UndoHooks", typeof(void));
			infernoBinding.SetUpIcon = infernoBinding.Method(owner3, "SetUpIcon", typeof(IEnumerator));
			infernoBinding.JankAsHell = infernoBinding.Method(owner3, "JankAsHell", typeof(IEnumerator), typeof(Scene));
			infernoBinding.SwapIcons = infernoBinding.Method(owner3, "SwapIcons", typeof(void), typeof(int), typeof(Transform));
			infernoBinding.enableMithrixChanges = infernoBinding.Config(owner, "EnableMithrixChanges");
			infernoBinding.infernalEclipse = infernoBinding.Config(owner, "InfernalEclipse");
			infernoBinding.hasFiredField = infernoBinding.Field(owner, "hasFired", typeof(bool));
			infernoBinding.bundleField = infernoBinding.Field(owner, "inferno", typeof(AssetBundle));
			infernoBinding.overlaysField = infernoBinding.Field(owner3, "languageOverlays", null);
			infernoBinding.overlaysEEField = infernoBinding.Field(owner3, "languageOverlaysEE", null);
			return infernoBinding;
		}

		private Type Find(string name)
		{
			Type? type = Assembly.GetType(name, throwOnError: false);
			if (type == null)
			{
				Problems.Add("type " + name + " not found");
			}
			return type;
		}

		private MethodInfo Method(Type owner, string name, Type returnType, params Type[] parameters)
		{
			if (owner == null)
			{
				return null;
			}
			MethodInfo method = owner.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameters, null);
			if (method == null || method.ReturnType != returnType)
			{
				Problems.Add(owner.FullName + "." + name + "(" + string.Join(", ", parameters.Select((Type p) => p.Name)) + ") returning " + returnType.Name + " not found");
				return null;
			}
			return method;
		}

		private ConfigEntry<bool> Config(Type owner, string name)
		{
			if (owner?.GetProperty(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null) is ConfigEntry<bool> result)
			{
				return result;
			}
			Problems.Add("config " + owner?.FullName + "." + name + " not readable (Inferno's default is assumed)");
			return null;
		}

		private FieldInfo Field(Type owner, string name, Type type)
		{
			FieldInfo fieldInfo = owner?.GetField(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (fieldInfo == null || (type != null && fieldInfo.FieldType != type) || (type == null && !typeof(IList).IsAssignableFrom(fieldInfo.FieldType)))
			{
				Problems.Add("field " + owner?.FullName + "." + name + " not found");
				return null;
			}
			return fieldInfo;
		}
	}
	internal static class InfernoCompat
	{
		private static MonoBehaviour host;

		private static InfernoBinding inferno;

		private static bool initialized;

		public static void Init(BaseUnityPlugin plugin, ManualLogSource logger, ConfigFile config)
		{
			CompatLog.Source = logger;
			host = (MonoBehaviour)(object)plugin;
			if (!config.Bind<bool>("Compatibility", "InfernoRuntimeRepairs", true, "Repairs Inferno 1.7.8 for the current game version (run start, Mithrix, Mini Mushrum, hook cleanup between runs, Eclipse menu). Only turn this off to diagnose a problem: without it Inferno runs fail to start on the current game.").Value)
			{
				CompatLog.Warning("disabled in the config (Compatibility.InfernoRuntimeRepairs); Inferno runs are expected to fail on this game version.");
				return;
			}
			try
			{
				InitCore();
			}
			catch (Exception ex)
			{
				CompatLog.Error("initialization failed; Inferno is left unpatched: " + ex);
			}
		}

		private static void InitCore()
		{
			if (!Chainloader.PluginInfos.TryGetValue("HIFU.Inferno", out var value) || !Object.op_Implicit((Object)(object)value.Instance))
			{
				CompatLog.Error("Inferno is not loaded; nothing to repair.");
				return;
			}
			inferno = InfernoBinding.Bind(value);
			CompatLog.Info("initializing for Inferno " + inferno.Version);
			if (inferno.Version != "1.7.8")
			{
				CompatLog.Warning("written for Inferno 1.7.8, found " + inferno.Version + ". Every repair checks the actual Inferno and game code before it is applied; repairs that do not fit are skipped and logged.");
			}
			foreach (string problem in inferno.Problems)
			{
				CompatLog.Warning("Inferno member: " + problem);
			}
			Step("Run event guard", delegate
			{
				CompatLog.Info($"Run start/destroy guard active for {RunEventGuard.Install(inferno.Assembly)} Inferno handler(s)");
			});
			Step("hook lifecycle", delegate
			{
				SafeHookLifecycle.Install(inferno, InfernoRepairs.Create(inferno));
			});
			Step("Eclipse UI", delegate
			{
				InfernoEclipseUi.Install(inferno);
			});
			Step("diagnostics", delegate
			{
				Run.onRunStartGlobal += OnRunStart;
				Run.onRunDestroyGlobal += OnRunDestroy;
			});
			initialized = true;
			CompatLog.Info("ready");
		}

		private static void Step(string what, Action install)
		{
			try
			{
				install();
			}
			catch (Exception arg)
			{
				CompatLog.Error($"{what} could not be installed: {arg}");
			}
		}

		public static void Shutdown()
		{
			if (initialized)
			{
				initialized = false;
				Run.onRunStartGlobal -= OnRunStart;
				Run.onRunDestroyGlobal -= OnRunDestroy;
				InfernoEclipseUi.Uninstall();
				SafeHookLifecycle.Uninstall();
				InfernoRepairs.Dispose();
				RunEventGuard.Restore();
			}
		}

		private static void OnRunStart(Run run)
		{
			try
			{
				CompatLog.Info("Run start reached the handlers after Inferno (" + (NetworkServer.active ? "host" : "client") + "; " + $"Inferno run hooks installed: {SafeHookLifecycle.RunHookCount})");
				if (Object.op_Implicit((Object)(object)host))
				{
					host.StartCoroutine(ReportKarmaManager(run));
				}
			}
			catch (Exception ex)
			{
				CompatLog.Error("run start diagnostics failed: " + ex);
			}
		}

		private static IEnumerator ReportKarmaManager(Run run)
		{
			float deadline = Time.realtimeSinceStartup + 15f;
			while (!Object.op_Implicit((Object)(object)KarmaManager.instance) && Object.op_Implicit((Object)(object)run) && Time.realtimeSinceStartup < deadline)
			{
				yield return null;
			}
			if (Object.op_Implicit((Object)(object)run))
			{
				KarmaManager instance = KarmaManager.instance;
				if (Object.op_Implicit((Object)(object)instance))
				{
					CompatLog.Info($"KarmaManager present after run start (karma {instance.GetEffectiveKarma()}, karma enabled {instance.IsKarmaEnabled()})");
				}
				else
				{
					CompatLog.Warning("no KarmaManager 15 s after run start; vanilla Karma (and the Karma HUD icon) will not work this run.");
				}
			}
		}

		private static void OnRunDestroy(Run run)
		{
			int runHookCount = SafeHookLifecycle.RunHookCount;
			if (runHookCount == 0)
			{
				CompatLog.Info($"run teardown complete: 0 Inferno run hooks remain, {SafeHookLifecycle.CleanupHookCount} Inferno cleanup hooks active");
			}
			else
			{
				CompatLog.Error($"run teardown left {runHookCount} Inferno run hooks installed");
			}
		}
	}
	internal static class InfernoEclipseUi
	{
		private const string RuleContentPath = "SafeArea/RightHandPanel/RuleVerticalLayout/RuleBookViewerVertical/Viewport/Content";

		private static readonly Regex EclipseChoice = new Regex("Difficulty\\.Eclipse(\\d+)", RegexOptions.IgnoreCase);

		private static InfernoBinding inferno;

		private static Hook setUpIconHook;

		private static Hook jankAsHellHook;

		private static MethodInfo addOverlay;

		public static void Install(InfernoBinding binding)
		{
			inferno = binding;
			setUpIconHook = TryHook(binding.SetUpIcon, "SetUpIcon", "lobby Eclipse icon");
			jankAsHellHook = TryHook(binding.JankAsHell, "JankAsHell", "Eclipse menu");
		}

		public static void Uninstall()
		{
			Hook obj = setUpIconHook;
			if (obj != null)
			{
				obj.Dispose();
			}
			Hook obj2 = jankAsHellHook;
			if (obj2 != null)
			{
				obj2.Dispose();
			}
			setUpIconHook = (jankAsHellHook = null);
		}

		private static Hook TryHook(MethodInfo target, string replacement, string what)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			if (target == null)
			{
				CompatLog.Warning(what + " repair not installed: Inferno's method was not found");
				return null;
			}
			try
			{
				Hook val = new Hook((MethodBase)target, typeof(InfernoEclipseUi).GetMethod(replacement, BindingFlags.Static | BindingFlags.NonPublic));
				CompatLog.Info(what + " repair active (replaces InfernalEclipse." + target.Name + ")");
				return val;
			}
			catch (Exception ex)
			{
				CompatLog.Error(what + " repair not installed: " + ex.GetType().Name + ": " + ex.Message);
				return null;
			}
		}

		private static IEnumerator SetUpIcon(Func<IEnumerator> orig)
		{
			return SetUpIconRoutine();
		}

		private static IEnumerator JankAsHell(Func<Scene, IEnumerator> orig, Scene scene)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return EclipseMenuRoutine(scene);
		}

		private static IEnumerator SetUpIconRoutine()
		{
			yield return (object)new WaitForSeconds(0.2f);
			float deadline = Time.realtimeSinceStartup + 5f;
			while (!TrySetUpIcon() && Time.realtimeSinceStartup < deadline)
			{
				yield return (object)new WaitForSeconds(0.25f);
			}
		}

		private static bool TrySetUpIcon()
		{
			try
			{
				GameObject val = GameObject.Find("CharacterSelectUIMain(Clone)");
				Transform val2 = (Object.op_Implicit((Object)(object)val) ? val.transform.Find("SafeArea/RightHandPanel/RuleVerticalLayout/RuleBookViewerVertical/Viewport/Content") : null);
				if (!Object.op_Implicit((Object)(object)val2) || val2.childCount < 2)
				{
					return false;
				}
				Transform val3 = ((IEnumerable<Transform>)((Component)val2.GetChild(1)).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform t) => ((Object)t).name == "ChoiceContainer"));
				if (!Object.op_Implicit((Object)(object)val3) || val3.childCount == 0)
				{
					return false;
				}
				Transform child = val3.GetChild(0);
				Match match = EclipseChoice.Match(((Object)child).name);
				if (!match.Success)
				{
					return true;
				}
				Transform val4 = child.Find("Button/Icon");
				Image val5 = ((val4 != null) ? ((Component)val4).GetComponent<Image>() : null);
				Sprite val6 = (Object.op_Implicit((Object)(object)inferno.Bundle) ? inferno.Bundle.LoadAsset<Sprite>("Assets/Inferno/texDifficultyEclipse" + match.Groups[1].Value + "IconGold.png") : null);
				if (!Object.op_Implicit((Object)(object)val5) || !Object.op_Implicit((Object)(object)val6))
				{
					CompatLog.Warning("lobby Eclipse icon: " + (Object.op_Implicit((Object)(object)val5) ? "Inferno's icon sprite" : "the choice icon") + " for " + ((Object)child).name + " was not found");
					return true;
				}
				val5.sprite = val6;
				CompatLog.Debug("lobby Eclipse icon set for " + ((Object)child).name);
			}
			catch (Exception ex)
			{
				CompatLog.Warning("lobby Eclipse icon repair failed (cosmetic): " + ex);
			}
			return true;
		}

		private static IEnumerator EclipseMenuRoutine(Scene scene)
		{
			//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)
			yield return (object)new WaitForSeconds(0.15f);
			Step("descriptions", UpdateEclipseDescriptions);
			Step("colours", delegate
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				RecolourWeather(scene);
			});
			Step("menu", delegate
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				RecolourMenu(scene);
			});
			Step("language refresh", RefreshLanguage);
		}

		private static void Step(string what, Action step)
		{
			try
			{
				step();
			}
			catch (Exception arg)
			{
				CompatLog.Warning($"Eclipse menu repair, {what} step failed (cosmetic): {arg}");
			}
		}

		private static void UpdateEclipseDescriptions()
		{
			IList languageOverlays = inferno.LanguageOverlays;
			IList languageOverlaysEE = inferno.LanguageOverlaysEE;
			if (languageOverlays == null || languageOverlaysEE == null)
			{
				throw new InvalidOperationException("Inferno's language overlay lists were not found");
			}
			if (inferno.InfernalEclipseEnabled)
			{
				if (languageOverlays.Count <= 0)
				{
					for (int i = 1; i <= 16; i++)
					{
						languageOverlays.Add(AddOverlay($"ECLIPSE_{i}_DESCRIPTION"));
						languageOverlaysEE.Add(AddOverlay($"GROOVYECLIPSE_{i}_DESCRIPTION"));
					}
				}
				return;
			}
			IList[] array = new IList[2] { languageOverlays, languageOverlaysEE };
			foreach (IList list in array)
			{
				foreach (object item in list)
				{
					item?.GetType().GetMethod("Remove", Type.EmptyTypes)?.Invoke(item, null);
				}
				list.Clear();
			}
		}

		private static object AddOverlay(string token)
		{
			if (addOverlay == null)
			{
				addOverlay = ((from a in AppDomain.CurrentDomain.GetAssemblies()
					select a.GetType("R2API.LanguageAPI", throwOnError: false)).FirstOrDefault((Type t) => t != null) ?? throw new InvalidOperationException("R2API.LanguageAPI not found")).GetMethod("AddOverlay", BindingFlags.Static | BindingFlags.Public, null, new Type[2]
				{
					typeof(string),
					typeof(string)
				}, null) ?? throw new InvalidOperationException("R2API.LanguageAPI.AddOverlay(string, string) not found");
			}
			string text = Language.GetString(token).Replace("Monsoon", "<style=cDeath>Inferno</style>").Replace("\"You only celebrate in the light... because I allow it.\"", "<style=cDeath>\"You'll never bow to another god.</style>\"")
				.Replace("<style=cIsHealth", "<style=cDeath");
			return addOverlay.Invoke(null, new object[2] { token, text });
		}

		private static GameObject Root(Scene scene, string name)
		{
			return ((IEnumerable<GameObject>)((Scene)(ref scene)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject g) => ((Object)g).name == name));
		}

		private static void RecolourWeather(Scene scene)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Root(scene, "Weather, Eclipse");
			Transform val2 = ((val != null) ? val.transform.Find("PP + Amb") : null);
			PostProcessVolume obj = (Object.op_Implicit((Object)(object)val2) ? ((Component)val2).GetComponent<PostProcessVolume>() : null);
			if (!Object.op_Implicit((Object)(object)obj))
			{
				throw new InvalidOperationException("'Weather, Eclipse/PP + Amb' post-processing volume not found");
			}
			ColorGrading setting = obj.profile.GetSetting<ColorGrading>();
			if (Object.op_Implicit((Object)(object)setting))
			{
				if (inferno.InfernalEclipseEnabled)
				{
					((ParameterOverride<float>)(object)setting.saturation).value = 50f;
					((ParameterOverride)setting.hueShift).overrideState = true;
					((ParameterOverride<float>)(object)setting.hueShift).value = 143f;
				}
				else
				{
					((ParameterOverride<float>)(object)setting.saturation).value = -23f;
					((ParameterOverride<float>)(object)setting.hueShift).value = 0f;
				}
				((Component)val2).gameObject.SetActive(false);
				((Component)val2).gameObject.SetActive(true);
			}
		}

		private static void RecolourMenu(Scene scene)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Root(scene, "MENU");
			Transform obj = ((val != null) ? val.transform.Find("EclipseRunMenu/Main Panel") : null);
			if (!Object.op_Implicit((Object)(object)obj))
			{
				throw new InvalidOperationException("'MENU/EclipseRunMenu/Main Panel' not found");
			}
			Transform val2 = obj.Find("GenericMenuButtonPanel/JuicePanel/ReadyButton");
			if (val2 != null)
			{
				Image component = ((Component)val2).GetComponent<Image>();
				if (component != null)
				{
					((Graphic)component).color = Color32.op_Implicit(new Color32((byte)172, (byte)27, (byte)42, byte.MaxValue));
				}
			}
			Transform val3 = obj.Find("RightPanel/MedalPanel/HorizontalLayout");
			if (Object.op_Implicit((Object)(object)val3) && inferno.SwapIcons != null)
			{
				inferno.SwapIcons.Invoke(null, new object[2] { 0, val3 });
			}
		}

		private static void RefreshLanguage()
		{
			LanguageConVar instance = LanguageConVar.instance;
			if (instance != null)
			{
				((BaseConVar)instance).SetString(((BaseConVar)instance).GetString());
			}
		}
	}
	internal enum HookPlanAction
	{
		Install,
		RemoveCleanup
	}
	internal sealed class HookPlanEntry
	{
		public int Index;

		public HookPlanAction Action;

		public MethodInfo InfernoHook;

		public MethodInfo AddAccessor;

		public MethodInfo RemoveAccessor;

		public Type HookDelegateType;

		public Type SelfType;

		public MethodBase Target;

		public Delegate Handler;

		public string Incompatibility;

		public string ObsoleteUses;

		public object Replacement;

		public bool Compatible => Incompatibility == null;

		public string TargetName
		{
			get
			{
				if (!(Target != null))
				{
					if (!(AddAccessor != null))
					{
						return "<unresolved>";
					}
					return AddAccessor.DeclaringType?.FullName + "." + EventName(AddAccessor);
				}
				return Target.DeclaringType?.FullName + "." + Target.Name + "(" + string.Join(", ", from p in Target.GetParameters()
					select p.ParameterType.Name) + ")";
			}
		}

		public string Label => TargetName + " <- Inferno " + InfernoHook?.DeclaringType?.Name + "." + InfernoHook?.Name;

		internal static string EventName(MethodInfo accessor)
		{
			return accessor.Name.Substring(accessor.Name.IndexOf('_') + 1);
		}
	}
	internal sealed class InfernoHookPlan
	{
		private const BindingFlags AllDeclared = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public readonly List<HookPlanEntry> Entries = new List<HookPlanEntry>();

		public IEnumerable<HookPlanEntry> Installs => Entries.Where((HookPlanEntry e) => e.Action == HookPlanAction.Install);

		public IEnumerable<HookPlanEntry> Cleanups => Entries.Where((HookPlanEntry e) => e.Action == HookPlanAction.RemoveCleanup);

		public static InfernoHookPlan Build(MethodInfo applyHooks)
		{
			InfernoHookPlan infernoHookPlan = new InfernoHookPlan();
			Module module = applyHooks.Module;
			MethodInfo methodInfo = null;
			foreach (IlInstruction item in IlReader.Read(applyHooks))
			{
				if (item.OpCode == OpCodes.Ldftn)
				{
					methodInfo = module.ResolveMethod(item.Token) as MethodInfo;
				}
				else
				{
					if (methodInfo == null || (item.OpCode != OpCodes.Call && item.OpCode != OpCodes.Callvirt))
					{
						continue;
					}
					HookPlanEntry hookPlanEntry = new HookPlanEntry
					{
						Index = infernoHookPlan.Entries.Count,
						InfernoHook = methodInfo
					};
					MethodInfo methodInfo2;
					try
					{
						methodInfo2 = module.ResolveMethod(item.Token) as MethodInfo;
					}
					catch (Exception ex)
					{
						hookPlanEntry.Incompatibility = $"hook event at IL_{item.Offset:X4} does not exist in the current MMHOOK ({ex.GetType().Name}: {ex.Message})";
						infernoHookPlan.Entries.Add(hookPlanEntry);
						methodInfo = null;
						continue;
					}
					if (IsHookAccessor(methodInfo2))
					{
						try
						{
							Resolve(hookPlanEntry, methodInfo2);
						}
						catch (Exception ex2)
						{
							hookPlanEntry.Incompatibility = "could not be checked (" + ex2.GetType().Name + ": " + ex2.Message + ")";
						}
						infernoHookPlan.Entries.Add(hookPlanEntry);
						methodInfo = null;
					}
				}
			}
			return infernoHookPlan;
		}

		private static bool IsHookAccessor(MethodInfo m)
		{
			if (m != null && m.IsStatic && (m.Name.StartsWith("add_", StringComparison.Ordinal) || m.Name.StartsWith("remove_", StringComparison.Ordinal)) && m.DeclaringType?.Namespace != null && (m.DeclaringType.Namespace.StartsWith("On.", StringComparison.Ordinal) || m.DeclaringType.Namespace.StartsWith("IL.", StringComparison.Ordinal)) && m.GetParameters().Length == 1)
			{
				return typeof(Delegate).IsAssignableFrom(m.GetParameters()[0].ParameterType);
			}
			return false;
		}

		private static void Resolve(HookPlanEntry entry, MethodInfo accessor)
		{
			bool flag = accessor.Name.StartsWith("add_", StringComparison.Ordinal);
			string text = HookPlanEntry.EventName(accessor);
			Type declaringType = accessor.DeclaringType;
			entry.Action = ((!flag) ? HookPlanAction.RemoveCleanup : HookPlanAction.Install);
			entry.HookDelegateType = accessor.GetParameters()[0].ParameterType;
			entry.AddAccessor = (flag ? accessor : declaringType.GetMethod("add_" + text, BindingFlags.Static | BindingFlags.Public, null, new Type[1] { entry.HookDelegateType }, null));
			entry.RemoveAccessor = (flag ? declaringType.GetMethod("remove_" + text, BindingFlags.Static | BindingFlags.Public, null, new Type[1] { entry.HookDelegateType }, null) : accessor);
			if (declaringType.Namespace.StartsWith("IL.", StringComparison.Ordinal))
			{
				entry.Incompatibility = "IL hooks inside ApplyHooks are not expected (Inferno 1.7.8 has none)";
				return;
			}
			if (entry.AddAccessor == null || entry.RemoveAccessor == null)
			{
				entry.Incompatibility = "MMHOOK has no matching add_/remove_" + text;
				return;
			}
			MethodInfo method = entry.HookDelegateType.GetMethod("Invoke");
			ParameterInfo[] array = method?.GetParameters() ?? Array.Empty<ParameterInfo>();
			if (array.Length < 2)
			{
				entry.Incompatibility = "unexpected hook delegate " + entry.HookDelegateType.FullName;
				return;
			}
			entry.SelfType = array[1].ParameterType;
			Type[] parameters = (from p in array.Skip(2)
				select p.ParameterType).ToArray();
			entry.Target = FindTarget(entry.SelfType, text, parameters, method.ReturnType);
			if (entry.Target == null)
			{
				entry.Incompatibility = entry.SelfType.FullName + "." + text + " not found in the current game";
				return;
			}
			ParameterInfo[] parameters2 = entry.InfernoHook.GetParameters();
			if (parameters2.Length != array.Length || entry.InfernoHook.ReturnType != method.ReturnType || parameters2.Zip(array, (ParameterInfo h, ParameterInfo w) => h.ParameterType == w.ParameterType).Any((bool same) => !same))
			{
				entry.Incompatibility = "signature changed: Inferno's hook takes (" + Names(parameters2) + "), the current game needs (" + Names(array) + ")";
			}
			else
			{
				entry.Handler = Delegate.CreateDelegate(entry.HookDelegateType, entry.InfernoHook, throwOnBindFailure: false);
				if ((object)entry.Handler == null)
				{
					entry.Incompatibility = "cannot bind " + entry.InfernoHook.Name + " to " + entry.HookDelegateType.FullName;
					return;
				}
				entry.ObsoleteUses = FindObsoleteFields(entry.InfernoHook);
				entry.Incompatibility = FindBrokenReference(entry.InfernoHook, new HashSet<MethodBase>(), 2);
			}
		}

		public static string FindObsoleteFields(MethodBase method)
		{
			SortedSet<string> sortedSet = new SortedSet<string>();
			Module module = method.Module;
			foreach (IlInstruction item in IlReader.Read(method))
			{
				if (item.OpCode.OperandType != OperandType.InlineField)
				{
					continue;
				}
				try
				{
					FieldInfo fieldInfo = module.ResolveField(item.Token);
					if (fieldInfo != null && fieldInfo.Module != module && fieldInfo.IsDefined(typeof(ObsoleteAttribute), inherit: false))
					{
						sortedSet.Add(fieldInfo.DeclaringType?.Name + "." + fieldInfo.Name);
					}
				}
				catch (Exception)
				{
				}
			}
			if (sortedSet.Count <= 0)
			{
				return null;
			}
			return string.Join(", ", sortedSet);
		}

		private static MethodBase FindTarget(Type self, string eventName, Type[] parameters, Type returnType)
		{
			MethodInfo[] methods = self.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			return methods.FirstOrDefault((MethodInfo m) => m.Name == eventName && Matches(m, parameters, returnType)) ?? methods.FirstOrDefault((MethodInfo m) => eventName.StartsWith(m.Name + "_", StringComparison.Ordinal) && Matches(m, parameters, returnType));
		}

		private static bool Matches(MethodInfo m, Type[] parameters, Type returnType)
		{
			try
			{
				ParameterInfo[] parameters2 = m.GetParameters();
				return m.ReturnType == returnType && parameters2.Length == parameters.Length && parameters2.Select((ParameterInfo x) => x.ParameterType).SequenceEqual(parameters);
			}
			catch (Exception)
			{
				return false;
			}
		}

		private static string Names(ParameterInfo[] p)
		{
			return string.Join(", ", p.Select((ParameterInfo x) => x.ParameterType.Name));
		}

		public static string FindBrokenReference(MethodBase method, HashSet<MethodBase> visited, int depth)
		{
			if (!visited.Add(method))
			{
				return null;
			}
			List<IlInstruction> list;
			try
			{
				list = IlReader.Read(method);
			}
			catch (Exception ex)
			{
				return "cannot read the IL of " + IlReader.Describe(method) + ": " + ex.Message;
			}
			Module module = method.Module;
			Type[] genericTypeArguments = ((method.DeclaringType != null && method.DeclaringType.IsGenericType) ? method.DeclaringType.GetGenericArguments() : null);
			Type[] genericMethodArguments = (method.IsGenericMethod ? method.GetGenericArguments() : null);
			foreach (IlInstruction item in list)
			{
				if (!item.HasToken)
				{
					continue;
				}
				try
				{
					switch (item.OpCode.OperandType)
					{
					case OperandType.InlineField:
					{
						FieldInfo fieldInfo = module.ResolveField(item.Token, genericTypeArguments, genericMethodArguments);
						bool flag = item.OpCode == OpCodes.Ldsfld || item.OpCode == OpCodes.Stsfld || item.OpCode == OpCodes.Ldsflda;
						if (fieldInfo.IsStatic != flag)
						{
							return IlReader.Describe(method) + " uses " + fieldInfo.DeclaringType?.FullName + "." + fieldInfo.Name + " as a " + (flag ? "static" : "instance") + " field, but it is now an " + (fieldInfo.IsStatic ? "static" : "instance") + " field";
						}
						break;
					}
					case OperandType.InlineMethod:
					{
						MethodBase methodBase = module.ResolveMethod(item.Token, genericTypeArguments, genericMethodArguments);
						if (methodBase == null)
						{
							return $"{IlReader.Describe(method)} IL_{item.Offset:X4}: method token 0x{item.Token:X8} does not resolve";
						}
						if (depth > 0 && methodBase.Module == module && methodBase.GetMethodBody() != null)
						{
							string text = FindBrokenReference(methodBase, visited, depth - 1);
							if (text != null)
							{
								return text;
							}
						}
						break;
					}
					case OperandType.InlineType:
						module.ResolveType(item.Token, genericTypeArguments, genericMethodArguments);
						break;
					case OperandType.InlineTok:
						module.ResolveMember(item.Token, genericTypeArguments, genericMethodArguments);
						break;
					}
				}
				catch (Exception ex2)
				{
					return $"{IlReader.Describe(method)} IL_{item.Offset:X4} {item.OpCode}: {ex2.GetType().Name}: {ex2.Message}";
				}
			}
			return null;
		}
	}
	internal sealed class HookReplacement
	{
		public string Name;

		public string InfernoHookName;

		public Type SelfType;

		public MethodBase Target;

		public Hook Detour;

		public string Error;

		public Action Enable;

		public Action Disable;

		public bool Available
		{
			get
			{
				if (Enable != null)
				{
					return Disable != null;
				}
				return false;
			}
		}

		public bool Replaces(HookPlanEntry entry)
		{
			if (entry.InfernoHook?.Name == InfernoHookName)
			{
				return entry.SelfType == SelfType;
			}
			return false;
		}
	}
	internal static class InfernoRepairs
	{
		internal delegate void FireWaveOrig(UltChannelState self, Vector3 position, bool useStationary, bool incrementCount);

		private static InfernoBinding inferno;

		private static readonly List<HookReplacement> replacements = new List<HookReplacement>();

		private static readonly HashSet<string> reported = new HashSet<string>();

		private static GameObject pillarGhost;

		private static bool pillarScaled;

		public static List<HookReplacement> Create(InfernoBinding binding)
		{
			inferno = binding;
			replacements.Clear();
			Add("FireWave", "FireWave", typeof(UltChannelState), typeof(UltChannelState).GetMethod("FireWave", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3]
			{
				typeof(Vector3),
				typeof(bool),
				typeof(bool)
			}, null), "FireWave");
			Add("SporeGrenade", "SporeGrenade", typeof(SporeGrenade), DeclaredOnEnter(typeof(SporeGrenade)), "SporeGrenadeOnEnter");
			Add("Mithrix Phase 2", "Phase2", typeof(Phase2), DeclaredOnEnter(typeof(Phase2)), "Phase2OnEnter");
			Add("WeaponSlam", "WeaponSlam", typeof(WeaponSlam), DeclaredOnEnter(typeof(WeaponSlam)), "WeaponSlamOnEnter");
			Add("CleanupPillar", "CleanupPillar", typeof(WeaponSlam), DeclaredOnEnter(typeof(WeaponSlam)), "CleanupPillarOnEnter");
			return replacements;
		}

		private static MethodBase DeclaredOnEnter(Type type)
		{
			return type.GetMethod("OnEnter", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
		}

		private static void Add(string name, string infernoHook, Type self, MethodBase target, string hookMethod)
		{
			//IL_0050: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			HookReplacement hookReplacement = new HookReplacement
			{
				Name = name,
				InfernoHookName = infernoHook,
				SelfType = self,
				Target = target
			};
			replacements.Add(hookReplacement);
			if (target == null)
			{
				hookReplacement.Error = self.FullName + " has no method with the expected current-game signature";
				return;
			}
			try
			{
				HookConfig val = new HookConfig
				{
					ManualApply = true
				};
				hookReplacement.Detour = new Hook(target, typeof(InfernoRepairs).GetMethod(hookMethod, BindingFlags.Static | BindingFlags.NonPublic), val);
				hookReplacement.Enable = hookReplacement.Detour.Apply;
				hookReplacement.Disable = hookReplacement.Detour.Undo;
			}
			catch (Exception ex)
			{
				hookReplacement.Error = ex.GetType().Name + ": " + ex.Message;
			}
		}

		public static void Dispose()
		{
			foreach (HookReplacement replacement in replacements)
			{
				Hook detour = replacement.Detour;
				if (detour != null)
				{
					detour.Dispose();
				}
			}
			replacements.Clear();
		}

		public static void BeginRun()
		{
			reported.Clear();
		}

		private static void ReportOnce(string key, string message, bool warning = false)
		{
			if (reported.Add(key))
			{
				if (warning)
				{
					CompatLog.Warning(message);
				}
				else
				{
					CompatLog.Info(message);
				}
			}
		}

		private static void FireWave(FireWaveOrig orig, UltChannelState self, Vector3 position, bool useStationary, bool incrementCount)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (incrementCount)
			{
				try
				{
					FireInfernoWaves(self);
				}
				catch (Exception ex)
				{
					ReportOnce("FireWave.error", "FireWave replacement: Inferno's extra ult waves failed (the game's own waves still fire): " + ex, warning: true);
				}
			}
			orig(self, position, useStationary, incrementCount);
		}

		private static void FireInfernoWaves(UltChannelState self)
		{
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			EntityStateMachine outer = ((EntityState)self).outer;
			if (!inferno.MithrixChangesEnabled || !Object.op_Implicit((Object)(object)outer) || !Util.HasEffectiveAuthority(outer.networkIdentity))
			{
				return;
			}
			CharacterBody characterBody = outer.commonComponents.characterBody;
			InputBankTest inputBank = outer.commonComponents.inputBank;
			GameObject waveProjectileLeftPrefab = UltChannelState.waveProjectileLeftPrefab;
			if (!Object.op_Implicit((Object)(object)characterBody) || !Object.op_Implicit((Object)(object)inputBank) || !Object.op_Implicit((Object)(object)waveProjectileLeftPrefab) || !Object.op_Implicit((Object)(object)ProjectileManager.instance))
			{
				ReportOnce("FireWave.missing", $"FireWave replacement: skipping Inferno's extra waves (body {Object.op_Implicit((Object)(object)characterBody)}, input {Object.op_Implicit((Object)(object)inputBank)}, " + $"waveProjectileLeftPrefab {Object.op_Implicit((Object)(object)waveProjectileLeftPrefab)}, ProjectileManager {Object.op_Implicit((Object)(object)ProjectileManager.instance)})", warning: true);
				return;
			}
			Transform val = FindModelChild(outer, WeaponSlam.muzzleString);
			if (!Object.op_Implicit((Object)(object)val))
			{
				ReportOnce("FireWave.muzzle", "FireWave replacement: Mithrix model child '" + WeaponSlam.muzzleString + "' not found; centering Inferno's extra waves on his feet", warning: true);
			}
			Vector3 val2 = (Object.op_Implicit((Object)(object)val) ? val.position : characterBody.footPosition) + new Vector3(Random.Range(-50f, 50f), 0f, Random.Range(-50f, 50f));
			Vector3 val3 = Vector3.ProjectOnPlane(inputBank.aimDirection, Vector3.up);
			for (int i = 0; i < 4; i++)
			{
				Vector3 val4 = Quaternion.AngleAxis(90f * (float)i, Vector3.up) * val3;
				ProjectileManager.instance.FireProjectile(waveProjectileLeftPrefab, val2, Util.QuaternionSafeLookRotation(val4), ((Component)outer).gameObject, characterBody.damage * 4f, FistSlam.waveProjectileForce, Util.CheckRoll(characterBody.crit, characterBody.master), (DamageColorIndex)0, (GameObject)null, -1f, (DamageTypeCombo?)null);
			}
			ReportOnce("FireWave.ok", "FireWave replacement active: Inferno's extra Mithrix ult waves fired (first time this run)");
		}

		private static Transform FindModelChild(EntityStateMachine outer, string childName)
		{
			ModelLocator modelLocator = outer.commonComponents.modelLocator;
			ChildLocator val = ((Object.op_Implicit((Object)(object)modelLocator) && Object.op_Implicit((Object)(object)modelLocator.modelTransform)) ? ((Component)modelLocator.modelTransform).GetComponent<ChildLocator>() : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			return val.FindChild(childName);
		}

		private static void SporeGrenadeOnEnter(Action<SporeGrenade> orig, SporeGrenade self)
		{
			self.baseChargeTime = 1.25f;
			self.baseDuration = 1.25f;
			self.damageCoefficient = 1.1f;
			ReportOnce("SporeGrenade", "SporeGrenade replacement active: Inferno's Mini Mushrum tuning applied (first time this run)");
			orig(self);
		}

		private static void Phase2OnEnter(Action<Phase2> orig, Phase2 self)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			orig(self);
			if (inferno.MithrixChangesEnabled && NetworkServer.active && Object.op_Implicit((Object)(object)((EntityState)self).outer))
			{
				ReportOnce("Phase2", "Mithrix Phase 2 repair active: skipping to Phase 3 without spawning the Brother Throne");
				((EntityState)self).outer.SetNextState((EntityState)new Phase3());
			}
		}

		private static void WeaponSlamOnEnter(Action<WeaponSlam> orig, WeaponSlam self)
		{
			try
			{
				ApplyInfernoWeaponSlam(self);
			}
			catch (Exception ex)
			{
				ReportOnce("WeaponSlam.error", "WeaponSlam replacement: Inferno's slam changes failed (the game's slam still runs): " + ex, warning: true);
			}
			orig(self);
		}

		private static void ApplyInfernoWeaponSlam(WeaponSlam self)
		{
			string arg = "pillar unchanged (Mithrix changes off)";
			bool flag = false;
			if (inferno.MithrixChangesEnabled)
			{
				WeaponSlam.waveProjectileArc = 360f;
				WeaponSlam.waveProjectileCount = 8;
				WeaponSlam.waveProjectileDamageCoefficient = 2f;
				WeaponSlam.waveProjectileForce = -1600f;
				WeaponSlam.weaponForce = -2300f;
				arg = ScalePillar(4f);
				flag = inferno.ResetWeaponSlamBurst();
				if (!flag)
				{
					ReportOnce("WeaponSlam.burst", "WeaponSlam replacement: Inferno's Main.hasFired was not found; Inferno's post-slam wave burst fires only once", warning: true);
				}
			}
			WeaponSlam.duration = 3f;
			ReportOnce("WeaponSlam.ok", $"WeaponSlam replacement active: Inferno's slam tuning applied before the game's slam (duration {WeaponSlam.duration:0.##} s; {arg}; " + "post-slam wave burst " + (flag ? "re-armed" : "not re-armed") + "); first time this run");
		}

		private static void CleanupPillarOnEnter(Action<WeaponSlam> orig, WeaponSlam self)
		{
			try
			{
				if (pillarScaled)
				{
					CompatLog.Info("CleanupPillar replacement: Mithrix pillar reset to normal size after the Inferno run (" + ScalePillar(1f) + ")");
				}
			}
			catch (Exception ex)
			{
				ReportOnce("CleanupPillar.error", "CleanupPillar replacement failed (the game's slam still runs): " + ex, warning: true);
			}
			orig(self);
		}

		private static string ScalePillar(float scale)
		{
			//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_0058: 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)
			GameObject pillarProjectilePrefab = WeaponSlam.pillarProjectilePrefab;
			if (!Object.op_Implicit((Object)(object)pillarProjectilePrefab))
			{
				return "pillar not changed (WeaponSlam.pillarProjectilePrefab is not set)";
			}
			pillarProjectilePrefab.transform.localScale = Vector3.one * scale;
			GameObject val = (Object.op_Implicit((Object)(object)pillarGhost) ? pillarGhost : (pillarGhost = FindGhostPrefab(pillarProjectilePrefab)));
			if (Object.op_Implicit((Object)(object)val))
			{
				val.transform.localScale = Vector3.one * scale;
			}
			pillarScaled = scale != 1f;
			return string.Format("pillar {0} at {1}x", Object.op_Implicit((Object)(object)val) ? "and its visual" : "scaled, its visual not found,", scale);
		}

		private static GameObject FindGhostPrefab(GameObject projectile)
		{
			//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)
			ProjectileController component = projectile.GetComponent<ProjectileController>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return null;
			}
			if (Object.op_Implicit((Object)(object)component.ghostPrefab))
			{
				return component.ghostPrefab;
			}
			if (component.ghostPrefabAddress == null || !((AssetReference)component.ghostPrefabAddress).RuntimeKeyIsValid())
			{
				return null;
			}
			return Addressables.LoadAssetAsync<GameObject>(((AssetReference)component.ghostPrefabAddress).RuntimeKey).WaitForCompletion();
		}
	}
	[BepInPlugin("Nhiblam.InfernoSkinFix", "InfernoSkinFix", "0.2.1")]
	[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.*/)]
	public sealed class InfernoSkinFixPlugin : BaseUnityPlugin
	{
		private delegate IEnumerator ApplySkinAsyncFn(ModelSkinController self, int skinIndex, AsyncReferenceHandleUnloadType unloadType);

		public const string Guid = "Nhiblam.InfernoSkinFix";

		public const string PluginName = "InfernoSkinFix";

		public const string PluginVersion = "0.2.1";

		private const string LobbySkinsFixGuid = "com.KingEnderBrine.LobbySkinsFix";

		private const string R2ApiSkinsGuid = "com.bepis.r2api.skins";

		private const string DynamicSkinsFixGuid = "Miyowi.DynamicSkinsFix";

		private Hook skinCatalogInitHook;

		private Hook applySkinHook;

		private void Awake()
		{
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Expected O, but got Unknown
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Expected O, but got Unknown
			SkinTrace.Log = ((BaseUnityPlugin)this).Logger.LogInfo;
			SkinTrace.Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "TraceSkinApplication", false, "Troubleshooting: log the renderer, mesh, bone and material state of Inferno-skinned survivors whenever a skin is applied (lobby and run).").Value;
			SkinRepairs.LogInfo = ((BaseUnityPlugin)this).Logger.LogInfo;
			SkinRepairs.LogError = ((BaseUnityPlugin)this).Logger.LogError;
			AccessoryBoneRig.LogError = ((BaseUnityPlugin)this).Logger.LogError;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("InfernoSkinFix 0.2.1 build=" + BuildId() + " sha256=" + OwnHash() + " with Inferno " + InfernoSkins.GetPluginVersion("HIFU.Inferno") + " (InfernoSkinMod " + InfernoSkins.GetPluginVersion("com.Dotflare.InfernoSkinMod") + ")"));
			InfernoCompat.Init((BaseUnityPlugin)(object)this, ((BaseUnityPlugin)this).Logger, ((BaseUnityPlugin)this).Config);
			string pluginVersion = InfernoSkins.GetPluginVersion("Miyowi.DynamicSkinsFix");
			if (pluginVersion != null)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("DynamicSkinsFix " + pluginVersion + " detected: Inferno's own Bandit/Railgunner bone hook stays disabled; InfernoSkinFix adds those bones."));
			}
			if (!InfernoDynamicSkins.Bind())
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Could not read InfernoSkinMod's DynamicSkins data (" + InfernoDynamicSkins.BindError + "); Bandit and Railgunner will not be repaired."));
			}
			try
			{
				MethodInfo methodInfo = typeof(SkinCatalog).GetMethod("Init", BindingFlags.Static | BindingFlags.NonPublic, null, Type.EmptyTypes, null) ?? throw new MissingMethodException("RoR2.SkinCatalog", "Init");
				skinCatalogInitHook = new Hook((MethodBase)methodInfo, (Delegate)new Func<Func<IEnumerator>, IEnumerator>(OnSkinCatalogInit));
				MethodInfo method = typeof(ModelSkinController).GetMethod("ApplySkinAsync", new Type[2]
				{
					typeof(int),
					typeof(AsyncReferenceHandleUnloadType)
				});
				applySkinHook = new Hook((MethodBase)method, (Delegate)new Func<ApplySkinAsyncFn, ModelSkinController, int, AsyncReferenceHandleUnloadType, IEnumerator>(OnApplySkinAsync));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Hook installation failed; Inferno skins are not repaired: " + ex));
				Hook obj = skinCatalogInitHook;
				if (obj != null)
				{
					obj.Dispose();
				}
				Hook obj2 = applySkinHook;
				if (obj2 != null)
				{
					obj2.Dispose();
				}
				return;
			}
			((ResourceAvailability)(ref SkinCatalog.availability)).CallWhenAvailable((Action)SkinRepairs.Report);
			if (SkinTrace.Enabled)
			{
				((ResourceAvailability)(ref SkinCatalog.availability)).CallWhenAvailable((Action)ReportBodySkins);
				MainMenuController.OnMainMenuInitialised += ReportDisplaySkins;
			}
		}

		private void OnDestroy()
		{
			InfernoCompat.Shutdown();
			Hook obj = skinCatalogInitHook;
			if (obj != null)
			{
				obj.Dispose();
			}
			Hook obj2 = applySkinHook;
			if (obj2 != null)
			{
				obj2.Dispose();
			}
			MainMenuController.OnMainMenuInitialised -= ReportDisplaySkins;
		}

		private static IEnumerator OnSkinCatalogInit(Func<IEnumerator> orig)
		{
			SkinRepairs.PatchSkinDefs();
			return orig();
		}

		private static IEnumerator OnApplySkinAsync(ApplySkinAsyncFn orig, ModelSkinController self, int skinIndex, AsyncReferenceHandleUnloadType unloadType)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			IEnumerator inner = orig(self, skinIndex, unloadType);
			bool flag = false;
			try
			{
				SkinDef[] skins = self.skins;
				AccessoryRigSpec accessoryRigSpec = SkinRepairs.FindRig(InfernoSkins.Identify((skins != null && skins.Length != 0) ? skins[((uint)skinIndex < skins.Length) ? skinIndex : 0] : null));
				if (accessoryRigSpec != null)
				{
					AccessoryBoneRig.Ensure(self, accessoryRigSpec);
				}
				AccessoryBoneRig accessoryBoneRig = default(AccessoryBoneRig);
				flag = ((Component)self).TryGetComponent<AccessoryBoneRig>(ref accessoryBoneRig);
			}
			catch (Exception arg)
			{
				AccessoryBoneRig.LogError(string.Format("Accessory bone setup failed on '{0}': {1}", Object.op_Implicit((Object)(object)self) ? ((Object)self).name : "null", arg));
			}
			if (flag)
			{
				inner = SyncAfter(self, inner);
			}
			return SkinTrace.Wrap(self, skinIndex, inner);
		}

		private static IEnumerator SyncAfter(ModelSkinController controller, IEnumerator inner)
		{
			while (inner.MoveNext())
			{
				yield return inner.Current;
			}
			AccessoryBoneRig accessoryBoneRig = default(AccessoryBoneRig);
			if (Object.op_Implicit((Object)(object)controller) && ((Component)controller).TryGetComponent<AccessoryBoneRig>(ref accessoryBoneRig))
			{
				accessoryBoneRig.Sync();
			}
		}

		private void ReportBodySkins()
		{
			InfernoSkin[] all = InfernoSkins.All;
			foreach (InfernoSkin infernoSkin in all)
			{
				try
				{
					ModelSkinController val = InfernoSkins.FindBodyModelSkinController(infernoSkin.BodyName);
					SkinDef val2 = infernoSkin.FindBodySkin();
					if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val2))
					{
						((BaseUnityPlugin)this).Logger.LogInfo((object)(SkinTrace.DescribeModel(infernoSkin.Survivor + " body", val) + "\n" + SkinTrace.DescribeLegacyTargets(val2, val) + "\n" + SkinTrace.DescribeSkin(val2, "  ") + "\n" + SkinTrace.DescribeSkin(val.skins[0], "  ")));
					}
				}
				catch (Exception arg)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)$"{infernoSkin.Survivor}: body report failed: {arg}");
				}
			}
		}

		private void ReportDisplaySkins()
		{
			MainMenuController.OnMainMenuInitialised -= ReportDisplaySkins;
			InfernoSkin[] all = InfernoSkins.All;
			foreach (InfernoSkin infernoSkin in all)
			{
				try
				{
					SurvivorDef val = SurvivorCatalog.FindSurvivorDefFromBody(BodyCatalog.FindBodyPrefab(infernoSkin.BodyName));
					ModelSkinController val2 = ((Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val.displayPrefab)) ? val.displayPrefab.GetComponentInChildren<ModelSkinController>() : null);
					if (!Object.op_Implicit((Object)(object)val2))
					{
						continue;
					}
					string text = SkinTrace.DescribeModel(infernoSkin.Survivor + " display", val2);
					SkinDef[] skins = val2.skins;
					foreach (SkinDef skin in skins)
					{
						if (InfernoSkins.Identify(skin) == infernoSkin)
						{
							text = text + "\n" + SkinTrace.DescribeSkin(skin, "  ");
						}
					}
					((BaseUnityPlugin)this).Logger.LogInfo((object)text);
				}
				catch (Exception arg)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)$"{infernoSkin.Survivor}: display report failed: {arg}");
				}
			}
		}

		private static string BuildId()
		{
			return typeof(InfernoSkinFixPlugin).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "unknown";
		}

		private string OwnHash()
		{
			try
			{
				using SHA256 sHA = SHA256.Create();
				using FileStream inputStream = File.OpenRead(((BaseUnityPlugin)this).Info.Location);
				return BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", "");
			}
			catch (Exception ex)
			{
				return "unavailable (" + ex.GetType().Name + ")";
			}
		}
	}
	internal sealed class InfernoSkin
	{
		public readonly string Survivor;

		public readonly string BodyName;

		public readonly string SkinName;

		public readonly string Token;

		public InfernoSkin(string survivor, string bodyName, string skinName, string token)
		{
			Survivor = survivor;
			BodyName = bodyName;
			SkinName = skinName;
			Token = token;
		}

		public SkinDef FindBodySkin()
		{
			ModelSkinController val = InfernoSkins.FindBodyModelSkinController(BodyName);
			if (!Object.op_Implicit((Object)(object)val) || val.skins == null)
			{
				return null;
			}
			SkinDef[] skins = val.skins;
			foreach (SkinDef val2 in skins)
			{
				if (Object.op_Implicit((Object)(object)val2) && ((Object)val2).name == SkinName && val2.nameToken == Token)
				{
					return val2;
				}
			}
			return null;
		}
	}
	internal static class InfernoSkins
	{
		public const string InfernoGuid = "HIFU.Inferno";

		public const string SkinModGuid = "com.Dotflare.InfernoSkinMod";

		public static readonly InfernoSkin Commando = new InfernoSkin("Commando", "CommandoBody", "MMando", "DOTFLARE_SKIN_MMANDO_NAME");

		public static readonly InfernoSkin Bandit = new InfernoSkin("Bandit", "Bandit2Body", "DBandit", "DOTFLARE_SKIN_DBANDIT_NAME");

		public static readonly InfernoSkin Captain = new InfernoSkin("Captain", "CaptainBody", "BCaptain", "DOTFLARE_SKIN_BCAPTAIN_NAME");

		public static readonly InfernoSkin Mercenary = new InfernoSkin("Mercenary", "MercBody", "HMerc", "DOTFLARE_SKIN_HMERC_NAME");

		public static readonly InfernoSkin Artificer = new InfernoSkin("Artificer", "MageBody", "CArti", "DOTFLARE_SKIN_CARTI_NAME");

		public static readonly InfernoSkin Railgunner = new InfernoSkin("Railgunner", "RailgunnerBody", "PGunner", "DOTFLARE_SKIN_PGUNNER_NAME");

		public static readonly InfernoSkin[] All = new InfernoSkin[6] { Commando, Bandit, Captain, Mercenary, Artificer, Railgunner };

		public static InfernoSkin Identify(SkinDef skin)
		{
			if (!Object.op_Implicit((Object)(object)skin))
			{
				return null;
			}
			string name = ((Object)skin).name;
			InfernoSkin[] all = All;
			foreach (InfernoSkin infernoSkin in all)
			{
				if (skin.nameToken == infernoSkin.Token && (name == infernoSkin.SkinName || name.StartsWith(infernoSkin.SkinName + "(", StringComparison.Ordinal)))
				{
					return infernoSkin;
				}
			}
			return null;
		}

		public static InfernoSkin FindOnController(ModelSkinController controller)
		{
			if (!Object.op_Implicit((Object)(object)controller) || controller.skins == null)
			{
				return null;
			}
			SkinDef[] skins = controller.skins;
			for (int i = 0; i < skins.Length; i++)
			{
				InfernoSkin infernoSkin = Identify(skins[i]);
				if (infernoSkin != null)
				{
					return infernoSkin;
				}
			}
			return null;
		}

		public static ModelSkinController FindBodyModelSkinController(string bodyName)
		{
			GameObject val = BodyCatalog.FindBodyPrefab(bodyName);
			ModelLocator val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<ModelLocator>() : null);
			if (!Object.op_Implicit((Object)(object)val2) || !Object.op_Implicit((Object)(object)val2.modelTransform))
			{
				return null;
			}
			return ((Component)val2.modelTransform).GetComponent<ModelSkinController>();
		}

		public static string GetPluginVersion(string guid)
		{
			if (!Chainloader.PluginInfos.TryGetValue(guid, out var value))
			{
				return null;
			}
			return value.Metadata.Version.ToString();
		}
	}
	internal static class InfernoDynamicSkins
	{
		private const BindingFlags Fields = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public static object Manager { get; private set; }

		public static string BindError { get; private set; }

		public static int ModifiedObjectCount
		{
			get
			{
				if (!(GetField(Manager, "ModifiedObjects") is ICollection collection))
				{
					return -1;
				}
				return collection.Count;
			}
		}

		public static bool Bind()
		{
			try
			{
				if (!Chainloader.PluginInfos.TryGetValue("com.Dotflare.InfernoSkinMod", out var value) || !Object.op_Implicit((Object)(object)value.Instance))
				{
					return Fail("InfernoSkinMod is not loaded");
				}
				Type type = ((object)value.Instance).GetType();
				Manager = type.GetField("_DynamicSkinManager", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null);
				return Manager != null || Fail(type.FullName + "._DynamicSkinManager not found");
			}
			catch (Exception ex)
			{
				return Fail(ex.GetType().Name + ": " + ex.Message);
			}
		}

		private static bool Fail(string error)
		{
			BindError = error;
			Manager = null;
			return false;
		}

		public static object GetField(object owner, string name)
		{
			return owner?.GetType().GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(owner);
		}

		public static object[] GetModifications(string token)
		{
			if (!(GetField(Manager, "ModificationList") is IDictionary dictionary) || !(dictionary[token] is IDictionary dictionary2))
			{
				return Array.Empty<object>();
			}
			object[] array = new object[dictionary2.Count];
			dictionary2.Values.CopyTo(array, 0);
			return array;
		}

		public static void DisableOriginal(string token)
		{
			if (GetField(Manager, "SkinDefs") is IDictionary dictionary)
			{
				dictionary.Remove(token);
			}
		}
	}
	internal static class RunEventGuard
	{
		private sealed class Wrapped
		{
			public FieldInfo Field;

			public Delegate Wrapper;

			public Delegate Original;
		}

		private static readonly List<Wrapped> wrapped = new List<Wrapped>();

		public static int Install(Assembly inferno)
		{
			return 0 + Wrap<Action<Run>>("onRunStartGlobal", inferno, (Action<Run> inner) => delegate(Run run)
			{
				Guard(inner, "Run start", delegate
				{
					inner(run);
				});
			}) + Wrap<Action<Run>>("onRunDestroyGlobal", inferno, (Action<Run> inner) => delegate(Run run)
			{
				Guard(inner, "Run destroy", delegate
				{
					inner(run);
				});
			}) + Wrap<Action<Run, RuleBook>>("onRunSetRuleBookGlobal", inferno, (Action<Run, RuleBook> inner) => delegate(Run run, RuleBook book)
			{
				Guard(inner, "Run rulebook", delegate
				{
					inner(run, book);
				});
			});
		}

		private static void Guard(Delegate inner, string what, Action call)
		{
			try
			{
				call();
			}
			catch (Exception arg)
			{
				CompatLog.Error("Inferno's " + what + " handler (" + inner.Method.DeclaringType?.FullName + "." + inner.Method.Name + ") threw; contained so that " + $"the rest of {what} continues: {arg}");
			}
		}

		private static int Wrap<T>(string eventName, Assembly owner, Func<T, T> makeWrapper) where T : Delegate
		{
			FieldInfo field = typeof(Run).GetField(eventName, BindingFlags.Static | BindingFlags.NonPublic);
			if (field == null || field.FieldType != typeof(T))
			{
				CompatLog.Warning("Run." + eventName + " has no backing field of type " + typeof(T).Name + "; its Inferno handlers are not guarded");
				return 0;
			}
			if (!(field.GetValue(null) is Delegate obj))
			{
				return 0;
			}
			Delegate[] invocationList = obj.GetInvocationList();
			int num = 0;
			for (int i = 0; i < invocationList.Length; i++)
			{
				if (!(invocationList[i].Method.DeclaringType?.Assembly != owner))
				{
					T val = makeWrapper((T)invocationList[i]);
					wrapped.Add(new Wrapped
					{
						Field = field,
						Wrapper = val,
						Original = invocationList[i]
					});
					invocationList[i] = val;
					num++;
				}
			}
			if (num > 0)
			{
				field.SetValue(null, Delegate.Combine(invocationList));
			}
			return num;
		}

		public static void Restore()
		{
			foreach (Wrapped item in wrapped)
			{
				if (item.Field.GetValue(null) is Delegate obj)
				{
					Delegate[] invocationList = obj.GetInvocationList();
					int num = Array.IndexOf(invocationList, item.Wrapper);
					if (num >= 0)
					{
						invocationList[num] = item.Original;
						item.Field.SetValue(null, Delegate.Combine(invocationList));
					}
				}
			}
			wrapped.Clear();
		}
	}
	internal static class SafeHookLifecycle
	{
		private sealed class InstalledHook
		{
			public string Label;

			public Action Remove;
		}

		private static InfernoHookPlan plan;

		private static Hook applyDetour;

		private static Hook undoDetour;

		private static readonly List<InstalledHook> runHooks = new List<InstalledHook>();

		private static readonly Dictionary<HookPlanEntry, InstalledHook> cleanupHooks = new Dictionary<HookPlanEntry, InstalledHook>();

		private static bool runHooksApplied;

		private static int infernoRuns;

		public static int RunHookCount => runHooks.Count;

		public static int CleanupHookCount => cleanupHooks.Count;

		public static void Install(InfernoBinding inferno, List<HookReplacement> replacements)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			if (inferno.ApplyHooks == null || inferno.UndoHooks == null)
			{
				CompatLog.Error("Inferno's HookBehavior.ApplyHooks/UndoHooks were not found; Inferno's skill hooks are left to Inferno (the Run start/destroy guard still contains their errors).");
				return;
			}
			try
			{
				plan = InfernoHookPlan.Build(inferno.ApplyHooks);
			}
			catch (Exception ex)
			{
				plan = null;
				CompatLog.Error("could not read Inferno's ApplyHooks; falling back to calling Inferno's originals with errors contained: " + ex);
			}
			if (plan != null)
			{
				Describe(plan, replacements);
			}
			try
			{
				applyDetour = new Hook((MethodBase)inferno.ApplyHooks, Method("OnApplyHooks"));
				undoDetour = new Hook((MethodBase)inferno.UndoHooks, Method("OnUndoHooks"));
				CompatLog.Info((plan != null) ? "replaced Inferno's ApplyHooks/UndoHooks with the tracked hook lifecycle" : "wrapped Inferno's ApplyHooks/UndoHooks (fallback mode, errors contained)");
			}
			catch (Exception ex2)
			{
				Hook obj = applyDetour;
				if (obj != null)
				{
					obj.Dispose();
				}
				applyDetour = null;
				undoDetour = null;
				CompatLog.Error("could not replace Inferno's ApplyHooks/UndoHooks (the Run start/destroy guard still contains their errors): " + ex2);
			}
		}

		private static MethodInfo Method(string name)
		{
			return typeof(SafeHookLifecycle).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic);
		}

		private static void Describe(InfernoHookPlan p, List<HookReplacement> replacements)
		{
			foreach (HookReplacement replacement in replacements)
			{
				HookPlanEntry hookPlanEntry = p.Entries.FirstOrDefault(replacement.Replaces);
				if (hookPlanEntry == null)
				{
					CompatLog.Warning(replacement.Name + " repair: Inferno no longer installs Hooks." + replacement.InfernoHookName + "; repair not needed");
				}
				else if (!replacement.Available)
				{
					CompatLog.Error(replacement.Name + " repair unavailable (" + replacement.Error + "); " + (hookPlanEntry.Compatible ? "Inferno's own hook is used" : "this Inferno hook is skipped"));
				}
				else
				{
					hookPlanEntry.Replacement = replacement;
					CompatLog.Info(replacement.Name + " repair ready: " + hookPlanEntry.TargetName + " replaces Inferno's Hooks." + replacement.InfernoHookName + (hookPlanEntry.Compatible ? "" : (" (Inferno's version: " + hookPlanEntry.Incompatibility + ")")));
				}
			}
			foreach (HookPlanEntry entry in p.Entries)
			{
				if (entry.Replacement == null && !entry.Compatible)
				{
					CompatLog.Error($"Inferno hook #{entry.Index} skipped, does not fit this game version: {entry.Label}: {entry.Incompatibility}");
				}
				else if (entry.Replacement == null && entry.ObsoleteUses != null)
				{
					CompatLog.Warning($"Inferno hook #{entry.Index} uses game fields the game marks obsolete (they may be empty at runtime): {entry.Label}: {entry.ObsoleteUses}");
				}
				CompatLog.Debug(string.Format("plan #{0} {1} ", entry.Index, (entry.Action == HookPlanAction.Install) ? "+=" : "-=") + ((entry.Replacement != null) ? "REPLACED" : (entry.Compatible ? "ok" : "SKIP")) + " " + entry.Label);
			}
			int num = p.Installs.Count();
			int num2 = p.Installs.Count((HookPlanEntry e) => e.Replacement != null);
			int num3 = p.Installs.Count((HookPlanEntry e) => e.Replacement == null && e.Compatible);
			int num4 = p.Cleanups.Count();
			int num5 = p.Cleanups.Count((HookPlanEntry e) => e.Replacement != null);
			int num6 = p.Cleanups.Count((HookPlanEntry e) => e.Replacement == null && e.Compatible);
			CompatLog.Info($"Inferno hook plan: {p.Entries.Count} ApplyHooks entries ({num} run hooks, {num4} cleanup hooks); " + $"run hooks: {num3} Inferno + {num2} replaced by InfernoSkinFix, {num - num3 - num2} skipped; " + $"cleanup hooks: {num6} Inferno + {num5} replaced by InfernoSkinFix, {num4 - num6 - num5} skipped");
		}

		public static void Uninstall()
		{
			try
			{
				Undo(silent: true);
				foreach (InstalledHook value in cleanupHooks.Values)
				{
					TryRemove(value);
				}
				cleanupHooks.Clear();
			}
			finally
			{
				Hook obj = applyDetour;
				if (obj != null)
				{
					obj.Dispose();
				}
				Hook obj2 = undoDetour;
				if (obj2 != null)
				{
					obj2.Dispose();
				}
				applyDetour = (undoDetour = null);
			}
		}

		private static void OnApplyHooks(Action orig)
		{
			try
			{
				if (plan == null)
				{
					orig();
				}
				else
				{
					Apply();
				}
			}
			catch (Exception ex)
			{
				CompatLog.Error("ApplyHooks failed; the run continues without the remaining Inferno skill hooks: " + ex);
			}
		}

		private static void OnUndoHooks(Action orig)
		{
			try
			{
				if (plan == null)
				{
					orig();
				}
				else
				{
					Undo(silent: false);
				}
			}
			catch (Exception ex)
			{
				CompatLog.Error("UndoHooks failed; the run teardown continues: " + ex);
			}
		}

		private static void Apply()
		{
			if (runHooksApplied)
			{
				CompatLog.Warning($"ApplyHooks called while {runHooks.Count} Inferno run hooks are still installed; not installing them twice");
				return;
			}
			runHooksApplied = true;
			infernoRuns++;
			InfernoRepairs.BeginRun();
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			foreach (HookPlanEntry entry in plan.Entries)
			{
				InstalledHook hook2;
				if (entry.Action == HookPlanAction.RemoveCleanup)
				{
					if (cleanupHooks.TryGetValue(entry, out var value))
					{
						if (TryRemove(value))
						{
							num5++;
						}
						cleanupHooks.Remove(entry);
					}
				}
				else if (entry.Replacement is HookReplacement r)
				{
					if (TryApply(r, entry, out var hook))
					{
						runHooks.Add(hook);
						num2++;
					}
					else
					{
						num4++;
					}
				}
				else if (!entry.Compatible)
				{
					num3++;
				}
				else if (TryAdd(entry, out hook2))
				{
					runHooks.Add(hook2);
					num++;
				}
				else
				{
					num4++;
				}
			}
			string m = $"ApplyHooks (Inferno run #{infernoRuns}): {num} Inferno hooks + {num2} InfernoSkinFix replacements installed, " + $"{num3} incompatible skipped, {num4} failed; {num5} cleanup hooks removed";
			if (num4 > 0)
			{
				CompatLog.Warning(m);
			}
			else
			{
				CompatLog.Info(m);
			}
		}

		private static void Undo(bool silent)
		{
			bool flag = runHooksApplied;
			int num = 0;
			int num2 = 0;
			for (int num3 = runHooks.Count - 1; num3 >= 0; num3--)
			{
				if (TryRemove(runHooks[num3]))
				{
					num++;
				}
				else
				{
					num2++;
				}
			}
			runHooks.Clear();
			runHooksApplied = false;
			if (silent)
			{
				return;
			}
			int num4 = 0;
			foreach (HookPlanEntry cleanup in plan.Cleanups)
			{
				if (cleanupHooks.ContainsKey(cleanup))
				{
					continue;
				}
				InstalledHook hook = null;
				bool num5;
				if (!(cleanup.Replacement is HookReplacement r))
				{
					if (!cleanup.Compatible)
					{
						continue;
					}
					num5 = TryAdd(cleanup, out hook);
				}
				else
				{
					num5 = TryApply(r, cleanup, out hook);
				}
				if (num5)
				{
					cleanupHooks[cleanup] = hook;
					num4++;
				}
			}
			if (flag || num2 > 0)
			{
				CompatLog.Info($"UndoHooks: removed {num} Inferno run hooks ({num2} failed); {cleanupHooks.Count} cleanup hooks active ({num4} added)");
			}
			else
			{
				CompatLog.Debug($"UndoHooks: no Inferno run hooks were installed this run; {cleanupHooks.Count} cleanup hooks active ({num4} added)");
			}
		}

		private static bool TryApply(HookReplacement r, HookPlanEntry entry, out InstalledHook hook)
		{
			hook = null;
			try
			{
				r.Enable();
			}
			catch (Exception ex)
			{
				CompatLog.Error("could not install the " + r.Name + " repair on " + entry.TargetName + ": " + ex.GetType().Name + ": " + ex.Message);
				return false;
			}
			hook = new InstalledHook
			{
				Label = entry.TargetName + " <- InfernoSkinFix " + r.Name,
				Remove = r.Disable
			};
			return true;
		}

		private static bool TryAdd(HookPlanEntry entry, out InstalledHook hook)
		{
			hook = null;
			try
			{
				entry.AddAccessor.Invoke(null, new object[1] { entry.Handler });
			}
			catch (Exception ex)
			{
				Exception ex2 = ((ex is TargetInvocationException { InnerException: not null } ex3) ? ex3.InnerException : ex);
				CompatLog.Error($"Inferno hook #{entry.Index} could not be installed and is skipped ({entry.Label}): {ex2.GetType().Name}: {ex2.Message}");
				return false;
			}
			hook = new InstalledHook
			{
				Label = entry.Label,
				Remove = delegate
				{
					entry.RemoveAccessor.Invoke(null, new object[1] { entry.Handler });
				}
			};
			return true;
		}

		private static bool TryRemove(InstalledHook hook)
		{
			try
			{
				hook.Remove();
				return true;
			}
			catch (Exception ex)
			{
				Exception ex2 = ((ex is TargetInvocationException { InnerException: not null } ex3) ? ex3.InnerException : ex);
				CompatLog.Error("could not remove " + hook.Label + ": " + ex2.GetType().Name + ": " + ex2.Message);
				return false;
			}
		}
	}
	internal sealed class SkinRepair
	{
		public readonly InfernoSkin Skin;

		public readonly string BaseSkinName;

		public readonly string[] ExtraActivations;

		public readonly bool AccessoryBones;

		public SkinRepair(InfernoSkin skin, string baseSkinName, string[] extraActivations = null, bool accessoryBones = false)
		{
			Skin = skin;
			BaseSkinName = baseSkinName;
			ExtraActivations = extraActivations ?? Array.Empty<string>();
			AccessoryBones = accessoryBones;
		}
	}
	internal static class SkinRepairs
	{
		internal static Action<string> LogInfo = delegate
		{
		};

		internal static Action<string> LogError = delegate
		{
		};

		public static readonly SkinRepair[] All = new SkinRepair[3]
		{
			new SkinRepair(InfernoSkins.Captain, "skinCaptainDefault"),
			new SkinRepair(InfernoSkins.Bandit, "skinBandit2Default", new string[1] { "Bandit2AccessoriesMesh" }, accessoryBones: true),
			new SkinRepair(InfernoSkins.Railgunner, "skinRailGunnerDefault", null, accessoryBones: true)
		};

		private static readonly Dictionary<InfernoSkin, AccessoryRigSpec> rigs = new Dictionary<InfernoSkin, AccessoryRigSpec>();

		private static readonly HashSet<SkinDef> patched = new HashSet<SkinDef>();

		private static readonly Dictionary<InfernoSkin, string> failures = new Dictionary<InfernoSkin, string>();

		public static AccessoryRigSpec FindRig(InfernoSkin skin)
		{
			if (skin == null || !rigs.TryGetValue(skin, out var value))
			{
				return null;
			}
			return value;
		}

		public static void PatchSkinDefs()
		{
			SkinRepair[] all = All;
			foreach (SkinRepair skinRepair in all)
			{
				try
				{
					string text = Patch(skinRepair);
					if (text != null)
					{
						failures[skinRepair.Skin] = text;
					}
				}
				catch (Exception ex)
				{
					failures[skinRepair.Skin] = ex.GetType().Name + ": " + ex.Message;
				}
			}
		}

		private static string Patch(SkinRepair repair)
		{
			//IL_01e4: 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)
			InfernoSkin skin = repair.Skin;
			ModelSkinController val = InfernoSkins.FindBodyModelSkinController(skin.BodyName);
			SkinDef val2 = skin.FindBodySkin();
			if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val2))
			{
				return "skin '" + skin.SkinName + "' not found on " + skin.BodyName;
			}
			if (patched.Contains(val2))
			{
				return null;
			}
			if (val2.runtimeSkin != null || Object.op_Implicit((Object)(object)val2.skinDefParams))
			{
				return "skin was already converted or baked before InfernoSkinFix could repair it";
			}
			SkinDef val3 = ((IEnumerable<SkinDef>)val.skins).FirstOrDefault((Func<SkinDef, bool>)((SkinDef d) => Object.op_Implicit((Object)(object)d) && ((Object)d).name == repair.BaseSkinName));
			if (!Object.op_Implicit((Object)(object)val3))
			{
				return "vanilla skin '" + repair.BaseSkinName + "' not found";
			}
			List<Transform> list = new List<Transform>();
			string[] extraActivations = repair.ExtraActivations;
			foreach (string text in extraActivations)
			{
				Transform val4 = ((Component)val).transform.Find(text);
				if (!Object.op_Implicit((Object)(object)val4))
				{
					return "'" + text + "' not found on the body model";
				}
				list.Add(val4);
			}
			AccessoryRigSpec accessoryRigSpec = null;
			if (repair.AccessoryBones)
			{
				accessoryRigSpec = AccessoryRigSpec.TryCreate(skin, val2, val, out var error);
				if (accessoryRigSpec == null)
				{
					return "accessory bones: " + error;
				}
			}
			if (!val2.baseSkins.Contains(val3))
			{
				val2.baseSkins = ((IEnumerable<SkinDef>)(object)new SkinDef[1] { val3 }).Concat(val2.baseSkins.Where((SkinDef b) => Object.op_Implicit((Object)(object)b))).ToArray();
			}
			foreach (Transform t in list)
			{
				if (!val2.gameObjectActivations.Any((GameObjectActivation a) => (Object)(object)a.gameObject == (Object)(object)((Component)t).gameObject))
				{
					val2.gameObjectActivations = val2.gameObjectActivations.Append(new GameObjectActivation
					{
						gameObject = ((Component)t).gameObject,
						shouldActivate = true
					}).ToArray();
				}
			}
			if (accessoryRigSpec != null)
			{
				rigs[skin] = accessoryRigSpec;
				InfernoDynamicSkins.DisableOriginal(skin.Token);
			}
			patched.Add(val2);
			return null;
		}

		public static void Report()
		{
			List<string> list = new List<string>();
			SkinRepair[] all = All;
			foreach (SkinRepair repair in all)
			{
				InfernoSkin skin = repair.Skin;
				if (failures.TryGetValue(skin, out var value))
				{
					LogError(skin.Survivor + " (" + skin.SkinName + ") not repaired: " + value);
					continue;
				}
				SkinDef val = skin.FindBodySkin();
				RuntimeSkin val2 = (Object.op_Implicit((Object)(object)val) ? val.runtimeSkin : null);
				if (val2 == null || !val.baseSkins.Any((SkinDef b) => Object.op_Implicit((Object)(object)b) && ((Object)b).name == repair.BaseSkinName))
				{
					LogError(skin.Survivor + " (" + skin.SkinName + ") not repaired: the skin was not patched before it was baked.");
					continue;
				}
				AccessoryRigSpec accessoryRigSpec = FindRig(skin);
				list.Add($"{skin.Survivor} (base {repair.BaseSkinName}, {val2.gameObjectActivationTemplates.Length} activations" + ((accessoryRigSpec != null) ? string.Format(", +{0} bone{1} at {2} for {3} meshes", accessoryRigSpec.ChainLength, (accessoryRigSpec.ChainLength == 1) ? "" : "s", accessoryRigSpec.InsertAt, accessoryRigSpec.Meshes.Count) : "") + ")");
			}
			if (list.Count > 0)
			{
				LogInfo("Repaired Inferno skins: " + string.Join("; ", list) + ". Commando, Mercenary and Artificer need no repair.");
			}
		}
	}
	internal static class SkinTrace
	{
		internal static Action<string> Log = delegate
		{
		};

		internal static bool Enabled;

		private static int nextId;

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

		private static readonly HashSet<int> describedSkins = new HashSet<int>();

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

		private static bool IsDetailed(InfernoSkin s)
		{
			if (s != InfernoSkins.Captain && s != InfernoSkins.Bandit)
			{
				return s == InfernoSkins.Railgunner;
			}
			return true;
		}

		internal static IEnumerator Wrap(ModelSkinController controller, int requestedIndex, IEnumerator inner)
		{
			if (!Enabled)
			{
				return inner;
			}
			InfernoSkin infernoSkin = InfernoSkins.FindOnController(controller);
			if (infernoSkin != null)
			{
				return Traced(controller, infernoSkin, requestedIndex, inner);
			}
			return inner;
		}

		private static IEnumerator Traced(ModelSkinController controller, InfernoSkin survivor, int requestedIndex, IEnumerator inner)
		{
			int id = ++nextId;
			int key = ((Object)controller).GetInstanceID();
			pendingByController.TryGetValue(key, out var overlapping);
			pendingByController[key] = overlapping + 1;
			bool completed = false;
			try
			{
				Safe(delegate
				{
					Snapshot(id, controller, survivor, requestedIndex, "start", overlapping);
				});
				while (inner.MoveNext())
				{
					yield return inner.Current;
				}
				completed = true;
			}
			finally
			{
				if (pendingByController.TryGetValue(key, out var value))
				{
					pendingByController[key] = value - 1;
				}
				if (!completed)
				{
					Log($"#{id} {survivor.Survivor}: skin application ended without completing (exception or abandoned coroutine).");
				}
			}
			Safe(delegate
			{
				Snapshot(id, controller, survivor, requestedIndex, "done", pendingByController[key]);
			});
			if (Object.op_Implicit((Object)(object)controller))
			{
				((MonoBehaviour)controller).StartCoroutine(Settled(id, controller, survivor, requestedIndex));
			}
		}

		private static IEnumerator Settled(int id, ModelSkinController controller, InfernoSkin survivor, int requestedIndex)
		{
			yield return (object)new WaitForSecondsRealtime(1f);
			if (Object.op_Implicit((Object)(object)controller))
			{
				Safe(delegate
				{
					Snapshot(id, controller, survivor, requestedIndex, "+1s", pendingByController.TryGetValue(((Object)controller).GetInstanceID(), out var value) ? value : 0);
				});
			}
		}

		private static void Safe(Action a)
		{
			try
			{
				a();
			}
			catch (Exception ex)
			{
				Log("trace failed: " + ex);
			}
		}

		private static void Snapshot(int id, ModelSkinController controller, InfernoSkin survivor, int requestedIndex, string phase, int pending)
		{
			CharacterModel component = ((Component)controller).GetComponent<CharacterModel>();
			SkinDef[] array = controller.skins ?? Array.Empty<SkinDef>();
			int num = (((uint)requestedIndex < array.Length) ? requestedIndex : 0);
			SkinDef val = ((array.Length != 0) ? array[num] : null);
			SkinDef s = (((uint)controller.currentSkinIndex < array.Length) ? array[controller.currentSkinIndex] : null);
			string text = ((Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.body)) ? "body" : "display");
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(string.Format("#{0} {1} {2} {3}: target[{4}]={5}{6} current[{7}]={8} otherPending={9} dynSkinsModified={10}", id, survivor.Survivor, text, phase, requestedIndex, Name(val), (InfernoSkins.Identify(val) != null) ? " (Inferno)" : "", controller.currentSkinIndex, Name(s), pending, InfernoDynamicSkins.ModifiedObjectCount));
			if (Object.op_Implicit((Object)(object)val) && describedSkins.Add(((Object)val).GetInstanceID()) && val.runtimeSkin != null)
			{
				stringBuilder.Append('\n').Append(DescribeSkin(val, "  "));
			}
			HashSet<string> hashSet = MeshTemplatePaths(val);
			Renderer[] componentsInChildren = ((Component)controller).GetComponentsInChildren<Renderer>(true);
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			int num6 = 0;
			StringBuilder stringBuilder2 = new StringBuilder();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Renderer val2 = componentsInChildren[i];
				string text2 = PathFrom(((Component)controller).transform, ((Component)val2).transform);
				bool hasMeshSlot;
				Mesh val3 = MeshOf(val2, out hasMeshSlot);
				bool flag = ((Component)val2).gameObject.activeInHierarchy && val2.enabled;
				List<string> list = new List<string>();
				if (!((Component)val2).gameObject.activeInHierarchy)
				{
					num2++;
				}
				if (!((Component)val2).gameObject.activeInHierarchy && hashSet.Contains(text2))
				{
					list.Add("OFF-BUT-SKINNED");
					num6++;
				}
				if (hasMeshSlot && flag && !Object.op_Implicit((Object)(object)val3))
				{
					list.Add("NO-MESH");
					num3++;
				}
				if (flag && !(val2 is ParticleSystemRenderer) && val2.sharedMaterials.All((Material m) => !Object.op_Implicit((Object)(object)m)))
				{
					list.Add("NO-MATERIAL");
					num4++;
				}
				string text3 = "";
				SkinnedMeshRenderer val4 = (SkinnedMeshRenderer)(object)((val2 is SkinnedMeshRenderer) ? val2 : null);
				if (val4 != null)
				{
					int num7 = val4.bones.Length;
					int num8 = (Object.op_Implicit((Object)(object)val3) ? BindposeCount(val3) : (-1));
					text3 = $" bones={num7}" + (Object.op_Implicit((Object)(object)val3) ? (" bindposes=" + ((num8 >= 0) ? num8.ToString() : "?")) : "");
					if (num8 >= 0 && num8 != num7)
					{
						list.Add("BONES-MISMATCH");
						num5++;
					}
				}
				stringBuilder2.Append(string.Format("\n  r[{0}] {1} '{2}' self={3} hier={4} en={5}", i, ((object)val2).GetType().Name.Replace("Renderer", ""), text2, On(((Component)val2).gameObject.activeSelf), On(((Component)val2).gameObject.activeInHierarchy), On(val2.enabled)) + " mesh=" + (hasMeshSlot ? MeshName(val3) : "-") + text3 + " mats=[" + string.Join(",", val2.sharedMaterials.Select((Material m) => (!Object.op_Implicit((Object)(object)m)) ? "null" : ((Object)m).name)) + "]" + ((list.Count > 0) ? ("  !! " + string.Join(" ", list)) : ""));
			}
			stringBuilder.Append($"\n  renderers={componentsInChildren.Length} inactive={num2} offButSkinned={num6} noMesh={num3} noMaterial={num4} boneMismatch={num5}");
			if (IsDetailed(survivor))
			{
				stringBuilder.Append(stringBuilder2);
				if (Object.op_Implicit((Object)(object)component))
				{
					stringBuilder.Append($"\n  baseRendererInfos({component.baseRendererInfos.Length}): " + string.Join(", ", component.baseRendererInfos.Select((RendererInfo ri) => (Object.op_Implicit((Object)(object)ri.renderer) ? PathFrom(((Component)controller).transform, ((Component)ri.renderer).transform) : "null") + "=" + (Object.op_Implicit((Object)(object)ri.defaultMaterial) ? ((Object)ri.defaultMaterial).name : "null"))));
					stringBuilder.Append($"\n  activatedBySkin({component.gameObjectActivationTransforms.Count}): " + string.Join(", ", component.gameObjectActivationTransforms.Select((Transform t) => (!Object.op_Implicit((Object)(object)t)) ? "destroyed" : (PathFrom(((Component)controller).transform, t) + "=" + On(((Component)t).gameObject.activeSelf)))));
				}
			}
			Log(stringBuilder.ToString());
		}

		private static HashSet<string> MeshTemplatePaths(SkinDef skin)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: 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)
			HashSet<string> hashSet = new HashSet<string>();
			if (Object.op_Implicit((Object)(object)skin) && skin.runtimeSkin != null)
			{
				Enumerator<MeshReplacementTemplate> enumerator = skin.runtimeSkin.meshReplacementTemplates.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						MeshReplacementTemplate current = enumerator.Current;
						if (Object.op_Implicit((Object)(object)current.meshReference.directRef) || (current.meshReference.address != null && ((AssetReference)current.meshReference.address).RuntimeKeyIsValid()))
						{
							hashSet.Add(current.transformPath);
						}
					}
				}
				finally
				{
					((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
				}
			}
			return hashSet;
		}

		internal static string DescribeSkin(SkinDef skin, string indent)
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected I4, but got Unknown
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due t