Decompiled source of Stylemeter v0.4.1

Stylemeter.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GlobalEnums;
using GlobalSettings;
using HarmonyLib;
using HutongGames.PlayMaker;
using HutongGames.PlayMaker.Actions;
using Microsoft.CodeAnalysis;
using Stylemeter.Core;
using Stylemeter.Game;
using Stylemeter.Game.Hud;
using TMProOld;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
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("Stylemeter")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.4.1.0")]
[assembly: AssemblyInformationalVersion("0.4.1+e88e59177d65ccfa3bdb190af13a4137b11b7ed6")]
[assembly: AssemblyProduct("Stylemeter")]
[assembly: AssemblyTitle("Stylemeter")]
[assembly: AssemblyVersion("0.4.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 Stylemeter
{
	[BepInPlugin("com.glowystar.stylemeter", "Stylemeter", "0.4.1")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "com.glowystar.stylemeter";

		public const string Name = "Stylemeter";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> MeterEnabled;

		internal static ConfigEntry<bool> ShowOverlay;

		internal static ConfigEntry<bool> SilkReward;

		internal static ConfigEntry<float> PointsMultiplier;

		internal static ConfigEntry<string> DisabledBonuses;

		internal static ConfigEntry<bool> LogStyle;

		private static bool isHudBroken;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			BindConfig();
			string text = SessionLog.Open(Paths.BepInExRootPath);
			EngineHost.Init();
			SceneManager.activeSceneChanged += EngineHost.OnSceneChanged;
			PatchAll();
			Out("Stylemeter 0.4.1 loaded, session log: " + (text ?? "-"));
		}

		private void BindConfig()
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			MeterEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Meter", "Enabled", true, "Count style points.");
			ShowOverlay = ((BaseUnityPlugin)this).Config.Bind<bool>("Meter", "ShowOverlay", true, "Show the style meter in the top right corner: the rank, the needle and the feed of bonuses.");
			SilkReward = ((BaseUnityPlugin)this).Config.Bind<bool>("Meter", "SilkReward", true, "Holding the top rank, SILKSONG, gives Hornet one silk for every 5 seconds held.");
			PointsMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("Meter", "PointsMultiplier", 1f, new ConfigDescription("Every style point is multiplied by this (also in the mod menu: Options > Stylemeter).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 3f), Array.Empty<object>()));
			DisabledBonuses = ((BaseUnityPlugin)this).Config.Bind<string>("Bonuses", "Disabled", "", "Bonuses switched off, by name, separated by | (easier in the mod menu: Options > Stylemeter).");
			LogStyle = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogStyle", true, "Write every style bonus and rank change to the session log in BepInEx\\Stylemeter\\logs.");
		}

		private void Update()
		{
			EngineHost.Update();
			UpdateHud();
		}

		private static void UpdateHud()
		{
			if (isHudBroken)
			{
				return;
			}
			try
			{
				MeterHud.Tick(EngineHost.Engine);
			}
			catch (Exception arg)
			{
				isHudBroken = true;
				Log.LogError((object)$"Stylemeter: the meter display is off after an error: {arg}");
			}
		}

		internal static void Out(string line)
		{
			Log.LogInfo((object)line);
			SessionLog.Write(line);
		}

		private static void PatchAll()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			Harmony val = new Harmony("com.glowystar.stylemeter");
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(typeof(Plugin).Assembly);
			foreach (Type type in typesFromAssembly)
			{
				try
				{
					val.CreateClassProcessor(type).Patch();
				}
				catch (Exception arg)
				{
					Log.LogError((object)$"Hooks in {type.Name} are off: {arg}");
				}
			}
		}
	}
	internal static class PluginInfo
	{
		public const string Version = "0.4.1";
	}
}
namespace Stylemeter.Game
{
	internal static class Describe
	{
		public static string PathOf(GameObject go)
		{
			if (!Object.op_Implicit((Object)(object)go))
			{
				return "-";
			}
			string text = ((Object)go).name;
			Transform parent = go.transform.parent;
			while (Object.op_Implicit((Object)(object)parent))
			{
				text = ((Object)parent).name + "/" + text;
				parent = parent.parent;
			}
			return text;
		}

		public static string JournalName(HealthManager hm)
		{
			EnemyDeathEffects val = (Object.op_Implicit((Object)(object)hm) ? ((Component)hm).GetComponent<EnemyDeathEffects>() : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return "-";
			}
			EnemyJournalRecord value = Traverse.Create((object)val).Field("journalRecord").GetValue<EnemyJournalRecord>();
			if (!Object.op_Implicit((Object)(object)value))
			{
				return "-";
			}
			return ((Object)value).name;
		}

		public static string Enemy(HealthManager hm)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			Traverse val = Traverse.Create((object)hm);
			return string.Format("{0} journal={1} hp={2}/{3} ", ((Object)hm).name, JournalName(hm), hm.hp, val.Field("initHp").GetValue<int>()) + string.Format("type={0} size={1} ", hm.EnemyType, val.Field("enemySize").GetValue()) + $"pos=({((Component)hm).transform.position.x:0.0},{((Component)hm).transform.position.y:0.0})";
		}
	}
	internal static class EnemyFinder
	{
		private const int MinSharedWords = 2;

		private const float NearbyDistance = 10f;

		private static readonly Regex Brackets = new Regex("\\(.*?\\)");

		private static readonly char[] Separators = new char[2] { ' ', '/' };

		public static HealthManager Owner(Component attack)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: 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 (!Object.op_Implicit((Object)(object)attack))
			{
				return null;
			}
			HealthManager componentInParent = attack.GetComponentInParent<HealthManager>();
			if (Object.op_Implicit((Object)(object)componentInParent))
			{
				return componentInParent;
			}
			string[] a = Words(Describe.PathOf(attack.gameObject));
			Vector3 position = attack.transform.position;
			HealthManager result = null;
			HealthManager result2 = null;
			int num = 0;
			float num2 = float.MaxValue;
			float num3 = 100f;
			foreach (HealthManager item in HealthManager.EnumerateActiveEnemies())
			{
				if (Object.op_Implicit((Object)(object)item))
				{
					Vector3 val = ((Component)item).transform.position - position;
					float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
					int num4 = Shared(a, Words(((Object)item).name));
					if (num4 > num || (num4 > 0 && num4 == num && sqrMagnitude < num2))
					{
						result = item;
						num = num4;
						num2 = sqrMagnitude;
					}
					if (sqrMagnitude < num3)
					{
						result2 = item;
						num3 = sqrMagnitude;
					}
				}
			}
			if (num < 2)
			{
				return result2;
			}
			return result;
		}

		private static string[] Words(string name)
		{
			return Brackets.Replace(name, "").Split(Separators, StringSplitOptions.RemoveEmptyEntries);
		}

		private static int Shared(string[] a, string[] b)
		{
			int num = 0;
			foreach (string value in a)
			{
				if (Array.IndexOf(b, value) >= 0)
				{
					num++;
				}
			}
			return num;
		}
	}
	internal static class EnemyRegistry
	{
		private static readonly FieldRef<HealthManager, int> InitHp = GameField.Find<HealthManager, int>("initHp");

		private static readonly FieldRef<HealthManager, EnemySize> SizeOf = GameField.Find<HealthManager, EnemySize>("enemySize");

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

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

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

		public static EnemyInfo Get(HealthManager hm)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			int instanceID = ((Object)hm).GetInstanceID();
			if (!Known.TryGetValue(instanceID, out var value))
			{
				Rigidbody2D component = ((Component)hm).GetComponent<Rigidbody2D>();
				int num = ((InitHp != null) ? InitHp.Invoke(hm) : 0);
				value = new EnemyInfo
				{
					Id = instanceID,
					Name = ((Object)hm).name,
					MaxHp = num,
					Large = ((SizeOf != null && (int)SizeOf.Invoke(hm) == 2) || num >= 100),
					Flying = (Object.op_Implicit((Object)(object)component) && (int)component.bodyType == 0 && component.gravityScale == 0f),
					Species = Species.Key(Describe.JournalName(hm))
				};
				Known[instanceID] = value;
				Threads[instanceID] = ((Component)hm).GetComponent<BlackThreadState>();
			}
			value.IsBoss = Bosses.TryGetValue(instanceID, out var value2);
			value.BossKey = value2;
			BlackThreadState val = Threads[instanceID];
			value.BlackThreaded = Object.op_Implicit((Object)(object)val) && val.IsBlackThreaded;
			return value;
		}

		public static void MarkBoss(HealthManager hm, string key)
		{
			int instanceID = ((Object)hm).GetInstanceID();
			Bosses[instanceID] = key ?? "";
			if (Known.TryGetValue(instanceID, out var value))
			{
				value.IsBoss = true;
				value.BossKey = key;
			}
		}

		public static void Clear()
		{
			Known.Clear();
			Threads.Clear();
			Bosses.Clear();
		}
	}
	internal static class EnemyWatch
	{
		private sealed class Watched
		{
			public PlayMakerFSM[] Fsms;

			public bool Stunnable;

			public bool Stunned;

			public float StunnedUntil = float.NegativeInfinity;

			public int SongId;

			public float SangAt = float.NegativeInfinity;

			public float HitAt = float.NegativeInfinity;

			public bool Shelled;

			public bool Fell;

			public float ThiefAt = float.NegativeInfinity;

			public int LastHp = -1;

			public HashSet<string> HealStates;

			public HashSet<string> ChannelStates;

			public bool HitInChannel;
		}

		private const float SongAfter = 2f;

		private const float LureAfter = 5f;

		private const float FallY = -2f;

		private const float ThiefRange = 4f;

		private const float ThiefMemory = 10f;

		private const float StunGrace = 0.3f;

		private static readonly HashSet<string> SingStates = new HashSet<string> { "Sing", "Pray", "Needolin", "Praying", "Sing Ground", "Sing Air" };

		private static readonly FieldRef<HealthManager, PlayMakerFSM> StunFsm = GameField.Find<HealthManager, PlayMakerFSM>("stunControlFsm");

		private static readonly Dictionary<HealthManager, Watched> All = new Dictionary<HealthManager, Watched>();

		private static int songId;

		private static bool singing;

		private static float songEndedAt = float.NegativeInfinity;

		private static int lastGeo = -1;

		public static void Tick(float now)
		{
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			bool isPerforming = HeroPerformanceRegion.IsPerforming;
			if (isPerforming && !singing)
			{
				songId++;
			}
			if (!isPerforming && singing)
			{
				songEndedAt = now;
			}
			singing = isPerforming;
			bool flag = singing || now - songEndedAt <= 2f;
			bool flag2 = Robbed();
			HeroController instance = HeroController.instance;
			foreach (HealthManager item in HealthManager.EnumerateActiveEnemies())
			{
				if (Object.op_Implicit((Object)(object)item) && !item.GetIsDead())
				{
					Watched watched = Of(item);
					EnemyInfo enemyInfo = EnemyRegistry.Get(item);
					if (flag && IsSinging(watched))
					{
						watched.SongId = songId;
						watched.SangAt = now;
					}
					if (watched.Stunnable)
					{
						TickStun(item, watched, enemyInfo, now);
					}
					if (enemyInfo.Species != null && Species.Shelled.Contains(enemyInfo.Species) && watched.HitAt > float.NegativeInfinity && item.IsInvincible)
					{
						watched.Shelled = true;
					}
					if (!watched.Fell && ((Component)item).transform.position.y < -2f && now - watched.HitAt <= 4f)
					{
						watched.Fell = true;
						EngineHost.EnemyFell(item);
					}
					if (flag2 && Object.op_Implicit((Object)(object)instance) && enemyInfo.Species == "ROSARY_THIEF" && Vector2.Distance(Vector2.op_Implicit(((Component)instance).transform.position), Vector2.op_Implicit(((Component)item).transform.position)) <= 4f)
					{
						watched.ThiefAt = now;
					}
					if (enemyInfo.BossKey == "FIRST_WEAVER")
					{
						TickSinner(item, watched, enemyInfo);
					}
				}
			}
		}

		private static Watched Of(HealthManager hm)
		{
			if (All.TryGetValue(hm, out var value))
			{
				return value;
			}
			PlayMakerFSM stun = ((StunFsm != null) ? StunFsm.Invoke(hm) : null);
			value = new Watched
			{
				Fsms = (from f in ((Component)hm).GetComponentsInChildren<PlayMakerFSM>(true)
					where (Object)(object)f != (Object)(object)stun
					select f).ToArray(),
				Stunnable = Object.op_Implicit((Object)(object)stun)
			};
			All[hm] = value;
			return value;
		}

		private static bool IsSinging(Watched w)
		{
			PlayMakerFSM[] fsms = w.Fsms;
			foreach (PlayMakerFSM val in fsms)
			{
				if (Object.op_Implicit((Object)(object)val) && ((Behaviour)val).enabled && SingStates.Contains(val.ActiveStateName))
				{
					return true;
				}
			}
			return false;
		}

		private static void TickStun(HealthManager hm, Watched w, EnemyInfo info, float now)
		{
			bool flag = false;
			PlayMakerFSM[] fsms = w.Fsms;
			foreach (PlayMakerFSM val in fsms)
			{
				string text = ((Object.op_Implicit((Object)(object)val) && ((Behaviour)val).enabled) ? val.ActiveStateName : null);
				if (text != null && text.StartsWith("Stun"))
				{
					flag = true;
					break;
				}
			}
			if (flag)
			{
				w.StunnedUntil = now + 0.3f;
			}
			if (flag && !w.Stunned)
			{
				EngineHost.EnemyStunned(hm);
			}
			w.Stunned = flag;
		}

		private static bool Robbed()
		{
			PlayerData instance = PlayerData.instance;
			if (instance == null)
			{
				return false;
			}
			int geo = instance.geo;
			bool result = lastGeo >= 0 && geo < lastGeo;
			lastGeo = geo;
			return result;
		}

		private static void TickSinner(HealthManager hm, Watched w, EnemyInfo info)
		{
			if (w.HealStates == null)
			{
				ScanHeal(w);
			}
			if (w.LastHp >= 0 && hm.hp > w.LastHp)
			{
				EngineHost.BossHealed(hm);
			}
			w.LastHp = hm.hp;
			bool flag = InStates(w, w.ChannelStates);
			if (w.HitInChannel && !flag)
			{
				w.HitInChannel = false;
				if (!InStates(w, w.HealStates))
				{
					EngineHost.BindBroken(hm);
				}
			}
		}

		private static void ScanHeal(Watched w)
		{
			w.HealStates = new HashSet<string>();
			w.ChannelStates = new HashSet<string>();
			PlayMakerFSM[] fsms = w.Fsms;
			foreach (PlayMakerFSM val in fsms)
			{
				if (!Object.op_Implicit((Object)(object)val))
				{
					continue;
				}
				FsmState[] fsmStates = val.FsmStates;
				foreach (FsmState val2 in fsmStates)
				{
					if (val2.Actions.Any((FsmStateAction a) => a is AddHP || a is SetHP))
					{
						w.HealStates.Add(val2.Name);
					}
				}
				fsmStates = val.FsmStates;
				foreach (FsmState val3 in fsmStates)
				{
					if (!w.HealStates.Contains(val3.Name) && val3.Transitions.Any((FsmTransition t) => w.HealStates.Contains(t.ToState)))
					{
						w.ChannelStates.Add(val3.Name);
					}
				}
			}
			if (Plugin.LogStyle.Value)
			{
				Plugin.Out("SINNER heal=" + string.Join(",", w.HealStates) + " channel=" + string.Join(",", w.ChannelStates));
			}
		}

		private static bool InStates(Watched w, HashSet<string> states)
		{
			if (states == null || states.Count == 0)
			{
				return false;
			}
			PlayMakerFSM[] fsms = w.Fsms;
			foreach (PlayMakerFSM val in fsms)
			{
				if (Object.op_Implicit((Object)(object)val) && ((Behaviour)val).enabled && states.Contains(val.ActiveStateName))
				{
					return true;
				}
			}
			return false;
		}

		public static void HitByHornet(HealthManager hm, float now)
		{
			if (Object.op_Implicit((Object)(object)hm))
			{
				Watched watched = Of(hm);
				watched.HitAt = now;
				if (watched.ChannelStates != null && InStates(watched, watched.ChannelStates))
				{
					watched.HitInChannel = true;
				}
			}
		}

		public static void Read(HealthManager hm, float now, ref HitEvent hit)
		{
			if (Object.op_Implicit((Object)(object)hm))
			{
				Watched watched = Of(hm);
				string text = hit.Enemy?.Species;
				hit.Stunned = watched.Stunned || now <= watched.StunnedUntil;
				hit.SongId = ((now - watched.SangAt <= 2f) ? watched.SongId : 0);
				hit.Lured = text == "CRYPT_WORM" && (singing || now - songEndedAt <= 5f);
				hit.Exposed = text != null && Species.Shelled.Contains(text) && !watched.Shelled;
				hit.Thief = text == "ROSARY_THIEF" && now - watched.ThiefAt <= 10f;
			}
		}

		public static void HurtBy(HealthManager hm, float now)
		{
			if (Object.op_Implicit((Object)(object)hm) && EnemyRegistry.Get(hm).Species == "ROSARY_THIEF")
			{
				Of(hm).ThiefAt = now;
			}
		}

		public static void Clear()
		{
			All.Clear();
			lastGeo = -1;
		}
	}
	internal static class EngineHost
	{
		private const float MeterLogPeriod = 2f;

		private static bool stopped;

		private static int tauntFrame = -1;

		private static float sourcesCheckedAt = float.NegativeInfinity;

		private static float meterLoggedAt = float.NegativeInfinity;

		private static float silentPoints;

		private const float SpikePogoWindow = 0.3f;

		private static float lastSpikeTink = float.NegativeInfinity;

		private static float lastBounce = float.NegativeInfinity;

		public static StyleEngine Engine { get; private set; }

		private static bool Running
		{
			get
			{
				if (Engine != null && !stopped)
				{
					return Plugin.MeterEnabled.Value;
				}
				return false;
			}
		}

		public static void Init()
		{
			Engine = new StyleEngine();
			BindSettings(Engine.Settings);
			Engine.Awarded += delegate(Award a)
			{
				if (a.Silent)
				{
					silentPoints += a.Total;
				}
				else if (Plugin.LogStyle.Value)
				{
					Plugin.Out(FormattableString.Invariant($"STYLE +{a.Total:0.#} {a.Name} ({a.Base:0.#} x{a.Thread:0.##} ") + FormattableString.Invariant(FormattableStringFactory.Create("x{0:0.##} x{1:0.#}) src={2} {3}", a.Height, a.Boss, a.Source ?? "-", MeterText())));
				}
			};
			Engine.Meter.RankChanged += delegate(int from, int to)
			{
				if (Plugin.LogStyle.Value)
				{
					Plugin.Out("RANK " + RankName(from) + " -> " + RankName(to));
				}
			};
			Engine.SilkEarned += delegate
			{
				HeroController instance = HeroController.instance;
				if (Object.op_Implicit((Object)(object)instance))
				{
					instance.AddSilk(1, true);
					Plugin.Out("SILK +1 for SILKSONG held");
				}
			};
		}

		private static void BindSettings(StyleSettings settings)
		{
			settings.PointsMultiplier = Plugin.PointsMultiplier.Value;
			settings.LoadDisabled(Plugin.DisabledBonuses.Value);
			settings.IsSilkRewardOn = Plugin.SilkReward.Value;
			Plugin.SilkReward.SettingChanged += delegate
			{
				settings.IsSilkRewardOn = Plugin.SilkReward.Value;
			};
			settings.Changed += delegate
			{
				Plugin.PointsMultiplier.Value = settings.PointsMultiplier;
				if (Plugin.DisabledBonuses.Value != settings.DisabledText)
				{
					Plugin.DisabledBonuses.Value = settings.DisabledText;
				}
			};
			Plugin.PointsMultiplier.SettingChanged += delegate
			{
				settings.PointsMultiplier = Plugin.PointsMultiplier.Value;
			};
			Plugin.DisabledBonuses.SettingChanged += delegate
			{
				if (Plugin.DisabledBonuses.Value != settings.DisabledText)
				{
					settings.LoadDisabled(Plugin.DisabledBonuses.Value);
				}
			};
		}

		public static void Update()
		{
			if (!Running)
			{
				return;
			}
			Guard(delegate
			{
				if (HeroProbe.TryRead(out var state))
				{
					float now = Time.time;
					Engine.Observe(now, state);
					Engine.Tick(now, Time.deltaTime, HeroProbe.DrainActive());
					if (now - sourcesCheckedAt > 5f)
					{
						sourcesCheckedAt = now;
						Engine.Threads.SourceCount = HeroProbe.SourceCount();
						Engine.AttackTools = HeroProbe.AttackTools();
					}
					GrazeWatcher.Tick(HeroController.instance, now);
					HookGuard.Run("hero watch", delegate
					{
						HeroWatch.Tick(HeroController.instance, now);
					});
					HookGuard.Run("tool watch", delegate
					{
						ToolWatch.Tick(now);
					});
					HookGuard.Run("enemy watch", delegate
					{
						EnemyWatch.Tick(now);
					});
					LogMeter(now);
				}
			});
		}

		private static void LogMeter(float now)
		{
			if (Plugin.LogStyle.Value && Engine.Meter.InCombo && !(now - meterLoggedAt < 2f))
			{
				meterLoggedAt = now;
				string lastSource = Engine.Threads.LastSource;
				string text = ((lastSource == null) ? "-" : (ThreadSet.StateOf(Engine.Threads.Tension(lastSource)).ToString() + " " + lastSource));
				string text2 = (HeroProbe.DrainActive() ? "" : " paused");
				Plugin.Out(FormattableString.Invariant($"METER {MeterText()} height=x{Engine.Height.Current(now):0.0#} thread={text}") + FormattableString.Invariant($" silent=+{silentPoints:0}{text2}"));
				silentPoints = 0f;
			}
		}

		public static void OnSceneChanged(Scene from, Scene to)
		{
			//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)
			EnemyRegistry.Clear();
			GrazeWatcher.Clear();
			HeroWatch.Clear();
			ToolWatch.Clear();
			EnemyWatch.Clear();
			if (!Running)
			{
				return;
			}
			Guard(delegate
			{
				if (((Scene)(ref to)).name == "Quit_To_Menu" || ((Scene)(ref to)).name == "Menu_Title")
				{
					Engine.OnQuitToMenu();
				}
				Engine.OnSceneChanged();
			});
		}

		public static void Hit(HealthManager target, HitInstance hit, int hpBefore, int hpAfter, bool killed, HitContext context)
		{
			//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)
			if (!Running || !hit.IsHeroDamage)
			{
				return;
			}
			Guard(delegate
			{
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Invalid comparison between Unknown and I4
				//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e8: Invalid comparison between Unknown and I4
				//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
				//IL_0201: Expected I4, but got Unknown
				ToolItem representingTool = hit.RepresentingTool;
				string path = Describe.PathOf(hit.Source);
				string name;
				AttackKind attackKind = Attacks.Classify(path, Object.op_Implicit((Object)(object)representingTool) ? representingTool.name : null, Object.op_Implicit((Object)(object)representingTool) && (int)representingTool.Type == 3, out name);
				EnemyInfo enemyInfo = EnemyRegistry.Get(target);
				float num = DistanceTo(target);
				if (killed && Plugin.LogStyle.Value)
				{
					Plugin.Out(FormattableString.Invariant(FormattableStringFactory.Create("FOE {0} kind={1} tool=\"{2}\" dist={3:0.0}", ((Object)target).name, attackKind, name ?? "-", num)) + FormattableString.Invariant($" large={enemyInfo.Large} flying={enemyInfo.Flying} black={enemyInfo.BlackThreaded}"));
				}
				Observe();
				HitEvent hitEvent = new HitEvent
				{
					Time = Time.time,
					Enemy = enemyInfo,
					Kind = attackKind,
					Tool = name,
					SwingId = (Object.op_Implicit((Object)(object)hit.Source) ? ((Object)hit.Source).GetInstanceID() : 0),
					HpBefore = hpBefore,
					HpAfter = hpAfter,
					Killed = killed,
					Crit = hit.CriticalHit,
					Taunted = (tauntFrame == Time.frameCount),
					Element = ElementOf(hit),
					Explosion = ((int)hit.AttackType == 11),
					Flags = (DamageFlags)hit.ToolDamageFlags,
					Zap = (hit.ZapDamageTicks > 0),
					HunterCombo = hit.HunterCombo,
					RageHit = hit.RageHit,
					FromBind = Attacks.IsBindEffect(path),
					Distance = num,
					PiercedGuard = context.Pierced,
					Flanked = context.Flanked,
					Backstab = context.Backstab,
					WallSlash = Leaf(path).Contains("Wall"),
					DashFinisher = Leaf(path).Contains("RecoilStab")
				};
				GameObject source = hit.Source;
				float now = Time.time;
				hitEvent.ChargeHeld = ((attackKind == AttackKind.NeedleCharge) ? HookGuard.Get("patience", () => HeroWatch.ChargeHeldFor(now), 0f) : 0f);
				hitEvent.DodgedThrough = name == "Silk Charge" && HookGuard.Get("thread the needle", () => HeroWatch.DartedThrough(target), fallback: false);
				hitEvent.ReturnLeg = Tools.IsCurveclaw(name) && HookGuard.Get("boomerang", () => ToolWatch.OnReturnLeg(source), fallback: false);
				hitEvent.AfterWallBounce = name == "Shakra Ring" && HookGuard.Get("trick shot", () => ToolWatch.AfterWallBounce(source), fallback: false);
				hitEvent.WheelClimbed = name == "Cogwork Saw" && HookGuard.Get("wall ride", () => ToolWatch.WheelClimbed(source), fallback: false);
				hitEvent.Shrapnel = name == "Sting Shard" && HookGuard.Get("shrapnel", () => ToolWatch.IsShrapnel(source), fallback: false);
				hitEvent.WallSlash = hitEvent.WallSlash || HookGuard.Get("blueprint", () => HeroWatch.FromWall(source, now), fallback: false);
				HitEvent read = hitEvent;
				hitEvent = HookGuard.Get("enemy watch", delegate
				{
					HitEvent hit2 = read;
					EnemyWatch.Read(target, now, ref hit2);
					return hit2;
				}, hitEvent);
				HookGuard.Run("enemy watch", delegate
				{
					EnemyWatch.HitByHornet(target, now);
				});
				Engine.OnHit(hitEvent);
			});
		}

		public static void WorldHit(HealthManager target, HitInstance hit, bool killed)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			On(delegate
			{
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_0115: Unknown result type (might be due to invalid IL or missing references)
				EnemyInfo enemy = EnemyRegistry.Get(target);
				Hazard hazard = HazardOf(target, hit);
				GameObject source = hit.Source;
				bool flag = HookGuard.Get("return to sender", () => ToolWatch.WasDeflected(source) || (enemy.BossKey == "SPINNER" && ToolWatch.RecentLooseClash(2f)), fallback: false);
				if (Plugin.LogStyle.Value)
				{
					Plugin.Out($"WORLDHIT {((Object)target).name} hazard={hazard} type={hit.AttackType} killed={killed} " + $"deflected={flag} src={Describe.PathOf(hit.Source)}");
				}
				if (flag)
				{
					Engine.OnReturnToSender(Time.time, enemy);
					hazard = Hazard.Other;
				}
				if (killed)
				{
					Engine.OnEnemyDied(Time.time, enemy, new DeathCause
					{
						Hazard = hazard,
						Element = ElementOf(hit)
					});
				}
				else
				{
					Engine.OnWorldHit(Time.time, enemy, hazard);
				}
			});
		}

		public static void EnemyDied(HealthManager target, DeathCause cause)
		{
			On(delegate
			{
				Engine.OnEnemyDied(Time.time, EnemyRegistry.Get(target), cause);
			});
		}

		public static void TickDamage(HealthManager target, Element element)
		{
			On(delegate
			{
				if (Plugin.LogStyle.Value)
				{
					Plugin.Out($"TICK {((Object)target).name} element={element} hp={target.hp}");
				}
				Engine.OnTickDamage(Time.time, EnemyRegistry.Get(target), element);
			});
		}

		public static void ToolUsed(ToolItem tool, bool auto)
		{
			ToolWatch.ToolThrown(tool);
			On(delegate
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Invalid comparison between Unknown and I4
				Engine.OnToolUsed(Time.time, tool.name, (int)tool.Type == 3, auto);
			});
		}

		public static void FlintslateExpired()
		{
			On(delegate
			{
				Engine.OnFlintslateExpired(Time.time);
			});
		}

		public static void GlideStarted()
		{
			On(delegate
			{
				Engine.OnGlideStarted(Time.time);
			});
		}

		public static void GlideEnded()
		{
			On(delegate
			{
				Engine.OnGlideEnded(Time.time);
			});
		}

		public static void BossDeath()
		{
			On(delegate
			{
				Engine.OnBossDeath(Time.time);
			});
		}

		public static void BossTitle(HealthManager boss, string key)
		{
			EnemyRegistry.MarkBoss(boss, key);
			On(delegate
			{
				Engine.OnBossTitle(Time.time, EnemyRegistry.Get(boss));
			});
		}

		internal static Element ElementOf(HitInstance hit)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//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_0015: Unknown result type (might be due to invalid IL or missing references)
			Element element = ElementOf(hit.NailElement, hit.AttackType);
			if (element != Element.None || hit.ZapDamageTicks <= 0)
			{
				return element;
			}
			return Element.Lightning;
		}

		internal static Element ElementOf(NailElements element, AttackTypes type)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if ((int)element == 1 || (int)type == 19)
			{
				return Element.Fire;
			}
			if ((int)element == 2)
			{
				return Element.Poison;
			}
			if ((int)type != 9)
			{
				return Element.None;
			}
			return Element.Lightning;
		}

		private static Hazard HazardOf(HealthManager target, HitInstance hit)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//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: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected I4, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Invalid comparison between Unknown and I4
			//IL_0058: 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_005f: 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_0074: Unknown result type (might be due to invalid IL or missing references)
			AttackTypes attackType = hit.AttackType;
			switch (attackType - 3)
			{
			default:
				if ((int)attackType == 17)
				{
					return Hazard.Spikes;
				}
				break;
			case 5:
			case 9:
				return Hazard.Lava;
			case 0:
				return Hazard.Acid;
			case 10:
				return Hazard.Trap;
			case 8:
				return Hazard.Explosion;
			case 7:
				return Hazard.Enemy;
			case 1:
			case 2:
			case 3:
			case 4:
			case 6:
				break;
			}
			if ((hit.SpecialType & 1) != 0)
			{
				return Hazard.Acid;
			}
			if ((hit.SpecialType & 2) != 0)
			{
				return Hazard.Lava;
			}
			HealthManager val = (Object.op_Implicit((Object)(object)hit.Source) ? hit.Source.GetComponentInParent<HealthManager>() : null);
			if (!Object.op_Implicit((Object)(object)val) || !((Object)(object)val != (Object)(object)target))
			{
				return Hazard.Other;
			}
			return Hazard.Enemy;
		}

		private static string Leaf(string path)
		{
			if (path != null)
			{
				return path.Substring(path.LastIndexOf('/') + 1);
			}
			return "";
		}

		private static float DistanceTo(HealthManager target)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			HeroController instance = HeroController.instance;
			if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)target))
			{
				return 0f;
			}
			return Vector2.Distance(Vector2.op_Implicit(((Component)instance).transform.position), Vector2.op_Implicit(((Component)target).transform.position));
		}

		public static float NearestEnemyDistance()
		{
			return NearestEnemy();
		}

		private static float NearestEnemy()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			HeroController instance = HeroController.instance;
			if (!Object.op_Implicit((Object)(object)instance))
			{
				return float.PositiveInfinity;
			}
			Vector2 val = Vector2.op_Implicit(((Component)instance).transform.position);
			float num = float.PositiveInfinity;
			HealthManager[] array = Object.FindObjectsByType<HealthManager>((FindObjectsSortMode)0);
			foreach (HealthManager val2 in array)
			{
				if (Object.op_Implicit((Object)(object)val2) && ((Behaviour)val2).isActiveAndEnabled && !val2.GetIsDead() && val2.hp > 0)
				{
					num = Mathf.Min(num, Vector2.Distance(val, Vector2.op_Implicit(((Component)val2).transform.position)));
				}
			}
			return num;
		}

		public static void Clash(HealthManager enemy, bool parryCounter)
		{
			GrazeWatcher.Spoil();
			On(delegate
			{
				Engine.OnClash(Time.time, Info(enemy), parryCounter);
			});
		}

		public static void EnemyStunned(HealthManager enemy)
		{
			Say("STUN " + (Object.op_Implicit((Object)(object)enemy) ? ((Object)enemy).name : "-"), delegate
			{
				Engine.OnEnemyStunned(Time.time, Info(enemy));
			});
		}

		public static void EnemyFell(HealthManager enemy)
		{
			Say("FELL " + (Object.op_Implicit((Object)(object)enemy) ? ((Object)enemy).name : "-"), delegate
			{
				Engine.OnEnemyFell(Time.time, Info(enemy));
			});
		}

		public static void BossHealed(HealthManager enemy)
		{
			Say(string.Format("HEALED {0} hp={1}", Object.op_Implicit((Object)(object)enemy) ? ((Object)enemy).name : "-", Object.op_Implicit((Object)(object)enemy) ? enemy.hp : 0), delegate
			{
				Engine.OnBossHealed(Time.time, Info(enemy));
			});
		}

		public static void BindBroken(HealthManager enemy)
		{
			Say("BINDBREAK " + (Object.op_Implicit((Object)(object)enemy) ? ((Object)enemy).name : "-"), delegate
			{
				Engine.OnBindBroken(Time.time, Info(enemy));
			});
		}

		public static void Parried(HealthManager enemy)
		{
			GrazeWatcher.Spoil();
			On(delegate
			{
				Engine.OnParry(Time.time, Info(enemy));
			});
		}

		public static void Evaded(HealthManager enemy)
		{
			On(delegate
			{
				Engine.OnEvade(Time.time, Info(enemy));
			});
		}

		public static void Grazed(HealthManager enemy)
		{
			On(delegate
			{
				Engine.OnGraze(Time.time, Info(enemy));
			});
		}

		public static void HeroDamaged(HazardType hazard)
		{
			//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)
			GrazeWatcher.Spoil();
			GameObject lastAttacker = DefenseHooks.LastAttacker;
			if (Object.op_Implicit((Object)(object)lastAttacker))
			{
				EnemyWatch.HurtBy(EnemyFinder.Owner((Component)(object)lastAttacker.transform), Time.time);
			}
			On(delegate
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Invalid comparison between Unknown and I4
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Invalid comparison between Unknown and I4
				Engine.OnHeroDamaged(Time.time, (int)hazard == 0, (int)hazard == 8);
			});
		}

		public static void PogoBounce()
		{
			lastBounce = Time.time;
			if (lastBounce - lastSpikeTink <= 0.3f)
			{
				SpikePogo();
			}
			On(delegate
			{
				Engine.OnPogoBounce(Time.time);
			});
		}

		public static void SpringBounce()
		{
			On(delegate
			{
				Engine.OnSpringBounce(Time.time);
			});
		}

		public static void DownDash()
		{
			On(delegate
			{
				Engine.OnDownDash(Time.time);
			});
		}

		public static void WallJump()
		{
			On(delegate
			{
				Engine.OnWallJump(Time.time);
			});
		}

		public static void DoubleJump()
		{
			On(delegate
			{
				Engine.OnDoubleJump(Time.time);
			});
		}

		public static void Taunted()
		{
			On(delegate
			{
				Engine.OnTaunt(Time.time);
			});
		}

		public static void TauntSpent()
		{
			tauntFrame = Time.frameCount;
		}

		public static void BindStarted()
		{
			HeroWatch.BindStarted();
			On(delegate
			{
				Engine.OnBindStarted(Time.time);
			});
		}

		public static void BindCompleted()
		{
			On(delegate
			{
				float num = NearestEnemy();
				bool flag = HeroWatch.TakeDive();
				if (Plugin.LogStyle.Value)
				{
					Plugin.Out(FormattableString.Invariant(FormattableStringFactory.Create("BIND nearest={0:0.0}{1}", num, flag ? " dive" : "")));
				}
				if (flag)
				{
					Engine.OnDesolateDive(Time.time);
				}
				Engine.OnBindCompleted(Time.time, num);
			});
		}

		public static void DiceSaved()
		{
			Say("SAVE dice", delegate
			{
				Engine.OnDiceSaved(Time.time);
			});
		}

		public static void MaskSaved()
		{
			Say("SAVE mask", delegate
			{
				Engine.OnMaskSaved(Time.time);
			});
		}

		public static void BellBlocked(HealthManager enemy)
		{
			Say("SAVE bell", delegate
			{
				Engine.OnBellBlocked(Time.time, Info(enemy));
			});
		}

		public static void ReserveBind()
		{
			Say("BIND reserve", delegate
			{
				Engine.OnReserveBind(Time.time);
			});
		}

		public static void Restocked(int charges)
		{
			Say($"RESTOCK +{charges}", delegate
			{
				Engine.OnRestock(Time.time);
			});
		}

		public static void Pickpocket(HealthManager enemy, int rosaries)
		{
			Say(string.Format("STEAL {0} rosaries={1}", Object.op_Implicit((Object)(object)enemy) ? ((Object)enemy).name : "-", rosaries), delegate
			{
				Engine.OnPickpocket(Time.time, Info(enemy));
			});
		}

		public static void SpikeTink()
		{
			lastSpikeTink = Time.time;
			if (lastSpikeTink - lastBounce <= 0.3f)
			{
				SpikePogo();
			}
		}

		private static void SpikePogo()
		{
			lastSpikeTink = (lastBounce = float.NegativeInfinity);
			Say("POGO spikes", delegate
			{
				Engine.OnSpikePogo(Time.time);
			});
		}

		private static void Say(string line, Action action)
		{
			if (Running && Plugin.LogStyle.Value)
			{
				Plugin.Out(line);
			}
			On(action);
		}

		public static void ArenaStarted()
		{
			On(delegate
			{
				Engine.OnArenaStarted(Time.time);
			});
		}

		public static void ArenaCleared()
		{
			On(delegate
			{
				Engine.OnArenaCleared(Time.time);
			});
		}

		public static string RankName(int rank)
		{
			if (rank >= 0)
			{
				return Tuning.Ranks[rank].Name;
			}
			return "-";
		}

		private static EnemyInfo Info(HealthManager enemy)
		{
			if (!Object.op_Implicit((Object)(object)enemy))
			{
				return null;
			}
			return EnemyRegistry.Get(enemy);
		}

		private static string MeterText()
		{
			if (!Engine.Meter.InCombo)
			{
				return "rank=-";
			}
			return $"rank={RankName(Engine.Meter.Rank)} {Engine.Meter.Fill:0}/{Engine.Meter.Size:0}";
		}

		private static void On(Action action)
		{
			if (Running)
			{
				Guard(delegate
				{
					Observe();
					action();
				});
			}
		}

		private static void Observe()
		{
			if (HeroProbe.TryRead(out var state))
			{
				Engine.Observe(Time.time, state);
			}
		}

		private static void Guard(Action action)
		{
			try
			{
				action();
			}
			catch (Exception arg)
			{
				stopped = true;
				Plugin.Log.LogError((object)$"Style engine stopped after an error: {arg}");
			}
		}
	}
	internal static class GameField
	{
		public static FieldRef<TOwner, TValue> Find<TOwner, TValue>(string name)
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(TOwner), name);
			if (fieldInfo != null && fieldInfo.FieldType == typeof(TValue))
			{
				return AccessTools.FieldRefAccess<TOwner, TValue>(fieldInfo);
			}
			Plugin.Log.LogWarning((object)("Stylemeter: " + typeof(TOwner).Name + "." + name + " is not in this game version, the bonus reading it is off"));
			return null;
		}
	}
	internal static class GrazeWatcher
	{
		private sealed class Pass
		{
			public DamageHero Attack;

			public float First;

			public float Last;

			public bool Moving;

			public bool Spoiled;
		}

		private const float Margin = 1f;

		private const float LeaveGap = 0.15f;

		private const float MaxExposure = 1.5f;

		private static readonly Collider2D[] Nearby = (Collider2D[])(object)new Collider2D[32];

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

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

		private static readonly ContactFilter2D Filter = new ContactFilter2D
		{
			useTriggers = true,
			useLayerMask = false
		};

		private static BoxCollider2D hurtbox;

		public static void Tick(HeroController hero, float now)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)hurtbox))
			{
				HeroBox componentInChildren = ((Component)hero).GetComponentInChildren<HeroBox>(true);
				hurtbox = (Object.op_Implicit((Object)(object)componentInChildren) ? ((Component)componentInChildren).GetComponent<BoxCollider2D>() : null);
				if (!Object.op_Implicit((Object)(object)hurtbox))
				{
					return;
				}
			}
			HeroControllerStates cState = hero.cState;
			bool flag = hero.CanTakeDamage() && !cState.invulnerable && !cState.parrying;
			bool flag2 = !cState.onGround || cState.dashing;
			Bounds bounds = ((Collider2D)hurtbox).bounds;
			Vector2 val = Vector2.op_Implicit(((Bounds)(ref bounds)).size) + Vector2.one * 2f;
			int num = Physics2D.OverlapBox(Vector2.op_Implicit(((Bounds)(ref bounds)).center), val, 0f, Filter, Nearby);
			for (int i = 0; i < num; i++)
			{
				DamageHero val2 = AttackOf(Nearby[i]);
				if (Object.op_Implicit((Object)(object)val2))
				{
					int instanceID = ((Object)val2).GetInstanceID();
					if (!Passes.TryGetValue(instanceID, out var value))
					{
						Dictionary<int, Pass> passes = Passes;
						Pass obj = new Pass
						{
							Attack = val2,
							First = now
						};
						value = obj;
						passes[instanceID] = obj;
					}
					value.Last = now;
					value.Moving |= flag2;
					value.Spoiled |= !flag;
				}
			}
			Gone.Clear();
			foreach (KeyValuePair<int, Pass> pass2 in Passes)
			{
				if (now - pass2.Value.Last > 0.15f)
				{
					Gone.Add(pass2.Key);
				}
			}
			foreach (int item in Gone)
			{
				Pass pass = Passes[item];
				Passes.Remove(item);
				if (!pass.Spoiled && pass.Moving && !(pass.Last - pass.First > 1.5f) && Object.op_Implicit((Object)(object)pass.Attack))
				{
					EngineHost.Grazed(EnemyFinder.Owner((Component)(object)pass.Attack));
				}
			}
		}

		public static void Spoil()
		{
			foreach (Pass value in Passes.Values)
			{
				value.Spoiled = true;
			}
		}

		public static void Clear()
		{
			Passes.Clear();
		}

		private static DamageHero AttackOf(Collider2D collider)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Invalid comparison between Unknown and I4
			if (!Object.op_Implicit((Object)(object)collider) || Object.op_Implicit((Object)(object)((Component)collider).GetComponent<HealthManager>()) || ((Object)collider).name.IndexOf("Body", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return null;
			}
			DamageHero component = ((Component)collider).GetComponent<DamageHero>();
			if (!Object.op_Implicit((Object)(object)component) || !((Behaviour)component).enabled || component.damageDealt <= 0 || (int)component.hazardType != 1)
			{
				return null;
			}
			return component;
		}
	}
	internal static class HeroProbe
	{
		public static bool TryRead(out HeroState state)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			state = default(HeroState);
			HeroController instance = HeroController.instance;
			if (!Object.op_Implicit((Object)(object)instance))
			{
				return false;
			}
			PlayerData val = instance.playerData ?? PlayerData.instance;
			if (val == null)
			{
				return false;
			}
			HeroControllerStates cState = instance.cState;
			Rigidbody2D body = instance.Body;
			string currentCrestID = val.CurrentCrestID;
			state = new HeroState
			{
				OnGround = cState.onGround,
				OnWall = (cState.wallClinging || cState.wallSliding),
				VelocityX = (Object.op_Implicit((Object)(object)body) ? body.linearVelocity.x : 0f),
				VelocityY = (Object.op_Implicit((Object)(object)body) ? body.linearVelocity.y : 0f),
				Health = val.health,
				MaxHealth = val.maxHealth,
				Silk = val.silk,
				SilkMax = val.CurrentSilkMax,
				SkillCost = val.SilkSkillCost,
				Dead = cState.dead,
				Crest = currentCrestID,
				HunterStage = HunterStage(instance, currentCrestID),
				InRage = instance.WarriorState.IsInRageMode,
				InReaperMode = instance.ReaperState.IsInReaperMode,
				BarbedBracelet = IsEquipped(Gameplay.BarbedWireTool)
			};
			return true;
		}

		public static bool DrainActive()
		{
			HeroController instance = HeroController.instance;
			GameManager instance2 = GameManager.instance;
			if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)instance2) || instance2.isPaused || Time.timeScale <= 0f)
			{
				return false;
			}
			HeroControllerStates cState = instance.cState;
			bool flag = instance.playerData != null && instance.playerData.atBench;
			if (!cState.transitioning && !cState.dead && !instance.controlReqlinquished)
			{
				return !flag;
			}
			return false;
		}

		public static int SourceCount()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Invalid comparison between Unknown and I4
			int num = 4;
			foreach (ToolItem allTool in ToolItemManager.GetAllTools())
			{
				if (Object.op_Implicit((Object)(object)allTool) && ((ToolBase)allTool).IsEquipped && ((int)allTool.Type == 0 || (int)allTool.Type == 3))
				{
					num++;
				}
			}
			PlayerData instance = PlayerData.instance;
			if (instance != null && instance.hasHarpoonDash)
			{
				num++;
			}
			return num;
		}

		public static string[] AttackTools()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = new List<string>();
			foreach (ToolItem allTool in ToolItemManager.GetAllTools())
			{
				if (Object.op_Implicit((Object)(object)allTool) && ((ToolBase)allTool).IsEquipped && (int)allTool.Type == 0)
				{
					list.Add(allTool.name);
				}
			}
			return list.ToArray();
		}

		private static int HunterStage(HeroController hero, string crest)
		{
			//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_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			HunterUpgCrestStateInfo hunterUpgState = hero.HunterUpgState;
			if (crest == "Hunter_v2")
			{
				return (hunterUpgState.CurrentMeterHits >= Gameplay.HunterComboHits) ? 1 : 0;
			}
			if (crest != "Hunter_v3")
			{
				return 0;
			}
			if (((HunterUpgCrestStateInfo)(ref hunterUpgState)).IsComboMeterAboveExtra)
			{
				return 2;
			}
			return (hunterUpgState.CurrentMeterHits >= Gameplay.HunterCombo2Hits) ? 1 : 0;
		}

		private static bool IsEquipped(ToolItem tool)
		{
			if (Object.op_Implicit((Object)(object)tool))
			{
				return ((ToolBase)tool).IsEquipped;
			}
			return false;
		}
	}
	internal static class HeroWatch
	{
		private const float ChargeReleaseWindow = 1f;

		private const float DiveMinHeight = 4f;

		private const float DiveRange = 3f;

		private const float WallAttackWindow = 0.5f;

		private static readonly FieldRef<HeroController, float> NailChargeTimer = GameField.Find<HeroController, float>("nailChargeTimer");

		private static HeroController hero;

		private static Transform dartDamager;

		private static bool charging;

		private static float chargeHeld;

		private static float chargeReleasedAt = float.NegativeInfinity;

		private static bool darting;

		private static int dartId;

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

		private static string bindState;

		private static float diveTopY = float.NaN;

		private static bool diveReady;

		private static GameObject wallSlash;

		private static float wallAttackAt = float.NegativeInfinity;

		public static void Tick(HeroController hc, float now)
		{
			if (!Object.op_Implicit((Object)(object)hc))
			{
				return;
			}
			if ((Object)(object)hc != (Object)(object)hero)
			{
				hero = hc;
				dartDamager = ((Component)hc).transform.Find("Special Attacks/Silk Charge Damager");
				Dodged.Clear();
			}
			TickCharge(hc, now);
			int num;
			if (Object.op_Implicit((Object)(object)dartDamager))
			{
				num = (((Component)dartDamager).gameObject.activeInHierarchy ? 1 : 0);
				if (num != 0 && !darting)
				{
					dartId++;
				}
			}
			else
			{
				num = 0;
			}
			darting = (byte)num != 0;
			TickBind(hc);
		}

		private static void TickCharge(HeroController hc, float now)
		{
			if (hc.cState.nailCharging)
			{
				charging = true;
				chargeHeld = ((NailChargeTimer != null) ? NailChargeTimer.Invoke(hc) : 0f);
			}
			else if (charging)
			{
				charging = false;
				chargeReleasedAt = now;
			}
		}

		public static float ChargeHeldFor(float now)
		{
			if (!(now - chargeReleasedAt <= 1f))
			{
				return 0f;
			}
			return chargeHeld;
		}

		public static void WallAttack(NailSlash slash, float now)
		{
			wallSlash = (Object.op_Implicit((Object)(object)slash) ? ((Component)slash).gameObject : null);
			wallAttackAt = now;
		}

		public static bool FromWall(GameObject source, float now)
		{
			if (Object.op_Implicit((Object)(object)source) && Object.op_Implicit((Object)(object)wallSlash) && now - wallAttackAt <= 0.5f)
			{
				if (!((Object)(object)source == (Object)(object)wallSlash))
				{
					return source.transform.IsChildOf(wallSlash.transform);
				}
				return true;
			}
			return false;
		}

		public static void Touched(GameObject attack, HazardType hazard, int damage)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Invalid comparison between Unknown and I4
			if (darting && Object.op_Implicit((Object)(object)attack) && damage > 0 && attack.layer != 11 && ((int)hazard == 1 || (int)hazard == 8))
			{
				HealthManager val = EnemyFinder.Owner((Component)(object)attack.transform);
				if (Object.op_Implicit((Object)(object)val))
				{
					Dodged[val] = dartId;
				}
			}
		}

		public static bool DartedThrough(HealthManager enemy)
		{
			if (Object.op_Implicit((Object)(object)enemy) && Dodged.TryGetValue(enemy, out var value))
			{
				return value == dartId;
			}
			return false;
		}

		private static void TickBind(HeroController hc)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			PlayMakerFSM spellControl = hc.spellControl;
			string text = (Object.op_Implicit((Object)(object)spellControl) ? spellControl.ActiveStateName : null);
			if (text == bindState)
			{
				return;
			}
			bindState = text;
			float y = ((Component)hc).transform.position.y;
			switch (text)
			{
			case "Shaman Fall":
				diveTopY = y;
				diveReady = false;
				break;
			case "Shaman Impact":
			case "Bind Ground":
				if (!float.IsNaN(diveTopY))
				{
					diveReady = diveTopY - y >= 4f && EngineHost.NearestEnemyDistance() <= 3f;
					diveTopY = float.NaN;
				}
				break;
			}
		}

		public static bool TakeDive()
		{
			bool result = diveReady;
			diveReady = false;
			return result;
		}

		public static void BindStarted()
		{
			diveReady = false;
			diveTopY = float.NaN;
		}

		public static void Clear()
		{
			Dodged.Clear();
			charging = false;
			diveReady = false;
			diveTopY = float.NaN;
			wallSlash = null;
		}
	}
	internal struct HitContext
	{
		public bool Pierced;

		public bool Flanked;

		public bool Backstab;

		private static readonly FieldRef<Walker, float> WalkerRight = GameField.Find<Walker, float>("rightScale");

		private static readonly FieldRef<Crawler, bool> CrawlerFacesRight = GameField.Find<Crawler, bool>("spriteFacesRight");

		public static HitContext Read(HealthManager hm, HitInstance hit)
		{
			//IL_0008: 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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			HitContext result = default(HitContext);
			if (!hit.IsHeroDamage)
			{
				return result;
			}
			int cardinalDirection = DirectionUtils.GetCardinalDirection(((HitInstance)(ref hit)).GetActualDirection(((Component)hm).transform, (TargetType)0));
			if (hm.IsInvincible)
			{
				bool flag = hm.IsBlockingByDirection(cardinalDirection, hit.AttackType, hit.SpecialType);
				bool flag2 = hm.IsBlockingByDirection(cardinalDirection, hit.AttackType, (SpecialTypes)(hit.SpecialType & -5));
				result.Pierced = flag2 && !flag;
				result.Flanked = hm.InvincibleFromDirection != 0 && !flag2;
			}
			if (((HitInstance)(ref hit)).IsNailDamage && (cardinalDirection == 0 || cardinalDirection == 2) && TryFacingRight(hm, out var right))
			{
				result.Backstab = ((cardinalDirection == 0) ? right : (!right));
			}
			return result;
		}

		private static bool TryFacingRight(HealthManager hm, out bool right)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			right = false;
			float x = ((Component)hm).transform.localScale.x;
			Walker component = ((Component)hm).GetComponent<Walker>();
			if (Object.op_Implicit((Object)(object)component) && WalkerRight != null)
			{
				right = x * WalkerRight.Invoke(component) >= 0f;
				return true;
			}
			WalkerV2 component2 = ((Component)hm).GetComponent<WalkerV2>();
			if (Object.op_Implicit((Object)(object)component2))
			{
				right = Mathf.Sign(x) * component2.RightDirection > 0f;
				return true;
			}
			Climber component3 = ((Component)hm).GetComponent<Climber>();
			if (Object.op_Implicit((Object)(object)component3))
			{
				right = component3.IsFacingRight;
				return true;
			}
			Crawler component4 = ((Component)hm).GetComponent<Crawler>();
			if (Object.op_Implicit((Object)(object)component4) && CrawlerFacesRight != null)
			{
				right = Mathf.Sign(x) * (CrawlerFacesRight.Invoke(component4) ? 1f : (-1f)) > 0f;
				return true;
			}
			return false;
		}
	}
	internal static class HookGuard
	{
		private const int ErrorsBeforeOff = 10;

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

		public static void Run(string name, Action action)
		{
			if (IsOff(name))
			{
				return;
			}
			try
			{
				action();
			}
			catch (Exception e)
			{
				Report(name, e);
			}
		}

		public static T Get<T>(string name, Func<T> read, T fallback)
		{
			if (IsOff(name))
			{
				return fallback;
			}
			try
			{
				return read();
			}
			catch (Exception e)
			{
				Report(name, e);
				return fallback;
			}
		}

		private static bool IsOff(string name)
		{
			if (Errors.TryGetValue(name, out var value))
			{
				return value >= 10;
			}
			return false;
		}

		private static void Report(string name, Exception e)
		{
			Errors.TryGetValue(name, out var value);
			value = (Errors[name] = value + 1);
			switch (value)
			{
			case 1:
				Plugin.Log.LogWarning((object)$"Stylemeter: {name} failed: {e}");
				break;
			case 10:
				Plugin.Log.LogWarning((object)$"Stylemeter: {name} is off for this session after {value} errors");
				break;
			}
		}
	}
	[HarmonyPatch]
	internal static class HitHooks
	{
		private sealed class PendingHit
		{
			public HealthManager Target;

			public HitInstance Hit;

			public int HpBefore;

			public int Frame;

			public bool Sent;

			public HitContext Context;
		}

		private static readonly Stack<PendingHit> Pending = new Stack<PendingHit>();

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HealthManager), "Hit")]
		private static void BeforeHit(HealthManager __instance, HitInstance hitInstance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			HookGuard.Run("hits", delegate
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				Remember(__instance, hitInstance);
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HealthManager), "Hit")]
		private static void AfterHit(HealthManager __instance)
		{
			HookGuard.Run("hits", delegate
			{
				SendWound(__instance);
			});
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HealthManager), "Die", new Type[]
		{
			typeof(float?),
			typeof(AttackTypes),
			typeof(NailElements),
			typeof(GameObject),
			typeof(bool),
			typeof(float),
			typeof(bool),
			typeof(bool)
		})]
		private static void BeforeDie(HealthManager __instance, AttackTypes attackType, NailElements nailElement)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			HookGuard.Run("deaths", delegate
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				SendDeath(__instance, attackType, nailElement);
			});
		}

		private static void Remember(HealthManager hm, HitInstance hit)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: 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)
			while (Pending.Count > 0 && Pending.Peek().Frame != Time.frameCount)
			{
				Pending.Pop();
			}
			Pending.Push(new PendingHit
			{
				Target = hm,
				Hit = hit,
				HpBefore = hm.hp,
				Frame = Time.frameCount,
				Context = HookGuard.Get("hit context", () => HitContext.Read(hm, hit), default(HitContext))
			});
		}

		private static void SendWound(HealthManager hm)
		{
			//IL_006c: 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)
			if (Pending.Count == 0)
			{
				return;
			}
			PendingHit pendingHit = Pending.Pop();
			if (!pendingHit.Sent && !((Object)(object)pendingHit.Target != (Object)(object)hm) && hm.hp < pendingHit.HpBefore)
			{
				if (pendingHit.Hit.IsHeroDamage)
				{
					EngineHost.Hit(hm, pendingHit.Hit, pendingHit.HpBefore, hm.hp, killed: false, pendingHit.Context);
				}
				else
				{
					EngineHost.WorldHit(hm, pendingHit.Hit, killed: false);
				}
			}
		}

		private static void SendDeath(HealthManager hm, AttackTypes attackType, NailElements nailElement)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			if (hm.GetIsDead())
			{
				return;
			}
			PendingHit pendingHit = ((Pending.Count > 0) ? Pending.Peek() : null);
			if (pendingHit != null && !pendingHit.Sent && (Object)(object)pendingHit.Target == (Object)(object)hm)
			{
				pendingHit.Sent = true;
				if (pendingHit.Hit.IsHeroDamage)
				{
					EngineHost.Hit(hm, pendingHit.Hit, pendingHit.HpBefore, hm.hp, killed: true, pendingHit.Context);
				}
				else
				{
					EngineHost.WorldHit(hm, pendingHit.Hit, killed: true);
				}
			}
			else
			{
				EngineHost.EnemyDied(hm, TickHooks.CauseOf(hm, attackType, nailElement));
			}
		}
	}
	[HarmonyPatch]
	internal static class TickHooks
	{
		private static HealthManager target;

		private static DeathCause cause;

		private static int depth;

		private static int frame = -1;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HealthManager), "ApplyTagDamage")]
		private static void BeforeTag(HealthManager __instance, DamageTagInstance damageTagInstance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			HookGuard.Run("damage ticks", delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				Enter(__instance, damageTagInstance.isHeroDamage, ElementOf(damageTagInstance));
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HealthManager), "ApplyTagDamage")]
		private static void AfterTag()
		{
			HookGuard.Run("damage ticks", Exit);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HealthManager), "ApplyExtraDamage", new Type[] { typeof(HitInstance) })]
		private static void BeforeExtra(HealthManager __instance, HitInstance hitInstance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			HookGuard.Run("damage ticks", delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				Enter(__instance, hitInstance.IsHeroDamage, EngineHost.ElementOf(hitInstance));
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HealthManager), "ApplyExtraDamage", new Type[] { typeof(HitInstance) })]
		private static void AfterExtra()
		{
			HookGuard.Run("damage ticks", Exit);
		}

		public static DeathCause CauseOf(HealthManager hm, AttackTypes attackType, NailElements nailElement)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)hm == (Object)(object)target && frame == Time.frameCount)
			{
				return cause;
			}
			return new DeathCause
			{
				Element = EngineHost.ElementOf(nailElement, attackType)
			};
		}

		private static Element ElementOf(DamageTagInstance tag)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if ((int)tag.specialDamageType != 2)
			{
				return EngineHost.ElementOf(tag.nailElements, (AttackTypes)1);
			}
			return Element.Lightning;
		}

		private static void Enter(HealthManager hm, bool byHornet, Element element)
		{
			if (frame != Time.frameCount)
			{
				depth = 0;
			}
			frame = Time.frameCount;
			if (depth++ <= 0)
			{
				target = hm;
				cause = new DeathCause
				{
					ByHornet = byHornet,
					Element = element
				};
				if (byHornet && element != Element.None)
				{
					EngineHost.TickDamage(hm, element);
				}
			}
		}

		private static void Exit()
		{
			if (--depth <= 0)
			{
				depth = 0;
				target = null;
			}
		}
	}
	[HarmonyPatch]
	internal static class HeroHooks
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "SendHeroDamagedEvent", new Type[] { typeof(DamageInfo) })]
		private static void AfterHeroDamaged(DamageInfo damageInfo)
		{
			//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)
			HookGuard.Run("hurt", delegate
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				EngineHost.HeroDamaged(damageInfo.hazardType);
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "DownspikeBounce")]
		private static void AfterDownspikeBounce()
		{
			HookGuard.Run("pogo", EngineHost.PogoBounce);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "DownspikeBounceShort")]
		private static void AfterDownspikeBounceShort()
		{
			HookGuard.Run("pogo", EngineHost.PogoBounce);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "DownspikeBounceSlightlyShort")]
		private static void AfterDownspikeBounceSlightlyShort()
		{
			HookGuard.Run("pogo", EngineHost.PogoBounce);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "ShroomBounce")]
		private static void AfterShroomBounce()
		{
			HookGuard.Run("spring", EngineHost.SpringBounce);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "BounceHigh")]
		private static void AfterBounceHigh()
		{
			HookGuard.Run("spring", EngineHost.SpringBounce);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "SilkTaunted")]
		private static void AfterSilkTaunted()
		{
			HookGuard.Run("taunt", EngineHost.Taunted);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "SilkTauntEffectConsume")]
		private static void AfterTauntConsume(bool __result)
		{
			if (__result)
			{
				HookGuard.Run("taunt", EngineHost.TauntSpent);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "BindCompleted")]
		private static void AfterBindCompleted()
		{
			HookGuard.Run("bind", EngineHost.BindCompleted);
		}
	}
	[HarmonyPatch]
	internal static class MoveHooks
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "DoWallJump")]
		private static void AfterWallJump()
		{
			HookGuard.Run("wall jump", EngineHost.WallJump);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "DoDoubleJump")]
		private static void AfterDoubleJump()
		{
			HookGuard.Run("double jump", EngineHost.DoubleJump);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "HeroDash")]
		private static void AfterDash(HeroController __instance)
		{
			if (__instance.dashingDown)
			{
				HookGuard.Run("down dash", EngineHost.DownDash);
			}
		}
	}
	[HarmonyPatch]
	internal static class ToolHooks
	{
		private static readonly FieldRef<HeroController, ToolItem> WillThrowTool = GameField.Find<HeroController, ToolItem>("willThrowTool");

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HeroController), "ThrowTool")]
		private static void BeforeThrowTool(HeroController __instance, bool isAutoThrow)
		{
			HookGuard.Run("tools", delegate
			{
				ToolItem val = ((WillThrowTool != null) ? WillThrowTool.Invoke(__instance) : null);
				if (Object.op_Implicit((Object)(object)val))
				{
					EngineHost.ToolUsed(val, isAutoThrow);
				}
			});
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HeroNailImbuement), "SetElement")]
		private static void BeforeSetElement(HeroNailImbuement __instance, NailElements element)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			HookGuard.Run("flintslate", delegate
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Invalid comparison between Unknown and I4
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Invalid comparison between Unknown and I4
				if ((int)__instance.CurrentElement == 1 && (int)element != 1)
				{
					EngineHost.FlintslateExpired();
				}
			});
		}
	}
	[HarmonyPatch]
	internal static class ParryHooks
	{
		private struct ParryState
		{
			public bool Parrying;

			public bool EvadeClashed;
		}

		private static readonly FieldRef<HeroController, bool> EvadeClashed = GameField.Find<HeroController, bool>("evadingDidClash");

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HeroController), "CheckParry")]
		private static void BeforeCheckParry(HeroController __instance, out ParryState __state)
		{
			__state = new ParryState
			{
				Parrying = HookGuard.Get("parry", () => __instance.cState.parrying, fallback: false),
				EvadeClashed = HookGuard.Get("evade", () => EvadeClashed.Invoke(__instance), fallback: false)
			};
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "CheckParry")]
		private static void AfterCheckParry(HeroController __instance, DamageHero damageHero, ParryState __state)
		{
			HookGuard.Run("parry", delegate
			{
				if (__state.Parrying && !__instance.cState.parrying && __instance.cState.parryAttack)
				{
					EngineHost.Parried(EnemyFinder.Owner((Component)(object)damageHero));
				}
			});
			HookGuard.Run("evade", delegate
			{
				if (!__state.EvadeClashed && EvadeClashed.Invoke(__instance))
				{
					EngineHost.Evaded(EnemyFinder.Owner((Component)(object)damageHero));
				}
			});
		}
	}
	[HarmonyPatch]
	internal static class WorldHooks
	{
		private static readonly Dictionary<string, Action> GameEvents = new Dictionary<string, Action>
		{
			["STARTED BIND"] = EngineHost.BindStarted,
			["RESERVE BIND USED"] = EngineHost.ReserveBind,
			["BROLLY START"] = EngineHost.GlideStarted,
			["BROLLY END"] = EngineHost.GlideEnded,
			["BOSS DEATH"] = EngineHost.BossDeath
		};

		[HarmonyPrefix]
		[HarmonyPatch(typeof(DamageHero), "NailClash")]
		private static void BeforeNailClash(DamageHero __instance, string colliderTag)
		{
			if (!(colliderTag != "Nail Attack"))
			{
				HookGuard.Run("deflect", delegate
				{
					ToolWatch.Clashed((Component)(object)__instance);
				});
				bool parryCounter = HookGuard.Get("parry this", () => Describe.PathOf(((Component)__instance).gameObject).Contains("Parry"), fallback: false);
				HookGuard.Run("clash", delegate
				{
					EngineHost.Clash(EnemyFinder.Owner((Component)(object)__instance), parryCounter);
				});
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(EventRegister), "SendEvent", new Type[]
		{
			typeof(string),
			typeof(GameObject)
		})]
		private static void BeforeSendEvent(string eventName)
		{
			if (eventName != null && GameEvents.TryGetValue(eventName, out var value))
			{
				HookGuard.Run("game events", value);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BattleScene), "StartBattle")]
		private static void AfterStartBattle()
		{
			HookGuard.Run("arena", EngineHost.ArenaStarted);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BattleScene), "BattleCompleted")]
		private static void AfterBattleCompleted()
		{
			HookGuard.Run("arena", EngineHost.ArenaCleared);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(DisplayBossTitle), "OnEnter")]
		private static void AfterBossTitle(DisplayBossTitle __instance)
		{
			HookGuard.Run("boss title", delegate
			{
				MarkBoss(__instance);
			});
		}

		private static void MarkBoss(DisplayBossTitle title)
		{
			GameObject owner = ((FsmStateAction)title).Owner;
			if (Object.op_Implicit((Object)(object)owner))
			{
				HealthManager val = owner.GetComponentInParent<HealthManager>();
				if (!Object.op_Implicit((Object)(object)val))
				{
					val = owner.GetComponentInChildren<HealthManager>();
				}
				if (Object.op_Implicit((Object)(object)val))
				{
					HealthManager boss = val;
					FsmString bossTitle = title.bossTitle;
					EngineHost.BossTitle(boss, BossKey((bossTitle != null) ? bossTitle.Value : null, val));
				}
			}
		}

		private static string BossKey(string title, HealthManager hm)
		{
			PlayerData instance = PlayerData.instance;
			if (instance == null || string.IsNullOrEmpty(title))
			{
				return title;
			}
			if (title == "LACE")
			{
				if (!instance.defeatedLace1)
				{
					return "LACE_1";
				}
				return "LACE_2";
			}
			if (title == "MOSSBONE_MOTHER" && IsVoid(hm))
			{
				return "MOSSBONE_MOTHER_VOID";
			}
			if (title == "MOSSBONE_MOTHER" && instance.defeatedMossMother)
			{
				return "MOSSBONE_MOTHER_2";
			}
			return title;
		}

		private static bool IsVoid(HealthManager hm)
		{
			BlackThreadState component = ((Component)hm).GetComponent<BlackThreadState>();
			if ((!Object.op_Implicit((Object)(object)component) || !component.IsBlackThreaded) && !((Object)hm).name.Contains("Void"))
			{
				return ((Object)hm).name.Contains("Abyss");
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class DefenseHooks
	{
		private static readonly FieldRef<HeroController, int> DiceHits = GameField.Find<HeroController, int>("luckyDiceShieldedHits");

		private static int takeDamageFrame = -1;

		private static GameObject attacker;

		public static GameObject LastAttacker => attacker;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HeroController), "TakeDamage")]
		private static void BeforeTakeDamage(HeroController __instance, GameObject go, int damageAmount, HazardType hazardType, out int __state)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			takeDamageFrame = Time.frameCount;
			attacker = go;
			HeroController hero = __instance;
			__state = HookGuard.Get("dice", () => DiceHits.Invoke(hero), 0);
			HookGuard.Run("dart", delegate
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				HeroWatch.Touched(go, hazardType, damageAmount);
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "TakeDamage")]
		private static void AfterTakeDamage(HeroController __instance, HazardType hazardType, int __state)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			takeDamageFrame = -1;
			HookGuard.Run("dice", delegate
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Invalid comparison between Unknown and I4
				ToolItem luckyDiceTool = Gameplay.LuckyDiceTool;
				if (__state > 0 && DiceHits.Invoke(__instance) == 0 && (int)hazardType == 1 && Object.op_Implicit((Object)(object)luckyDiceTool) && ((ToolBase)luckyDiceTool).IsEquipped)
				{
					EngineHost.DiceSaved();
				}
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "WillDoBellBindHit", new Type[] { typeof(bool) })]
		private static void AfterBellCheck(bool sendEvent, bool __result)
		{
			if (__result && (sendEvent || takeDamageFrame == Time.frameCount))
			{
				HookGuard.Run("bell", delegate
				{
					EngineHost.BellBlocked(Object.op_Implicit((Object)(object)attacker) ? EnemyFinder.Owner((Component)(object)attacker.transform) : null);
				});
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlayerData), "TakeHealth", new Type[]
		{
			typeof(int),
			typeof(bool),
			typeof(bool)
		})]
		private static void BeforeTakeHealth(PlayerData __instance, int amount, out bool __state)
		{
			__state = HookGuard.Get("mask", delegate
			{
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				ToolItem fracturedMaskTool = Gameplay.FracturedMaskTool;
				return __instance.healthBlue <= 0 && amount > 0 && __instance.health - amount <= 0 && Object.op_Implicit((Object)(object)fracturedMaskTool) && ((ToolBase)fracturedMaskTool).IsEquipped && fracturedMaskTool.SavedData.AmountLeft > 0;
			}, fallback: false);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerData), "TakeHealth", new Type[]
		{
			typeof(int),
			typeof(bool),
			typeof(bool)
		})]
		private static void AfterTakeHealth(PlayerData __instance, bool __state)
		{
			if (!__state || __instance.health <= 0)
			{
				return;
			}
			HookGuard.Run("mask", delegate
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				ToolItem fracturedMaskTool = Gameplay.FracturedMaskTool;
				if (Object.op_Implicit((Object)(object)fracturedMaskTool) && fracturedMaskTool.SavedData.AmountLeft <= 0)
				{
					EngineHost.MaskSaved();
				}
			});
		}
	}
	[HarmonyPatch]
	internal static class WallAttackHooks
	{
		private static readonly FieldRef<HeroController, NailSlash> CurrentSlash = GameField.Find<HeroController, NailSlash>("_slashComponent");

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HeroController), "Attack")]
		private static void BeforeAttack(HeroController __instance, AttackDirection attackDir, out bool __state)
		{
			//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)
			__state = HookGuard.Get("blueprint", () => (int)attackDir == 0 && (__instance.cState.wallSliding || __instance.cState.wallScrambling) && ((ToolBase)Gameplay.ToolmasterCrest).IsEquipped, fallback: false);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeroController), "Attack")]
		private static void AfterAttack(HeroController __instance, bool __state)
		{
			if (__state)
			{
				HeroController hc = __instance;
				HookGuard.Run("blueprint", delegate
				{
					HeroWatch.WallAttack(CurrentSlash.Invoke(hc), Time.time);
				});
			}
		}
	}
	[HarmonyPatch]
	internal static class CraftHooks
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(ToolItemManager), "TryReplenishTools")]
		private static void BeforeReplenish(out int __state)
		{
			__state = HookGuard.Get("restock", EquippedCharges, 0);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ToolItemManager), "TryReplenishTools")]
		private static void AfterReplenish(bool doReplenish, ReplenishMethod method, bool __result, int __state)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			if (!doReplenish || (int)method != 1 || !__result)
			{
				return;
			}
			int before = __state;
			HookGuard.Run("restock", delegate
			{
				int num = EquippedCharges() - before;
				if (num > 0)
				{
					EngineHost.Restocked(num);
				}
			});
		}

		private static int EquippedCharges()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			PlayerData instance = PlayerData.instance;
			List<ToolItem> list = ((instance == null) ? null : ToolItemManager.GetEquippedToolsForCrest(instance.CurrentCrestID));
			int num = 0;
			if (list != null)
			{
				foreach (ToolItem item in list)
				{
					if (Object.op_Implicit((Object)(object)item))
					{
						num += item.SavedData.AmountLeft;
					}
				}
			}
			return num;
		}
	}
	[HarmonyPatch]
	internal static class StealHooks
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(HealthManager), "StealCurrency")]
		private static void AfterSteal(HealthManager __instance, ref int stolenGeo, ref int flingGeo)
		{
			int rosaries = stolenGeo + flingGeo;
			if (rosaries > 0)
			{
				HookGuard.Run("pickpocket", delegate
				{
					EngineHost.Pickpocket(__instance, rosaries);
				});
			}
		}
	}
	[HarmonyPatch]
	internal static class TinkHooks
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(TinkEffect), "Hit")]
		private static void AfterTinkHit(TinkEffect __instance, HitInstance damageInstance)
		{
			//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)
			HookGuard.Run("spike pogo", delegate
			{
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0044: Invalid comparison between Unknown and I4
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_004e: Invalid comparison between Unknown and I4
				HeroController instance = HeroController.instance;
				if (Object.op_Implicit((Object)(object)instance) && instance.cState.downAttacking && ((HitInstance)(ref damageInstance)).IsNailDamage)
				{
					DamageHero component = ((Component)__instance).GetComponent<DamageHero>();
					if (Object.op_Implicit((Object)(object)component) && ((int)component.hazardType == 2 || (int)component.hazardType == 12))
					{
						EngineHost.SpikeTink();
					}
				}
			});
		}
	}
	[HarmonyPatch]
	internal static class RingHooks
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(ToolRing), "OnCollisionEnter2D")]
		private static void AfterRingCollision(ToolRing __instance, Collision2D collision)
		{
			HookGuard.Run("trick shot", delegate
			{
				ToolWatch.RingTouchedTerrain(__instance, collision);
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ToolRing), "OnEnable")]
		private static void AfterRingEnable(ToolRing __instance)
		{
			HookGuard.Run("trick shot", delegate
			{
				ToolWatch.RingThrown(__instance);
			});
		}
	}
	internal static class SessionLog
	{
		private const int Keep = 10;

		private const int KeepOld = 200;

		private static StreamWriter writer;

		public static string Open(string bepInExRoot)
		{
			try
			{
				string text = Path.Combine(bepInExRoot, "Stylemeter", "logs");
				string text2 = Path.Combine(text, "old");
				Directory.CreateDirectory(text2);
				foreach (string item in (from f in Directory.GetFiles(text, "session-*.log")
					orderby f descending
					select f).Skip(9))
				{
					string text3 = Path.Combine(text2, Path.GetFileName(item));
					if (File.Exists(text3))
					{
						File.Delete(item);
					}
					else
					{
						File.Move(item, text3);
					}
				}
				foreach (string item2 in (from f in Directory.GetFiles(text2, "session-*.log")
					orderby f descending
					select f).Skip(200))
				{
					File.Delete(item2);
				}
				string text4 = Path.Combine(text, $"session-{DateTime.Now:yyyyMMdd-HHmmss}.log");
				writer = new StreamWriter(text4)
				{
					AutoFlush = true
				};
				return text4;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogWarning((object)$"Session log disabled: {arg}");
				return null;
			}
		}

		public static void Write(string line)
		{
			writer?.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {line}");
		}
	}
	internal static class ToolWatch
	{
		private sealed class WheelTrack
		{
			public float LowY;

			public float LowX;

			public float LowAt;

			public bool Climbed;
		}

		private const float WallNormal = 0.7f;

		private const float ClimbHeight = 2f;

		private const float ClimbDrift = 0.6f;

		private const float ClimbTime = 1f;

		private const float DeflectWindow = 5f;

		private static readonly FieldRef<ToolBoomerang, float> BoomerangElapsed = GameField.Find<ToolBoomerang, float>("elapsedTime");

		private static readonly FieldRef<ToolBoomerang, float> BoomerangDuration = GameField.Find<ToolBoomerang, float>("flyOutCurveDuration");

		private static readonly FieldRef<ToolBoomerang, float> BoomerangReturnPoint = GameField.Find<ToolBoomerang, float>("flyOutReturnPoint");

		private static readonly FieldRef<ToolBoomerang, bool> BoomerangNailHit = GameField.Find<ToolBoomerang, bool>("wasNailHit");

		private static readonly FieldRef<FireballProjectile, bool> FireballWasHit = GameField.Find<FireballProjectile, bool>("wasHit");

		private static string shardName;

		private static string wheelName;

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

		private static readonly Dictionary<GameObject, WheelTrack> Wheels = new Dictionary<GameObject, WheelTrack>();

		private static readonly Dictionary<GameObject, float> Deflected = new Dictionary<GameObject, float>();

		private static float wheelThrownAt = float.NegativeInfinity;

		private static float lastLooseClash = float.NegativeInfinity;

		public static bool OnReturnLeg(GameObject source)
		{
			ToolBoomerang val = (Object.op_Implicit((Object)(object)source) ? source.GetComponentInParent<ToolBoomerang>() : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return false;
			}
			string text = Traverse.Create((object)val).Field("currentState").GetValue()?.ToString();
			if (text == "Translating")
			{
				return BoomerangElapsed.Invoke(val) / BoomerangDuration.Invoke(val) >= BoomerangReturnPoint.Invoke(val);
			}
			if (text == "Body")
			{
				return !BoomerangNailHit.Invoke(val);
			}
			return false;
		}

		public static void RingTouchedTerrain(ToolRing ring, Collision2D collision)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)ring) && collision != null && collision.contactCount != 0 && collision.gameObject.layer == 8)
			{
				ContactPoint2D contact = collision.GetContact(0);
				if (Mathf.Abs(((ContactPoint2D)(ref contact)).normal.x) >= 0.7f)
				{
					BouncedRings.Add(((Object)ring).GetInstanceID());
				}
			}
		}

		public static void RingThrown(ToolRing ring)
		{
			if (Object.op_Implicit((Object)(object)ring))
			{
				BouncedRings.Remove(((Object)ring).GetInstanceID());
			}
		}

		public static bool AfterWallBounce(GameObject source)
		{
			ToolRing val = (Object.op_Implicit((Object)(object)source) ? source.GetComponentInParent<ToolRing>() : null);
			if (Object.op_Implicit((Object)(object)val))
			{
				return BouncedRings.Contains(((Object)val).GetInstanceID());
			}
			return false;
		}

		public static void ToolThrown(ToolItem tool)
		{
			if (Object.op_Implicit((Object)(object)tool) && tool.name == "Cogwork Saw")
			{
				wheelThrownAt = Time.time;
			}
		}

		public static void Tick(float now)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			if (now - wheelThrownAt < 0.5f)
			{
				FindWheels(now);
			}
			if (Wheels.Count == 0)
			{
				return;
			}
			List<GameObject> list = null;
			foreach (KeyValuePair<GameObject, WheelTrack> wheel in Wheels)
			{
				GameObject key = wheel.Key;
				if (!Object.op_Implicit((Object)(object)key) || !key.activeInHierarchy)
				{
					(list ?? (list = new List<GameObject>())).Add(key);
					continue;
				}
				WheelTrack value = wheel.Value;
				Vector3 position = key.transform.position;
				if (position.y < value.LowY || now - value.LowAt > 1f || Mathf.Abs(position.x - value.LowX) > 0.6f)
				{
					value.LowY = position.y;
					value.LowX = position.x;
					value.LowAt = now;
				}
				else if (position.y - value.LowY >= 2f)
				{
					value.Climbed = true;
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (GameObject item in list)
			{
				Wheels.Remove(item);
			}
		}

		private static void FindWheels(float now)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			string text = CloneName("Cogwork Saw", ref wheelName);
			GameObject val = ((text == null) ? null : GameObject.Find(text));
			if (Object.op_Implicit((Object)(object)val) && val.activeInHierarchy && !Wheels.ContainsKey(val))
			{
				Vector3 position = val.transform.position;
				Wheels[val] = new WheelTrack
				{
					LowY = position.y,
					LowX = position.x,
					LowAt = now
				};
			}
		}

		public static bool WheelClimbed(GameObject source)
		{
			if (!Object.op_Implicit((Object)(object)source))
			{
				return false;
			}
			foreach (KeyValuePair<GameObject, WheelTrack> wheel in Wheels)
			{
				if (Object.op_Implicit((Object)(object)wheel.Key) && wheel.Value.Climbed && source.transform.IsChildOf(wheel.Key.transform))
				{
					return true;
				}
			}
			return false;
		}

		private static string CloneName(string tool, ref string cache)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if (cache != null)
			{
				return cache;
			}
			ToolItem toolByName = ToolItemManager.GetToolByName(tool);
			GameObject val = (Object.op_Implicit((Object)(object)toolByName) ? toolByName.Usage.ThrowPrefab : null);
			if (Object.op_Implicit((Object)(object)val))
			{
				cache = ((Object)val).name + "(Clone)";
			}
			return cache;
		}

		public static void Clashed(Component attack)
		{
			if (Object.op_Implicit((Object)(object)attack))
			{
				GameObject gameObject = ((Component)attack.transform.root).gameObject;
				if (!Object.op_Implicit((Object)(object)gameObject.GetComponentInChildren<HealthManager>()))
				{
					Deflected[gameObject] = Time.time;
					lastLooseClash = Time.time;
				}
			}
		}

		public static bool RecentLooseClash(float window)
		{
			return Time.time - lastLooseClash <= window;
		}

		public static bool IsShrapnel(GameObject source)
		{
			string text = CloneName("Sting Shard", ref shardName);
			if (!Object.op_Implicit((Object)(object)source) || text == null)
			{
				return false;
			}
			Transform val = source.transform;
			while (Object.op_Implicit((Object)(object)val))
			{
				if (((Object)val).name == text)
				{
					return false;
				}
				val = val.parent;
			}
			return true;
		}

		public static bool WasDeflected(GameObject source)
		{
			if (!Object.op_Implicit((Object)(object)source))
			{
				return false;
			}
			FireballProjectile componentInParent = source.GetComponentInParent<FireballProjectile>();
			if (Object.op_Implicit((Object)(object)componentInParent) && FireballWasHit.Invoke(componentInParent))
			{
				return true;
			}
			if (Deflected.TryGetValue(((Component)source.transform.root).gameObject, out var value))
			{
				return Time.time - value <= 5f;
			}
			return false;
		}

		public static void Clear()
		{
			BouncedRings.Clear();
			Wheels.Clear();
			Deflected.Clear();
		}
	}
}
namespace Stylemeter.Game.Menu
{
	internal sealed class ModPanel : MonoBehaviour, IScrollHandler, IEventSystemHandler
	{
		private const string Guard = "mod menu";

		private const float PanelWidth = 1180f;

		private const float PanelHeight = 900f;

		private const float RowWidth = 980f;

		private const float ViewTop = 188f;

		private const float ViewHeight = 556f;

		private const float MultiplierHeight = 64f;

		private const float SectionHeight = 58f;

		private const float WholeSectionHeight = 46f;

		private const float BonusHeight = 44f;

		private const float RevealMargin = 44f;

		private const float WheelStep = 88f;

		private const float FadeTime = 0.15f;

		private const float ScrollSharpness = 14f;

		private const float GlowAlpha = 0.17f;

		private const float MouseRestTime = 0.4f;

		private const float MultiplierStep = 0.25f;

		private static readonly float[] MultiplierSteps = (from index in Enumerable.Range(0, (int)Math.Round(11.0) + 1)
			select 0.25f + (float)index * 0.25f).ToArray();

		private static ModPanel instance;

		private readonly List<PanelRow> listRows = new List<PanelRow>();

		private readonly List<PanelRow> shownRows = new List<PanelRow>();

		private readonly HashSet<BonusGroup> openSections = new HashSet<BonusGroup>();

		private CanvasGroup fade;

		private RectTransform body;

		private RectTransform content;

		private Font font;

		private Font titleFont;

		private PanelRow multiplierRow;

		private PanelRow focus;

		private MenuScreen screen;

		private MenuButton returnTo;

		private bool wasScreenInteractable;

		private bool isOpen;

		private bool isSelectSoundMuted;

		private bool isFocusReturnPending;

		private Vector3 lastMousePosition;

		private float mouseMovedAt = float.NegativeInfinity;

		private readonly List<(CanvasGroup Group, float Alpha)> coveredGroups = new List<(CanvasGroup, float)>();

		private float scroll;

		private float targetScroll;

		private float contentHeight;

		private Action tick;

		private static StyleSettings Settings => EngineHost.Engine.Settings;

		public static void Open(MenuScreen screen, MenuButton returnTo)
		{
			HookGuard.Run("mod menu", delegate
			{
				if (!Object.op_Implicit((Object)(object)instance))
				{
					instance = Create(screen);
				}
				instance.Show(screen, returnTo);
			});
		}

		private static ModPanel Create(MenuScreen screen)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Stylemeter Panel", new Type[1] { typeof(RectTransform) });
			Object.DontDestroyOnLoad((Object)(object)val);
			Canvas obj = val.AddComponent<Canvas>();
			obj.renderMode = (RenderMode)0;
			obj.sortingOrder = 1000;
			CanvasScaler obj2 = val.AddComponent<CanvasScaler>();
			obj2.uiScaleMode = (ScaleMode)1;
			obj2.referenceResolution = new Vector2(1920f, 1080f);
			obj2.matchWidthOrHeight = 1f;
			val.AddComponent<GraphicRaycaster>();
			ModPanel modPanel = val.AddComponent<ModPanel>();
			try
			{
				modPanel.Build(screen);
			}
			catch
			{
				Object.Destroy((Object)(object)val);
				throw;
			}
			val.SetActive(false);
			return modPanel;
		}

		private void Awake()
		{
			tick = Tick;
		}

		private void Update()
		{
			if (Object.op_Implicit((Object)(object)fade) && (isOpen || fade.alpha > 0f))
			{
				HookGuard.Run("mod menu", tick);
			}
		}

		private void Tick()
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: 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)
			float unscaledDeltaTime = Time.unscaledDeltaTime;
			fade.alpha = Mathf.MoveTowards(fade.alpha, isOpen ? 1f : 0f, unscaledDeltaTime / 0.15f);
			if (!isOpen && fade.alpha <= 0f)
			{
				((Component)this).gameObject.SetActive(false);
				return;
			}
			if (isOpen && !IsScreenShowing())
			{
				Leave();
			}
			if (isOpen)
			{
				KeepFocus();
			}
			scroll = Mathf.Lerp(scroll, targetScroll, 1f - Mathf.Exp(-14f * unscaledDeltaTime));
			content.anchoredPosition = new Vector2(0f, scroll);
			if (Object.op_Implicit((Object)(object)focus))
			{
				Color color = ((Graphic)focus.Glow).color;
				color.a = Mathf.MoveTowards(color.a, 0.17f, unscaledDeltaTime * 0.17f / 0.15f);
				((Graphic)focus.Glow).color = color;
			}
		}

		public void OnScroll(PointerEventData eventData)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			if (isOpen)
			{
				targetScroll -= eventData.scrollDelta.y * 88f;
				ClampScroll();
			}
		}

		private void Show(MenuScreen optionsScreen, MenuButton button)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			screen = optionsScreen;
			returnTo = button;
			focus = multiplierRow;
			lastMousePosition = Input.mousePosition;
			mouseMovedAt = float.NegativeInfinity;
			Refresh();
			scroll = (targetScroll = 0f);
			Relayout();
			CanvasGroup screenCanvasGroup = screen.ScreenCanvasGroup;
			wasScreenInteractable = Object.op_Implicit((Object)(object)screenCanvasGroup) && screenCanvasGroup.interactable;
			if (Object.op_Implicit((Object)(object)screenCanvasGroup))
			{
				screenCanvasGroup.interactable = false;
			}
			CoverScreen();
			((Component)this).gameObject.SetActive(true);
			fade.blocksRaycasts = true;
			fade.interactable = true;
			isOpen = true;
			isSelectSoundMuted = true;
			if (Object.op_Implicit((Object)(object)EventSystem.current))
			{
				EventSystem.current.SetSelectedGameObject(((Component)multiplierRow).gameObject);
			}
		}

		public void Close()
		{
			if (isOpen)
			{
				Hide();
				CanvasGroup val = (Object.op_Implicit((Object)(object)screen) ? screen.ScreenCanvasGroup : null);
				if (Object.op_Implicit((Object)(object)val))
				{
					val.interactable = wasScreenInteractable;
				}
				Sound(delegate(MenuAudioController audio)
				{
					audio.PlayCancel();
				});
				if (Object.op_Implicit((Object)(object)returnTo))
				{
					UIManager.HighlightSelectableNoSound((Selectable)(object)returnTo);
				}
			}
		}

		private void Leave()
		{
			Hide();
			CanvasGroup val = (Object.op_Implicit((Object)(object)screen) ? screen.ScreenCanvasGroup : null);
			if (Object.op_Implicit((Object)(object)val) && ((Behaviour)screen).isActiveAndEnabled && val.alpha > 0.99f)
			{
				val.interactable = wasScreenInteractable;
			}
			EventSystem current = EventSystem.current;
			GameObject val2 =