Decompiled source of Arcane Row v0.5.1

SpellBrigadeArcane.dll

Decompiled 7 hours 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.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using FMODUnity;
using HarmonyLib;
using Il2CppInterop.Common;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.MethodInfo;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using SpellBrigadeArcane.Core;
using SpellBrigadeArcane.Game;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Localization;
using UnityEngine.Localization.Components;
using UnityEngine.SceneManagement;
using UnityEngine.Sprites;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("SpellBrigadeArcane")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.5.1.0")]
[assembly: AssemblyInformationalVersion("0.5.1+5fd13e1ad22fceab06e6dcd96c7295345dbc512a")]
[assembly: AssemblyProduct("SpellBrigadeArcane")]
[assembly: AssemblyTitle("SpellBrigadeArcane")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.5.1.0")]
[module: UnverifiableCode]
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte flag)
		{
			Flag = flag;
		}
	}
}
namespace SpellBrigadeArcane
{
	public class ArcaneRunner : MonoBehaviour
	{
		public ArcaneRunner(IntPtr ptr)
			: base(ptr)
		{
		}

		public void Update()
		{
			float unscaledTime = Time.unscaledTime;
			try
			{
				ArcaneShop.Tick(unscaledTime);
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("arcane-shop", ex, unscaledTime);
			}
			try
			{
				MissionBonuses.Tick(unscaledTime);
			}
			catch (Exception ex2)
			{
				ModLog.ErrorThrottled("mission-bonuses", ex2, unscaledTime);
			}
			try
			{
				PotionBeltRunner.Tick(unscaledTime);
			}
			catch (Exception ex3)
			{
				ModLog.ErrorThrottled("potion-belt", ex3, unscaledTime);
			}
			try
			{
				LongShotHook.Update();
			}
			catch (Exception ex4)
			{
				LongShotHook.Pause();
				ModLog.ErrorThrottled("long-shot-update", ex4, unscaledTime);
			}
			try
			{
				BeltHud.Update(unscaledTime);
			}
			catch (Exception ex5)
			{
				ModLog.ErrorThrottled("belt-hud", ex5, unscaledTime);
			}
			try
			{
				TestHotkeys.Update();
			}
			catch (Exception ex6)
			{
				ModLog.ErrorThrottled("test-hotkeys", ex6, unscaledTime);
			}
			if (ModConfig.DumpArt.Value)
			{
				try
				{
					ArtDump.Tick(unscaledTime);
				}
				catch (Exception ex7)
				{
					ModLog.ErrorThrottled("art-dump", ex7, unscaledTime);
				}
			}
			if (!ModConfig.Scan.Value)
			{
				return;
			}
			try
			{
				EnchantmentScan.Tick(unscaledTime);
			}
			catch (Exception ex8)
			{
				ModLog.ErrorThrottled("enchantment-scan", ex8, unscaledTime);
			}
			try
			{
				StatScan.Tick(unscaledTime);
			}
			catch (Exception ex9)
			{
				ModLog.ErrorThrottled("stat-scan", ex9, unscaledTime);
			}
		}

		public void OnApplicationQuit()
		{
			ModLog.Step("clean exit");
		}
	}
	internal static class ModConfig
	{
		public static ConfigEntry<bool> LongShot { get; private set; }

		public static ConfigEntry<bool> Scan { get; private set; }

		public static ConfigEntry<bool> UnlockRow { get; private set; }

		public static ConfigEntry<bool> DumpArt { get; private set; }

		public static ConfigEntry<string> TestLevelOverride { get; private set; }

		public static ConfigEntry<bool> TestHotkeys { get; private set; }

		public static void Init(ConfigFile config)
		{
			LongShot = config.Bind<bool>("General", "LongShot", true, "Long Shot (Reach's Mastery) changes the game's damage code with one small patch. Turn this off if a game update makes it misbehave; the rest of the mod keeps working.");
			Scan = config.Bind<bool>("Debug", "Scan", false, "Write BepInEx/SpellBrigadeArcane-scan.txt (the previous one is kept as ...-scan.prev.txt): the Enchantments screen (scanned up to 3 times per session, each time it opens), the enchantments you hover, and your wizard's stats (once per mission, max 5). Read-only development aid.");
			UnlockRow = config.Bind<bool>("Debug", "UnlockRow", false, "Open the sixth tier without the 12 Masteries it normally needs (for testing). Buying spends real gold; middle-click a sixth-tier enchantment (or use the game's Refund All) to get it back.");
			DumpArt = config.Bind<bool>("Debug", "DumpArt", false, "Write the game's enchantment icons and how the Enchantments screen draws them to BepInEx/SpellBrigadeArcane-art/ (each time the screen has been open 1.5 s, max 3 times per session). Read-only development aid.");
			TestLevelOverride = config.Bind<string>("Debug", "TestLevels", "", "Test aid: missions use these levels instead of the ones you bought, e.g. \"Volley=6, Alchemy=6\" (6 = with its Mastery). Costs no gold and changes no save. Leave empty to play normally.");
			TestHotkeys = config.Bind<bool>("Debug", "TestHotkeys", false, "Test aid: in a mission, Ctrl+8 infuses one of your Spells with the next element (Fire, Ice, Acid, Lightning, Dark in turn), without the choice screen; Ctrl+9 drops a Health Potion next to you (host or solo).");
		}
	}
	internal static class ModLog
	{
		private static ManualLogSource? _log;

		private static StreamWriter? _file;

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

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

		public const string CleanExit = "clean exit";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		public const string Name = "SpellBrigadeArcane";

		public const string Version = "0.5.1";

		public static Harmony Harmony { get; private set; }

		public override void Load()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			ModLog.Init(((BasePlugin)this).Log);
			Harmony = new Harmony("com.stefanws0.spellbrigadearcane");
			ModLog.Step("Load: config");
			ModConfig.Init(((BasePlugin)this).Config);
			ModLog.Step("Load: registering ArcaneRunner");
			((BasePlugin)this).AddComponent<ArcaneRunner>();
			ModLog.Step("Load: done");
			ModLog.Info($"{"SpellBrigadeArcane"} {"0.5.1"} loaded. Scan: {(ModConfig.Scan.Value ? "ON" : "off")}.");
		}
	}
}
namespace SpellBrigadeArcane.Game
{
	internal static class ArcaneColumn
	{
		public const string ColumnName = "ARC_Upgrade_Tier_6";

		private static readonly Dictionary<ArcaneId, UpgradeIdentifier> PlaceholderIcons = new Dictionary<ArcaneId, UpgradeIdentifier>
		{
			[ArcaneId.Volley] = (UpgradeIdentifier)8,
			[ArcaneId.Reach] = (UpgradeIdentifier)1,
			[ArcaneId.Attunement] = (UpgradeIdentifier)0,
			[ArcaneId.Alchemy] = (UpgradeIdentifier)11
		};

		private static readonly Dictionary<ArcaneId, UpgradeButton> Buttons = new Dictionary<ArcaneId, UpgradeButton>();

		private static readonly List<Action> KeepAlive = new List<Action>();

		private static IntPtr _builtFor;

		private static GameObject? _column;

		public static bool IsBuilt(UpgradeBuyerUI buyer)
		{
			if ((Object)(object)_column != (Object)null)
			{
				return _builtFor == ((Il2CppObjectBase)buyer).Pointer;
			}
			return false;
		}

		public static void Build(UpgradeBuyerUI buyer, Action<ArcaneId> onHighlight, Action<ArcaneId> onClick, Action<ArcaneId> onMiddleClick)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			ModLog.Step("ArcaneColumn: building the sixth tier");
			List<UpgradeTierUI> tiers = buyer.tiers;
			UpgradeTierUI val = tiers[tiers.Count - 1];
			Transform parent = ((Component)val).transform.parent;
			Transform val2 = parent.Find("ARC_Upgrade_Tier_6");
			if ((Object)(object)val2 != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)val2).gameObject);
			}
			Buttons.Clear();
			KeepAlive.Clear();
			GameObject val3 = new GameObject("ARC_Holder");
			val3.SetActive(false);
			GameObject val4;
			try
			{
				val4 = Object.Instantiate<GameObject>(((Component)val).gameObject, val3.transform);
				((Object)val4).name = "ARC_Upgrade_Tier_6";
				UpgradeTierUI component = val4.GetComponent<UpgradeTierUI>();
				ModLog.Step("ArcaneColumn: removing the copy's UpgradeTierUI");
				if ((Object)(object)component != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)component);
				}
				ModLog.Step("ArcaneColumn: moving the copy next to Tier V");
				val4.transform.SetParent(parent, false);
				val4.transform.SetAsLastSibling();
			}
			finally
			{
				Object.Destroy((Object)(object)val3);
			}
			try
			{
				Il2CppArrayBase<UpgradeButton> componentsInChildren = val4.GetComponentsInChildren<UpgradeButton>(true);
				ArcaneId[] array = (ArcaneId[])Enum.GetValues(typeof(ArcaneId));
				if (componentsInChildren.Length < array.Length)
				{
					throw new InvalidOperationException($"Tier V's column has {componentsInChildren.Length} buttons, the sixth tier needs {array.Length}");
				}
				for (int i = 0; i < array.Length; i++)
				{
					Prepare(componentsInChildren[i], array[i], onHighlight, onClick, onMiddleClick);
				}
				LinkNavigation(val);
				_column = val4;
				_builtFor = ((Il2CppObjectBase)buyer).Pointer;
				try
				{
					LogListeners(val, componentsInChildren[0]);
				}
				catch (Exception ex)
				{
					ModLog.Warn("ArcaneColumn: could not read the buttons' listeners: " + ex.Message);
				}
				ModLog.Info("ArcaneColumn: sixth tier built at " + Ui.Path(val4.transform));
			}
			catch
			{
				Object.Destroy((Object)(object)val4);
				_column = null;
				Buttons.Clear();
				KeepAlive.Clear();
				throw;
			}
		}

		private static void LogListeners(UpgradeTierUI tierV, UpgradeButton ours)
		{
			ModLog.StepOnce("arcane-listeners", "ArcaneColumn: reading the buttons' listeners");
			UpgradeButton val = tierV.upgradeButtons[0];
			ModLog.Info($"ArcaneColumn: game button listeners: highlight [{Ui.Listeners((Delegate?)(object)((ButtonInteractionHook)val).OnHighlight)}], click [{Ui.Listeners((Delegate?)(object)((ButtonInteractionHook)val).OnClicked)}], middle [{Ui.Listeners((Delegate?)(object)((ButtonInteractionHook)val).OnMiddleMouseButtonClicked)}]");
			ModLog.Info($"ArcaneColumn: our button listeners: highlight [{Ui.Listeners((Delegate?)(object)((ButtonInteractionHook)ours).OnHighlight)}], click [{Ui.Listeners((Delegate?)(object)((ButtonInteractionHook)ours).OnClicked)}], middle [{Ui.Listeners((Delegate?)(object)((ButtonInteractionHook)ours).OnMiddleMouseButtonClicked)}]");
		}

		public static UpgradeButton? Button(ArcaneId id)
		{
			if (!Buttons.TryGetValue(id, out UpgradeButton value))
			{
				return null;
			}
			return value;
		}

		public static void Show(ArcaneId id, ButtonView view)
		{
			if (Buttons.TryGetValue(id, out UpgradeButton value) && !((Object)(object)value == (Object)null) && ((Behaviour)value).isActiveAndEnabled)
			{
				value.SetLevel(view.Level, view.MaxLevel);
				value.SetAffordableState(view.Unlocked && (view.Maxed || view.CanAfford));
				List<LockReason> val = new List<LockReason>();
				if (!view.Unlocked)
				{
					val.Add((LockReason)1);
				}
				value.UpdateLockState(val);
			}
		}

		public static void PlayFail(ArcaneId id)
		{
			if (Buttons.TryGetValue(id, out UpgradeButton value) && (Object)(object)value != (Object)null)
			{
				Animator animator = ((ClickableButton)value).Animator;
				if (animator != null)
				{
					animator.SetTrigger(UpgradeButton.UpgradeFailed);
				}
			}
		}

		public static void PlayRefund(ArcaneId id)
		{
			if (Buttons.TryGetValue(id, out UpgradeButton value) && (Object)(object)value != (Object)null)
			{
				value.TriggerSingleRefundAnimation();
			}
		}

		private static void Prepare(UpgradeButton button, ArcaneId id, Action<ArcaneId> onHighlight, Action<ArcaneId> onClick, Action<ArcaneId> onMiddleClick)
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			ModLog.StepOnce("arcane-prepare", "ArcaneColumn: first button setup");
			((Object)((Component)button).gameObject).name = "ARC_" + id;
			button.configuration = null;
			UpgradeConfiguration val = GameUpgrades.Configuration(PlaceholderIcons[id]);
			Sprite val2 = IconSprites.Icon(id);
			Sprite val3 = IconSprites.Glow(id);
			if ((Object)(object)val2 != (Object)null)
			{
				button.iconImage.sprite = val2;
			}
			else if ((Object)(object)val != (Object)null)
			{
				button.iconImage.sprite = val.Icon;
			}
			if ((Object)(object)val3 != (Object)null)
			{
				button.iconGlow.sprite = val3;
			}
			else if ((Object)(object)val != (Object)null)
			{
				button.iconGlow.sprite = val.Glow;
			}
			((ButtonInteractionHook)button).OnHighlight += Keep(delegate
			{
				onHighlight(id);
			});
			((ButtonInteractionHook)button).OnClicked += Keep(delegate
			{
				onClick(id);
			});
			((ButtonInteractionHook)button).OnMiddleMouseButtonClicked += Keep(delegate
			{
				onMiddleClick(id);
			});
			Buttons[id] = button;
		}

		private static Action Keep(Action action)
		{
			Action val = DelegateSupport.ConvertDelegate<Action>((Delegate)action) ?? throw new InvalidOperationException("DelegateSupport returned no delegate");
			KeepAlive.Add(val);
			return val;
		}

		private static void LinkNavigation(UpgradeTierUI tierV)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: 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_0065: Invalid comparison between Unknown and I4
			ModLog.StepOnce("arcane-nav", "ArcaneColumn: navigation");
			List<UpgradeButton> upgradeButtons = tierV.upgradeButtons;
			if (upgradeButtons == null || upgradeButtons.Count == 0)
			{
				return;
			}
			Mode mode = ((Selectable)((ButtonInteractionHook)upgradeButtons[0]).Button).navigation.mode;
			ModLog.Info($"ArcaneColumn: the game's enchantment buttons use navigation mode {mode}");
			if ((int)mode != 4)
			{
				return;
			}
			List<UpgradeButton> list = new List<UpgradeButton>();
			foreach (ArcaneId value in Enum.GetValues(typeof(ArcaneId)))
			{
				list.Add(Buttons[value]);
			}
			for (int i = 0; i < list.Count; i++)
			{
				Navigation navigation = ((Selectable)((ButtonInteractionHook)list[i]).Button).navigation;
				navigation.mode = (Mode)4;
				navigation.selectOnUp = (Selectable)(object)((i > 0) ? ((ButtonInteractionHook)list[i - 1]).Button : null);
				navigation.selectOnDown = (Selectable)(object)((i < list.Count - 1) ? ((ButtonInteractionHook)list[i + 1]).Button : null);
				navigation.selectOnLeft = (Selectable)(object)((i < upgradeButtons.Count) ? ((ButtonInteractionHook)upgradeButtons[i]).Button : null);
				((Selectable)((ButtonInteractionHook)list[i]).Button).navigation = navigation;
				if (i < upgradeButtons.Count)
				{
					Navigation navigation2 = ((Selectable)((ButtonInteractionHook)upgradeButtons[i]).Button).navigation;
					navigation2.selectOnRight = (Selectable)(object)((ButtonInteractionHook)list[i]).Button;
					((Selectable)((ButtonInteractionHook)upgradeButtons[i]).Button).navigation = navigation2;
				}
			}
		}
	}
	internal static class ArcaneDetails
	{
		private const float HiddenMasteryOpacity = 0.2f;

		public static void Show(UpgradeDetailsUI details, EnchantmentDef def, ButtonView view, int masteries)
		{
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			ModLog.StepOnce("arcane-details", "ArcaneDetails: first fill of the details panel");
			details.nameText.text = def.Name;
			details.titleLevelText.text = ArcaneText.Level(view.Level);
			if (view.Maxed)
			{
				details.SetTitleColorForMaxLevel();
			}
			else
			{
				details.SetDefaultTitleColor();
			}
			TMP_Text val = (((Object)(object)details.descriptionStringLocalizer != (Object)null) ? ((Component)details.descriptionStringLocalizer).GetComponent<TMP_Text>() : null);
			if ((Object)(object)val != (Object)null)
			{
				val.text = (view.Unlocked ? def.Description : (ArcaneText.Locked(masteries, 12) + "\n" + def.Description));
			}
			ShowStats(details, def, view);
			details.finalUpgradeDescription.text = (view.MasteryRevealed ? ArcaneText.Mastery(def.MasteryName, def.MasteryText) : ArcaneText.MasteryHidden(def.MasteryRevealLevel));
			details.SetFinalUpgradeOpacity(view.MasteryRevealed ? 1f : 0.2f);
			TMP_Text costText = details.costText;
			((Component)costText.transform.parent).gameObject.SetActive(view.Unlocked && !view.Maxed);
			costText.text = ArcaneText.Price(view.Price);
			((Graphic)costText).color = (view.CanAfford ? details.canAffordTextColor : details.cannotAffordTextColor);
			if ((Object)(object)details.animator != (Object)null)
			{
				details.animator.SetBool(UpgradeDetailsUI.IsMastered, view.Maxed);
			}
		}

		private static void ShowStats(UpgradeDetailsUI details, EnchantmentDef def, ButtonView view)
		{
			details.HideAllStatUpgradeUIElements();
			List<StatUpgradeUIElement> statUpgradeUIElements = details.statUpgradeUIElements;
			bool flag = view.Level >= def.StatLevels;
			for (int i = 0; i < def.Gains.Count && i < statUpgradeUIElements.Count; i++)
			{
				StatGain statGain = def.Gains[i];
				StatUpgradeUIElement val = statUpgradeUIElements[i];
				((Component)val).gameObject.SetActive(true);
				val.statName.text = statGain.Label;
				string text = ArcaneText.Percent(def.PercentAt(statGain.Stat, view.Level));
				val.currentStatPanel.SetActive(flag);
				val.currentToNextStatPanel.SetActive(!flag);
				for (int j = 0; j < val.currentValues.Count; j++)
				{
					val.currentValues[j].text = text;
				}
				val.nextValue.text = ArcaneText.Percent(def.PercentAt(statGain.Stat, view.Level + 1));
			}
		}
	}
	internal static class ArcaneShop
	{
		private const float Interval = 0.25f;

		private const float FindInterval = 2f;

		private static float _next;

		private static float _nextFind;

		private static UpgradeBuyerUI? _buyer;

		private static bool _wasOpen;

		private static int _lastGold = -1;

		private static int _lastTotal = -1;

		private static bool _broken;

		private static IntPtr _refundHookedOn;

		private static Action? _refundHandler;

		public static void Tick(float now)
		{
			ArcaneState.FlushIfDirty();
			if (_broken || now < _next)
			{
				return;
			}
			_next = now + 0.25f;
			if ((Object)(object)_buyer == (Object)null)
			{
				if (now < _nextFind)
				{
					return;
				}
				_nextFind = now + 2f;
				ModLog.StepOnce("shop-find", "ArcaneShop: first FindObjectsOfType");
				_buyer = FindReadyBuyer();
				if ((Object)(object)_buyer == (Object)null)
				{
					return;
				}
			}
			UpgradeBuyerUI buyer = _buyer;
			if (!ArcaneState.EnsureLoaded())
			{
				return;
			}
			if (!ArcaneColumn.IsBuilt(buyer))
			{
				try
				{
					ArcaneColumn.Build(buyer, OnHighlight, OnClick, OnMiddleClick);
				}
				catch (Exception value)
				{
					_broken = true;
					ModLog.Error($"ArcaneShop: could not build the sixth tier; it stays off this session: {value}");
					return;
				}
				try
				{
					HookRefundAll();
				}
				catch (Exception ex)
				{
					ModLog.Warn($"ArcaneShop: Refund All won't refund the sixth tier this session; middle-click still does ({ex.GetType().Name}: {ex.Message})");
				}
				SafeRefresh(now);
			}
			bool isOpen = ((Panel)buyer).IsOpen;
			if (isOpen && !_wasOpen)
			{
				ArcaneState.CheckGameSave();
				if (ArcaneState.Current == null)
				{
					_wasOpen = false;
					return;
				}
			}
			int gold = GameUpgrades.Gold;
			int totalBought = GameUpgrades.TotalBought;
			if (isOpen && !_wasOpen)
			{
				LogOpened();
			}
			if (isOpen && (!_wasOpen || gold != _lastGold || totalBought != _lastTotal))
			{
				SafeRefresh(now);
			}
			_wasOpen = isOpen;
			_lastGold = gold;
			_lastTotal = totalBought;
		}

		private static void SafeRefresh(float now)
		{
			try
			{
				Refresh();
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("arcane-refresh", ex, now);
			}
		}

		private static void LogOpened()
		{
			try
			{
				Progress current = ArcaneState.Current;
				if (current == null)
				{
					return;
				}
				int num = GameUpgrades.Masteries();
				List<string> list = new List<string>();
				foreach (ArcaneId value in Enum.GetValues(typeof(ArcaneId)))
				{
					list.Add($"{value} {GameUpgrades.Price(current.Level(value), current.TotalLevels)}");
				}
				ModLog.Info($"ArcaneShop: screen opened: {num} Mastery/Masteries, unlocked={ArcaneState.IsUnlocked(num)}, gold {GameUpgrades.Gold}, game levels bought {GameUpgrades.TotalBought}, next prices: {string.Join(", ", list)}");
			}
			catch (Exception ex)
			{
				ModLog.Warn("ArcaneShop: could not log the opened screen: " + ex.Message);
			}
		}

		private static void RefreshGameButtons()
		{
			try
			{
				UpgradeBuyerUI? buyer = _buyer;
				if (buyer != null)
				{
					buyer.RefreshButtons();
				}
			}
			catch (Exception ex)
			{
				ModLog.WarnOnce("shop-refresh-buttons", "ArcaneShop: RefreshButtons failed: " + ex.Message);
			}
		}

		private static UpgradeBuyerUI? FindReadyBuyer()
		{
			foreach (Object item in (Il2CppArrayBase<Object>)(object)Object.FindObjectsOfType(Il2CppType.Of<UpgradeBuyerUI>(), true))
			{
				UpgradeBuyerUI val = ((item != null) ? ((Il2CppObjectBase)item).TryCast<UpgradeBuyerUI>() : null);
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				List<UpgradeTierUI> tiers = val.tiers;
				if (tiers != null && tiers.Count != 0 && val.upgradeButtons != null && val.upgradeButtons.Count != 0)
				{
					List<UpgradeButton> upgradeButtons = tiers[0].upgradeButtons;
					if (upgradeButtons != null && upgradeButtons.Count != 0 && !((Object)(object)upgradeButtons[0].configuration == (Object)null))
					{
						return val;
					}
				}
			}
			return null;
		}

		private static ButtonView View(ArcaneId id, Progress progress, bool unlocked, int gold)
		{
			return ButtonView.For(ArcaneState.Def(id), progress, unlocked, gold, GameUpgrades.Price(progress.Level(id), progress.TotalLevels));
		}

		private static void Refresh()
		{
			Progress current = ArcaneState.Current;
			if (current == null)
			{
				return;
			}
			ModLog.StepOnce("shop-refresh", "ArcaneShop: first refresh");
			bool unlocked = ArcaneState.IsUnlocked(GameUpgrades.Masteries());
			int gold = GameUpgrades.Gold;
			foreach (ArcaneId value in Enum.GetValues(typeof(ArcaneId)))
			{
				ArcaneColumn.Show(value, View(value, current, unlocked, gold));
			}
		}

		private static void OnHighlight(ArcaneId id)
		{
			try
			{
				UpgradeButton val = ArcaneColumn.Button(id);
				if ((Object)(object)_buyer != (Object)null && (Object)(object)val != (Object)null)
				{
					_buyer.currentHighlightedUpgradeButton = val;
				}
				Progress current = ArcaneState.Current;
				UpgradeBuyerUI? buyer = _buyer;
				UpgradeDetailsUI val2 = ((buyer != null) ? buyer.upgradeDetailsUI : null);
				if (current != null && !((Object)(object)val2 == (Object)null))
				{
					int masteries = GameUpgrades.Masteries();
					ButtonView view = View(id, current, ArcaneState.IsUnlocked(masteries), GameUpgrades.Gold);
					ArcaneDetails.Show(val2, ArcaneState.Def(id), view, masteries);
				}
			}
			catch (Exception value)
			{
				ModLog.Error($"ArcaneShop: showing {id} failed: {value}");
			}
		}

		private static void OnClick(ArcaneId id)
		{
			try
			{
				Buy(id);
			}
			catch (Exception value)
			{
				ModLog.Error($"ArcaneShop: buying {id} failed: {value}");
				ArcaneState.Discard();
			}
		}

		private static void OnMiddleClick(ArcaneId id)
		{
			try
			{
				RefundOne(id);
			}
			catch (Exception value)
			{
				ModLog.Error($"ArcaneShop: refunding {id} failed: {value}");
				ArcaneState.Discard();
			}
		}

		private static void Buy(ArcaneId id)
		{
			ArcaneState.CheckGameSave();
			Progress current = ArcaneState.Current;
			if (current == null)
			{
				Fail(id, "the sixth tier's save isn't loaded");
				return;
			}
			if (!GameUpgrades.CanSaveGame)
			{
				Fail(id, "the game can't save right now");
				return;
			}
			ButtonView buttonView = View(id, current, ArcaneState.IsUnlocked(GameUpgrades.Masteries()), GameUpgrades.Gold);
			if (buttonView.Check != BuyResult.Ok)
			{
				Fail(id, buttonView.Check.ToString());
				return;
			}
			ModLog.Step($"ArcaneShop: buying {id} level {buttonView.Level + 1} for {buttonView.Price}");
			int gold = GameUpgrades.Gold;
			if (!current.TryBuy(id, buttonView.Price))
			{
				Fail(id, "already maxed");
				return;
			}
			if (!ArcaneState.Save())
			{
				current.RefundLast(id);
				Fail(id, "our save could not be written");
				return;
			}
			GameUpgrades.Spend(buttonView.Price);
			GameUpgrades.SaveGame();
			UpgradeBuyerUI? buyer = _buyer;
			if (buyer != null)
			{
				UpgradeBuyerSoundPlayer soundPlayer = buyer.soundPlayer;
				if (soundPlayer != null)
				{
					soundPlayer.PlayUpgradeDoneSound(current.IsMaxed(id));
				}
			}
			ModLog.Info($"ArcaneShop: bought {id} level {current.Level(id)} for {buttonView.Price} gold; gold {gold} -> {GameUpgrades.Gold}, game levels bought {GameUpgrades.TotalBought}.");
			RefreshGameButtons();
			Refresh();
			OnHighlight(id);
		}

		private static void RefundOne(ArcaneId id)
		{
			ArcaneState.CheckGameSave();
			Progress current = ArcaneState.Current;
			if (current == null || current.Level(id) == 0)
			{
				return;
			}
			if (!GameUpgrades.CanSaveGame)
			{
				ModLog.Warn($"ArcaneShop: not refunding {id}: the game can't save right now.");
				return;
			}
			ModLog.Step($"ArcaneShop: refunding one level of {id}");
			int gold = GameUpgrades.Gold;
			int num = current.RefundLast(id);
			GameUpgrades.Give(num);
			if (!GameUpgrades.SaveGame())
			{
				current.TryBuy(id, num);
				GameUpgrades.Spend(num);
				ModLog.Warn($"ArcaneShop: refund of {id} undone, the game could not be asked to save.");
				return;
			}
			ArcaneState.MarkDirty();
			ArcaneColumn.PlayRefund(id);
			ModLog.Info($"ArcaneShop: refunded {id} to level {current.Level(id)}, {num} gold back; gold {gold} -> {GameUpgrades.Gold}, game levels bought {GameUpgrades.TotalBought}.");
			RefreshGameButtons();
			Refresh();
			OnHighlight(id);
		}

		private static void HookRefundAll()
		{
			UpgradeManager manager = GameUpgrades.Manager;
			if (!(((Il2CppObjectBase)manager).Pointer == _refundHookedOn))
			{
				ModLog.Step("ArcaneShop: hooking the game's Refund All");
				if (_refundHandler == null)
				{
					_refundHandler = DelegateSupport.ConvertDelegate<Action>((Delegate)new Action(OnGameRefundAll));
				}
				manager.OnUpgradesRefunded = ((Il2CppObjectBase)Delegate.Combine((Delegate)(object)manager.OnUpgradesRefunded, (Delegate)(object)_refundHandler)).Cast<Action>();
				_refundHookedOn = ((Il2CppObjectBase)manager).Pointer;
			}
		}

		private static void OnGameRefundAll()
		{
			try
			{
				int totalBought = GameUpgrades.TotalBought;
				if (totalBought != 0)
				{
					ModLog.Info($"ArcaneShop: Refund All event: game levels still {totalBought}, so only a partial refund; sixth tier left as it is.");
					return;
				}
				ArcaneState.CheckGameSave();
				Progress current = ArcaneState.Current;
				if (current == null || current.TotalLevels == 0)
				{
					ModLog.Info("ArcaneShop: Refund All event: nothing to refund in the sixth tier (" + ((current == null) ? "save not loaded" : "no levels") + ").");
					return;
				}
				if (!GameUpgrades.CanSaveGame)
				{
					ModLog.Warn("ArcaneShop: Refund All left the sixth tier as it is: the game can't save right now (middle-click to refund).");
					return;
				}
				ModLog.Step("ArcaneShop: Refund All");
				int totalLevels = current.TotalLevels;
				int gold = GameUpgrades.Gold;
				int num = current.RefundAll();
				GameUpgrades.Give(num);
				if (!GameUpgrades.SaveGame())
				{
					GameUpgrades.Spend(num);
					ArcaneState.Discard();
					ArcaneState.EnsureLoaded();
					ModLog.Warn("ArcaneShop: Refund All of the sixth tier undone, the game could not be asked to save.");
					return;
				}
				ArcaneState.MarkDirty();
				ModLog.Info($"ArcaneShop: Refund All gave back {num} gold for {totalLevels} sixth-tier level(s); gold {gold} -> {GameUpgrades.Gold}, game levels bought {GameUpgrades.TotalBought}.");
				Refresh();
			}
			catch (Exception value)
			{
				ModLog.Error($"ArcaneShop: Refund All of the sixth tier failed: {value}");
				ArcaneState.Discard();
			}
		}

		private static void Fail(ArcaneId id, string why)
		{
			ModLog.Info($"ArcaneShop: can't buy {id}: {why}");
			UpgradeBuyerUI? buyer = _buyer;
			if (buyer != null)
			{
				UpgradeBuyerSoundPlayer soundPlayer = buyer.soundPlayer;
				if (soundPlayer != null)
				{
					soundPlayer.PlayUpgradeFailSound();
				}
			}
			ArcaneColumn.PlayFail(id);
		}
	}
	internal static class ArcaneState
	{
		public static readonly IReadOnlyList<EnchantmentDef> Defs = Catalog.Build();

		private const float WaitSeconds = 1f;

		private const float ErrorSeconds = 5f;

		private static long? _gameStamp;

		private static float _nextTry;

		private static bool _firstLoadLogged;

		private static bool _dirty;

		private static bool _flushFailed;

		private static bool _saveFailing;

		private static int _dirtyFrame;

		private static float _dirtySince;

		private static float _nextFlush;

		public static Progress? Current { get; private set; }

		public static string SavePath => Path.Combine(Paths.ConfigPath, "SpellBrigadeArcane", "save.json");

		public static EnchantmentDef Def(ArcaneId id)
		{
			return Catalog.Get(Defs, id);
		}

		public static bool IsUnlocked(int masteries)
		{
			return Progress.IsUnlocked(masteries, 12, ModConfig.UnlockRow.Value);
		}

		private static string AsDate(long? ticks)
		{
			if (!ticks.HasValue)
			{
				return "none";
			}
			try
			{
				return new DateTime(ticks.Value).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) + $" ({ticks.Value})";
			}
			catch (Exception)
			{
				return ticks.Value.ToString(CultureInfo.InvariantCulture);
			}
		}

		public static bool EnsureLoaded()
		{
			if (Current != null)
			{
				return true;
			}
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime < _nextTry)
			{
				return false;
			}
			_nextTry = unscaledTime + 5f;
			if (!GameUpgrades.IsReady)
			{
				_nextTry = unscaledTime + 1f;
				ModLog.InfoOnce("arcane-wait", "ArcaneState: waiting for the game's save to load");
				return false;
			}
			ModLog.StepOnce("arcane-load", "ArcaneState: first load of " + SavePath);
			SaveData saveData;
			try
			{
				saveData = SaveFile.Read(SavePath, out string note);
				if (note != null)
				{
					ModLog.WarnOnce("arcane-load-note-" + note, "ArcaneState: " + note);
				}
			}
			catch (Exception ex)
			{
				ModLog.WarnOnce("arcane-load-failed", $"ArcaneState: can't load the sixth tier yet ({ex.GetType().Name}: {ex.Message}); retrying.");
				return false;
			}
			long saveClearedTicks;
			try
			{
				saveClearedTicks = GameUpgrades.SaveClearedTicks;
				if (!_firstLoadLogged)
				{
					_firstLoadLogged = true;
					ModLog.Info($"ArcaneState: game is initialised; save stamp {AsDate(saveClearedTicks)}, gold {GameUpgrades.Gold}, {GameUpgrades.TotalBought} level(s) bought.");
				}
			}
			catch (Exception ex2)
			{
				ModLog.WarnOnce("arcane-stamp-failed", $"ArcaneState: can't read the game's save stamp yet ({ex2.GetType().Name}: {ex2.Message}); retrying.");
				return false;
			}
			LoadResult loadResult = LoadRules.Decide(Defs, saveData, saveClearedTicks);
			foreach (string note2 in loadResult.Notes)
			{
				ModLog.WarnOnce("arcane-note-" + note2, "ArcaneState: " + note2);
			}
			if (loadResult.WasReset)
			{
				long? gameSaveClearedTicks = saveData.GameSaveClearedTicks;
				string text = gameSaveClearedTicks?.ToString(CultureInfo.InvariantCulture) ?? "unknown";
				string text2 = SavePath + ".reset-" + text;
				try
				{
					SaveFile.Write(text2, saveData);
				}
				catch (Exception ex3)
				{
					ModLog.WarnOnce("arcane-reset-copy-" + text, $"ArcaneState: could not keep a copy of the old save at {text2} ({ex3.GetType().Name}: {ex3.Message}); retrying, the reset can't be undone without it.");
					return false;
				}
				int excessGold;
				List<string> notes;
				Progress progress = Progress.FromSave(Defs, saveData, out excessGold, out notes);
				ModLog.WarnOnce("arcane-reset-" + text, $"ArcaneState: the game's save was reset (our save was for {AsDate(gameSaveClearedTicks)}, the game's is now {AsDate(saveClearedTicks)}); dropping {progress.TotalLevels} sixth-tier level(s) / {progress.TotalPaid} gold (no gold back: the reset took the gold too). Old file kept at {text2}.");
			}
			if (loadResult.ExcessGold > 0 && !GameUpgrades.CanSaveGame)
			{
				ModLog.InfoOnce("arcane-excess-wait", "ArcaneState: waiting for the game to be able to save before refunding excess gold.");
				return false;
			}
			_gameStamp = loadResult.StampToWrite;
			Current = loadResult.Progress;
			if (!Save())
			{
				Current = null;
				return false;
			}
			if (loadResult.ExcessGold > 0)
			{
				try
				{
					ModLog.StepOnce("arcane-excess", "ArcaneState: refunding excess gold");
					GameUpgrades.Give(loadResult.ExcessGold);
					if (GameUpgrades.SaveGame())
					{
						MarkDirty();
					}
					ModLog.Info($"ArcaneState: refunded {loadResult.ExcessGold} gold for levels above the max level.");
				}
				catch (Exception ex4)
				{
					ModLog.Error($"ArcaneState: refunding {loadResult.ExcessGold} gold for levels above the max level failed ({ex4.GetType().Name}: {ex4.Message}); add that gold back by hand.");
				}
			}
			ModLog.Info($"ArcaneState: loaded {loadResult.Progress.TotalLevels} sixth-tier level(s), {loadResult.Progress.TotalPaid} gold paid in total.");
			return true;
		}

		public static void CheckGameSave()
		{
			if (Current == null || !GameUpgrades.IsReady)
			{
				return;
			}
			long saveClearedTicks;
			try
			{
				saveClearedTicks = GameUpgrades.SaveClearedTicks;
			}
			catch (Exception)
			{
				return;
			}
			if (saveClearedTicks > 0)
			{
				if (!_gameStamp.HasValue)
				{
					_gameStamp = saveClearedTicks;
				}
				else if (saveClearedTicks != _gameStamp)
				{
					ModLog.Warn("ArcaneState: the game's save changed during the session; reloading the sixth tier.");
					Discard();
				}
			}
		}

		public static void MarkDirty()
		{
			_dirty = true;
			_dirtyFrame = Time.frameCount;
			_dirtySince = Time.unscaledTime;
		}

		public static void FlushIfDirty()
		{
			if (!_dirty || Time.frameCount < _dirtyFrame + 2 || Time.unscaledTime < _dirtySince + 0.5f || (_flushFailed && Time.unscaledTime < _nextFlush))
			{
				return;
			}
			if (Current == null)
			{
				_dirty = false;
				return;
			}
			if (Save())
			{
				_dirty = false;
				_flushFailed = false;
			}
			else if (!_flushFailed)
			{
				_flushFailed = true;
				ModLog.Warn("ArcaneState: the delayed save failed; retrying every second until it works.");
			}
			if (_dirty)
			{
				_nextFlush = Time.unscaledTime + 1f;
			}
		}

		public static bool Save()
		{
			if (Current == null)
			{
				return false;
			}
			try
			{
				SaveData saveData = Current.ToSave();
				saveData.GameSaveClearedTicks = _gameStamp;
				SaveFile.Write(SavePath, saveData);
				_dirty = false;
				_saveFailing = false;
				return true;
			}
			catch (Exception ex)
			{
				if (!_saveFailing)
				{
					_saveFailing = true;
					ModLog.Error($"ArcaneState: could not write {SavePath}: {ex.GetType().Name}: {ex.Message}");
				}
				return false;
			}
		}

		public static void Discard()
		{
			Current = null;
			_nextTry = 0f;
		}
	}
	internal static class ArtDump
	{
		private const float OpenDelay = 1.5f;

		private const int MaxReports = 3;

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

		private static float _nextFind;

		private static UpgradeBuyerUI? _buyer;

		private static float _openSince = -1f;

		private static bool _reportedThisOpen;

		private static int _reports;

		public static string Folder => Path.Combine(Paths.BepInExRootPath, "SpellBrigadeArcane-art");

		public static void Tick(float now)
		{
			if (_reports >= 3)
			{
				return;
			}
			if ((Object)(object)_buyer == (Object)null)
			{
				if (now < _nextFind)
				{
					return;
				}
				_nextFind = now + 2f;
				foreach (Object item in (Il2CppArrayBase<Object>)(object)Object.FindObjectsOfType(Il2CppType.Of<UpgradeBuyerUI>(), true))
				{
					_buyer = ((item != null) ? ((Il2CppObjectBase)item).TryCast<UpgradeBuyerUI>() : null);
					if ((Object)(object)_buyer != (Object)null)
					{
						break;
					}
				}
				if ((Object)(object)_buyer == (Object)null)
				{
					return;
				}
			}
			if (!((Panel)_buyer).IsOpen)
			{
				_openSince = -1f;
				_reportedThisOpen = false;
				return;
			}
			if (_openSince < 0f)
			{
				_openSince = now;
			}
			if (!_reportedThisOpen && !(now - _openSince < 1.5f) && GameUpgrades.IsReady)
			{
				_reportedThisOpen = true;
				_reports++;
				ModLog.Step($"ArtDump: report {_reports}");
				Report(_buyer, _reports);
			}
		}

		private static void Report(UpgradeBuyerUI buyer, int number)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			Directory.CreateDirectory(Folder);
			List<string> list = new List<string> { $"Art dump {number}, {DateTime.Now:yyyy-MM-dd HH:mm:ss}" };
			if (number == 1)
			{
				list.Add("");
				list.Add("== Enchantment sprites (rects in texture pixels, origin bottom-left)");
				foreach (UpgradeIdentifier id in Enum.GetValues(typeof(UpgradeIdentifier)))
				{
					UpgradeConfiguration val = Safe(() => GameUpgrades.Configuration(id));
					if ((Object)(object)val == (Object)null)
					{
						list.Add($"{id}: no configuration");
						continue;
					}
					list.Add($"{id}: icon {Describe(val.Icon)}");
					list.Add($"{id}: glow {Describe(val.Glow)}");
					DumpTexture(val.Icon, list);
					DumpTexture(val.Glow, list);
				}
			}
			UpgradeButton val2 = null;
			UpgradeButton val3 = null;
			Enumerator<UpgradeTierUI> enumerator2 = buyer.tiers.GetEnumerator();
			while (enumerator2.MoveNext())
			{
				UpgradeTierUI current = enumerator2.Current;
				if ((Object)(object)current == (Object)null)
				{
					continue;
				}
				Enumerator<UpgradeButton> enumerator3 = current.upgradeButtons.GetEnumerator();
				while (enumerator3.MoveNext())
				{
					UpgradeButton current2 = enumerator3.Current;
					if ((Object)(object)current2 == (Object)null)
					{
						continue;
					}
					if (current2.maxLevelAchieved)
					{
						if (val2 == null)
						{
							val2 = current2;
						}
					}
					else if (val3 == null)
					{
						val3 = current2;
					}
				}
			}
			if ((Object)(object)val2 != (Object)null)
			{
				DescribeButton("game button, Mastered", val2, list, number == 1);
			}
			if ((Object)(object)val3 != (Object)null)
			{
				DescribeButton("game button, not Mastered", val3, list, number == 1);
			}
			UpgradeTierUI obj = buyer.tiers[buyer.tiers.Count - 1];
			object obj2;
			if (obj == null)
			{
				obj2 = null;
			}
			else
			{
				Transform parent = ((Component)obj).transform.parent;
				obj2 = ((parent != null) ? parent.Find("ARC_Upgrade_Tier_6") : null);
			}
			Transform val4 = (Transform)obj2;
			if ((Object)(object)val4 != (Object)null)
			{
				foreach (UpgradeButton componentsInChild in ((Component)val4).GetComponentsInChildren<UpgradeButton>(true))
				{
					DescribeButton("our button " + ((Object)((Component)componentsInChild).gameObject).name, componentsInChild, list, dumpTextures: false);
				}
			}
			else
			{
				list.Add("our column: not found");
			}
			string text = Path.Combine(Folder, $"report{number}.txt");
			File.WriteAllLines(text, list);
			ModLog.Info($"ArtDump: wrote {text} ({DumpedTextures.Count} texture(s) so far)");
		}

		private static void DescribeButton(string label, UpgradeButton button, List<string> lines, bool dumpTextures)
		{
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Expected I4, but got Unknown
			//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_052a: Unknown result type (might be due to invalid IL or missing references)
			//IL_056e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0573: Unknown result type (might be due to invalid IL or missing references)
			//IL_0596: Unknown result type (might be due to invalid IL or missing references)
			//IL_059b: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0612: Unknown result type (might be due to invalid IL or missing references)
			//IL_063b: Unknown result type (might be due to invalid IL or missing references)
			lines.Add("");
			lines.Add("== " + label + ": " + Ui.Path(((Component)button).transform));
			lines.Add($"  canAfford={button.canAfford} maxLevelAchieved={button.maxLevelAchieved} config={Safe(delegate
			{
				UpgradeConfiguration configuration = button.configuration;
				return (configuration == null) ? null : ((Object)configuration).name;
			}) ?? "null"}");
			lines.Add("  iconImage=" + (Safe(() => Ui.Path(((Component)button.iconImage).transform)) ?? "null") + " iconGlow=" + (Safe(() => Ui.Path(((Component)button.iconGlow).transform)) ?? "null"));
			Animator animator = ((ClickableButton)button).Animator;
			if ((Object)(object)animator != (Object)null)
			{
				lines.Add($"  animator enabled={((Behaviour)animator).isActiveAndEnabled} controller={Safe(delegate
				{
					RuntimeAnimatorController runtimeAnimatorController = animator.runtimeAnimatorController;
					return (runtimeAnimatorController == null) ? null : ((Object)runtimeAnimatorController).name;
				}) ?? "null"} state={Safe((Func<object?>)delegate
				{
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
					return ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash;
				})} t={Safe((Func<object?>)delegate
				{
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
					return ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime;
				})}");
				foreach (AnimatorControllerParameter item in (Il2CppArrayBase<AnimatorControllerParameter>)(object)animator.parameters)
				{
					AnimatorControllerParameterType type = item.type;
					string value = (type - 1) switch
					{
						3 => animator.GetBool(item.nameHash).ToString(), 
						2 => animator.GetInteger(item.nameHash).ToString(), 
						0 => animator.GetFloat(item.nameHash).ToString("0.###"), 
						_ => "(trigger)", 
					};
					lines.Add($"  param {item.name} ({item.type}) = {value}");
				}
			}
			foreach (CanvasGroup componentsInChild in ((Component)button).GetComponentsInChildren<CanvasGroup>(true))
			{
				lines.Add($"  canvasGroup {Rel(button, ((Component)componentsInChild).transform)} alpha={componentsInChild.alpha:0.###}");
			}
			foreach (Image image in ((Component)button).GetComponentsInChildren<Image>(true))
			{
				RectTransform rectTransform = ((Graphic)image).rectTransform;
				IntPtr pointer = ((Il2CppObjectBase)image).Pointer;
				Image iconImage = button.iconImage;
				IntPtr? obj = ((iconImage != null) ? new IntPtr?(((Il2CppObjectBase)iconImage).Pointer) : ((IntPtr?)null));
				object obj3;
				if (!(pointer == obj))
				{
					pointer = ((Il2CppObjectBase)image).Pointer;
					Image iconGlow = button.iconGlow;
					IntPtr? obj2 = ((iconGlow != null) ? new IntPtr?(((Il2CppObjectBase)iconGlow).Pointer) : ((IntPtr?)null));
					obj3 = ((pointer == obj2) ? " [iconGlow]" : "");
				}
				else
				{
					obj3 = " [iconImage]";
				}
				string value2 = (string)obj3;
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(108, 15);
				defaultInterpolatedStringHandler.AppendLiteral("  image ");
				defaultInterpolatedStringHandler.AppendFormatted(Rel(button, ((Component)image).transform));
				defaultInterpolatedStringHandler.AppendFormatted(value2);
				defaultInterpolatedStringHandler.AppendLiteral(": active=");
				defaultInterpolatedStringHandler.AppendFormatted(((Component)image).gameObject.activeInHierarchy);
				defaultInterpolatedStringHandler.AppendLiteral(" enabled=");
				defaultInterpolatedStringHandler.AppendFormatted(((Behaviour)image).enabled);
				defaultInterpolatedStringHandler.AppendLiteral(" ");
				defaultInterpolatedStringHandler.AppendLiteral("color=");
				defaultInterpolatedStringHandler.AppendFormatted(Color(((Graphic)image).color));
				defaultInterpolatedStringHandler.AppendLiteral(" canvasAlpha=");
				defaultInterpolatedStringHandler.AppendFormatted<object>(Safe((Func<object?>)(() => ((Graphic)image).canvasRenderer.GetAlpha())));
				defaultInterpolatedStringHandler.AppendLiteral(" size=");
				Rect rect = rectTransform.rect;
				defaultInterpolatedStringHandler.AppendFormatted(((Rect)(ref rect)).width, "0.#");
				defaultInterpolatedStringHandler.AppendLiteral("x");
				rect = rectTransform.rect;
				defaultInterpolatedStringHandler.AppendFormatted(((Rect)(ref rect)).height, "0.#");
				defaultInterpolatedStringHandler.AppendLiteral(" ");
				defaultInterpolatedStringHandler.AppendLiteral("pos=(");
				defaultInterpolatedStringHandler.AppendFormatted(rectTransform.anchoredPosition.x, "0.#");
				defaultInterpolatedStringHandler.AppendLiteral(",");
				defaultInterpolatedStringHandler.AppendFormatted(rectTransform.anchoredPosition.y, "0.#");
				defaultInterpolatedStringHandler.AppendLiteral(") scale=");
				defaultInterpolatedStringHandler.AppendFormatted(((Transform)rectTransform).localScale.x, "0.###");
				defaultInterpolatedStringHandler.AppendLiteral(" type=");
				defaultInterpolatedStringHandler.AppendFormatted<Type>(image.type);
				defaultInterpolatedStringHandler.AppendLiteral(" ");
				defaultInterpolatedStringHandler.AppendLiteral("preserveAspect=");
				defaultInterpolatedStringHandler.AppendFormatted(image.preserveAspect);
				defaultInterpolatedStringHandler.AppendLiteral(" material=");
				defaultInterpolatedStringHandler.AppendFormatted(Safe(delegate
				{
					Material material = ((Graphic)image).material;
					return (material == null) ? null : ((Object)material).name;
				}) ?? "null");
				defaultInterpolatedStringHandler.AppendLiteral(" sprite ");
				defaultInterpolatedStringHandler.AppendFormatted(Describe(image.sprite));
				lines.Add(defaultInterpolatedStringHandler.ToStringAndClear());
				if (dumpTextures)
				{
					DumpTexture(image.sprite, lines);
				}
			}
		}

		private static string Rel(UpgradeButton button, Transform t)
		{
			List<string> list = new List<string>();
			Transform val = t;
			while ((Object)(object)val != (Object)null && ((Il2CppObjectBase)val).Pointer != ((Il2CppObjectBase)((Component)button).transform).Pointer)
			{
				list.Add(((Object)((Component)val).gameObject).name);
				val = val.parent;
			}
			list.Reverse();
			if (list.Count != 0)
			{
				return string.Join("/", list);
			}
			return ".";
		}

		private static string Describe(Sprite? sprite)
		{
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)sprite == (Object)null)
			{
				return "null";
			}
			Texture2D texture = sprite.texture;
			object value = Safe((Func<object?>)(() => RectText(sprite.textureRect))) ?? "n/a";
			return $"'{((Object)sprite).name}' tex='{((texture != null) ? ((Object)texture).name : null)}' {((texture != null) ? new int?(((Texture)texture).width) : ((int?)null))}x{((texture != null) ? new int?(((Texture)texture).height) : ((int?)null))} rect={RectText(sprite.rect)} textureRect={value} pivot=({sprite.pivot.x:0.#},{sprite.pivot.y:0.#}) ppu={sprite.pixelsPerUnit:0.#} packed={sprite.packed} border=({sprite.border.x:0},{sprite.border.y:0},{sprite.border.z:0},{sprite.border.w:0})";
		}

		private static string RectText(Rect r)
		{
			return $"({((Rect)(ref r)).x:0.#},{((Rect)(ref r)).y:0.#} {((Rect)(ref r)).width:0.#}x{((Rect)(ref r)).height:0.#})";
		}

		private static string Color(Color c)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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_0071: Unknown result type (might be due to invalid IL or missing references)
			return $"({c.r:0.###},{c.g:0.###},{c.b:0.###},{c.a:0.###})";
		}

		internal static void DumpTexture(Sprite? sprite, List<string> lines)
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Expected O, but got Unknown
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = ((sprite != null) ? sprite.texture : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			string text = (string.IsNullOrEmpty(((Object)val).name) ? ("texture_" + ((Object)val).GetInstanceID()) : ((Object)val).name);
			char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
			foreach (char oldChar in invalidFileNameChars)
			{
				text = text.Replace(oldChar, '_');
			}
			if (!DumpedTextures.Add(text))
			{
				return;
			}
			RenderTexture val2 = null;
			Texture2D val3 = null;
			RenderTexture active = RenderTexture.active;
			try
			{
				val2 = RenderTexture.GetTemporary(((Texture)val).width, ((Texture)val).height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
				Graphics.Blit((Texture)(object)val, val2);
				RenderTexture.active = val2;
				val3 = new Texture2D(((Texture)val).width, ((Texture)val).height, (TextureFormat)4, false);
				val3.ReadPixels(new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), 0, 0);
				val3.Apply();
				Il2CppStructArray<byte> val4 = ImageConversion.EncodeToPNG(val3);
				byte[] array = new byte[((Il2CppArrayBase<byte>)(object)val4).Length];
				for (int j = 0; j < array.Length; j++)
				{
					array[j] = ((Il2CppArrayBase<byte>)(object)val4)[j];
				}
				File.WriteAllBytes(Path.Combine(Folder, text + ".png"), array);
			}
			catch (Exception ex)
			{
				lines.Add($"  ! texture {text} not saved: {ex.GetType().Name}: {ex.Message}");
			}
			finally
			{
				RenderTexture.active = active;
				if ((Object)(object)val2 != (Object)null)
				{
					RenderTexture.ReleaseTemporary(val2);
				}
				if ((Object)(object)val3 != (Object)null)
				{
					Object.Destroy((Object)(object)val3);
				}
			}
		}

		private static T? Safe<T>(Func<T?> getter) where T : class
		{
			try
			{
				return getter();
			}
			catch
			{
				return null;
			}
		}
	}
	internal static class BeltHud
	{
		private const float PopSeconds = 0.35f;

		private const float HueShift = 0.065f;

		private static readonly Color Amber = new Color(1f, 0.85f, 0.35f, 1f);

		private static PlayerHealthDisplay? _display;

		private static Slider? _bar;

		private static GameObject? _slot;

		private static Image? _bottle;

		private static RectTransform? _marker;

		private static RectTransform? _fill;

		private static RectTransform? _safe;

		private static GameObject? _safeEnd;

		private static float _nextFind;

		private static float _popUntil;

		private static bool _failed;

		private static EventReference _storeSound;

		private static EventReference _drinkSound;

		private static bool _haveSounds;

		public static void Update(float now)
		{
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Invalid comparison between Unknown and I4
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0297: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			//IL_0337: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			if (_failed)
			{
				return;
			}
			if (!((Object)(object)MissionBonuses.Identity != (Object)null) || !MissionBonuses.PotionBeltActive)
			{
				if ((Object)(object)_slot != (Object)null)
				{
					_slot.SetActive(false);
				}
				if ((Object)(object)_marker != (Object)null)
				{
					((Component)_marker).gameObject.SetActive(false);
				}
				if ((Object)(object)_safe != (Object)null)
				{
					((Component)_safe).gameObject.SetActive(false);
				}
				return;
			}
			if ((Object)(object)_slot == (Object)null || (Object)(object)_bar == (Object)null || (Object)(object)_marker == (Object)null)
			{
				if (now < _nextFind)
				{
					return;
				}
				_nextFind = now + 1f;
				try
				{
					if (!Build())
					{
						return;
					}
				}
				catch (Exception value)
				{
					_failed = true;
					ModLog.Error($"BeltHud: could not add the potion slot; Potion Belt still works without it: {value}");
					return;
				}
			}
			bool hasPotion = PotionBeltRunner.HasPotion;
			_slot.SetActive(true);
			((Component)_bottle).gameObject.SetActive(hasPotion);
			float num = ((now < _popUntil) ? (1f + 0.5f * (_popUntil - now) / 0.35f) : 1f);
			_slot.transform.localScale = new Vector3(num, num, 1f);
			float num2 = _bar.maxValue - _bar.minValue;
			float num3 = ((num2 > 0f) ? Mathf.Clamp01((0.3f * _bar.maxValue - _bar.minValue) / num2) : 0.3f);
			float normalizedValue = _bar.normalizedValue;
			bool flag = (int)_bar.direction == 0;
			((Component)_marker).gameObject.SetActive(hasPotion && flag);
			bool flag2 = hasPotion && flag && (Object)(object)_safe != (Object)null && (Object)(object)_fill != (Object)null && normalizedValue > num3;
			if ((Object)(object)_safe != (Object)null)
			{
				((Component)_safe).gameObject.SetActive(flag2);
			}
			if (!hasPotion || !flag || (Object)(object)_fill == (Object)null)
			{
				return;
			}
			float x = _fill.offsetMax.x;
			_marker.anchorMin = new Vector2(num3, _fill.anchorMin.y);
			_marker.anchorMax = new Vector2(num3, _fill.anchorMax.y);
			_marker.offsetMin = new Vector2(x - 2f, _fill.offsetMin.y);
			_marker.offsetMax = new Vector2(x + 2f, _fill.offsetMax.y);
			if (flag2)
			{
				_safe.anchorMin = new Vector2(num3, _fill.anchorMin.y);
				_safe.anchorMax = new Vector2(normalizedValue, _fill.anchorMax.y);
				_safe.offsetMin = new Vector2(x, _fill.offsetMin.y);
				_safe.offsetMax = new Vector2(x, _fill.offsetMax.y);
				if ((Object)(object)_safeEnd != (Object)null && (Object)(object)_display != (Object)null && (Object)(object)_display.rightCorner != (Object)null)
				{
					_safeEnd.SetActive(_display.rightCorner.activeSelf);
				}
			}
		}

		public static void OnStored(Vector3 position)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			_popUntil = Time.unscaledTime + 0.35f;
			try
			{
				if (!_haveSounds)
				{
					ModLog.StepOnce("belt-sounds", "BeltHud: first read of the potion's sounds");
					Object obj = Object.FindObjectOfType(Il2CppType.Of<HealthPickupSoundPlayer>());
					HealthPickupSoundPlayer val = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<HealthPickupSoundPlayer>() : null);
					if ((Object)(object)val != (Object)null)
					{
						_storeSound = val.spawnSound;
						_drinkSound = val.pickupSound;
						_haveSounds = true;
					}
				}
				if (_haveSounds)
				{
					RuntimeManager.PlayOneShot(_storeSound, position);
				}
			}
			catch (Exception ex)
			{
				ModLog.WarnOnce("belt-store-sound", "BeltHud: no sound for storing a potion: " + ex.Message);
			}
		}

		public static void OnDrunk(Vector3 position)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			_popUntil = Time.unscaledTime + 0.35f;
			try
			{
				if (_haveSounds)
				{
					RuntimeManager.PlayOneShot(_drinkSound, position);
				}
			}
			catch (Exception ex)
			{
				ModLog.WarnOnce("belt-drink-sound", "BeltHud: no sound for drinking the potion: " + ex.Message);
			}
		}

		private static bool Build()
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_036a: Unknown result type (might be due to invalid IL or missing references)
			//IL_037c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0381: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			ModLog.StepOnce("belt-hud-find", "BeltHud: first FindObjectOfType PlayerHealthDisplay");
			Object obj = Object.FindObjectOfType(Il2CppType.Of<PlayerHealthDisplay>());
			_display = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<PlayerHealthDisplay>() : null);
			if ((Object)(object)_display == (Object)null)
			{
				return false;
			}
			_bar = _display.bar;
			RectTransform val = (((Object)(object)_bar == (Object)null) ? null : ((Il2CppObjectBase)((Component)_bar).transform).TryCast<RectTransform>());
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			ModLog.Step("BeltHud: building the potion slot, marker and safe zone");
			Rect rect = val.rect;
			float num = Mathf.Max(((Rect)(ref rect)).height * 1.25f, 32f);
			_slot = NewChild("ARC_PotionSlot", val);
			RectTransform component = _slot.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0f, 0.5f);
			component.anchorMax = new Vector2(0f, 0.5f);
			component.pivot = new Vector2(1f, 0.5f);
			component.anchoredPosition = new Vector2((0f - num) * 0.14f, 0f);
			component.sizeDelta = new Vector2(num, num);
			Image obj2 = _slot.AddComponent<Image>();
			obj2.sprite = IconSprites.Named("belt_slot.png") ?? throw new InvalidOperationException("belt_slot.png is not built in");
			((Graphic)obj2).raycastTarget = false;
			GameObject obj3 = NewChild("Bottle", component);
			Stretch(obj3.GetComponent<RectTransform>());
			_bottle = obj3.AddComponent<Image>();
			_bottle.sprite = IconSprites.Named("belt_bottle.png") ?? throw new InvalidOperationException("belt_bottle.png is not built in");
			((Graphic)_bottle).raycastTarget = false;
			_fill = _bar.fillRect;
			RectTransform val2 = (((Object)(object)_fill == (Object)null) ? null : ((Il2CppObjectBase)((Transform)_fill).parent).TryCast<RectTransform>());
			Image val3 = (((Object)(object)_fill == (Object)null) ? null : ((Component)_fill).GetComponent<Image>());
			if ((Object)(object)_fill != (Object)null && (Object)(object)val2 != (Object)null && (Object)(object)val3 != (Object)null)
			{
				GameObject val4 = NewChild("ARC_PotionSafe", val2);
				_safe = val4.GetComponent<RectTransform>();
				((Transform)_safe).SetSiblingIndex(((Transform)_fill).GetSiblingIndex() + 1);
				Copy(val3, val4.AddComponent<Image>());
				RectTransform val5 = (((Object)(object)_display.rightCorner == (Object)null) ? null : ((Il2CppObjectBase)_display.rightCorner.transform).TryCast<RectTransform>());
				Image val6 = (((Object)(object)val5 == (Object)null) ? null : ((Component)val5).GetComponent<Image>());
				if ((Object)(object)val5 != (Object)null && (Object)(object)val6 != (Object)null)
				{
					_safeEnd = NewChild("End", _safe);
					RectTransform component2 = _safeEnd.GetComponent<RectTransform>();
					component2.anchorMin = val5.anchorMin;
					component2.anchorMax = val5.anchorMax;
					component2.pivot = val5.pivot;
					component2.offsetMin = val5.offsetMin;
					component2.offsetMax = val5.offsetMax;
					Copy(val6, _safeEnd.AddComponent<Image>());
				}
			}
			else
			{
				ModLog.Warn("BeltHud: the health bar has no fill to copy; no orange zone.");
			}
			GameObject obj4 = NewChild("ARC_PotionMarker", val2 ?? val);
			_marker = obj4.GetComponent<RectTransform>();
			Image obj5 = obj4.AddComponent<Image>();
			((Graphic)obj5).color = Amber;
			((Graphic)obj5).raycastTarget = false;
			object[] obj6 = new object[6]
			{
				Ui.Path((Transform)(object)val),
				null,
				null,
				null,
				null,
				null
			};
			rect = val.rect;
			obj6[1] = ((Rect)(ref rect)).width;
			rect = val.rect;
			obj6[2] = ((Rect)(ref rect)).height;
			obj6[3] = num;
			obj6[4] = (((Object)(object)_safe != (Object)null) ? "on" : "off");
			obj6[5] = (((Object)(object)_safeEnd != (Object)null) ? "on" : "off");
			ModLog.Info(FormattableString.Invariant(FormattableStringFactory.Create("BeltHud: built on {0} (bar {1:0}x{2:0}, slot {3:0}, orange zone {4}, end piece {5}).", obj6)));
			return true;
		}

		private static void Copy(Image source, Image target)
		{
			//IL_0002: 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_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			target.type = source.type;
			target.preserveAspect = source.preserveAspect;
			((Graphic)target).material = ((Graphic)source).material;
			((Graphic)target).raycastTarget = false;
			Sprite val = (((Object)(object)source.sprite == (Object)null) ? null : Recolour(source.sprite));
			if ((Object)(object)val != (Object)null)
			{
				target.sprite = val;
				((Graphic)target).color = ((Graphic)source).color;
			}
			else
			{
				target.sprite = source.sprite;
				((Graphic)target).color = new Color(1f, 0.9f, 0.3f, ((Graphic)source).color.a);
			}
		}

		private static Sprite? Recolour(Sprite sprite)
		{
			//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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: 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_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			RenderTexture val = null;
			RenderTexture active = RenderTexture.active;
			try
			{
				ModLog.StepOnce("belt-recolour", "BeltHud: first sprite recolour");
				Texture2D texture = sprite.texture;
				Rect rect = sprite.rect;
				int num = Mathf.RoundToInt(((Rect)(ref rect)).width);
				int num2 = Mathf.RoundToInt(((Rect)(ref rect)).height);
				val = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
				Graphics.Blit((Texture)(object)texture, val);
				RenderTexture.active = val;
				Texture2D val2 = new Texture2D(num, num2, (TextureFormat)4, false);
				val2.ReadPixels(new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, (float)num, (float)num2), 0, 0);
				float num3 = default(float);
				float num4 = default(float);
				float num5 = default(float);
				for (int i = 0; i < num2; i++)
				{
					for (int j = 0; j < num; j++)
					{
						Color pixel = val2.GetPixel(j, i);
						Color.RGBToHSV(pixel, ref num3, ref num4, ref num5);
						Color val3 = Color.HSVToRGB(Mathf.Repeat(num3 + 0.065f, 1f), num4, num5);
						val3.a = pixel.a;
						val2.SetPixel(j, i, val3);
					}
				}
				val2.Apply();
				((Texture)val2).wrapMode = (TextureWrapMode)1;
				((Texture)val2).filterMode = ((Texture)texture).filterMode;
				((Object)val2).hideFlags = (HideFlags)61;
				Sprite obj = Sprite.Create(val2, new Rect(0f, 0f, (float)num, (float)num2), new Vector2(0.5f, 0.5f), sprite.pixelsPerUnit, 0u, (SpriteMeshType)0, sprite.border);
				((Object)obj).name = "ARC_" + ((Object)sprite).name;
				((Object)obj).hideFlags = (HideFlags)61;
				return obj;
			}
			catch (Exception ex)
			{
				ModLog.WarnOnce("belt-recolour-failed", "BeltHud: could not recolour '" + ((Object)sprite).name + "': " + ex.Message);
				return null;
			}
			finally
			{
				RenderTexture.active = active;
				if ((Object)(object)val != (Object)null)
				{
					RenderTexture.ReleaseTemporary(val);
				}
			}
		}

		private static GameObject NewChild(string name, RectTransform parent)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			GameObject val = new GameObject(name);
			((Transform)val.AddComponent<RectTransform>()).SetParent((Transform)(object)parent, false);
			return val;
		}

		private static void Stretch(RectTransform rect)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			rect.anchorMin = Vector2.zero;
			rect.anchorMax = Vector2.one;
			rect.offsetMin = Vector2.zero;
			rect.offsetMax = Vector2.zero;
		}
	}
	internal static class EnchantmentScan
	{
		private const float Interval = 1f;

		private const int MaxScans = 3;

		private static float _next;

		private static int _scans;

		private static int _readyTicks;

		private static bool _scannedThisOpen;

		private static UpgradeBuyerUI? _buyer;

		private static string? _lastState;

		private static bool _done;

		public static void Tick(float now)
		{
			if (!_done)
			{
				if (now >= _next)
				{
					_next = now + 1f;
					Poll();
				}
				try
				{
					HighlightScan.Tick(now, _buyer);
				}
				catch (Exception ex)
				{
					ModLog.ErrorThrottled("highlight-scan", ex, now);
				}
				if (_scans >= 3 && HighlightScan.IsFinished)
				{
					_done = true;
					_buyer = null;
					ModLog.Info("EnchantmentScan: done, polling stopped");
				}
			}
		}

		private static void Poll()
		{
			UpgradeBuyerUI buyer = FindBuyer();
			_buyer = buyer;
			if ((Object)(object)buyer != (Object)null)
			{
				LogState(buyer);
			}
			if ((Object)(object)buyer == (Object)null || !((Panel)buyer).IsOpen)
			{
				_scannedThisOpen = false;
				_readyTicks = 0;
			}
			else
			{
				if (_scannedThisOpen || _scans >= 3)
				{
					return;
				}
				CanvasGroup component = ((Component)buyer).GetComponent<CanvasGroup>();
				if ((Object)(object)component != (Object)null && component.alpha < 0.99f)
				{
					_readyTicks = 0;
				}
				else if (++_readyTicks >= 2)
				{
					_scannedThisOpen = true;
					_scans++;
					ModLog.Step($"EnchantmentScan: Enchantments screen open and settled, scan {_scans}");
					List<string> lines = new List<string>();
					ScanReport.Guard(lines, "EnchantmentScan: screen", delegate
					{
						DescribeScreen(buyer, lines);
					});
					ScanReport.Guard(lines, "EnchantmentScan: rows", delegate
					{
						DescribeRows(buyer, lines);
					});
					ScanReport.Guard(lines, "EnchantmentScan: levels and prices", delegate
					{
						DescribeManager(buyer, lines);
					});
					ScanReport.Guard(lines, "EnchantmentScan: details panel", delegate
					{
						DescribeDetails(buyer, lines);
					});
					ScanReport.Guard(lines, "EnchantmentScan: local player save flags", delegate
					{
						DescribeSaveFlags(lines);
					});
					ScanReport.Guard(lines, "EnchantmentScan: events", delegate
					{
						DescribeEvents(lines);
					});
					ScanReport.Section($"Enchantments screen (scan {_scans})", lines);
				}
			}
		}

		private static void LogState(UpgradeBuyerUI buyer)
		{
			CanvasGroup component = ((Component)buyer).GetComponent<CanvasGroup>();
			float num = (((Object)(object)component != (Object)null) ? component.alpha : 1f);
			string text = $"IsOpen={((Panel)buyer).IsOpen} active={((Behaviour)buyer).isActiveAndEnabled} alphaOk={num >= 0.99f}";
			if (!(text == _lastState))
			{
				ModLog.Info((_lastState == null) ? $"EnchantmentScan: configured buyer found, {text} (alpha={num})" : $"EnchantmentScan: buyer state {text} (alpha={num})");
				_lastState = text;
			}
		}

		private static UpgradeBuyerUI? FindBuyer()
		{
			ModLog.StepOnce("enchant-find", "EnchantmentScan: first FindObjectsOfType");
			foreach (Object item in (Il2CppArrayBase<Object>)(object)Object.FindObjectsOfType(Il2CppType.Of<UpgradeBuyerUI>(), true))
			{
				UpgradeBuyerUI val = ((item != null) ? ((Il2CppObjectBase)item).TryCast<UpgradeBuyerUI>() : null);
				if ((Object)(object)val == (Object)null || !((Behaviour)val).isActiveAndEnabled)
				{
					continue;
				}
				List<UpgradeTierUI> tiers = val.tiers;
				if (tiers != null && tiers.Count != 0)
				{
					List<UpgradeButton> upgradeButtons = tiers[0].upgradeButtons;
					if (upgradeButtons != null && upgradeButtons.Count != 0 && !((Object)(object)upgradeButtons[0].configuration == (Object)null))
					{
						return val;
					}
				}
			}
			return null;
		}

		private static void DescribeScreen(UpgradeBuyerUI buyer, List<string> lines)
		{
			ScanReport.Guard(lines, "screen: header", delegate
			{
				//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
				lines.Add($"Screen {Screen.width}x{Screen.height}; buyer at {Ui.Path(((Component)buyer).transform)} {Ui.Span(((Component)buyer).transform)} IsOpen={((Panel)buyer).IsOpen} lossyScale={((Component)buyer).transform.lossyScale}");
			});
			Canvas canvas = null;
			ScanReport.Guard(lines, "screen: canvas and group", delegate
			{
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				canvas = ((Component)buyer).GetComponentInParent<Canvas>();
				if ((Object)(object)canvas != (Object)null)
				{
					lines.Add($"Canvas '{((Object)canvas).name}' renderMode={canvas.renderMode} scaleFactor={canvas.scaleFactor}");
				}
				CanvasGroup component = ((Component)buyer).GetComponent<CanvasGroup>();
				if ((Object)(object)component != (Object)null)
				{
					lines.Add($"Buyer CanvasGroup alpha={component.alpha} interactable={component.interactable}");
				}
			});
			List<UpgradeTierUI> tiers = buyer.tiers;
			Transform parent = ((Component)tiers[0]).transform.parent;
			ScanReport.Guard(lines, "screen: rows' parent and children", delegate
			{
				lines.Add($"Rows' parent: {Ui.Path(parent)} [{Ui.Components(parent)}] {Ui.Span(parent)}");
				VerticalLayoutGroup component = ((Component)parent).GetComponent<VerticalLayoutGroup>();
				if ((Object)(object)component != (Object)null)
				{
					lines.Add($"  VerticalLayoutGroup spacing={((HorizontalOrVerticalLayoutGroup)component).spacing} padding(l,r,t,b)=({((LayoutGroup)component).padding.left},{((LayoutGroup)component).padding.right},{((LayoutGroup)component).padding.top},{((LayoutGroup)component).padding.bottom}) controlHeight={((HorizontalOrVerticalLayoutGroup)component).childControlHeight}");
				}
				for (int i = 0; i < parent.childCount; i++)
				{
					Transform child = parent.GetChild(i);
					lines.Add($"  child {i}: '{((Object)child).name}' active={((Component)child).gameObject.activeSelf} [{Ui.Components(child)}] {Ui.Span(child)}");
				}
			});
			ScanReport.Guard(lines, "screen: ancestors", delegate
			{
				int num = 0;
				Transform parent2 = parent.parent;
				while ((Object)(object)parent2 != (Object)null && num < 12)
				{
					lines.Add($"Ancestor +{num + 1}: '{((Object)parent2).name}' [{Ui.Components(parent2)}] {Ui.Span(parent2)}");
					if ((Object)(object)canvas != (Object)null && (Object)(object)parent2 == (Object)(object)((Component)canvas).transform)
					{
						break;
					}
					parent2 = parent2.parent;
					num++;
				}
			});
			ScanReport.Guard(lines, "screen: siblings", delegate
			{
				Transform parent2 = parent.parent;
				if (!((Object)(object)parent2 == (Object)null))
				{
					for (int i = 0; i < parent2.childCount; i++)
					{
						Transform child = parent2.GetChild(i);
						if (!((Object)(object)child == (Object)(object)parent))
						{
							lines.Add($"Sibling of rows' parent: '{((Object)child).name}' active={((Component)child).gameObject.activeSelf} [{Ui.Components(child)}] {Ui.Span(child)}");
						}
					}
				}
			});
			ScanReport.Guard(lines, "screen: Row V subtree", delegate
			{
				UpgradeTierUI val = tiers[tiers.Count - 1];
				lines.Add("Row V subtree ('" + ((Object)val).name + "'):");
				Subtree(((Component)val).transform, lines, 0);
			});
			ScanReport.Guard(lines, "screen: refund button", delegate
			{
				RefundButton refundButton = buyer.refundButton;
				lines.Add("Refund button: " + (((Object)(object)refundButton != (Object)null) ? (Ui.Path(((Component)refundButton).transform) + " " + Ui.Span(((Component)refundButton).transform)) : "none"));
			});
		}

		private static void Subtree(Transform t, List<string> lines, int depth)
		{
			lines.Add($"{new string(' ', 2 + depth * 2)}'{((Object)t).name}' active={((Component)t).gameObject.activeSelf} [{Ui.Components(t)}] {Ui.Span(t)}");
			if (depth < 4)
			{
				for (int i = 0; i < t.childCount; i++)
				{
					Subtree(t.GetChild(i), lines, depth + 1);
				}
			}
		}

		private static void DescribeRows(UpgradeBuyerUI buyer, List<string> lines)
		{
			List<UpgradeTierUI> tiers = buyer.tiers;
			for (int i = 0; i < tiers.Count; i++)
			{
				int index = i;
				ScanReport.Guard(lines, $"rows: row {index + 1}", delegate
				{
					DescribeRow(tiers[index], index, lines);
				});
			}
		}

		private static void DescribeRow(UpgradeTierUI tier, int i, List<string> lines)
		{
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			lines.Add($"Row {i + 1}: '{((Object)tier).name}' at {Ui.Path(((Component)tier).transform)} {Ui.Span(((Component)tier).transform)} [{Ui.Components(((Component)tier).transform)}]");
			lines.Add($"  locked={Ui.Try(() => tier.IsLocked)} lockReasons=[{Ui.Try(() => Join(tier.cachedLockReasons))}]");
			UpgradeTierConfiguration cfg = tier.upgradeTierConfiguration;
			if ((Object)(object)cfg != (Object)null)
			{
				lines.Add($"  config '{((Object)cfg).name}': challengeToUnlock={cfg.challengeToUnlock} lockedByProgression={Ui.Try(() => cfg.IsLockedByProgression())} comingSoon={Ui.Try(() => cfg.GetIsComingSoon())} inDemo={Ui.Try(() => cfg.GetIsIncludedInDemo())} upgrades={cfg.UpgradesIncludedInTier?.Count}");
			}
			ScanReport.Guard(lines, $"rows: row {i + 1} texts", delegate
			{
				Ui.Texts(((Component)tier).transform, lines, "  ");
			});
			List<UpgradeButton> buttons = tier.upgradeButtons;
			for (int num = 0; num < buttons.Count; num++)
			{
				int button = num;
				ScanReport.Guard(lines, $"rows: row {i + 1} button {button + 1}", delegate
				{
					DescribeButton(buttons[button], lines);
				});
			}
		}

		private static void DescribeButton(UpgradeButton button, List<string> lines)
		{
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Unknown result type (might be due to invalid IL or missing references)
			lines.Add($"  Button '{((Object)button).name}' {Ui.Span(((Component)button).transform)} levelPips={((Il2CppArrayBase<GameObject>)(object)button.upgradeLevelObjects)?.Length} lockReasons=[{Ui.Try(() => Join(button.lockReasons))}] canAfford={button.canAfford} maxed={button.maxLevelAchieved}");
			UpgradeConfiguration configuration = button.configuration;
			if ((Object)(object)configuration == (Object)null)
			{
				lines.Add("    (no configuration)");
				return;
			}
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(58, 7);
			defaultInterpolatedStringHandler.AppendLiteral("    '");
			defaultInterpolatedStringHandler.AppendFormatted(((Object)configuration).name);
			defaultInterpolatedStringHandler.AppendLiteral("' id=");
			defaultInterpolatedStringHandler.AppendFormatted<UpgradeIdentifier>(configuration.Identifier);
			defaultInterpolatedStringHandler.AppendLiteral(" Name='");
			defaultInterpolatedStringHandler.AppendFormatted(configuration.Name);
			defaultInterpolatedStringHandler.AppendLiteral("' Description='");
			defaultInterpolatedStringHandler.AppendFormatted(configuration.Description);
			defaultInterpolatedStringHandler.AppendLiteral("' InitialCost=");
			defaultInterpolatedStringHandler.AppendFormatted(configuration.InitialCost);
			defaultInterpolatedStringHandler.AppendLiteral(" ");
			defaultInterpolatedStringHandler.AppendLiteral("icon=");
			Sprite icon = configuration.Icon;
			defaultInterpolatedStringHandler.AppendFormatted((icon != null) ? ((Object)icon).name : null);
			defaultInterpolatedStringHandler.AppendLiteral(" glow=");
			Sprite glow = configuration.Glow;
			defaultInterpolatedStringHandler.AppendFormatted((glow != null) ? ((Object)glow).name : null);
			lines.Add(defaultInterpolatedStringHandler.ToStringAndClear());
			List<BaseUpgrade> upgradeLevels = configuration.UpgradeLevels;
			for (int num = 0; num < upgradeLevels.Count; num++)
			{
				BaseUpgrade val = upgradeLevels[num];
				StatUpgrade val2 = ((Il2CppObjectBase)val).TryCast<StatUpgrade>();
				FinalUpgrade val3 = ((Il2CppObjectBase)val).TryCast<FinalUpgrade>();
				if ((Object)(object)val2 != (Object)null)
				{
					lines.Add($"    level {num + 1}: StatUpgrade {val2.Stat} {val2.Amount} ('{val2.Name}')");
				}
				else if ((Object)(object)val3 != (Object)null)
				{
					lines.Add($"    level {num + 1}: Mastery {val3.FinalUpgradeType} params=[{FinalParams(val3)}] Description='{val3.Description}'");
				}
				else
				{
					lines.Add($"    level {num + 1}: {Ui.ClassName((Il2CppObjectBase)(object)val)}");
				}
			}
		}

		private static string FinalParams(FinalUpgrade final)
		{
			int num = final.FinalUpgradeParameters?.Count ?? 0;
			List<string> list = new List<string>();
			for (int i = 0; i < num; i++)
			{
				int index = i;
				list.Add(Ui.Try(() => final.GetParameterValue(index)));
			}
			return string.Join(", ", list);
		}

		private static void DescribeManager(UpgradeBuyerUI buyer, List<string> lines)
		{
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			LocalPlayer player = SingletonPersistent<LocalPlayer>.Instance;
			UpgradeManager manager = player.GetUpgradeManager();
			int total = manager.GetNumberOfUpgrades();
			lines.Add($"Gold={Ui.Try(() => player.GetGold())} upgradesBought={total} refundValue={Ui.Try(() => manager.GetRefundValue())} BaseIncreaseCost={Ui.Try(() => UpgradeManager.BaseIncreaseCost)} UpgradeCostGrowthRate={Ui.Try(() => UpgradeManager.UpgradeCostGrowthRate)}");
			Dictionary<UpgradeIdentifier, UpgradeConfiguration> configurationForUpgrades = manager.configurationForUpgrades;
			int num = 0;
			foreach (UpgradeIdentifier id in Enum.GetValues(typeof(UpgradeIdentifier)))
			{
				string text = Ui.Try(() => manager.GetLevel(id));
				string text2 = Ui.Try(() => manager.IsMaxLevel(id));
				if (text2 == "True")
				{
					num++;
				}
				string text3 = $"{id}: level {text}/{Ui.Try(() => manager.GetMaxLevel(id))} maxed={text2}";
				UpgradeConfiguration cfg = null;
				try
				{
					if (configurationForUpgrades != null && configurationForUpgrades.ContainsKey(id))
					{
						cfg = configurationForUpgrades[id];
					}
				}
				catch (Exception ex)
				{
					text3 = text3 + " config=!" + ex.GetType().Name + ": " + ex.Message;
				}
				if ((Object)(object)cfg != (Object)null)
				{
					int initial = cfg.InitialCost;
					int result;
					int level = (int.TryParse(text, out result) ? result : (-1));
					string text4 = Ui.Try(() => manager.CalculateCost(cfg));
					string text5 = Ui.Try(() => manager.CalculateCost(initial, level, total));
					text3 += $" InitialCost={initial} cost={text4} CalculateCost({initial},{text},{total})={text5} {((text4 == text5) ? "MATCH" : "DIFFERS")}";
					text3 = text3 + " lastBought=" + Ui.Try(() => manager.CalculateLastBoughtCost(cfg));
					text3 += $" value '{Ui.Try(() => manager.GetCurrentValueString(id))}' -> '{Ui.Try(() => manager.GetNextValueString(id))}'";
				}
				lines.Add(text3);
			}
			lines.Add($"Masteries (game enchantments at max level): {num}");
			SortedSet<int> sortedSet = new SortedSet<int>();
			List<UpgradeTierUI> tiers = buyer.tiers;
			for (int num2 = 0; num2 < tiers.Count; num2++)
			{
				List<UpgradeButton> upgradeButtons = tiers[num2].upgradeButtons;
				for (int num3 = 0; num3 < upgradeButtons.Count; num3++)
				{
					UpgradeConfiguration configuration = upgradeButtons[num3].configuration;
					if ((Object)(object)configuration != (Object)null)
					{
						sortedSet.Add(configuration.InitialCost);
					}
				}
			}
			foreach (int initial2 in sortedSet)
			{
				IEnumerable<string> values = from bought in Enumerable.Range(0, 7)
					select Ui.Try(() => manager.CalculateCost(initial2, bought, total));
				IEnumerable<string> values2 = new int[5] { 0, 10, 20, 40, 80 }.Select((int t) => $"{t}:{Ui.Try(() => manager.CalculateCost(initial2, 0, t))}");
				lines.Add($"Price curve initial={initial2}: bought 0..6 at total {total} = [{string.Join(", ", values)}]; bought 0 by total [{string.Join(", ", values2)}]; bought 3 at total 0 = {Ui.Try(() => manager.CalculateCost(initial2, 3, 0))}, at total 40 = {Ui.Try(() => manager.CalculateCost(initial2, 3, 40))}");
			}
		}

		private static void DescribeDetails(UpgradeBuyerUI buyer, List<string> lines)
		{
			UpgradeDetailsUI upgradeDetailsUI = buyer.upgradeDetailsUI;
			if ((Object)(object)upgradeDetailsUI == (Object)null)
			{
				lines.Add("No details panel.");
				return;
			}
			lines.Add($"Details panel at {Ui.Path(((Component)upgradeDetailsUI).transform)} {Ui.Span(((Component)upgradeDetailsUI).transform)} statRows={upgradeDetailsUI.statUpgradeUIElements?.Count} UpgradeFinalLockedTerm='{Ui.Try(() => UpgradeDetailsUI.UpgradeFinalLockedTerm)}'");
			Ui.Texts(((Component)upgradeDetailsUI).transform, lines, "  ");
		}

		private static void DescribeSaveFlags(List<string> lines)
		{
			LocalPlayer player = SingletonPersistent<LocalPlayer>.Instance;
			lines.Add($"LocalPlayer save flags: lastClearedSaveTimeStamp={Ui.Try(() => player.lastClearedSaveTimeStamp)} hasClearedSaveData={Ui.Try(() => player.hasClearedSaveData)} startPlayingTimestamp={Ui.Try(() => player.startPlayingTimestamp)}");
		}

		private static void DescribeEvents(List<string> lines)
		{
			lines.Add("OnUpgradePerformed listeners: " + Ui.Try(() => Ui.Listeners((Delegate?)(object)LocalEvents.OnUpgradePerformed?.OnAction)));
			lines.Add("OnUpgradeRefundsPerformed listeners: " + Ui.Try(() => Ui.Listeners((Delegate?)(object)LocalEvents.OnUpgradeRefundsPerformed?.OnAction)));
			lines.Add("OnHealthPotionCollected listeners: " + Ui.Try(() => Ui.Listeners((Delegate?)(object)LocalEvents.OnHealthPotionCollected?.OnAction)));
			lines.Add("UpgradeManager.OnUpgradesRefunded listeners: " + Ui.Try(() => Ui.Listeners((Delegate?)(object)SingletonPersistent<LocalPlayer>.Instance.GetUpgradeManager().OnUpgradesRefunded)));
			lines.Add("LocalPlayer.OnGoldChanged listeners: " + Ui.Try(() => Ui.Listeners((Delegate?)(object)SingletonPersistent<LocalPlayer>.Instance.OnGoldChanged)));
		}

		private static string Join(List<LockReason>? reasons)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (reasons == null)
			{
				return "null";
			}
			List<string> list = new List<string>();
			for (int i = 0; i < reasons.Count; i++)
			{
				list.Add(((object)reasons[i]/*cast due to .constrained prefix*/).ToString());
			}
			return string.Join(", ", list);
		}
	}
	internal static class GameUpgrades
	{
		public const int ArcaneInitialCost = 360;

		public static bool IsReady
		{
			get
			{
				try
				{
					LocalPlayer instance = SingletonPersistent<LocalPlayer>.Instance;
					return (Object)(object)instance != (Object)null && instance.IsInitialized && instance.GetUpgradeManager() != null;
				}
				catch (Exception)
				{
					return false;
				}
			}
		}

		public static bool CanSaveGame => (Delegate)(object)LocalEvents.OnUpgradeRefundsPerformed?.OnAction != (Delegate)null;

		public static LocalPlayer Player => SingletonPersistent<LocalPlayer>.Instance;

		public static UpgradeManager Manager => Player.GetUpgradeManager();

		public static int Gold => Player.GetGold();

		public static int TotalBought => Manager.GetNumberOfUpgrades();

		public static long SaveClearedTicks
		{
			get
			{
				//IL_0005: 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)
				DateTime lastClearedSaveTimeStamp = Player.lastClearedSaveTimeStamp;
				return ((DateTime)(ref lastClearedSaveTimeStamp)).Ticks;
			}
		}

		public static int Masteries()
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			UpgradeManager manager = Manager;
			int num = 0;
			foreach (UpgradeIdentifier value in Enum.GetValues(typeof(UpgradeIdentifier)))
			{
				try
				{
					if (manager.IsMaxLevel(value))
					{
						num++;
					}
				}
				catch (Exception ex)
				{
					ModLog.WarnOnce("mastery-" + ((object)value/*cast due to .constrained prefix*/).ToString(), $"GameUpgrades: IsMaxLevel({value}) failed: {ex.Message}");
				}
			}
			return num;
		}

		public static int Price(int levelOfThisEnchantment, int sixthTierLevels)
		{
			UpgradeManager manager = Manager;
			return manager.CalculateCost(360, levelOfThisEnchantment, manager.GetNumberOfUpgrades() + sixthTierLevels);
		}

		public static UpgradeConfiguration? Configuration(UpgradeIdentifier id)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<UpgradeIdentifier, UpgradeConfiguration> configurationForUpgrades = Manager.configurationForUpgrades;
			UpgradeConfiguration result = default(UpgradeConfiguration);
			if (configurationForUpgrades == null || !configurationForUpgrades.TryGetValue(id, ref result))
			{
				return null;
			}
			return result;
		}

		public static void Spend(int gold)
		{
			ModLog.StepOnce("game-spend", "GameUpgrades: first RemoveGold");
			Player.RemoveGold(gold);
		}

		public static void Give(int gold)
		{
			ModLog.StepOnce("game-give", "GameUpgrades: first AddGold");
			Player.AddGold(gold);
		}

		public static bool SaveGame()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			if (!CanSaveGame)
			{
				ModLog.WarnOnce("no-game-save", "GameUpgrades: nothing listens to OnUpgradeRefundsPerformed, so the game was not asked to save.");
				return false;
			}
			ModLog.StepOnce("game-save", "GameUpgrades: first triggered game save");
			LocalEvents.OnUpgradeRefundsPerformed.Trigger(new UpgradeRefundsPerformedEventArgs());
			try
			{
				SaveManager instance = SingletonPersistent<SaveManager>.Instance;
				ModLog.InfoOnce("game-save-state", "GameUpgrades: right after the first triggered save, SaveManager.IsSaving = " + (((instance != null) ? new bool?(instance.IsSaving) : ((bool?)null))?.ToString() ?? "n/a"));
			}
			catch (Exception ex)
			{
				ModLog.WarnOnce("game-save-state-failed", "GameUpgrades: could not read SaveManager.IsSaving: " + ex.Message);
			}
			return true;
		}
	}
	internal static class HighlightScan
	{
		private const float Interval = 0.25f;

		private const int MaxHighlights = 8;

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

		private static string? _pending;

		private static int _pendingTicks;

		private static float _next;

		public static bool IsFinished => Seen.Count >= 8;

		public static void Tick(float now, UpgradeBuyerUI? buyer)
		{
			if (now < _next)
			{
				return;
			}
			_next = now + 0.25f;
			if ((Object)(object)buyer == (Object)null || !((Panel)buyer).IsOpen || Seen.Count >= 8)
			{
				_pending = null;
				return;
			}
			UpgradeButton currentHighlightedUpgradeButton = buyer.currentHighlightedUpgradeButton;
			UpgradeConfiguration cfg = ((currentHighlightedUpgradeButton != null) ? currentHighlightedUpgradeButton.configuration : null);
			string shownName = Ui.Try(delegate
			{
				UpgradeDetailsUI upgradeDetailsUI = buyer.upgradeDetailsUI;
				if (upgradeDetailsUI == null)
				{
					return (object?)null;
				}
				TMP_Text nameText = upgradeDetailsUI.nameText;
				return (nameText == null) ? null : nameText.text;
			});
			if ((Object)(object)cfg == (Object)null && (shownName == "null" || shownName.StartsWith("!") || shownName.Length == 0))
			{
				_pending = null;
				return;
			}
			UpgradeConfiguration obj = cfg;
			string text = ((obj != null) ? ((Object)obj).name : null) + "|" + shownName;
			if (Seen.Contains(text))
			{
				return;
			}
			if (_pending != text)
			{
				_pending = text;
				_pendingTicks = 1;
			}
			else if (++_pendingTicks >= 2)
			{
				Seen.Add(text);
				_pending = null;
				List<string> lines = new List<string>();
				ScanReport.Guard(lines, "HighlightScan: " + text, delegate
				{
					Describe(buyer, cfg, shownName, lines);
				});
				ScanReport.Section("Highlighted " + Ui.Try(delegate
				{
					UpgradeConfiguration obj2 = cfg;
					return ((obj2 != null) ? obj2.Name : null) ?? shownName;
				}), lines);
			}
		}

		private static void Describe(UpgradeBuyerUI buyer, UpgradeConfiguration? cfg, string shownName, List<string> lines)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)cfg == (Object)null)
			{
				lines.Add("details name text='" + shownName + "' (no highlighted button configuration)");
			}
			else
			{
				UpgradeManager manager = SingletonPersistent<LocalPlayer>.Instance.GetUpgradeManager();
				UpgradeIdentifier id = cfg.Identifier;
				lines.Add($"details name text='{shownName}'; '{((Object)cfg).name}' id={id} level {Ui.Try(() => manager.GetLevel(id))}/{Ui.Try(() => manager.GetMaxLevel(id))} maxed={Ui.Try(() => manager.IsMaxLevel(id))} levels={cfg.UpgradeLevels?.Count}");
			}
			UpgradeDetailsUI details = buyer.upgradeDetailsUI;
			if ((Object)(object)details == (Object)null)
			{
				lines.Add("No details panel.");
				return;
			}
			lines.Add($"LevelText='{Ui.Try(() => details.LevelText)}' Parameter0='{Ui.Try(() => details.Parameter0)}' Parameter1='{Ui.Try(() => details.Parameter1)}'");
			Ui.Texts(((Component)details).transform, lines, "  ");
		}
	}
	internal static class HudDump
	{
		private sta