Decompiled source of FATE Pain FX v0.1.7

BepInEx/plugins/FatePainFX/FatePainFx.dll

Decompiled 17 hours ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Tableflip;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MikhailKillsZombies")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("0.1.7.0")]
[assembly: AssemblyInformationalVersion("0.1.7")]
[assembly: AssemblyProduct("FatePainFx")]
[assembly: AssemblyTitle("FatePainFx")]
[assembly: AssemblyVersion("0.1.7.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 MikhailKillsZombies.FatePainFx
{
	[BepInPlugin("mikhailkillszombies.fatepainfx", "FATE Pain FX", "0.1.7")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class FatePainFxPlugin : BaseUnityPlugin
	{
		public const string Guid = "mikhailkillszombies.fatepainfx";

		public const string Name = "FATE Pain FX";

		public const string Version = "0.1.7";

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<int> Design;

		internal static ConfigEntry<bool> Evolution;

		internal static ConfigEntry<float> Opacity;

		internal static ConfigEntry<float> FadeDuration;

		internal static ConfigEntry<bool> LowHealthEnabled;

		internal static ConfigEntry<float> LowHealthThreshold;

		internal static ConfigEntry<int> LowHealthDesign;

		internal static ConfigEntry<float> LowHealthOpacity;

		private static ManualLogSource log;

		internal static void Log(string message)
		{
			if (log != null)
			{
				log.LogInfo((object)message);
			}
		}

		internal static void LogWarning(string message)
		{
			if (log != null)
			{
				log.LogWarning((object)message);
			}
		}

		private void Awake()
		{
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Expected O, but got Unknown
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Expected O, but got Unknown
			log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "Enabled", true, "Show a screen effect when the local player takes damage.");
			Design = ((BaseUnityPlugin)this).Config.Bind<int>("Display", "Design", 0, "Selected overlay family. Change this in FATE Mod Menu.");
			Evolution = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "Evolution", true, "Use the related stronger variant when health is low.");
			Opacity = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "Opacity", 0.72f, "Maximum overlay opacity, from 0 to 1.");
			FadeDuration = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "FadeDuration", 0.8f, "Seconds for the overlay to fade away.");
			LowHealthEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Low health", "Enabled", true, "Show a second, fixed overlay that fades in as health falls from the threshold (50% by default) to 0%.");
			LowHealthThreshold = ((BaseUnityPlugin)this).Config.Bind<float>("Low health", "Threshold", 0.5f, "Health fraction where the warning starts fading in and paired designs evolve. Change this with the 'Show warning below' slider in FATE Mod Menu.");
			LowHealthDesign = ((BaseUnityPlugin)this).Config.Bind<int>("Low health", "Design", 13, "Warning overlay family. Change this in FATE Mod Menu.");
			LowHealthOpacity = ((BaseUnityPlugin)this).Config.Bind<float>("Low health", "Opacity", 0.5f, "Warning overlay opacity at 0% health, from 0 to 1.");
			PainFxRuntime.PluginFolder = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			Harmony val = new Harmony("mikhailkillszombies.fatepainfx");
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(PlayerUI), "Vitals_OnDamaged", (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					LogWarning("PAINFX_NO_DAMAGE_HOOK: PlayerUI.Vitals_OnDamaged was not found; damage overlays are unavailable.");
				}
				else
				{
					val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(PainFxRuntime), "OnPlayerDamaged", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Log("PAINFX_HOOK: PlayerUI.Vitals_OnDamaged patched");
				}
			}
			catch (Exception ex)
			{
				LogWarning("PAINFX_HOOK_FAILED: could not patch PlayerUI.Vitals_OnDamaged: " + ex.Message);
			}
			try
			{
				MethodInfo methodInfo2 = AccessTools.Method(typeof(PlayerUI), "Vitals_OnHealthChanged", (Type[])null, (Type[])null);
				if (methodInfo2 == null)
				{
					LogWarning("PAINFX_NO_HEALTH_HOOK: PlayerUI.Vitals_OnHealthChanged was not found; the warning only polls.");
				}
				else
				{
					val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(PainFxRuntime), "OnPlayerHealthChanged", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Log("PAINFX_HOOK: PlayerUI.Vitals_OnHealthChanged patched");
				}
			}
			catch (Exception ex2)
			{
				LogWarning("PAINFX_HEALTH_HOOK_FAILED: could not patch PlayerUI.Vitals_OnHealthChanged: " + ex2.Message);
			}
			PainFxRuntime.Initialize();
			PainFxRuntime.InstallFramePump(val);
			Log("PAINFX_LOADED 0.1.7 (guid mikhailkillszombies.fatepainfx)");
		}
	}
	internal static class PainFxRuntime
	{
		private sealed class Layer
		{
			internal Image Image;

			internal Texture2D Texture;

			internal Sprite Sprite;

			internal int Design = -1;

			internal bool Shown;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static WillRenderCanvases <0>__OnWillRenderCanvases;

			public static Action <1>__PreviewFlash;

			public static Func<Texture2D> <2>__SelectedTexture;

			public static Action <3>__PreviewWarning;

			public static Func<Texture2D> <4>__SelectedWarningTexture;
		}

		private const float RescanInterval = 0.5f;

		private const float PreviewHold = 2.5f;

		private static readonly Layer Flash = new Layer();

		private static readonly Layer Warning = new Layer();

		internal static string PluginFolder;

		private static Canvas canvas;

		private static float fadeStarted = -1f;

		private static float nextMenuAttempt;

		private static float warningPreviewUntil;

		private static float nextOverlayAttempt;

		private static float nextHealthLog;

		private static bool tickLogged;

		private static object menuModule;

		private static int pulses;

		private static int failures;

		private static bool ticking;

		private static bool sizeLogged;

		private static int lastTickFrame = -1;

		private static object playerUi;

		private static float nextPlayerScan;

		private static FieldInfo agentField;

		private static PropertyInfo vitalsProperty;

		private static MethodInfo healthPctMethod;

		private static readonly string[] FileNames = new string[19]
		{
			"Effect_1.png", "Effect_2.png", "Effect_3.png", "Effect_4.png", "Effect_5.png", "Effect_6.png", "Effect_7.png", "Effect_8.png", "Effect_9.png", "Effect_10.png",
			"Effect_11.png", "Blood_Blur_1.png", "Blood_Blur_2.png", "Blood_Drops.png", "Drip_1.png", "Drip_2.png", "Solid_Drip_1.png", "Solid_Drip_2.png", "Veins_1.png"
		};

		private static readonly int[] FirstStage = new int[14]
		{
			0, 2, 3, 4, 5, 6, 7, 8, 9, 11,
			13, 14, 16, 18
		};

		private static readonly int[] EvolvedStage = new int[14]
		{
			1, -1, -1, -1, -1, -1, -1, -1, 10, 12,
			-1, 15, 17, -1
		};

		internal static readonly string[] DesignNames = new string[14]
		{
			"Top Drips (Effect 1 → 2)", "Soft Fog", "Fine Splatter", "Dense Splatter", "Scattered Splatter", "Heavy Speckle", "Thick Splatter", "Soft Border", "Slash Burst (Effect 10 → 11)", "Blood Blur (1 → 2)",
			"Blood Drops", "Drips (1 → 2)", "Solid Drips (1 → 2)", "Veins"
		};

		private static float LowHealthThreshold => Mathf.Clamp(FatePainFxPlugin.LowHealthThreshold.Value, 0.1f, 1f);

		internal static void Initialize()
		{
			EnsureOverlay();
			EnsureDesign(Flash, ResolveDesign(1f));
			EnsureDesign(Warning, WarningDesign());
		}

		internal static void InstallFramePump(Harmony harmony)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Expected O, but got Unknown
			int num = 0;
			try
			{
				object obj = <>O.<0>__OnWillRenderCanvases;
				if (obj == null)
				{
					WillRenderCanvases val = OnWillRenderCanvases;
					<>O.<0>__OnWillRenderCanvases = val;
					obj = (object)val;
				}
				Canvas.willRenderCanvases += (WillRenderCanvases)obj;
				num++;
				FatePainFxPlugin.Log("PAINFX_PUMP: ticking with Canvas.willRenderCanvases");
			}
			catch (Exception ex)
			{
				FatePainFxPlugin.LogWarning("PAINFX_PUMP_FAILED: Canvas.willRenderCanvases: " + ex.Message);
			}
			(string, string)[] array = new(string, string)[3]
			{
				("Cleverous.Prodigy.Input.InputBroker", "ManagedTick"),
				("Tableflip.PlayerUI", "Update"),
				("Tableflip.FATE", "Update")
			};
			for (int i = 0; i < array.Length; i++)
			{
				(string, string) tuple = array[i];
				string item = tuple.Item1;
				string item2 = tuple.Item2;
				Type type = AccessTools.TypeByName(item);
				MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, item2, Type.EmptyTypes, (Type[])null));
				if (methodInfo == null)
				{
					continue;
				}
				try
				{
					harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(PainFxRuntime), "Tick", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
					FatePainFxPlugin.Log("PAINFX_PUMP: also ticking with " + item + "." + item2);
				}
				catch (Exception ex2)
				{
					FatePainFxPlugin.LogWarning("PAINFX_PUMP_FAILED: " + item + "." + item2 + ": " + ex2.Message);
					continue;
				}
				break;
			}
			if (num == 0)
			{
				FatePainFxPlugin.LogWarning("PAINFX_NO_PUMP: no frame source was found; the overlay will not fade.");
			}
		}

		private static void OnWillRenderCanvases()
		{
			Tick();
		}

		internal static void Tick()
		{
			if (ticking || Time.frameCount == lastTickFrame)
			{
				return;
			}
			lastTickFrame = Time.frameCount;
			ticking = true;
			try
			{
				if (!tickLogged)
				{
					tickLogged = true;
					FatePainFxPlugin.Log("PAINFX_TICK: frame loop is running");
				}
				EnsureOverlay();
				LogOverlaySize();
				UpdateFade();
				UpdateWarning();
				if (menuModule == null && Time.unscaledTime >= nextMenuAttempt)
				{
					nextMenuAttempt = Time.unscaledTime + 2f;
					RegisterMenuSettings();
				}
			}
			catch (Exception ex)
			{
				if (failures++ == 0)
				{
					FatePainFxPlugin.LogWarning("PAINFX_TICK_FAILED: " + ex);
				}
			}
			finally
			{
				ticking = false;
			}
		}

		internal static void OnPlayerDamaged(object __instance)
		{
			try
			{
				if (__instance != null)
				{
					playerUi = __instance;
				}
				if (FatePainFxPlugin.Enabled.Value)
				{
					Pulse(ReadHealthPercent(playerUi));
				}
			}
			catch (Exception ex)
			{
				if (failures++ == 0)
				{
					FatePainFxPlugin.LogWarning("PAINFX_DAMAGE_FAILED: " + ex);
				}
			}
		}

		internal static void Pulse(float healthPercent)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			EnsureOverlay();
			if (!((Object)(object)Flash.Image == (Object)null))
			{
				EnsureDesign(Flash, ResolveDesign(healthPercent));
				fadeStarted = Time.unscaledTime;
				((Graphic)Flash.Image).color = new Color(1f, 1f, 1f, Mathf.Clamp01(FatePainFxPlugin.Opacity.Value));
				if (pulses++ == 0)
				{
					FatePainFxPlugin.Log("PAINFX_PULSE: overlay shown, image=" + FileNames[Flash.Design] + " alpha=" + ((Graphic)Flash.Image).color.a.ToString("0.00") + " fade=" + FatePainFxPlugin.FadeDuration.Value);
				}
			}
		}

		internal static void OnPlayerHealthChanged(object __instance, float newHealth)
		{
			try
			{
				if (__instance != null)
				{
					playerUi = __instance;
				}
				if (!FatePainFxPlugin.LowHealthEnabled.Value)
				{
					SetWarningAlpha(0f);
					return;
				}
				float num = ReadHealthPercent(__instance);
				if (num >= 0f)
				{
					ApplyWarning(num);
				}
			}
			catch (Exception ex)
			{
				if (failures++ == 0)
				{
					FatePainFxPlugin.LogWarning("PAINFX_HEALTH_HOOK_FAILED: " + ex);
				}
			}
		}

		private static void UpdateWarning()
		{
			if (!((Object)(object)Warning.Image == (Object)null) && !(Time.unscaledTime < warningPreviewUntil))
			{
				if (!FatePainFxPlugin.LowHealthEnabled.Value)
				{
					SetWarningAlpha(0f);
				}
				else
				{
					ApplyWarning(PollHealth());
				}
			}
		}

		private static void ApplyWarning(float health)
		{
			if ((Object)(object)Warning.Image == (Object)null)
			{
				return;
			}
			if (health < 0f || health > LowHealthThreshold)
			{
				SetWarningAlpha(0f);
				return;
			}
			EnsureDesign(Warning, WarningDesign());
			float num = 1f - health / LowHealthThreshold;
			float warningAlpha = Mathf.Clamp01(FatePainFxPlugin.LowHealthOpacity.Value) * Mathf.Clamp01(num);
			SetWarningAlpha(warningAlpha);
			if (!Warning.Shown)
			{
				Warning.Shown = true;
				FatePainFxPlugin.Log("PAINFX_LOW_HEALTH: warning shown at " + (health * 100f).ToString("0") + "% health, image=" + FileNames[Warning.Design] + " alpha=" + warningAlpha.ToString("0.00"));
			}
			if (Time.unscaledTime >= nextHealthLog)
			{
				nextHealthLog = Time.unscaledTime + 2f;
				FatePainFxPlugin.Log("PAINFX_HEALTH: health=" + (health * 100f).ToString("0") + "% alpha=" + warningAlpha.ToString("0.00"));
			}
		}

		private static void SetWarningAlpha(float alpha)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)Warning.Image == (Object)null))
			{
				((Graphic)Warning.Image).color = new Color(1f, 1f, 1f, Mathf.Clamp01(alpha));
				if (alpha <= 0f)
				{
					Warning.Shown = false;
				}
			}
		}

		private static void EnsureOverlay()
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: 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)
			if (((Object)(object)Flash.Image != (Object)null && (Object)(object)Warning.Image != (Object)null && (Object)(object)canvas != (Object)null && (Object)(object)((Component)Flash.Image).gameObject != (Object)null) || Time.unscaledTime < nextOverlayAttempt)
			{
				return;
			}
			nextOverlayAttempt = Time.unscaledTime + 2f;
			try
			{
				Transform val = FindGameCanvas();
				GameObject val2 = new GameObject("FATE Pain FX Canvas", new Type[2]
				{
					typeof(RectTransform),
					typeof(Canvas)
				});
				if ((Object)(object)val != (Object)null)
				{
					val2.transform.SetParent(val, false);
				}
				else
				{
					Object.DontDestroyOnLoad((Object)(object)val2);
				}
				canvas = val2.GetComponent<Canvas>();
				canvas.renderMode = (RenderMode)0;
				canvas.overrideSorting = true;
				canvas.sortingOrder = 32000;
				RectTransform component = val2.GetComponent<RectTransform>();
				component.anchorMin = Vector2.zero;
				component.anchorMax = Vector2.one;
				component.offsetMin = Vector2.zero;
				component.offsetMax = Vector2.zero;
				((Transform)component).localScale = Vector3.one;
				((Transform)component).localPosition = Vector3.zero;
				Flash.Image = CreateImage(val2.transform, "Pain FX Flash");
				Warning.Image = CreateImage(val2.transform, "Pain FX Low Health");
				if ((Object)(object)Flash.Sprite != (Object)null)
				{
					Flash.Image.sprite = Flash.Sprite;
				}
				if ((Object)(object)Warning.Sprite != (Object)null)
				{
					Warning.Image.sprite = Warning.Sprite;
				}
				Warning.Shown = false;
				FatePainFxPlugin.Log("PAINFX_OVERLAY: created under " + (((Object)(object)val != (Object)null) ? ((Object)val).name : "its own root canvas"));
				sizeLogged = false;
			}
			catch (Exception ex)
			{
				Flash.Image = null;
				Warning.Image = null;
				canvas = null;
				if (failures++ == 0)
				{
					FatePainFxPlugin.LogWarning("PAINFX_OVERLAY_FAILED: " + ex);
				}
			}
		}

		private static Image CreateImage(Transform parent, string name)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name, new Type[3]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(Image)
			});
			val.transform.SetParent(parent, false);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.offsetMin = Vector2.zero;
			component.offsetMax = Vector2.zero;
			Image component2 = val.GetComponent<Image>();
			((Graphic)component2).raycastTarget = false;
			((Graphic)component2).color = new Color(1f, 1f, 1f, 0f);
			return component2;
		}

		private static void LogOverlaySize()
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			if (!sizeLogged && !((Object)(object)Flash.Image == (Object)null) && !((Object)(object)((Graphic)Flash.Image).rectTransform == (Object)null))
			{
				sizeLogged = true;
				Rect rect = ((Graphic)Flash.Image).rectTransform.rect;
				FatePainFxPlugin.Log("PAINFX_OVERLAY_SIZE: image=" + ((Rect)(ref rect)).width.ToString("0") + "x" + ((Rect)(ref rect)).height.ToString("0") + " screen=" + Screen.width + "x" + Screen.height);
			}
		}

		private static Transform FindGameCanvas()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Invalid comparison between Unknown and I4
			Transform result = null;
			int num = int.MinValue;
			Canvas[] array = Resources.FindObjectsOfTypeAll<Canvas>();
			foreach (Canvas val in array)
			{
				if (!((Object)(object)val == (Object)null) && val.isRootCanvas && ((Component)val).gameObject.activeInHierarchy && (int)val.renderMode <= 0 && val.sortingOrder >= num)
				{
					num = val.sortingOrder;
					result = ((Component)val).transform;
				}
			}
			return result;
		}

		private static void UpdateFade()
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			if (!(fadeStarted < 0f) && !((Object)(object)Flash.Image == (Object)null))
			{
				float num = Mathf.Max(0.05f, FatePainFxPlugin.FadeDuration.Value);
				float num2 = 1f - (Time.unscaledTime - fadeStarted) / num;
				if (num2 <= 0f)
				{
					((Graphic)Flash.Image).color = new Color(1f, 1f, 1f, 0f);
					fadeStarted = -1f;
				}
				else
				{
					((Graphic)Flash.Image).color = new Color(1f, 1f, 1f, Mathf.Clamp01(FatePainFxPlugin.Opacity.Value * num2));
				}
			}
		}

		private static float PollHealth()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			if (playerUi != null && (Object)playerUi == (Object)null)
			{
				ForgetPlayer();
			}
			if (playerUi == null)
			{
				if (Time.unscaledTime < nextPlayerScan)
				{
					return -1f;
				}
				nextPlayerScan = Time.unscaledTime + 0.5f;
				playerUi = FindPlayerUi();
				if (playerUi == null)
				{
					return -1f;
				}
			}
			float num = ReadHealthPercent(playerUi);
			if (num < 0f)
			{
				ForgetPlayer();
				return -1f;
			}
			return num;
		}

		private static void ForgetPlayer()
		{
			playerUi = null;
			agentField = null;
			vitalsProperty = null;
			healthPctMethod = null;
			nextPlayerScan = 0f;
		}

		private static object FindPlayerUi()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Object[] array = Resources.FindObjectsOfTypeAll(typeof(PlayerUI));
				foreach (Object obj in array)
				{
					Component val = (Component)(object)((obj is Component) ? obj : null);
					if (val != null && val.gameObject.activeInHierarchy)
					{
						Scene scene = val.gameObject.scene;
						if (((Scene)(ref scene)).IsValid())
						{
							return val;
						}
					}
				}
			}
			catch (Exception ex)
			{
				if (failures++ == 0)
				{
					FatePainFxPlugin.LogWarning("PAINFX_PLAYER_SCAN_FAILED: " + ex.Message);
				}
			}
			return null;
		}

		private static float ReadHealthPercent(object playerUiInstance)
		{
			try
			{
				if (playerUiInstance == null)
				{
					return -1f;
				}
				if (agentField == null)
				{
					agentField = AccessTools.Field(playerUiInstance.GetType(), "currentAgent");
				}
				object obj = agentField?.GetValue(playerUiInstance);
				if (obj == null)
				{
					return -1f;
				}
				if (vitalsProperty == null)
				{
					vitalsProperty = AccessTools.Property(obj.GetType(), "Vitals");
				}
				object obj2 = vitalsProperty?.GetValue(obj, null);
				if (obj2 == null)
				{
					return -1f;
				}
				if (healthPctMethod == null)
				{
					healthPctMethod = AccessTools.Method(obj2.GetType(), "GetHealthPct", (Type[])null, (Type[])null);
				}
				if (healthPctMethod == null)
				{
					return -1f;
				}
				return Mathf.Clamp01(Convert.ToSingle(healthPctMethod.Invoke(obj2, null)));
			}
			catch
			{
				return -1f;
			}
		}

		private static int ResolveDesign(float health)
		{
			int num = Mathf.Clamp(FatePainFxPlugin.Design.Value, 0, FirstStage.Length - 1);
			if (FatePainFxPlugin.Design.Value != num)
			{
				FatePainFxPlugin.Design.Value = num;
			}
			int num2 = EvolvedStage[num];
			return (FatePainFxPlugin.Evolution.Value && health >= 0f && health <= LowHealthThreshold && num2 >= 0) ? num2 : FirstStage[num];
		}

		private static int WarningDesign()
		{
			return FirstStage[Mathf.Clamp(FatePainFxPlugin.LowHealthDesign.Value, 0, FirstStage.Length - 1)];
		}

		private static void EnsureDesign(Layer layer, int index)
		{
			index = Mathf.Clamp(index, 0, FileNames.Length - 1);
			if (layer.Design != index || (Object)(object)layer.Sprite == (Object)null)
			{
				LoadDesign(layer, index);
			}
			if ((Object)(object)layer.Image != (Object)null && (Object)(object)layer.Sprite != (Object)null && (Object)(object)layer.Image.sprite != (Object)(object)layer.Sprite)
			{
				layer.Image.sprite = layer.Sprite;
			}
		}

		private static void LoadDesign(Layer layer, int index)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)layer.Sprite != (Object)null)
			{
				Object.Destroy((Object)(object)layer.Sprite);
			}
			if ((Object)(object)layer.Texture != (Object)null)
			{
				Object.Destroy((Object)(object)layer.Texture);
			}
			layer.Sprite = null;
			layer.Texture = null;
			try
			{
				string path = Path.Combine(PluginFolder ?? string.Empty, "assets", FileNames[index]);
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(val, File.ReadAllBytes(path), false))
				{
					Object.Destroy((Object)(object)val);
					throw new InvalidDataException("Unity could not decode the PNG.");
				}
				((Object)val).name = FileNames[index];
				layer.Texture = val;
				layer.Sprite = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
				((Object)layer.Sprite).name = FileNames[index];
				layer.Design = index;
				if ((Object)(object)layer.Image != (Object)null)
				{
					layer.Image.sprite = layer.Sprite;
					((Behaviour)layer.Image).enabled = true;
				}
			}
			catch (Exception ex)
			{
				layer.Design = -1;
				FatePainFxPlugin.LogWarning("PAINFX_ASSET_FAILED: could not load " + FileNames[index] + " from " + Path.Combine(PluginFolder ?? "(unknown folder)", "assets") + ": " + ex.Message);
			}
		}

		private static Texture2D SelectedTexture()
		{
			EnsureDesign(Flash, ResolveDesign(1f));
			return Flash.Texture;
		}

		private static Texture2D SelectedWarningTexture()
		{
			EnsureDesign(Warning, WarningDesign());
			return Warning.Texture;
		}

		private static void PreviewFlash()
		{
			Pulse(1f);
		}

		private static void PreviewWarning()
		{
			EnsureDesign(Warning, WarningDesign());
			warningPreviewUntil = Time.unscaledTime + 2.5f;
			Warning.Shown = true;
			SetWarningAlpha(FatePainFxPlugin.LowHealthOpacity.Value);
		}

		private static void RegisterMenuSettings()
		{
			try
			{
				MethodInfo methodInfo = AccessTools.TypeByName("ZombieGhost.ModMenu.ModMenuApi")?.GetMethod("RegisterModule", new Type[2]
				{
					typeof(string),
					typeof(string)
				});
				if (methodInfo == null)
				{
					return;
				}
				menuModule = methodInfo.Invoke(null, new object[2] { "mikhailkillszombies.fatepainfx", "FATE Pain FX" });
				if (menuModule != null)
				{
					Type type = menuModule.GetType();
					RowToggle(type, "display.enabled", "Show damage overlay", () => FatePainFxPlugin.Enabled.Value, delegate(bool value)
					{
						FatePainFxPlugin.Enabled.Value = value;
					}, "Display");
					RowToggle(type, "display.evolution", "Evolve paired design at low health", () => FatePainFxPlugin.Evolution.Value, delegate(bool value)
					{
						FatePainFxPlugin.Evolution.Value = value;
					}, "Display");
					RowChoice(type, "display.design", "Design", () => FatePainFxPlugin.Design.Value, delegate(int value)
					{
						FatePainFxPlugin.Design.Value = value;
					}, "Display");
					RowSlider(type, "display.opacity", "Opacity", () => FatePainFxPlugin.Opacity.Value, delegate(float value)
					{
						FatePainFxPlugin.Opacity.Value = value;
					}, 0.1f, 1f, "Display");
					RowSlider(type, "display.fade", "Fade time (seconds)", () => FatePainFxPlugin.FadeDuration.Value, delegate(float value)
					{
						FatePainFxPlugin.FadeDuration.Value = value;
					}, 0.1f, 3f, "Display");
					RowAction(type, "display.test", "Show the hit overlay now", PreviewFlash, "Display");
					RowPreview(type, "display.image", "Hit design preview", SelectedTexture, "Display");
					RowToggle(type, "low.enabled", "Show low health warning", () => FatePainFxPlugin.LowHealthEnabled.Value, delegate(bool value)
					{
						FatePainFxPlugin.LowHealthEnabled.Value = value;
					}, "Low health");
					RowSlider(type, "low.threshold", "Show warning below", () => FatePainFxPlugin.LowHealthThreshold.Value, delegate(float value)
					{
						FatePainFxPlugin.LowHealthThreshold.Value = value;
					}, 0.1f, 1f, "Low health");
					RowChoice(type, "low.design", "Warning design", () => FatePainFxPlugin.LowHealthDesign.Value, delegate(int value)
					{
						FatePainFxPlugin.LowHealthDesign.Value = value;
					}, "Low health");
					RowSlider(type, "low.opacity", "Opacity at 0% health", () => FatePainFxPlugin.LowHealthOpacity.Value, delegate(float value)
					{
						FatePainFxPlugin.LowHealthOpacity.Value = value;
					}, 0.1f, 1f, "Low health");
					RowAction(type, "low.test", "Show the warning overlay now", PreviewWarning, "Low health");
					RowPreview(type, "low.image", "Warning design preview", SelectedWarningTexture, "Low health");
					RowNote(type, "display.note", "Hits flash the selected design; related artwork evolves to its paired variant below " + (LowHealthThreshold * 100f).ToString("0") + "% health. The low health layer fades in from nothing at that point to its full opacity at 0%.");
					FatePainFxPlugin.Log("PAINFX_MENU: settings registered with FATE Mod Menu");
				}
			}
			catch (Exception ex)
			{
				FatePainFxPlugin.LogWarning("PAINFX_MENU_FAILED: FATE Mod Menu settings registration failed: " + ex.Message);
				(menuModule as IDisposable)?.Dispose();
				menuModule = null;
				nextMenuAttempt = Time.unscaledTime + 30f;
			}
		}

		private static void RowToggle(Type type, string id, string label, Func<bool> get, Action<bool> set, string category)
		{
			type.GetMethod("RegisterToggle")?.Invoke(menuModule, new object[5] { id, label, get, set, category });
		}

		private static void RowChoice(Type type, string id, string label, Func<int> get, Action<int> set, string category)
		{
			type.GetMethod("RegisterChoice")?.Invoke(menuModule, new object[6] { id, label, get, set, DesignNames, category });
		}

		private static void RowSlider(Type type, string id, string label, Func<float> get, Action<float> set, float min, float max, string category)
		{
			type.GetMethod("RegisterSlider")?.Invoke(menuModule, new object[9] { id, label, get, set, min, max, 0.05f, category, "0%" });
		}

		private static void RowAction(Type type, string id, string label, Action run, string category)
		{
			type.GetMethod("RegisterAction")?.Invoke(menuModule, new object[4] { id, label, run, category });
		}

		private static void RowPreview(Type type, string id, string label, Func<Texture2D> get, string category)
		{
			type.GetMethod("RegisterPreview")?.Invoke(menuModule, new object[5] { id, label, get, category, 180f });
		}

		private static void RowNote(Type type, string id, string text)
		{
			type.GetMethod("RegisterNote")?.Invoke(menuModule, new object[3] { id, text, "Display" });
		}
	}
}