Decompiled source of Health Bars v0.1.0

SpellBrigadeHealthBars.dll

Decompiled 8 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using SpellBrigadeHealthBars.Core;
using SpellBrigadeHealthBars.Game;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("SpellBrigadeHealthBars")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+1d1a56b8f7346784255f41015e7f291a9062aef0")]
[assembly: AssemblyProduct("SpellBrigadeHealthBars")]
[assembly: AssemblyTitle("SpellBrigadeHealthBars")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
namespace SpellBrigadeHealthBars
{
	internal static class ModConfig
	{
		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<float> BarWidth;

		public static ConfigEntry<float> BarHeight;

		public static ConfigEntry<float> HeightOffset;

		public static ConfigEntry<string> ExtraTypes;

		public static ConfigEntry<float> ScanInterval;

		public static ConfigEntry<bool> LogEnemyTypes;

		public static ConfigEntry<bool> TestHotkeys;

		public static ConfigEntry<bool> GameStyle;

		public static ConfigEntry<bool> LogBarArt;

		public static void Init(ConfigFile cfg)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Expected O, but got Unknown
			Enabled = cfg.Bind<bool>("General", "Enabled", true, "Show a health bar above each mini-boss once it has taken damage. Can be switched off while playing.");
			BarWidth = cfg.Bind<float>("Bar", "Width", 100f, new ConfigDescription("Bar width in pixels on a 1080p screen (scales with screen height).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(20f, 400f), Array.Empty<object>()));
			BarHeight = cfg.Bind<float>("Bar", "Height", 16f, new ConfigDescription("Bar height in pixels on a 1080p screen (scales with screen height).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 40f), Array.Empty<object>()));
			HeightOffset = cfg.Bind<float>("Bar", "HeightOffset", 0.5f, new ConfigDescription("How far above the monster's head the bar floats, in world units.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-5f, 10f), Array.Empty<object>()));
			ExtraTypes = cfg.Bind<string>("General", "ExtraTypes", "", "Extra enemy types that also get a bar, comma-separated (for example: Snake, Exploder). Turn on Debug.LogEnemyTypes to see the type names in BepInEx/SpellBrigadeHealthBars.log. Read when a run starts.");
			ScanInterval = cfg.Bind<float>("General", "ScanInterval", 0.25f, new ConfigDescription("Seconds between looking for new mini-bosses.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 2f), Array.Empty<object>()));
			LogEnemyTypes = cfg.Bind<bool>("Debug", "LogEnemyTypes", false, "Write one line per enemy type the first time it is seen in a run: its type name and whether it gets a bar.");
			GameStyle = cfg.Bind<bool>("Bar", "GameStyle", true, "Draw the bars in the look of the game's own health bar (border, rounding, colours). Bar.Width and Bar.Height set the size. Off: a plain dark bar with a red fill.");
			LogBarArt = cfg.Bind<bool>("Debug", "LogBarArt", false, "Write the images of the game's own health bars (sizes, colours, sprites) to the log once per session.");
			TestHotkeys = cfg.Bind<bool>("Debug", "TestHotkeys", false, "For testing, as host inside a run: Ctrl+B spawns one of the run's elite enemies.");
		}
	}
	internal static class ModLog
	{
		private static ManualLogSource? _log;

		private static StreamWriter? _file;

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

		private static readonly Dictionary<string, float> Throttle = new Dictionary<string, float>();

		public const string CleanExit = "clean exit";

		public static string FilePath => Path.Combine(Paths.BepInExRootPath, "SpellBrigadeHealthBars.log");

		public static string PreviousFilePath => Path.Combine(Paths.BepInExRootPath, "SpellBrigadeHealthBars.prev.log");

		public static string? PreviousCrashStep { get; private set; }

		public static void Init(ManualLogSource log)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Expected O, but got Unknown
			_log = log;
			bool flag = default(bool);
			try
			{
				if (File.Exists(FilePath))
				{
					File.Copy(FilePath, PreviousFilePath, overwrite: true);
					string text = null;
					string[] array = File.ReadAllLines(FilePath);
					foreach (string text2 in array)
					{
						int num = text2.IndexOf(" STEP  ", StringComparison.Ordinal);
						if (num >= 0)
						{
							string text3 = text2;
							int num2 = num + 7;
							text = text3.Substring(num2, text3.Length - num2).Trim();
						}
					}
					if (text != null && text != "clean exit")
					{
						PreviousCrashStep = text;
					}
				}
			}
			catch (Exception ex)
			{
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(30, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not read the previous ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(FilePath);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				log.LogWarning(val);
			}
			try
			{
				_file = new StreamWriter(new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
				{
					AutoFlush = true
				};
				_file.WriteLine($"SpellBrigadeHealthBars {"0.1.0"} log, started {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
				if (PreviousCrashStep != null)
				{
					_file.WriteLine("Previous session did not exit cleanly; its last step was: " + PreviousCrashStep + " (log kept as SpellBrigadeHealthBars.prev.log)");
				}
			}
			catch (Exception ex2)
			{
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(17, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not open ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(FilePath);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex2.Message);
				}
				log.LogWarning(val);
			}
		}

		public static void Info(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogInfo((object)msg);
			}
			ToFile("INFO ", msg);
		}

		public static void Warn(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogWarning((object)msg);
			}
			ToFile("WARN ", msg);
		}

		public static void Error(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogError((object)msg);
			}
			ToFile("ERROR", msg);
		}

		public static void Debug(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogDebug((object)msg);
			}
			ToFile("DEBUG", msg);
		}

		public static void Step(string msg)
		{
			ToFile("STEP ", msg);
		}

		public static void StepOnce(string key, string msg)
		{
			if (Once.Add("step:" + key))
			{
				Step(msg);
			}
		}

		public static void InfoOnce(string key, string msg)
		{
			if (Once.Add(key))
			{
				Info(msg);
			}
		}

		public static void WarnOnce(string key, string msg)
		{
			if (Once.Add(key))
			{
				Warn(msg);
			}
		}

		public static void ErrorThrottled(string key, Exception ex, float now, float seconds = 10f)
		{
			if (!Throttle.TryGetValue(key, out var value) || !(now - value < seconds))
			{
				Throttle[key] = now;
				Error($"[{key}] {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
			}
		}

		private static void ToFile(string level, string msg)
		{
			if (_file == null)
			{
				return;
			}
			try
			{
				lock (_file)
				{
					_file.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {level} {msg}");
				}
			}
			catch
			{
			}
		}
	}
	[BepInPlugin("com.stefanws0.spellbrigadehealthbars", "SpellBrigadeHealthBars", "0.1.0")]
	public class Plugin : BasePlugin
	{
		public const string Guid = "com.stefanws0.spellbrigadehealthbars";

		public const string Name = "SpellBrigadeHealthBars";

		public const string Version = "0.1.0";

		public override void Load()
		{
			ModLog.Init(((BasePlugin)this).Log);
			ModLog.Step("Load: config");
			ModConfig.Init(((BasePlugin)this).Config);
			ModLog.Step("Load: registering HealthBarsRunner");
			((BasePlugin)this).AddComponent<HealthBarsRunner>();
			ModLog.Step("Load: done");
			string value = (ModConfig.Enabled.Value ? "" : " (General.Enabled is off: no bars are drawn)");
			ModLog.Info($"{"SpellBrigadeHealthBars"} {"0.1.0"} loaded{value}.");
		}
	}
}
namespace SpellBrigadeHealthBars.Game
{
	internal static class BarOverlay
	{
		private sealed class Bar
		{
			public GameObject Root;

			public RectTransform Rect;

			public RectTransform? Fill;

			public Slider? Slider;

			public float NativeHeight;

			public GameObject? RightCap;

			public bool Active;
		}

		private const int UiLayer = 5;

		private const float Border = 1f;

		private const float SpawnGraceSeconds = 0.5f;

		private const int SortingOrder = -10;

		private static readonly Color BackColor = new Color(0.06f, 0.06f, 0.07f, 0.85f);

		private static readonly Color FillColor = new Color(0.86f, 0.16f, 0.16f, 1f);

		private static readonly List<Bar> Pool = new List<Bar>();

		private static GameObject? _root;

		private static bool _poolIsGameStyle;

		public static void Render(List<TrackedEnemy> tracked, float now)
		{
			//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_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_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e5: 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_0252: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			Camera val = ((tracked.Count > 0) ? Camera.main : null);
			if ((Object)(object)val != (Object)null)
			{
				EnsureCanvas();
				bool flag = ModConfig.GameStyle.Value && GameBarStyle.TryFind(now);
				if (flag != _poolIsGameStyle)
				{
					ClearPool(flag);
				}
				float screenWidth = Screen.width;
				float screenHeight = Screen.height;
				float num2 = BarRules.CanvasScale(screenHeight);
				float value = ModConfig.BarWidth.Value;
				float value2 = ModConfig.BarHeight.Value;
				float value3 = ModConfig.HeightOffset.Value;
				for (int i = 0; i < tracked.Count; i++)
				{
					TrackedEnemy trackedEnemy = tracked[i];
					try
					{
						if ((Object)(object)trackedEnemy.Enemy == (Object)null || !((Behaviour)trackedEnemy.Enemy).isActiveAndEnabled || (Object)(object)trackedEnemy.Health == (Object)null)
						{
							trackedEnemy.Shown = false;
							trackedEnemy.Since = 0f;
							continue;
						}
						if (trackedEnemy.Since <= 0f)
						{
							trackedEnemy.Since = now;
						}
						float currentHealth = ((HealthContainer)trackedEnemy.Health).CurrentHealth;
						float maxHealth = ((HealthContainer)trackedEnemy.Health).MaxHealth;
						if (!BarRules.ShouldShow(currentHealth, maxHealth, trackedEnemy.Shown))
						{
							if (!(currentHealth > 0f))
							{
								trackedEnemy.Shown = false;
							}
						}
						else
						{
							if (!trackedEnemy.Shown && now - trackedEnemy.Since < 0.5f)
							{
								continue;
							}
							trackedEnemy.Shown = true;
							Vector3 val2 = ((Component)trackedEnemy.Enemy).transform.position + Vector3.up * (trackedEnemy.Height + value3);
							Vector3 val3 = val.WorldToScreenPoint(val2);
							if (!BarRules.OnScreen(val3.x, val3.y, val3.z, screenWidth, screenHeight))
							{
								continue;
							}
							Bar bar = BarAt(num++);
							float num3 = BarRules.Fill(currentHealth, maxHealth);
							bar.Rect.anchoredPosition = new Vector2(val3.x * num2, val3.y * num2);
							if ((Object)(object)bar.Slider != (Object)null)
							{
								float num4 = ((bar.NativeHeight > 0f) ? (value2 / bar.NativeHeight) : 1f);
								bar.Rect.sizeDelta = new Vector2(value / num4, bar.NativeHeight);
								((Transform)bar.Rect).localScale = new Vector3(num4, num4, 1f);
								bar.Slider.normalizedValue = num3;
								bool flag2 = num3 >= 0.999f;
								if ((Object)(object)bar.RightCap != (Object)null && bar.RightCap.activeSelf != flag2)
								{
									bar.RightCap.SetActive(flag2);
								}
							}
							else if ((Object)(object)bar.Fill != (Object)null)
							{
								bar.Rect.sizeDelta = new Vector2(value + 2f, value2 + 2f);
								bar.Fill.anchorMax = new Vector2(num3, 1f);
							}
							if (!bar.Active)
							{
								bar.Root.SetActive(true);
								bar.Active = true;
							}
							continue;
						}
					}
					catch (Exception ex)
					{
						ModLog.ErrorThrottled("bar", ex, now);
					}
				}
			}
			for (int j = num; j < Pool.Count; j++)
			{
				Bar bar2 = Pool[j];
				if (bar2.Active)
				{
					bar2.Active = false;
					if ((Object)(object)bar2.Root != (Object)null)
					{
						bar2.Root.SetActive(false);
					}
				}
			}
		}

		private static void EnsureCanvas()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_root != (Object)null))
			{
				ModLog.Step("BarOverlay: creating the canvas");
				Pool.Clear();
				_poolIsGameStyle = false;
				_root = new GameObject("SpellBrigadeHealthBars");
				_root.layer = 5;
				Object.DontDestroyOnLoad((Object)(object)_root);
				Canvas obj = _root.AddComponent<Canvas>();
				obj.renderMode = (RenderMode)0;
				obj.sortingOrder = -10;
				CanvasScaler obj2 = _root.AddComponent<CanvasScaler>();
				obj2.uiScaleMode = (ScaleMode)1;
				obj2.referenceResolution = new Vector2(1920f, 1080f);
				obj2.matchWidthOrHeight = 1f;
				ModLog.Step("BarOverlay: canvas created");
			}
		}

		private static void ClearPool(bool gameStyle)
		{
			for (int i = 0; i < Pool.Count; i++)
			{
				if ((Object)(object)Pool[i].Root != (Object)null)
				{
					Object.Destroy((Object)(object)Pool[i].Root);
				}
			}
			Pool.Clear();
			_poolIsGameStyle = gameStyle;
			ModLog.Info(gameStyle ? "Bars now use the game's own health bar look." : "Bars now use the plain look.");
		}

		private static Bar BarAt(int index)
		{
			while (Pool.Count <= index)
			{
				Pool.Add(_poolIsGameStyle ? (NewGameBar() ?? NewPlainBar()) : NewPlainBar());
			}
			return Pool[index];
		}

		private static Bar? NewGameBar()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			Slider val = GameBarStyle.Clone(_root.transform);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			RectTransform component = ((Component)val).GetComponent<RectTransform>();
			Rect rect = component.rect;
			float num = ((Rect)(ref rect)).height;
			if (!(num > 0f))
			{
				num = 59f;
			}
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.zero;
			component.pivot = new Vector2(0.5f, 0f);
			Transform val2 = ((Transform)component).Find("Fill Area/Fill/R");
			((Component)val).gameObject.SetActive(false);
			return new Bar
			{
				Root = ((Component)val).gameObject,
				Rect = component,
				Slider = val,
				NativeHeight = num,
				RightCap = (((Object)(object)val2 != (Object)null) ? ((Component)val2).gameObject : null)
			};
		}

		private static Bar NewPlainBar()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			Image val = NewImage("Bar", _root.transform, BackColor);
			RectTransform rectTransform = ((Graphic)val).rectTransform;
			rectTransform.anchorMin = Vector2.zero;
			rectTransform.anchorMax = Vector2.zero;
			rectTransform.pivot = new Vector2(0.5f, 0f);
			RectTransform val2 = NewRect("Track", (Transform)(object)rectTransform);
			val2.anchorMin = Vector2.zero;
			val2.anchorMax = Vector2.one;
			val2.offsetMin = new Vector2(1f, 1f);
			val2.offsetMax = new Vector2(-1f, -1f);
			RectTransform rectTransform2 = ((Graphic)NewImage("Fill", (Transform)(object)val2, FillColor)).rectTransform;
			rectTransform2.anchorMin = Vector2.zero;
			rectTransform2.anchorMax = Vector2.one;
			rectTransform2.offsetMin = Vector2.zero;
			rectTransform2.offsetMax = Vector2.zero;
			((Component)val).gameObject.SetActive(false);
			return new Bar
			{
				Root = ((Component)val).gameObject,
				Rect = rectTransform,
				Fill = rectTransform2
			};
		}

		private static RectTransform NewRect(string name, Transform parent)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = new GameObject(name)
			{
				layer = 5
			}.AddComponent<RectTransform>();
			((Transform)obj).SetParent(parent, false);
			return obj;
		}

		private static Image NewImage(string name, Transform parent, Color color)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			Image obj = ((Component)NewRect(name, parent)).gameObject.AddComponent<Image>();
			((Graphic)obj).raycastTarget = false;
			((Graphic)obj).color = color;
			return obj;
		}
	}
	internal sealed class TrackedEnemy
	{
		public Enemy Enemy;

		public EnemyHealthContainer Health;

		public float Height;

		public bool Shown;

		public float Since;
	}
	internal static class EnemyWatcher
	{
		private const float DefaultHeight = 2f;

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

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

		private static readonly List<int> Gone = new List<int>();

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

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

		private static HashSet<string> _extraNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static IntPtr _runPtr;

		private static float _nextScan;

		public static readonly List<TrackedEnemy> Tracked = new List<TrackedEnemy>();

		public static void Update(float now)
		{
			if (!ModConfig.Enabled.Value)
			{
				EndRun();
				return;
			}
			RunManager instance = NetworkSingleton<RunManager>.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				EndRun();
				return;
			}
			if (((Il2CppObjectBase)instance).Pointer != _runPtr)
			{
				StartRun(instance);
			}
			if (!(now < _nextScan))
			{
				_nextScan = now + ModConfig.ScanInterval.Value;
				Scan();
			}
		}

		private static void EndRun()
		{
			if (!(_runPtr == IntPtr.Zero) || ById.Count != 0)
			{
				_runPtr = IntPtr.Zero;
				ById.Clear();
				Tracked.Clear();
				EliteTypes.Clear();
				TypeVerdict.Clear();
				_nextScan = 0f;
			}
		}

		private static void StartRun(RunManager rm)
		{
			EndRun();
			_runPtr = ((Il2CppObjectBase)rm).Pointer;
			AddElites(rm.Configuration);
			AddElites(rm.verdantMeadowsConfiguration);
			AddElites(rm.frozenAncientsConfiguration);
			AddElites(rm.pyrestormPitConfiguration);
			AddElites(rm.astralPlanesConfiguration);
			_extraNames = ExtraTypesParser.Parse(ModConfig.ExtraTypes.Value);
			foreach (string extraName in _extraNames)
			{
				if (!Enum.TryParse<EnemyType>(extraName, ignoreCase: true, out EnemyType _))
				{
					ModLog.Warn("General.ExtraTypes: '" + extraName + "' is not an enemy type the game knows; it is ignored.");
				}
			}
			ModLog.Info($"Run started: {EliteTypes.Count} elite enemy types, {_extraNames.Count} extra types from the config.");
		}

		private static void AddElites(RunConfiguration? cfg)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected I4, but got Unknown
			try
			{
				if ((Object)(object)cfg == (Object)null)
				{
					return;
				}
				List<EliteEnemyConfiguration> eliteEnemies = cfg.EliteEnemies;
				if (eliteEnemies == null)
				{
					return;
				}
				for (int i = 0; i < eliteEnemies.Count; i++)
				{
					EliteEnemyConfiguration val = eliteEnemies[i];
					if ((Object)(object)val == (Object)null)
					{
						continue;
					}
					List<WeightedEnemy> weightedEnemies = val.weightedEnemies;
					if (weightedEnemies == null)
					{
						continue;
					}
					for (int j = 0; j < weightedEnemies.Count; j++)
					{
						WeightedEnemy val2 = weightedEnemies[j];
						if (val2 != null)
						{
							EliteTypes.Add((int)val2.Enemy);
						}
					}
				}
			}
			catch (Exception ex)
			{
				ModLog.WarnOnce("elites", "Could not read the run's elite enemy types: " + ex.Message);
			}
		}

		private static void Scan()
		{
			List<Enemy> allEnemies = Enemy.AllEnemies;
			if (allEnemies == null)
			{
				return;
			}
			Seen.Clear();
			for (int i = 0; i < allEnemies.Count; i++)
			{
				Enemy val = allEnemies[i];
				if ((Object)(object)val == (Object)null || !((Behaviour)val).isActiveAndEnabled)
				{
					continue;
				}
				int instanceID = ((Object)val).GetInstanceID();
				if (ById.ContainsKey(instanceID))
				{
					Seen.Add(instanceID);
					continue;
				}
				try
				{
					TrackedEnemy trackedEnemy = TryTrack(val);
					if (trackedEnemy != null)
					{
						ById[instanceID] = trackedEnemy;
						Seen.Add(instanceID);
					}
				}
				catch (Exception ex)
				{
					ModLog.WarnOnce("track", "Could not read an enemy: " + ex.Message);
				}
			}
			Gone.Clear();
			foreach (int key in ById.Keys)
			{
				if (!Seen.Contains(key))
				{
					Gone.Add(key);
				}
			}
			for (int j = 0; j < Gone.Count; j++)
			{
				ById.Remove(Gone[j]);
			}
			Tracked.Clear();
			foreach (TrackedEnemy value in ById.Values)
			{
				Tracked.Add(value);
			}
		}

		private unsafe static TrackedEnemy? TryTrack(Enemy e)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Expected I4, but got Unknown
			EnemyType enemyType = e.EnemyType;
			int num = (int)enemyType;
			if (TypeVerdict.TryGetValue(num, out var value) && !value)
			{
				return null;
			}
			EnemyHealthContainer val = ((Component)e).GetComponent<EnemyHealthContainer>() ?? ((Component)e).GetComponentInChildren<EnemyHealthContainer>();
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			if (!TypeVerdict.ContainsKey(num))
			{
				string text = ((object)(*(EnemyType*)(&enemyType))/*cast due to .constrained prefix*/).ToString();
				value = MiniBossRule.Qualifies(num, text, val.isBoss, EliteTypes, _extraNames);
				TypeVerdict[num] = value;
				if (ModConfig.LogEnemyTypes.Value)
				{
					ModLog.Info($"Enemy type {text}: max health {((HealthContainer)val).MaxHealth:0.#}{(val.isBoss ? ", end boss" : "")} -> {(value ? "gets a bar" : "no bar")}.");
				}
				if (!value)
				{
					return null;
				}
			}
			return new TrackedEnemy
			{
				Enemy = e,
				Health = val,
				Height = HeightOf(e)
			};
		}

		private static float HeightOf(Enemy e)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Il2CppArrayBase<SkinnedMeshRenderer> componentsInChildren = ((Component)e).GetComponentsInChildren<SkinnedMeshRenderer>();
				if (componentsInChildren == null)
				{
					return 2f;
				}
				float y = ((Component)e).transform.position.y;
				float num = 0f;
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					SkinnedMeshRenderer val = componentsInChildren[i];
					if (!((Object)(object)val == (Object)null))
					{
						Bounds bounds = ((Renderer)val).bounds;
						float num2 = ((Bounds)(ref bounds)).max.y - y;
						if (num2 > num)
						{
							num = num2;
						}
					}
				}
				return (num > 0f) ? Mathf.Clamp(num, 1f, 8f) : 2f;
			}
			catch (Exception ex)
			{
				ModLog.WarnOnce("height", "Could not measure an enemy's height: " + ex.Message);
				return 2f;
			}
		}
	}
	internal static class GameBarStyle
	{
		private const float RetrySeconds = 2f;

		private static Slider? _template;

		private static float _nextTry;

		private static bool _described;

		private static readonly HashSet<string> OwnParts = new HashSet<string> { "Background", "Fill Area", "Fill Area/Fill", "Fill Area/Fill/L", "Fill Area/Fill/R" };

		public static bool TryFind(float now)
		{
			if ((Object)(object)_template != (Object)null)
			{
				return true;
			}
			if (now < _nextTry)
			{
				return false;
			}
			_nextTry = now + 2f;
			try
			{
				ModLog.StepOnce("style", "GameBarStyle: first PlayerHealthDisplay lookup");
				PlayerHealthDisplay val = Object.FindObjectOfType<PlayerHealthDisplay>();
				if ((Object)(object)val == (Object)null)
				{
					return false;
				}
				Slider bar = val.bar;
				if ((Object)(object)bar == (Object)null)
				{
					return false;
				}
				_template = bar;
				if (ModConfig.LogBarArt.Value && !_described)
				{
					_described = true;
					Describe("Player health bar", ((Component)bar).transform);
					DescribeBossBar();
				}
				return true;
			}
			catch (Exception ex)
			{
				ModLog.WarnOnce("style", "Could not find the game's health bar; using the plain look. " + ex.Message);
				return false;
			}
		}

		public static Slider? Clone(Transform parent)
		{
			if ((Object)(object)_template == (Object)null)
			{
				return null;
			}
			try
			{
				GameObject val = Object.Instantiate<GameObject>(((Component)_template).gameObject, parent, false);
				((Object)val).name = "Bar";
				Slider component = val.GetComponent<Slider>();
				if ((Object)(object)component == (Object)null)
				{
					Object.Destroy((Object)(object)val);
					return null;
				}
				Prune(val.transform, "");
				((Selectable)component).interactable = false;
				((Selectable)component).transition = (Transition)0;
				Il2CppArrayBase<Animator> componentsInChildren = val.GetComponentsInChildren<Animator>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					((Behaviour)componentsInChildren[i]).enabled = false;
				}
				Il2CppArrayBase<TMP_Text> componentsInChildren2 = val.GetComponentsInChildren<TMP_Text>(true);
				for (int j = 0; j < componentsInChildren2.Length; j++)
				{
					((Component)componentsInChildren2[j]).gameObject.SetActive(false);
				}
				Il2CppArrayBase<Graphic> componentsInChildren3 = val.GetComponentsInChildren<Graphic>(true);
				for (int k = 0; k < componentsInChildren3.Length; k++)
				{
					componentsInChildren3[k].raycastTarget = false;
				}
				return component;
			}
			catch (Exception ex)
			{
				ModLog.WarnOnce("clone", "Could not copy the game's health bar; using the plain look. " + ex.Message);
				_template = null;
				return null;
			}
		}

		private static void Prune(Transform parent, string parentPath)
		{
			for (int num = parent.childCount - 1; num >= 0; num--)
			{
				Transform child = parent.GetChild(num);
				string text = ((parentPath.Length == 0) ? ((Object)child).name : (parentPath + "/" + ((Object)child).name));
				if (OwnParts.Contains(text))
				{
					Prune(child, text);
				}
				else
				{
					((Component)child).gameObject.SetActive(false);
					Object.Destroy((Object)(object)((Component)child).gameObject);
				}
			}
		}

		private static void DescribeBossBar()
		{
			try
			{
				Il2CppArrayBase<ObjectiveDetailPanel_BossHealth> val = Resources.FindObjectsOfTypeAll<ObjectiveDetailPanel_BossHealth>();
				if (val == null || val.Length == 0)
				{
					ModLog.Info("Bar art: no boss health panel loaded.");
				}
				else
				{
					Describe("Boss health panel", ((Component)val[0]).transform);
				}
			}
			catch (Exception ex)
			{
				ModLog.Warn("Bar art: could not read the boss health panel. " + ex.Message);
			}
		}

		private static void Describe(string title, Transform root)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			//IL_032d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0350: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_0398: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			RectTransform component = ((Component)root).GetComponent<RectTransform>();
			StringBuilder stringBuilder2 = stringBuilder;
			StringBuilder stringBuilder3 = stringBuilder2;
			StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(12, 2, stringBuilder2);
			handler.AppendLiteral("Bar art: ");
			handler.AppendFormatted(title);
			handler.AppendLiteral(" '");
			handler.AppendFormatted(((Object)root).name);
			handler.AppendLiteral("'");
			stringBuilder3.Append(ref handler);
			Rect rect;
			if ((Object)(object)component != (Object)null)
			{
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder4 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(7, 2, stringBuilder2);
				handler.AppendLiteral(" size=");
				rect = component.rect;
				handler.AppendFormatted(((Rect)(ref rect)).width, "0.#");
				handler.AppendLiteral("x");
				rect = component.rect;
				handler.AppendFormatted(((Rect)(ref rect)).height, "0.#");
				stringBuilder4.Append(ref handler);
			}
			Il2CppArrayBase<Image> componentsInChildren = ((Component)root).GetComponentsInChildren<Image>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Image val = componentsInChildren[i];
				RectTransform rectTransform = ((Graphic)val).rectTransform;
				Color color = ((Graphic)val).color;
				Sprite sprite = val.sprite;
				Material material = ((Graphic)val).material;
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder5 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(71, 14, stringBuilder2);
				handler.AppendLiteral("\n  ");
				handler.AppendFormatted(PathFrom(root, ((Component)val).transform));
				handler.AppendLiteral(": active=");
				handler.AppendFormatted(((Component)val).gameObject.activeSelf);
				handler.AppendLiteral(" enabled=");
				handler.AppendFormatted(((Behaviour)val).enabled);
				handler.AppendLiteral(" ");
				handler.AppendLiteral("size=");
				rect = rectTransform.rect;
				handler.AppendFormatted(((Rect)(ref rect)).width, "0.#");
				handler.AppendLiteral("x");
				rect = rectTransform.rect;
				handler.AppendFormatted(((Rect)(ref rect)).height, "0.#");
				handler.AppendLiteral(" type=");
				handler.AppendFormatted<Type>(val.type);
				handler.AppendLiteral(" fill=");
				handler.AppendFormatted<FillMethod>(val.fillMethod);
				handler.AppendLiteral("/");
				handler.AppendFormatted(val.fillAmount, "0.##");
				handler.AppendLiteral(" ");
				handler.AppendLiteral("color=(");
				handler.AppendFormatted(color.r, "0.##");
				handler.AppendLiteral(",");
				handler.AppendFormatted(color.g, "0.##");
				handler.AppendLiteral(",");
				handler.AppendFormatted(color.b, "0.##");
				handler.AppendLiteral(",");
				handler.AppendFormatted(color.a, "0.##");
				handler.AppendLiteral(") ");
				handler.AppendLiteral("sprite=");
				object value;
				if (!((Object)(object)sprite == (Object)null))
				{
					DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(17, 7);
					defaultInterpolatedStringHandler.AppendLiteral("'");
					defaultInterpolatedStringHandler.AppendFormatted(((Object)sprite).name);
					defaultInterpolatedStringHandler.AppendLiteral("' ");
					rect = sprite.rect;
					defaultInterpolatedStringHandler.AppendFormatted(((Rect)(ref rect)).width, "0");
					defaultInterpolatedStringHandler.AppendLiteral("x");
					rect = sprite.rect;
					defaultInterpolatedStringHandler.AppendFormatted(((Rect)(ref rect)).height, "0");
					defaultInterpolatedStringHandler.AppendLiteral(" border=(");
					defaultInterpolatedStringHandler.AppendFormatted(sprite.border.x, "0");
					defaultInterpolatedStringHandler.AppendLiteral(",");
					defaultInterpolatedStringHandler.AppendFormatted(sprite.border.y, "0");
					defaultInterpolatedStringHandler.AppendLiteral(",");
					defaultInterpolatedStringHandler.AppendFormatted(sprite.border.z, "0");
					defaultInterpolatedStringHandler.AppendLiteral(",");
					defaultInterpolatedStringHandler.AppendFormatted(sprite.border.w, "0");
					defaultInterpolatedStringHandler.AppendLiteral(")");
					value = defaultInterpolatedStringHandler.ToStringAndClear();
				}
				else
				{
					value = "none";
				}
				handler.AppendFormatted((string?)value);
				handler.AppendLiteral(" ");
				handler.AppendLiteral("material=");
				handler.AppendFormatted(((Object)(object)material == (Object)null) ? "none" : ("'" + ((Object)material).name + "'"));
				stringBuilder5.Append(ref handler);
			}
			ModLog.Info(stringBuilder.ToString());
		}

		private static string PathFrom(Transform root, Transform t)
		{
			string text = ((Object)t).name;
			Transform parent = t.parent;
			while ((Object)(object)parent != (Object)null && ((Il2CppObjectBase)parent).Pointer != ((Il2CppObjectBase)root).Pointer)
			{
				text = ((Object)parent).name + "/" + text;
				parent = parent.parent;
			}
			return text;
		}
	}
	public class HealthBarsRunner : MonoBehaviour
	{
		public HealthBarsRunner(IntPtr ptr)
			: base(ptr)
		{
		}

		public void Update()
		{
			float unscaledTime = Time.unscaledTime;
			try
			{
				EnemyWatcher.Update(unscaledTime);
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("watcher", ex, unscaledTime);
			}
			try
			{
				BarOverlay.Render(EnemyWatcher.Tracked, unscaledTime);
			}
			catch (Exception ex2)
			{
				ModLog.ErrorThrottled("overlay", ex2, unscaledTime);
			}
			try
			{
				TestHotkeys.Update();
			}
			catch (Exception ex3)
			{
				ModLog.ErrorThrottled("hotkeys", ex3, unscaledTime);
			}
		}

		public void OnApplicationQuit()
		{
			ModLog.Step("clean exit");
		}
	}
	internal static class TestHotkeys
	{
		private static bool _keyboardRead;

		private static int _next;

		public static void Update()
		{
			if (ModConfig.TestHotkeys.Value)
			{
				bool num = !_keyboardRead;
				_keyboardRead = true;
				if (num)
				{
					ModLog.Step("first Keyboard.current read");
				}
				Keyboard current = Keyboard.current;
				if (num)
				{
					ModLog.Step("first Keyboard.current read done");
				}
				if (current != null && (((ButtonControl)current.leftCtrlKey).isPressed || ((ButtonControl)current.rightCtrlKey).isPressed) && ((ButtonControl)current.bKey).wasPressedThisFrame)
				{
					SpawnElite();
				}
			}
		}

		private static void SpawnElite()
		{
			RunManager instance = NetworkSingleton<RunManager>.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				ModLog.Info("Ctrl+B: not in a run.");
				return;
			}
			ModLog.StepOnce("spawner", "first Ctrl+B: finding EnemySpawner");
			EnemySpawner val = Object.FindObjectOfType<EnemySpawner>();
			if ((Object)(object)val == (Object)null)
			{
				ModLog.Info("Ctrl+B: the run has no enemy spawner yet.");
				return;
			}
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				ModLog.Info("Ctrl+B: only the host can spawn enemies.");
				return;
			}
			List<EliteEnemyConfiguration> val2 = ElitesOf(instance.Configuration) ?? ElitesOf(instance.verdantMeadowsConfiguration) ?? ElitesOf(instance.frozenAncientsConfiguration) ?? ElitesOf(instance.pyrestormPitConfiguration) ?? ElitesOf(instance.astralPlanesConfiguration);
			if (val2 == null)
			{
				ModLog.Info("Ctrl+B: this run lists no elite enemies.");
				return;
			}
			int num = _next++ % val2.Count;
			EliteEnemyConfiguration val3 = val2[num];
			if ((Object)(object)val3 == (Object)null)
			{
				ModLog.Info($"Ctrl+B: elite {num + 1} of {val2.Count} is empty; press again for the next one.");
			}
			else
			{
				ModLog.Step("Ctrl+B: EnemySpawner.SpawnEliteEnemy");
				val.SpawnEliteEnemy(val3);
				ModLog.Step("Ctrl+B: SpawnEliteEnemy done");
				ModLog.Info($"Ctrl+B: spawned elite {num + 1} of {val2.Count}.");
			}
		}

		private static List<EliteEnemyConfiguration>? ElitesOf(RunConfiguration? cfg)
		{
			if ((Object)(object)cfg == (Object)null)
			{
				return null;
			}
			List<EliteEnemyConfiguration> eliteEnemies = cfg.EliteEnemies;
			if (eliteEnemies == null || eliteEnemies.Count <= 0)
			{
				return null;
			}
			return eliteEnemies;
		}
	}
}
namespace SpellBrigadeHealthBars.Core
{
	public static class BarRules
	{
		public const float ReferenceHeight = 1080f;

		public static bool ShouldShow(float current, float max, bool wasShown)
		{
			if (!(max > 0f) || !(current > 0f))
			{
				return false;
			}
			if (!wasShown)
			{
				return current < max;
			}
			return true;
		}

		public static float Fill(float current, float max)
		{
			if (!(max > 0f) || float.IsNaN(current))
			{
				return 0f;
			}
			float num = current / max;
			if (num < 0f)
			{
				return 0f;
			}
			if (!(num > 1f))
			{
				return num;
			}
			return 1f;
		}

		public static bool OnScreen(float x, float y, float z, float screenWidth, float screenHeight)
		{
			if (z > 0f && x >= 0f && x <= screenWidth && y >= 0f)
			{
				return y <= screenHeight;
			}
			return false;
		}

		public static float CanvasScale(float screenHeight)
		{
			if (!(screenHeight > 0f))
			{
				return 1f;
			}
			return 1080f / screenHeight;
		}
	}
	public static class ExtraTypesParser
	{
		private static readonly char[] Separators = new char[2] { ',', ';' };

		public static HashSet<string> Parse(string? text)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			if (string.IsNullOrWhiteSpace(text))
			{
				return hashSet;
			}
			string[] array = text.Split(Separators);
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length > 0)
				{
					hashSet.Add(text2);
				}
			}
			return hashSet;
		}
	}
	public static class MiniBossRule
	{
		public static bool Qualifies(int typeId, string typeName, bool isBoss, ISet<int> eliteTypes, ISet<string> extraNames)
		{
			if (isBoss)
			{
				return false;
			}
			if (!eliteTypes.Contains(typeId) && !(typeName == "HydraHealer") && !(typeName == "Hoarder") && !typeName.StartsWith("Elite", StringComparison.Ordinal))
			{
				return extraNames.Contains(typeName);
			}
			return true;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte flag)
		{
			Flag = flag;
		}
	}
}