Decompiled source of Skills v1.0.1

meadworks.skills.dll

Decompiled 29 minutes ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using MeadWorks.Core;
using MeadWorks.UI;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("expDARE")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2026 expDARE")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("meadworks.skills")]
[assembly: AssemblyTitle("meadworks.skills")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MeadWorks.Skills
{
	public enum AchievementTab
	{
		All,
		Active,
		Done,
		Tracked
	}
	public sealed class AchievementDef
	{
		public string Id { get; set; }

		public string Title { get; set; }

		public float Goal { get; set; }

		public string Unit { get; set; }

		public string Icon { get; set; }

		public string Shown => Lang.Derived("skills.achievement." + Id, Title);

		public AchievementDef(string id, string title, float goal, string unit = "", string icon = null)
		{
			Id = id;
			Title = title;
			Goal = goal;
			Unit = unit ?? "";
			Icon = icon ?? id;
		}
	}
	public sealed class AchievementState
	{
		public AchievementDef Def { get; set; }

		public float Progress { get; set; }

		public float Goal
		{
			get
			{
				if (Def == null)
				{
					return 1f;
				}
				return Def.Goal;
			}
		}

		public bool Done => Progress >= Goal;

		public bool Pinned { get; set; }

		public float Fraction
		{
			get
			{
				if (!(Goal <= 0f))
				{
					return Math.Min(1f, Math.Max(0f, Progress / Goal));
				}
				return 0f;
			}
		}

		public string FormattedProgress => AchievementRules.FormatProgress(Def, Progress);
	}
	public static class AchievementRules
	{
		public const int MaxPinned = 3;

		public const float CompletionHold = 4f;

		public const string ProgressPrefix = "mw.ach.p.";

		public const string PinnedPrefix = "mw.ach.pin.";

		public const string PinOrderKey = "mw.ach.order";

		public static readonly AchievementDef[] Definitions = new AchievementDef[11]
		{
			new AchievementDef("timber", "Timber!", 500f),
			new AchievementDef("forsaken_hunter", "Forsaken Hunter", 8f),
			new AchievementDef("long_walk", "Long Walk", 20000f, "km"),
			new AchievementDef("angler", "Angler", 50f),
			new AchievementDef("stonemason", "Stonemason", 400f),
			new AchievementDef("iron_will", "Iron Will", 100f),
			new AchievementDef("first_blood", "First Blood", 1f),
			new AchievementDef("deer_slayer", "Deer Slayer", 20f),
			new AchievementDef("home_sweet_home", "Home Sweet Home", 1f),
			new AchievementDef("trader", "Trader", 1f),
			new AchievementDef("cook", "Short Order Cook", 25f)
		};

		public static AchievementDef Find(string id)
		{
			if (string.IsNullOrEmpty(id))
			{
				return null;
			}
			for (int i = 0; i < Definitions.Length; i++)
			{
				if (string.Equals(Definitions[i].Id, id, StringComparison.OrdinalIgnoreCase))
				{
					return Definitions[i];
				}
			}
			return null;
		}

		public static string KeyProgress(string id)
		{
			return "mw.ach.p." + id;
		}

		public static string KeyPinned(string id)
		{
			return "mw.ach.pin." + id;
		}

		public static float GetProgress(IDictionary<string, string> customData, string id)
		{
			if (customData == null || string.IsNullOrEmpty(id))
			{
				return 0f;
			}
			if (customData.TryGetValue(KeyProgress(id), out var value) && float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return result;
			}
			return 0f;
		}

		public static void SetProgress(IDictionary<string, string> customData, string id, float value)
		{
			if (customData != null && !string.IsNullOrEmpty(id))
			{
				float num = Find(id)?.Goal ?? 1f;
				float num2 = Math.Max(0f, value);
				customData[KeyProgress(id)] = num2.ToString("0.##", CultureInfo.InvariantCulture);
				if (num2 >= num)
				{
					SetPinned(customData, id, pinned: false);
				}
			}
		}

		public static float AddProgress(IDictionary<string, string> customData, string id, float delta)
		{
			if (customData == null || string.IsNullOrEmpty(id) || delta <= 0f)
			{
				return 0f;
			}
			float num = GetProgress(customData, id) + delta;
			SetProgress(customData, id, num);
			return num;
		}

		public static bool IsPinned(IDictionary<string, string> customData, string id)
		{
			if (customData == null || string.IsNullOrEmpty(id))
			{
				return false;
			}
			if (customData.TryGetValue(KeyPinned(id), out var value))
			{
				return string.Equals(value, "true", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		public static bool SetPinned(IDictionary<string, string> customData, string id, bool pinned)
		{
			if (customData == null || string.IsNullOrEmpty(id))
			{
				return false;
			}
			AchievementDef achievementDef = Find(id);
			if (achievementDef == null)
			{
				return false;
			}
			id = achievementDef.Id;
			if (!pinned)
			{
				customData[KeyPinned(id)] = "false";
				WriteOrder(customData, ActivePins(customData));
				return true;
			}
			if (GetProgress(customData, id) >= achievementDef.Goal)
			{
				customData[KeyPinned(id)] = "false";
				WriteOrder(customData, ActivePins(customData));
				return false;
			}
			if (IsPinned(customData, id))
			{
				return true;
			}
			List<string> list = ActivePins(customData);
			while (list.Count >= 3)
			{
				string id2 = list[0];
				customData[KeyPinned(id2)] = "false";
				list.RemoveAt(0);
			}
			customData[KeyPinned(id)] = "true";
			list.Add(id);
			WriteOrder(customData, list);
			return true;
		}

		public static bool TogglePin(IDictionary<string, string> customData, string id)
		{
			bool flag = IsPinned(customData, id);
			SetPinned(customData, id, !flag);
			return IsPinned(customData, id);
		}

		public static List<string> GetPinnedIds(IDictionary<string, string> customData)
		{
			List<string> list = ActivePins(customData);
			if (customData != null && !SameOrder(ReadOrder(customData), list))
			{
				WriteOrder(customData, list);
			}
			return list;
		}

		public static List<string> Released(IList<string> pinnedBefore, IDictionary<string, string> customData)
		{
			HashSet<string> hashSet = new HashSet<string>(GetPinnedIds(customData), StringComparer.OrdinalIgnoreCase);
			List<string> list = new List<string>();
			if (pinnedBefore == null)
			{
				return list;
			}
			for (int i = 0; i < pinnedBefore.Count; i++)
			{
				string text = pinnedBefore[i];
				if (!string.IsNullOrEmpty(text) && !hashSet.Contains(text))
				{
					list.Add(text);
				}
			}
			return list;
		}

		public static string CompletedLine(IList<string> released, IDictionary<string, string> customData)
		{
			string result = null;
			if (released == null)
			{
				return null;
			}
			for (int i = 0; i < released.Count; i++)
			{
				AchievementDef achievementDef = Find(released[i]);
				if (achievementDef != null && GetProgress(customData, achievementDef.Id) >= achievementDef.Goal)
				{
					result = TrackText(achievementDef, achievementDef.Goal);
				}
			}
			return result;
		}

		public static string TrackText(AchievementDef def, float progress)
		{
			if (def == null)
			{
				return "";
			}
			if (progress >= def.Goal)
			{
				return Lang.T("skills.complete", "{0} complete", new object[1] { def.Shown ?? "" });
			}
			string text = FormatProgress(def, progress);
			if (!string.IsNullOrEmpty(text))
			{
				return def.Shown + "  " + text;
			}
			return def.Shown ?? "";
		}

		private static List<string> ActivePins(IDictionary<string, string> customData)
		{
			List<string> list = new List<string>();
			if (customData == null)
			{
				return list;
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (string item in ReadOrder(customData))
			{
				AchievementDef achievementDef = Find(item);
				if (achievementDef != null && hashSet.Add(achievementDef.Id) && IsPinned(customData, achievementDef.Id) && GetProgress(customData, achievementDef.Id) < achievementDef.Goal)
				{
					list.Add(achievementDef.Id);
				}
			}
			for (int i = 0; i < Definitions.Length; i++)
			{
				string id = Definitions[i].Id;
				if (hashSet.Add(id) && IsPinned(customData, id) && GetProgress(customData, id) < Definitions[i].Goal)
				{
					list.Add(id);
				}
			}
			return list;
		}

		private static List<string> ReadOrder(IDictionary<string, string> customData)
		{
			List<string> list = new List<string>();
			if (customData == null || !customData.TryGetValue("mw.ach.order", out var value) || string.IsNullOrEmpty(value))
			{
				return list;
			}
			string[] array = value.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length > 0)
				{
					list.Add(text);
				}
			}
			return list;
		}

		private static void WriteOrder(IDictionary<string, string> customData, IList<string> ids)
		{
			if (customData != null)
			{
				if (ids == null || ids.Count == 0)
				{
					customData.Remove("mw.ach.order");
				}
				else
				{
					customData["mw.ach.order"] = string.Join(",", ids);
				}
			}
		}

		private static bool SameOrder(IList<string> stored, IList<string> pins)
		{
			if (stored == null || pins == null || stored.Count != pins.Count)
			{
				return false;
			}
			for (int i = 0; i < pins.Count; i++)
			{
				if (!string.Equals(stored[i], pins[i], StringComparison.Ordinal))
				{
					return false;
				}
			}
			return true;
		}

		public static int PinnedCount(IDictionary<string, string> customData)
		{
			return GetPinnedIds(customData).Count;
		}

		public static int DoneCount(IDictionary<string, string> customData)
		{
			if (customData == null)
			{
				return 0;
			}
			int num = 0;
			for (int i = 0; i < Definitions.Length; i++)
			{
				AchievementDef achievementDef = Definitions[i];
				if (GetProgress(customData, achievementDef.Id) >= achievementDef.Goal)
				{
					num++;
				}
			}
			return num;
		}

		public static string FormatProgress(AchievementDef def, float progress)
		{
			if (def == null)
			{
				return "";
			}
			if (progress >= def.Goal)
			{
				return "";
			}
			if (string.Equals(def.Unit, "km", StringComparison.OrdinalIgnoreCase))
			{
				float num = progress / 1000f;
				float num2 = def.Goal / 1000f;
				return num.ToString("0.#", CultureInfo.InvariantCulture) + " / " + num2.ToString("0", CultureInfo.InvariantCulture) + " km";
			}
			return Math.Floor(progress).ToString("0", CultureInfo.InvariantCulture) + " / " + def.Goal.ToString("0", CultureInfo.InvariantCulture);
		}

		public static AchievementState GetState(IDictionary<string, string> customData, AchievementDef def)
		{
			if (def == null)
			{
				return null;
			}
			float progress = GetProgress(customData, def.Id);
			return new AchievementState
			{
				Def = def,
				Progress = progress,
				Pinned = IsPinned(customData, def.Id)
			};
		}

		public static List<AchievementState> GetStates(IDictionary<string, string> customData, AchievementTab tab = AchievementTab.All)
		{
			List<AchievementState> list = new List<AchievementState>();
			for (int i = 0; i < Definitions.Length; i++)
			{
				AchievementState state = GetState(customData, Definitions[i]);
				if ((tab != AchievementTab.Active || !state.Done) && (tab != AchievementTab.Done || state.Done) && (tab != AchievementTab.Tracked || (!state.Done && state.Pinned)))
				{
					list.Add(state);
				}
			}
			return list;
		}

		public static List<AchievementState> Tracked(IDictionary<string, string> customData)
		{
			List<AchievementState> list = new List<AchievementState>();
			foreach (string pinnedId in GetPinnedIds(customData))
			{
				AchievementState state = GetState(customData, Find(pinnedId));
				if (state != null && !state.Done && state.Pinned)
				{
					list.Add(state);
					if (list.Count >= 3)
					{
						break;
					}
				}
			}
			return list;
		}

		public static Dictionary<string, string> Export(IDictionary<string, string> customData)
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal);
			if (customData == null)
			{
				return dictionary;
			}
			foreach (KeyValuePair<string, string> customDatum in customData)
			{
				if (customDatum.Key.StartsWith("mw.ach.p.", StringComparison.Ordinal) || customDatum.Key.StartsWith("mw.ach.pin.", StringComparison.Ordinal) || customDatum.Key == "mw.ach.order")
				{
					dictionary[customDatum.Key] = customDatum.Value;
				}
			}
			return dictionary;
		}

		public static void Import(IDictionary<string, string> target, IDictionary<string, string> source)
		{
			if (target == null || source == null)
			{
				return;
			}
			foreach (KeyValuePair<string, string> item in source)
			{
				if (item.Key.StartsWith("mw.ach.p.", StringComparison.Ordinal) || item.Key.StartsWith("mw.ach.pin.", StringComparison.Ordinal) || item.Key == "mw.ach.order")
				{
					target[item.Key] = item.Value;
				}
			}
		}
	}
	public static class AchievementTracker
	{
		[HarmonyPatch]
		private static class Patches
		{
			[HarmonyPostfix]
			[HarmonyPatch(typeof(PlayerProfile), "IncrementStat")]
			private static void OnIncrementStat(PlayerStatType stat, float amount)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0003: Invalid comparison between Unknown and I4
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Invalid comparison between Unknown and I4
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Invalid comparison between Unknown and I4
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Invalid comparison between Unknown and I4
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Invalid comparison between Unknown and I4
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Invalid comparison between Unknown and I4
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Invalid comparison between Unknown and I4
				if ((int)stat <= 18)
				{
					if ((int)stat != 6)
					{
						if ((int)stat != 10)
						{
							if (stat - 16 <= 2)
							{
								Record("long_walk", amount);
							}
						}
						else
						{
							Record("iron_will", amount);
						}
					}
					else
					{
						Record("first_blood", amount);
					}
				}
				else if (stat - 27 > 1 && stat - 35 > 1)
				{
					if (stat - 37 <= 1)
					{
						Record("stonemason", amount);
					}
				}
				else
				{
					Record("timber", amount);
				}
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(PlayerProfile), "IncrementStatEnemy")]
			private static void OnIncrementStatEnemy(string name, float amount)
			{
				Record("first_blood", amount);
				if (!string.IsNullOrEmpty(name) && name.IndexOf("Deer", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					Record("deer_slayer", amount);
				}
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(PlayerProfile), "IncrementStatBuildPiecePlaced")]
			private static void OnIncrementStatBuildPiecePlaced(string name, float amount)
			{
				Record("home_sweet_home", amount);
				if (!string.IsNullOrEmpty(name) && name.IndexOf("stone", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					Record("stonemason", amount);
				}
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(StoreGui), "BuySelectedItem")]
			private static void OnBuySelectedItem()
			{
				Record("trader", 1f);
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(CookingStation), "SpawnItem")]
			private static void OnCookSpawnItem()
			{
				Record("cook", 1f);
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(Fish), "Pickup")]
			private static void OnFishPickup()
			{
				Record("angler", 1f);
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(Player), "SetLocalPlayer")]
			private static void PlayerChanged()
			{
				RestorePins();
			}
		}

		private static Harmony _harmony;

		private static readonly List<string> ShownPins = new List<string>();

		private static bool _doneRow;

		private static string _done;

		private static float _doneUntil;

		private const string DoneKey = "skills.ach.done";

		public static event Action TrackingChanged;

		public static List<AchievementState> Tracked()
		{
			return AchievementRules.Tracked(Player.m_localPlayer?.m_customData);
		}

		private static string GoalKey(string id)
		{
			return "skills.ach." + id;
		}

		public static void Track(string id, bool on)
		{
			AchievementRules.SetPinned(Player.m_localPlayer?.m_customData, id, on);
			AchievementTracker.TrackingChanged?.Invoke();
		}

		public static void Init()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			if (_harmony != null)
			{
				return;
			}
			_harmony = new Harmony("expdare.meadworks.skills.achievements");
			_harmony.PatchAll(typeof(Patches));
			LedgerTrack.Patch(_harmony, "skills achievements");
			TrackingChanged += SyncGoals;
			Ledger.Add("skills achievements tracker", (Action)delegate
			{
				TrackingChanged -= SyncGoals;
				ClearGoals();
				if (_harmony != null)
				{
					_harmony.UnpatchSelf();
					_harmony = null;
				}
				AchievementTracker.TrackingChanged = null;
			});
			SyncGoals();
		}

		internal static void RestorePins()
		{
			SkillGainFeed.Reset();
			ClearGoals();
			SyncGoals();
		}

		private static void SyncGoals()
		{
			Dictionary<string, string> customData = Player.m_localPlayer?.m_customData;
			List<string> list = AchievementRules.Released(ShownPins, customData);
			string text = AchievementRules.CompletedLine(list, customData);
			for (int i = 0; i < list.Count; i++)
			{
				HudDock.Untrack(GoalKey(list[i]));
				ShownPins.Remove(list[i]);
			}
			List<string> pinnedIds = AchievementRules.GetPinnedIds(customData);
			for (int j = 0; j < pinnedIds.Count; j++)
			{
				string text2 = pinnedIds[j];
				if (!ShownPins.Contains(text2))
				{
					string pin = text2;
					HudDock.Track(GoalKey(pin), (Func<string>)(() => GoalLine(pin)));
					ShownPins.Add(pin);
				}
			}
			if (!string.IsNullOrEmpty(text))
			{
				_done = text;
				_doneUntil = Time.unscaledTime + 4f;
				if (!_doneRow)
				{
					HudDock.Track("skills.ach.done", (Func<string>)DoneLine);
					_doneRow = true;
				}
			}
		}

		private static string GoalLine(string id)
		{
			AchievementDef achievementDef = AchievementRules.Find(id);
			if (achievementDef == null)
			{
				return "";
			}
			return AchievementRules.TrackText(achievementDef, AchievementRules.GetProgress(Player.m_localPlayer?.m_customData, id));
		}

		private static string DoneLine()
		{
			if (string.IsNullOrEmpty(_done) || Time.unscaledTime >= _doneUntil)
			{
				return "";
			}
			return _done;
		}

		private static void ClearGoals()
		{
			for (int i = 0; i < ShownPins.Count; i++)
			{
				HudDock.Untrack(GoalKey(ShownPins[i]));
			}
			ShownPins.Clear();
			if (_doneRow)
			{
				HudDock.Untrack("skills.ach.done");
			}
			_doneRow = false;
			_done = null;
		}

		public static void SyncBosses()
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && localPlayer.m_customData != null)
			{
				int num = ProgressivePowers.Defeated();
				AchievementRules.SetProgress(localPlayer.m_customData, "forsaken_hunter", num);
				AchievementTracker.TrackingChanged?.Invoke();
			}
		}

		public static void Record(string id, float amount)
		{
			if (!(amount <= 0f))
			{
				Player localPlayer = Player.m_localPlayer;
				if (!((Object)(object)localPlayer == (Object)null) && localPlayer.m_customData != null)
				{
					AchievementRules.AddProgress(localPlayer.m_customData, id, amount);
					AchievementTracker.TrackingChanged?.Invoke();
				}
			}
		}
	}
	public static class AttunementMigrationRules
	{
		public const string VersionKey = "mw.ski.migration.passive_switches";

		public const string Version = "1";

		public static void Apply(IDictionary<string, string> data, IEnumerable<string> disabled)
		{
			if (data == null || (data.TryGetValue("mw.ski.migration.passive_switches", out var value) && value == "1"))
			{
				return;
			}
			foreach (string item in disabled)
			{
				data["mw.ski.attuned." + item] = "false";
			}
			data["mw.ski.migration.passive_switches"] = "1";
		}
	}
	public static class AttunementRules
	{
		public const int DefaultLimit = 3;

		public const string FlagPrefix = "mw.ski.attuned.";

		public const string OrderPrefix = "mw.ski.attunedat.";

		public static int Limit(int limit)
		{
			return Math.Max(0, Math.Min(9, limit));
		}

		public static int Limit(float limit)
		{
			if (!float.IsNaN(limit) && !float.IsInfinity(limit))
			{
				return (int)Math.Max(0f, Math.Min(9f, limit));
			}
			return 3;
		}

		public static bool IsAttuned(IDictionary<string, string> data, string power)
		{
			string value;
			bool result = default(bool);
			return data == null || !data.TryGetValue("mw.ski.attuned." + power, out value) || !bool.TryParse(value, out result) || result;
		}

		private static long Order(IDictionary<string, string> data, string power)
		{
			if (!data.TryGetValue("mw.ski.attunedat." + power, out var value) || !long.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var result) || result <= 0)
			{
				return 0L;
			}
			return result;
		}

		private static long Next(IDictionary<string, string> data, IEnumerable<string> earned)
		{
			long num = 0L;
			List<string> list = new List<string>(earned);
			foreach (string item in list)
			{
				num = Math.Max(num, Order(data, item));
			}
			if (num >= long.MaxValue - list.Count - 1)
			{
				list.RemoveAll((string power) => Order(data, power) == 0);
				list.Sort(delegate(string a, string b)
				{
					int num3 = Order(data, a).CompareTo(Order(data, b));
					return (num3 == 0) ? string.CompareOrdinal(a, b) : num3;
				});
				num = 0L;
				foreach (string item2 in list)
				{
					IDictionary<string, string> dictionary = data;
					string key = "mw.ski.attunedat." + item2;
					long num2 = ++num;
					dictionary[key] = num2.ToString("D19", CultureInfo.InvariantCulture);
				}
			}
			return num + 1;
		}

		public static List<string> Reconcile(IDictionary<string, string> data, IEnumerable<string> earned, int limit, Func<string, bool> available = null, Func<string, bool> switchedOff = null)
		{
			SortedSet<string> sortedSet = new SortedSet<string>(StringComparer.Ordinal);
			List<string> list = new List<string>();
			if (earned != null)
			{
				foreach (string item in earned)
				{
					if (!string.IsNullOrEmpty(item) && item.StartsWith("GP_", StringComparison.Ordinal) && (available == null || available(item)))
					{
						if (switchedOff != null && switchedOff(item))
						{
							list.Add(item);
						}
						else
						{
							sortedSet.Add(item);
						}
					}
				}
			}
			List<string> list2 = new List<string>();
			if (data == null)
			{
				return list2;
			}
			foreach (string item2 in list)
			{
				data.Remove("mw.ski.attunedat." + item2);
			}
			long num = Next(data, sortedSet);
			foreach (string item3 in sortedSet)
			{
				bool flag = IsAttuned(data, item3);
				data["mw.ski.attuned." + item3] = (flag ? "true" : "false");
				if (flag)
				{
					if (Order(data, item3) == 0L)
					{
						data["mw.ski.attunedat." + item3] = num++.ToString("D19", CultureInfo.InvariantCulture);
					}
					list2.Add(item3);
				}
			}
			list2.Sort(delegate(string a, string b)
			{
				int num2 = Order(data, a).CompareTo(Order(data, b));
				return (num2 == 0) ? string.CompareOrdinal(a, b) : num2;
			});
			limit = Limit(limit);
			while (limit > 0 && list2.Count > limit)
			{
				data["mw.ski.attuned." + list2[0]] = "false";
				list2.RemoveAt(0);
			}
			return list2;
		}

		public static bool Set(IDictionary<string, string> data, IList<string> earned, string power, bool enabled, int limit, Func<string, bool> available = null, Func<string, bool> switchedOff = null)
		{
			if (data == null || earned == null || power == null || !earned.Contains(power) || (available != null && !available(power)) || (switchedOff != null && switchedOff(power)))
			{
				return false;
			}
			Reconcile(data, earned, limit, available, switchedOff);
			if (enabled && !IsAttuned(data, power))
			{
				data["mw.ski.attunedat." + power] = Next(data, earned).ToString("D19", CultureInfo.InvariantCulture);
			}
			data["mw.ski.attuned." + power] = (enabled ? "true" : "false");
			Reconcile(data, earned, limit, available, switchedOff);
			return true;
		}
	}
	public struct BossId : IEquatable<BossId>
	{
		public readonly long User;

		public readonly uint Id;

		public BossId(long user, uint id)
		{
			User = user;
			Id = id;
		}

		public bool Equals(BossId other)
		{
			if (User == other.User)
			{
				return Id == other.Id;
			}
			return false;
		}

		public override bool Equals(object obj)
		{
			if (obj is BossId other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			long user = User;
			return (user.GetHashCode() * 397) ^ (int)Id;
		}
	}
	public enum DeathReport
	{
		Held,
		Invalid,
		AlreadyCredited,
		Duplicate,
		SenderFull,
		QueueFull
	}
	public enum DeathVerdict
	{
		NoReport,
		Credit,
		DestroyedByAnotherPeer,
		ReporterNotOwner,
		WrongPrefab,
		NoDefeatKey,
		TooSoon
	}
	public struct DeathCredit
	{
		public BossId Id;

		public long Sender;

		public string Prefab;

		public string BossKey;

		public float X;

		public float Y;

		public float Z;

		public int Attempts;
	}
	public sealed class BossDeathLedger
	{
		private sealed class Claim
		{
			public BossId Id;

			public long Sender;

			public string Prefab;

			public string BossKey;

			public int PrefabHash;

			public int OwnerRevision;

			public bool OwnerSeen;

			public float X;

			public float Y;

			public float Z;

			public float Since;

			public bool KeySeen;

			public bool Reachable;
		}

		private struct PastOwner
		{
			public BossId Id;

			public long Owner;

			public float Until;
		}

		private struct SpacingRecord
		{
			public long Sender;

			public string BossKey;

			public float At;

			public float Left;
		}

		public const float WaitSeconds = 10f;

		public const int MaxWork = 64;

		public const int MaxPerSender = 4;

		public const int SendPerTick = 4;

		public const int MaxCredited = 256;

		public const float OwnerGrace = 5f;

		public const int MaxPastOwners = 64;

		public const float ZoneSize = 64f;

		public const float CreditSpacing = 60f;

		public const int CreditBurst = 3;

		public const int MaxSpacingRecords = 64;

		private readonly List<Claim> _claims = new List<Claim>(64);

		private readonly List<DeathCredit> _ready = new List<DeathCredit>(64);

		private readonly float _spacing;

		private readonly List<SpacingRecord> _lastCredit = new List<SpacingRecord>(64);

		private readonly List<PastOwner> _owners = new List<PastOwner>(64);

		private readonly HashSet<BossId> _credited = new HashSet<BossId>();

		private readonly Queue<BossId> _creditOrder = new Queue<BossId>();

		public const int MaxSendAttempts = 3;

		public int Count => _claims.Count;

		public int Waiting => _ready.Count;

		public int PastOwners => _owners.Count;

		public bool Idle
		{
			get
			{
				if (_claims.Count == 0 && _ready.Count == 0)
				{
					return _owners.Count == 0;
				}
				return false;
			}
		}

		public BossDeathLedger()
			: this(60f)
		{
		}

		public BossDeathLedger(float spacing)
		{
			_spacing = Math.Max(0f, spacing);
		}

		private float Left(SpacingRecord r, float now)
		{
			return Math.Min(3f, r.Left + Math.Max(0f, now - r.At) / _spacing);
		}

		private int Find(long sender, string key)
		{
			for (int i = 0; i < _lastCredit.Count; i++)
			{
				if (_lastCredit[i].Sender == sender && string.Equals(_lastCredit[i].BossKey, key, StringComparison.Ordinal))
				{
					return i;
				}
			}
			return -1;
		}

		private bool TooSoon(float now, long sender, string key)
		{
			if (_spacing <= 0f)
			{
				return false;
			}
			int num = Find(sender, key);
			if (num >= 0)
			{
				return Left(_lastCredit[num], now) < 1f;
			}
			return false;
		}

		private void Spaced(float now, long sender, string key)
		{
			if (_spacing <= 0f)
			{
				return;
			}
			int num = Find(sender, key);
			if (num >= 0)
			{
				_lastCredit[num] = new SpacingRecord
				{
					Sender = sender,
					BossKey = key,
					At = now,
					Left = Left(_lastCredit[num], now) - 1f
				};
				return;
			}
			if (_lastCredit.Count >= 64)
			{
				int index = 0;
				for (int i = 1; i < _lastCredit.Count; i++)
				{
					if (Left(_lastCredit[i], now) > Left(_lastCredit[index], now))
					{
						index = i;
					}
				}
				_lastCredit.RemoveAt(index);
			}
			_lastCredit.Add(new SpacingRecord
			{
				Sender = sender,
				BossKey = key,
				At = now,
				Left = 2f
			});
		}

		public int Held(long sender)
		{
			int num = 0;
			foreach (Claim claim in _claims)
			{
				if (claim.Sender == sender)
				{
					num++;
				}
			}
			foreach (DeathCredit item in _ready)
			{
				if (item.Sender == sender)
				{
					num++;
				}
			}
			return num;
		}

		public void Clear()
		{
			_claims.Clear();
			_ready.Clear();
			_owners.Clear();
			_credited.Clear();
			_creditOrder.Clear();
			_lastCredit.Clear();
		}

		public static bool WithinReach(float dx, float dz, int simulatedZones)
		{
			if (!Finite(dx) || !Finite(dz))
			{
				return false;
			}
			float num = (float)(Math.Max(1, simulatedZones) + 2) * 64f;
			if (Math.Abs(dx) <= num)
			{
				return Math.Abs(dz) <= num;
			}
			return false;
		}

		public DeathReport Report(float now, long sender, BossId id, string prefab, int prefabHash, string bossKey, float x, float y, float z, bool reachable = true, int ownerRevision = -1)
		{
			if (sender == 0L || string.IsNullOrEmpty(prefab) || string.IsNullOrEmpty(bossKey) || !Finite(x) || !Finite(y) || !Finite(z))
			{
				return DeathReport.Invalid;
			}
			if (_credited.Contains(id))
			{
				return DeathReport.AlreadyCredited;
			}
			foreach (Claim claim in _claims)
			{
				if (claim.Sender == sender && claim.Id.Equals(id))
				{
					return DeathReport.Duplicate;
				}
			}
			if (Held(sender) >= 4)
			{
				return DeathReport.SenderFull;
			}
			if (_claims.Count + _ready.Count >= 64)
			{
				return DeathReport.QueueFull;
			}
			_claims.Add(new Claim
			{
				Id = id,
				Sender = sender,
				Prefab = prefab,
				PrefabHash = prefabHash,
				BossKey = bossKey,
				X = x,
				Y = y,
				Z = z,
				Since = now,
				Reachable = reachable,
				OwnerRevision = ownerRevision,
				OwnerSeen = OwnedUntilLately(now, id, sender)
			});
			return DeathReport.Held;
		}

		public int DefeatKeySet(long actor, string key)
		{
			int num = 0;
			if (actor == 0L || string.IsNullOrEmpty(key))
			{
				return 0;
			}
			foreach (Claim claim in _claims)
			{
				if (claim.Sender == actor && !claim.KeySeen && string.Equals(claim.BossKey, key, StringComparison.Ordinal))
				{
					claim.KeySeen = true;
					num++;
				}
			}
			return num;
		}

		public void OwnerLeft(float now, BossId id, long owner)
		{
			if (owner == 0L)
			{
				return;
			}
			foreach (Claim claim in _claims)
			{
				if (claim.Sender == owner && claim.Id.Equals(id))
				{
					claim.OwnerSeen = true;
				}
			}
			int index = 0;
			for (int i = 0; i < _owners.Count; i++)
			{
				if (_owners[i].Owner == owner && _owners[i].Id.Equals(id))
				{
					_owners[i] = new PastOwner
					{
						Id = id,
						Owner = owner,
						Until = now
					};
					return;
				}
				if (_owners[i].Until < _owners[index].Until)
				{
					index = i;
				}
			}
			if (_owners.Count >= 64)
			{
				_owners.RemoveAt(index);
			}
			_owners.Add(new PastOwner
			{
				Id = id,
				Owner = owner,
				Until = now
			});
		}

		private bool OwnedUntilLately(float now, BossId id, long owner)
		{
			foreach (PastOwner owner2 in _owners)
			{
				if (owner2.Owner == owner)
				{
					BossId id2 = owner2.Id;
					if (id2.Equals(id) && now - owner2.Until <= 5f)
					{
						return true;
					}
				}
			}
			return false;
		}

		public DeathVerdict Destroyed(float now, long actor, BossId id, long owner, int ownerRevision, int prefabHash, float x, float y, float z, out DeathCredit credit)
		{
			credit = default(DeathCredit);
			DeathVerdict deathVerdict = DeathVerdict.NoReport;
			for (int num = _claims.Count - 1; num >= 0; num--)
			{
				Claim claim = _claims[num];
				if (claim.Id.Equals(id))
				{
					_claims.RemoveAt(num);
					if (deathVerdict != DeathVerdict.Credit && deathVerdict != DeathVerdict.TooSoon)
					{
						deathVerdict = Judge(claim, now, actor, owner, ownerRevision, prefabHash);
						if (deathVerdict == DeathVerdict.Credit && TooSoon(now, claim.Sender, claim.BossKey))
						{
							deathVerdict = DeathVerdict.TooSoon;
						}
						if (deathVerdict == DeathVerdict.Credit)
						{
							Spaced(now, claim.Sender, claim.BossKey);
							credit = new DeathCredit
							{
								Id = id,
								Sender = claim.Sender,
								Prefab = claim.Prefab,
								BossKey = claim.BossKey,
								X = claim.X,
								Y = claim.Y,
								Z = claim.Z
							};
							if (!claim.Reachable && Finite(x) && Finite(y) && Finite(z))
							{
								credit.X = x;
								credit.Y = y;
								credit.Z = z;
							}
						}
					}
				}
			}
			for (int num2 = _owners.Count - 1; num2 >= 0; num2--)
			{
				if (_owners[num2].Id.Equals(id))
				{
					_owners.RemoveAt(num2);
				}
			}
			if (deathVerdict == DeathVerdict.Credit)
			{
				Remember(id);
				_ready.Add(credit);
			}
			return deathVerdict;
		}

		private DeathVerdict Judge(Claim claim, float now, long actor, long owner, int ownerRevision, int prefabHash)
		{
			if (actor == 0L || actor != claim.Sender)
			{
				return DeathVerdict.DestroyedByAnotherPeer;
			}
			if (owner != claim.Sender && !claim.OwnerSeen && !OwnedUntilLately(now, claim.Id, claim.Sender) && (claim.OwnerRevision < 0 || claim.OwnerRevision <= ownerRevision))
			{
				return DeathVerdict.ReporterNotOwner;
			}
			if (prefabHash != claim.PrefabHash)
			{
				return DeathVerdict.WrongPrefab;
			}
			if (!claim.KeySeen)
			{
				return DeathVerdict.NoDefeatKey;
			}
			return DeathVerdict.Credit;
		}

		public bool Next(out DeathCredit credit)
		{
			if (_ready.Count == 0)
			{
				credit = default(DeathCredit);
				return false;
			}
			credit = _ready[0];
			_ready.RemoveAt(0);
			return true;
		}

		public bool Retry(DeathCredit credit)
		{
			credit.Attempts++;
			if (credit.Attempts >= 3)
			{
				return false;
			}
			_ready.Insert(0, credit);
			return true;
		}

		public int SendDue(Action<DeathCredit> send, Action<DeathCredit, Exception> gaveUp)
		{
			int num = 0;
			for (int i = 0; i < 4; i++)
			{
				if (!Next(out var credit))
				{
					break;
				}
				try
				{
					send(credit);
					num++;
				}
				catch (Exception arg)
				{
					if (Retry(credit))
					{
						break;
					}
					gaveUp?.Invoke(credit, arg);
				}
			}
			return num;
		}

		public int Expire(float now)
		{
			int num = 0;
			for (int num2 = _claims.Count - 1; num2 >= 0; num2--)
			{
				if (!(now - _claims[num2].Since < 10f))
				{
					_claims.RemoveAt(num2);
					num++;
				}
			}
			for (int num3 = _owners.Count - 1; num3 >= 0; num3--)
			{
				if (!(now - _owners[num3].Until <= 5f))
				{
					_owners.RemoveAt(num3);
				}
			}
			for (int num4 = _lastCredit.Count - 1; num4 >= 0; num4--)
			{
				if (Left(_lastCredit[num4], now) >= 3f)
				{
					_lastCredit.RemoveAt(num4);
				}
			}
			return num;
		}

		private void Remember(BossId id)
		{
			if (_credited.Add(id))
			{
				_creditOrder.Enqueue(id);
				while (_creditOrder.Count > 256)
				{
					_credited.Remove(_creditOrder.Dequeue());
				}
			}
		}

		private static bool Finite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}
	}
	public static class BossDiscovery
	{
		private static ZNetScene _scene;

		private static List<BossLink> _links = new List<BossLink>();

		private static List<CharInfo> _excluded = new List<CharInfo>();

		private static List<StandInfo> _stands = new List<StandInfo>();

		public static void Reset()
		{
			_scene = null;
			_links = new List<BossLink>();
			_excluded = new List<CharInfo>();
			_stands = new List<StandInfo>();
		}

		public static void Scan()
		{
			ZNetScene instance = ZNetScene.instance;
			if ((Object)(object)instance == (Object)null || instance.m_prefabs == null || instance == _scene)
			{
				return;
			}
			List<StandInfo> list = new List<StandInfo>();
			List<CharInfo> list2 = new List<CharInfo>();
			foreach (GameObject prefab in instance.m_prefabs)
			{
				if ((Object)(object)prefab == (Object)null)
				{
					continue;
				}
				ItemStand[] componentsInChildren = prefab.GetComponentsInChildren<ItemStand>(true);
				foreach (ItemStand val in componentsInChildren)
				{
					if ((Object)(object)val == (Object)null || (Object)(object)val.m_guardianPower == (Object)null || val.m_supportedItems == null)
					{
						continue;
					}
					List<string> list3 = new List<string>();
					foreach (ItemDrop supportedItem in val.m_supportedItems)
					{
						if ((Object)(object)supportedItem != (Object)null)
						{
							list3.Add(((Object)supportedItem).name);
						}
					}
					list.Add(new StandInfo
					{
						Power = ((Object)val.m_guardianPower).name,
						Trophies = list3.ToArray()
					});
				}
				Character component = prefab.GetComponent<Character>();
				if ((Object)(object)component == (Object)null || string.IsNullOrEmpty(component.m_defeatSetGlobalKey))
				{
					continue;
				}
				List<string> list4 = new List<string>();
				CharacterDrop component2 = prefab.GetComponent<CharacterDrop>();
				if ((Object)(object)component2 != (Object)null && component2.m_drops != null)
				{
					foreach (Drop drop in component2.m_drops)
					{
						if (drop != null && (Object)(object)drop.m_prefab != (Object)null)
						{
							list4.Add(((Object)drop.m_prefab).name);
						}
					}
				}
				list2.Add(new CharInfo
				{
					Prefab = ((Object)prefab).name,
					Key = component.m_defeatSetGlobalKey,
					IsBoss = component.m_boss,
					Drops = list4.ToArray()
				});
			}
			_links = BossLinks.Link(list, list2);
			_excluded = BossLinks.Excluded(list2, _links);
			_stands = list;
			_scene = instance;
			MwLog.Debug((object)("skills bosses: " + ((_links.Count == 0) ? "none found, using the fixed list" : (_links.Count + " found (" + string.Join(", ", BossLinks.Keys(_links).ToArray()) + ")")) + "; " + _excluded.Count + " other boss characters excluded"));
		}

		public static string[] Keys()
		{
			Scan();
			return BossLinks.Keys(_links).ToArray();
		}

		public static IList<BossLink> Links()
		{
			Scan();
			return _links.AsReadOnly();
		}

		public static int Defeated(IEnumerable<string> globalKeys)
		{
			if (!ProgressRules.IsFallback(Keys()))
			{
				return BossLinks.CountDefeated(_links, globalKeys);
			}
			return ProgressRules.CountDefeated(globalKeys);
		}

		public static string Report()
		{
			string[] array = Keys();
			ZoneSystem instance = ZoneSystem.instance;
			string[] array2 = (ProgressRules.IsFallback(array) ? ProgressRules.ForsakenKeys : array);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("bosses source=").Append(ProgressRules.IsFallback(array) ? "fallback" : "discovered").Append(" counted=")
				.Append(ProgressRules.IsFallback(array) ? array2.Length : BossLinks.PowerCount(_links))
				.Append(" defeated=")
				.Append(ProgressivePowers.Defeated());
			if (ProgressRules.IsFallback(array))
			{
				string[] array3 = array2;
				foreach (string text in array3)
				{
					stringBuilder.Append("\nboss key=").Append(text).Append(" defeated=")
						.Append((Object)(object)instance != (Object)null && instance.GetGlobalKey(text));
				}
			}
			foreach (BossLink link in _links)
			{
				stringBuilder.Append("\nboss prefab=").Append(link.Prefab).Append(" key=")
					.Append(link.Key)
					.Append(" power=")
					.Append(link.Power)
					.Append(" defeated=")
					.Append((Object)(object)instance != (Object)null && instance.GetGlobalKey(link.Key));
			}
			foreach (CharInfo item in _excluded)
			{
				stringBuilder.Append("\nexcluded prefab=").Append(item.Prefab).Append(" key=")
					.Append(item.Key)
					.Append(" defeated=")
					.Append((Object)(object)instance != (Object)null && instance.GetGlobalKey(item.Key))
					.Append(" drops=")
					.Append(string.Join(",", item.Drops ?? new string[0]));
			}
			foreach (StandInfo stand in _stands)
			{
				stringBuilder.Append("\nstand power=").Append(stand.Power).Append(" accepts=")
					.Append(string.Join(",", stand.Trophies ?? new string[0]));
			}
			return stringBuilder.ToString();
		}
	}
	public sealed class StandInfo
	{
		public string Power;

		public string[] Trophies;
	}
	public sealed class CharInfo
	{
		public string Prefab;

		public string Key;

		public bool IsBoss;

		public string[] Drops;
	}
	public sealed class BossLink
	{
		public string Prefab;

		public string Key;

		public string Power;
	}
	public static class BossLinks
	{
		public static readonly Dictionary<string, string> UnlinkedStones = new Dictionary<string, string>(StringComparer.Ordinal)
		{
			{ "FrozenKing", "GP_DeepNorth" },
			{ "FrozenKing_p2", "GP_DeepNorth" },
			{ "FrozenKing_p3", "GP_DeepNorth" }
		};

		public static List<BossLink> Link(IEnumerable<StandInfo> stands, IEnumerable<CharInfo> characters)
		{
			List<BossLink> list = new List<BossLink>();
			if (stands == null || characters == null)
			{
				return list;
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal);
			foreach (StandInfo stand in stands)
			{
				if (stand == null || string.IsNullOrEmpty(stand.Power) || stand.Trophies == null)
				{
					continue;
				}
				string[] trophies = stand.Trophies;
				foreach (string text in trophies)
				{
					if (!string.IsNullOrEmpty(text) && !dictionary.ContainsKey(text))
					{
						dictionary[text] = stand.Power;
					}
				}
			}
			foreach (CharInfo character in characters)
			{
				if (character == null || string.IsNullOrEmpty(character.Key) || character.Drops == null)
				{
					continue;
				}
				string[] trophies = character.Drops;
				foreach (string text2 in trophies)
				{
					if (text2 != null && dictionary.TryGetValue(text2, out var value))
					{
						list.Add(new BossLink
						{
							Prefab = character.Prefab,
							Key = character.Key,
							Power = value
						});
						break;
					}
				}
			}
			foreach (CharInfo c in characters)
			{
				if (c != null && !string.IsNullOrEmpty(c.Key) && UnlinkedStones.TryGetValue(c.Prefab ?? "", out var value2) && !list.Exists((BossLink l) => l.Prefab == c.Prefab))
				{
					list.Add(new BossLink
					{
						Prefab = c.Prefab,
						Key = c.Key,
						Power = value2
					});
				}
			}
			list.Sort((BossLink a, BossLink b) => string.CompareOrdinal(a.Prefab, b.Prefab));
			return list;
		}

		public static List<string> Keys(IEnumerable<BossLink> links)
		{
			List<string> list = new List<string>();
			if (links == null)
			{
				return list;
			}
			foreach (BossLink l in links)
			{
				if (!list.Exists((string k) => string.Equals(k, l.Key, StringComparison.OrdinalIgnoreCase)))
				{
					list.Add(l.Key);
				}
			}
			return list;
		}

		public static int CountDefeated(IEnumerable<BossLink> links, IEnumerable<string> globalKeys)
		{
			if (links == null || globalKeys == null)
			{
				return 0;
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (string globalKey in globalKeys)
			{
				if (globalKey != null)
				{
					hashSet.Add(globalKey);
				}
			}
			HashSet<string> hashSet2 = new HashSet<string>(StringComparer.Ordinal);
			foreach (BossLink link in links)
			{
				if (link != null && Counts(link.Key) && hashSet.Contains(link.Key))
				{
					hashSet2.Add(link.Power ?? link.Key);
				}
			}
			return hashSet2.Count;
		}

		private static bool Counts(string key)
		{
			if (!string.IsNullOrEmpty(key))
			{
				return !string.Equals(key, "defeated_frozenking", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		public static int PowerCount(IEnumerable<BossLink> links)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			if (links != null)
			{
				foreach (BossLink link in links)
				{
					if (link != null)
					{
						hashSet.Add(link.Power ?? link.Key);
					}
				}
			}
			return hashSet.Count;
		}

		public static List<CharInfo> Excluded(IEnumerable<CharInfo> characters, IEnumerable<BossLink> links)
		{
			List<string> list = Keys(links);
			List<CharInfo> list2 = new List<CharInfo>();
			if (characters == null)
			{
				return list2;
			}
			foreach (CharInfo c in characters)
			{
				if (c != null && c.IsBoss && !string.IsNullOrEmpty(c.Key) && !list.Exists((string k) => string.Equals(k, c.Key, StringComparison.OrdinalIgnoreCase)))
				{
					list2.Add(c);
				}
			}
			list2.Sort((CharInfo a, CharInfo b) => string.CompareOrdinal(a.Prefab, b.Prefab));
			return list2;
		}
	}
	public static class BossVisibilityRules
	{
		public static bool Known(string key, string power, IEnumerable<BossLink> links, IEnumerable<string> globalKeys, IEnumerable<string> playerKeys)
		{
			HashSet<string> world = new HashSet<string>(globalKeys ?? new string[0], StringComparer.OrdinalIgnoreCase);
			HashSet<string> hashSet = new HashSet<string>(playerKeys ?? new string[0], StringComparer.Ordinal);
			if (Defeated(key, world, hashSet))
			{
				return true;
			}
			if (string.IsNullOrEmpty(power))
			{
				return false;
			}
			if (hashSet.Contains(power))
			{
				return true;
			}
			if (links != null)
			{
				foreach (BossLink link in links)
				{
					if (link != null && link.Power == power && Defeated(link.Key, world, hashSet))
					{
						return true;
					}
				}
			}
			return false;
		}

		private static bool Defeated(string key, HashSet<string> world, HashSet<string> player)
		{
			if (!string.IsNullOrEmpty(key))
			{
				if (!world.Contains(key))
				{
					return player.Contains(PassivePowerRules.FightKey(key));
				}
				return true;
			}
			return false;
		}
	}
	internal static class CatchUp
	{
		private static class Patches
		{
			[HarmonyPatch(typeof(Skills), "RaiseSkill")]
			[HarmonyPrefix]
			private unsafe static void BeforeRaise(Skills __instance, SkillType skillType, ref float factor)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				if (Local(__instance) && (int)skillType != 0)
				{
					Ensure();
					Best.TryGetValue(((object)(*(SkillType*)(&skillType))/*cast due to .constrained prefix*/).ToString(), out var value);
					factor *= CatchUpRules.Factor(_on != null && _on.Value, Level(__instance, skillType), value);
				}
			}

			[HarmonyPatch(typeof(Skills), "RaiseSkill")]
			[HarmonyPostfix]
			private unsafe static void AfterRaise(Skills __instance, SkillType skillType)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				if (Local(__instance) && (int)skillType != 0)
				{
					Ensure();
					Note(((object)(*(SkillType*)(&skillType))/*cast due to .constrained prefix*/).ToString(), Level(__instance, skillType));
					Save();
				}
			}

			[HarmonyPatch(typeof(Skills), "CheatRaiseSkill")]
			[HarmonyPostfix]
			private static void AfterCheat(Skills __instance)
			{
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				if (!Local(__instance))
				{
					return;
				}
				Ensure();
				List<Skill> skillList = __instance.GetSkillList();
				for (int i = 0; i < skillList.Count; i++)
				{
					Skill val = skillList[i];
					if (val != null && val.m_info != null && (int)val.m_info.m_skill != 0)
					{
						Note(((object)Unsafe.As<SkillType, SkillType>(ref val.m_info.m_skill)/*cast due to .constrained prefix*/).ToString(), val.m_level);
					}
				}
				Save();
			}

			[HarmonyPatch(typeof(Skills), "ResetSkill")]
			[HarmonyPostfix]
			private unsafe static void AfterReset(Skills __instance, SkillType skillType)
			{
				if (Local(__instance))
				{
					Ensure();
					if (Best.Remove(((object)(*(SkillType*)(&skillType))/*cast due to .constrained prefix*/).ToString()))
					{
						Save();
					}
				}
			}

			[HarmonyPatch(typeof(Skills), "Clear")]
			[HarmonyPostfix]
			private static void AfterClear(Skills __instance)
			{
				if (Local(__instance))
				{
					Ensure();
					Dictionary<string, string> dictionary = (((Object)(object)Player.m_localPlayer == (Object)null) ? null : Player.m_localPlayer.m_customData);
					if (Best.Count != 0 || (dictionary != null && dictionary.ContainsKey("mw.ski.best")))
					{
						Best.Clear();
						Save();
					}
				}
			}

			[HarmonyPatch(typeof(Player), "SetLocalPlayer")]
			[HarmonyPostfix]
			private static void PlayerChanged()
			{
				Take(Player.m_localPlayer);
			}
		}

		private static Setting<bool> _on;

		private static readonly Dictionary<string, int> Best = new Dictionary<string, int>(StringComparer.Ordinal);

		private static bool _loaded;

		public static void Init(SettingsPage page)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			_on = page.Toggle("catch_up", "Catch up", true, (SettingPolicy)1, false);
			Harmony harmony = new Harmony("expdare.meadworks.skills.catchup");
			harmony.PatchAll(typeof(Patches));
			LedgerTrack.Patch(harmony, "skills catch up");
			Ledger.Add("skills catch up", (Action)delegate
			{
				Best.Clear();
				_loaded = false;
				_on = null;
				harmony.UnpatchSelf();
			});
		}

		internal static string Describe()
		{
			Ensure();
			string text = ((_on != null && _on.Value) ? "on" : "off");
			string text2 = CatchUpRules.Format(Best);
			if (text2.Length != 0)
			{
				return "catchup " + text + " " + text2;
			}
			return "catchup " + text;
		}

		private static void Ensure()
		{
			if (!_loaded)
			{
				Player localPlayer = Player.m_localPlayer;
				if (!((Object)(object)localPlayer == (Object)null))
				{
					Take(localPlayer);
				}
			}
		}

		internal static void Take(Player player)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			Best.Clear();
			_loaded = (Object)(object)player != (Object)null;
			if ((Object)(object)player == (Object)null || player.m_customData == null)
			{
				return;
			}
			player.m_customData.TryGetValue("mw.ski.best", out var value);
			CatchUpRules.Parse(value, Best);
			Skills skills = ((Character)player).GetSkills();
			List<Skill> list = (((Object)(object)skills == (Object)null) ? null : skills.GetSkillList());
			if (list != null)
			{
				for (int i = 0; i < list.Count; i++)
				{
					Skill val = list[i];
					if (val != null && val.m_info != null && (int)val.m_info.m_skill != 0)
					{
						Note(((object)Unsafe.As<SkillType, SkillType>(ref val.m_info.m_skill)/*cast due to .constrained prefix*/).ToString(), val.m_level);
					}
				}
			}
			Store(player, value ?? "");
		}

		private static void Note(string name, float level)
		{
			if (!string.IsNullOrEmpty(name))
			{
				Best.TryGetValue(name, out var value);
				int num = CatchUpRules.Note(value, level);
				if (num != value)
				{
					Best[name] = num;
				}
			}
		}

		private static void Store(Player player, string previous)
		{
			if (!((Object)(object)player == (Object)null) && player.m_customData != null)
			{
				string text = CatchUpRules.Format(Best);
				if (text.Length == 0)
				{
					player.m_customData.Remove("mw.ski.best");
				}
				else if (!(text == previous))
				{
					player.m_customData["mw.ski.best"] = text;
				}
			}
		}

		private static void Save()
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && localPlayer.m_customData != null)
			{
				localPlayer.m_customData.TryGetValue("mw.ski.best", out var value);
				Store(localPlayer, value ?? "");
			}
		}

		private static bool Local(Skills skills)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && (Object)(object)skills != (Object)null)
			{
				return skills == ((Character)localPlayer).GetSkills();
			}
			return false;
		}

		private static float Level(Skills skills, SkillType type)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			List<Skill> skillList = skills.GetSkillList();
			for (int i = 0; i < skillList.Count; i++)
			{
				Skill val = skillList[i];
				if (val != null && val.m_info != null && val.m_info.m_skill == type)
				{
					return val.m_level;
				}
			}
			return 0f;
		}
	}
	public static class CatchUpRules
	{
		public const float Rate = 2f;

		public const int MaxLevel = 100;

		public const string Key = "mw.ski.best";

		public static float Factor(bool on, float level, int best)
		{
			if (!on || best <= 0 || float.IsNaN(level))
			{
				return 1f;
			}
			if (!(level < (float)best))
			{
				return 1f;
			}
			return 2f;
		}

		public static int Note(int best, float level)
		{
			if (best < 0)
			{
				best = 0;
			}
			if (float.IsNaN(level) || level < 1f)
			{
				return best;
			}
			int num = (int)Math.Floor(level);
			if (num > 100)
			{
				num = 100;
			}
			if (num <= best)
			{
				return best;
			}
			return num;
		}

		public static string Format(IDictionary<string, int> best)
		{
			if (best == null || best.Count == 0)
			{
				return "";
			}
			List<string> list = new List<string>(best.Count);
			foreach (KeyValuePair<string, int> item in best)
			{
				if (!string.IsNullOrEmpty(item.Key) && item.Value > 0)
				{
					list.Add(item.Key);
				}
			}
			list.Sort(StringComparer.Ordinal);
			List<string> list2 = new List<string>(list.Count);
			foreach (string item2 in list)
			{
				list2.Add(item2 + "=" + best[item2].ToString(CultureInfo.InvariantCulture));
			}
			return string.Join(";", list2);
		}

		public static void Parse(string text, IDictionary<string, int> into)
		{
			if (into == null || string.IsNullOrEmpty(text))
			{
				return;
			}
			string[] array = text.Split(new char[1] { ';' });
			for (int i = 0; i < array.Length; i++)
			{
				int num = array[i].IndexOf('=');
				if (num > 0 && int.TryParse(array[i].Substring(num + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && result >= 1)
				{
					if (result > 100)
					{
						result = 100;
					}
					string key = array[i].Substring(0, num);
					if (!into.TryGetValue(key, out var value) || result > value)
					{
						into[key] = result;
					}
				}
			}
		}
	}
	internal static class FishingLoop
	{
		private sealed class Line
		{
			public float Tension;

			public float ProbeAt;

			public int Bucket = -1;

			public bool Snag;
		}

		private sealed class Receipt
		{
			public string Key;

			public string Item;

			public int Quality;

			public int Before;

			public float Until;
		}

		private struct Pickup
		{
			public ZDOID Id;

			public Receipt Receipt;

			public bool Provisional;
		}

		private static class Patches
		{
			[HarmonyPatch(typeof(FishingFloat), "FixedUpdate")]
			[HarmonyPrefix]
			private static void Update(FishingFloat __instance)
			{
				//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
				//IL_0103: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)__instance.m_nview == (Object)null || !__instance.m_nview.IsValid() || !__instance.m_nview.IsOwner() || (Object)(object)__instance.GetOwner() != (Object)(object)Player.m_localPlayer || (Object)(object)Player.m_localPlayer == (Object)null || ((Character)Player.m_localPlayer).InAttack() || ((Character)Player.m_localPlayer).IsDrawingBow())
				{
					return;
				}
				Fish val = __instance.GetCatch();
				if ((Object)(object)val == (Object)null)
				{
					Lines.Remove(__instance);
					return;
				}
				if (!Lines.TryGetValue(__instance, out var value))
				{
					value = (Lines[__instance] = new Line());
				}
				bool reeling = ((Character)Player.m_localPlayer).IsBlocking() && ((Character)Player.m_localPlayer).HaveStamina(0f);
				if (Time.time >= value.ProbeAt)
				{
					value.ProbeAt = Time.time + 0.5f;
					Transform rodTop = __instance.GetRodTop((Character)(object)Player.m_localPlayer);
					bool flag = (Object)(object)rodTop != (Object)null && Physics.Linecast(rodTop.position, ((Component)__instance).transform.position, LayerMask.GetMask(new string[1] { "terrain" }), (QueryTriggerInteraction)1);
					if (flag && !value.Snag)
					{
						HudPickup.Show("skills.fishing.snag", Lang.T("skills.line_snag", "Snag"), 0, (string)null, (Sprite)null);
					}
					value.Snag = flag;
				}
				int quality = (((Object)(object)val.m_itemDrop == (Object)null) ? 1 : val.m_itemDrop.m_itemData.m_quality);
				value.Tension = FishingLoopRules.Tension(value.Tension, Time.fixedDeltaTime, reeling, val.IsEscaping() || value.Snag, quality, ((Character)Player.m_localPlayer).GetSkillFactor((SkillType)104));
				if (value.Tension >= 1f)
				{
					__instance.SetCatch((Fish)null);
					val.OnHooked((FishingFloat)null);
					Game.instance.IncrementPlayerStat((PlayerStatType)159, 1f, false);
					((Character)Player.m_localPlayer).Message((MessageType)1, Lang.T("skills.line_lost", "Line tension lost the fish"), 0, (Sprite)null, false);
					Lines.Remove(__instance);
					return;
				}
				int num = (int)(value.Tension * 5f);
				if (num != value.Bucket)
				{
					value.Bucket = num;
					HudPickup.Show("skills.fishing.tension", Lang.T("skills.line_tension", "Tension {0}%", new object[1] { num * 20 }), 0, (string)null, (Sprite)null);
				}
			}

			[HarmonyPatch(typeof(FishingFloat), "OnDestroy")]
			[HarmonyPostfix]
			private static void Destroyed(FishingFloat __instance)
			{
				Lines.Remove(__instance);
			}

			[HarmonyPatch(typeof(FishingFloat), "RPC_Nibble")]
			[HarmonyPrefix]
			private static void BeforeNibble(FishingFloat __instance, out float __state)
			{
				__state = __instance.m_nibbleTime;
			}

			[HarmonyPatch(typeof(FishingFloat), "RPC_Nibble")]
			[HarmonyPostfix]
			private static void Bite(FishingFloat __instance, bool correctBait, float __state)
			{
				if (__instance.m_nibbleTime != __state && (Object)(object)Player.m_localPlayer != (Object)null && correctBait && (Object)(object)__instance.m_nibbler != (Object)null && (Object)(object)__instance.GetOwner() == (Object)(object)Player.m_localPlayer)
				{
					HudPickup.Show("skills.fishing.bite", Lang.T("skills.bite", "Bite"), 0, (string)null, (Sprite)null);
				}
			}

			[HarmonyPatch(typeof(FishingFloat), "Catch")]
			[HarmonyPrefix]
			private static void Catch(Fish fish, Character owner)
			{
				if (!((Object)(object)owner != (Object)(object)Player.m_localPlayer) && !((Object)(object)fish == (Object)null))
				{
					Remember(fish);
				}
			}

			private static bool LocalCatch(Fish fish)
			{
				FishingFloat val = FishingFloat.FindFloat(fish);
				if ((Object)(object)val != (Object)null)
				{
					return (Object)(object)val.GetOwner() == (Object)(object)Player.m_localPlayer;
				}
				return false;
			}

			private static Receipt Remember(Fish fish)
			{
				//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
				ItemDrop val = (((Object)(object)fish.m_itemDrop != (Object)null) ? fish.m_itemDrop : (((Object)(object)fish.m_pickupItem == (Object)null) ? null : fish.m_pickupItem.GetComponent<ItemDrop>()));
				if ((Object)(object)val == (Object)null || val.m_itemData == null || val.m_itemData.m_shared == null)
				{
					return null;
				}
				ItemData itemData = val.m_itemData;
				if (Pending.Count >= 32)
				{
					Pending.Clear();
				}
				Receipt receipt = new Receipt
				{
					Key = "mw.skills.catch.v1." + Utils.GetPrefabName(((Component)fish).gameObject),
					Item = itemData.m_shared.m_name,
					Quality = itemData.m_quality,
					Until = Time.time + 30f
				};
				Pending[fish.GetZDOID()] = receipt;
				return receipt;
			}

			[HarmonyPatch(typeof(Humanoid), "Pickup")]
			[HarmonyPrefix]
			private static void BeforePickup(Humanoid __instance, GameObject go, out Pickup __state)
			{
				//IL_0030: 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_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
				//IL_006b: Unknown result type (might be due to invalid IL or missing references)
				__state = default(Pickup);
				if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)go == (Object)null)
				{
					return;
				}
				Fish component = go.GetComponent<Fish>();
				if ((Object)(object)component == (Object)null)
				{
					return;
				}
				ZDOID zDOID = component.GetZDOID();
				Receipt value;
				bool flag = Pending.TryGetValue(zDOID, out value);
				bool flag2 = flag && Time.time <= value.Until;
				bool provisional = false;
				if (!flag2)
				{
					if (flag)
					{
						Pending.Remove(zDOID);
					}
					if (!FishingLoopRules.ArmProvisional(flag2, LocalCatch(component)))
					{
						return;
					}
					value = Remember(component);
					if (value == null)
					{
						return;
					}
					provisional = true;
				}
				value.Before = Count(__instance, value);
				__state = new Pickup
				{
					Id = zDOID,
					Receipt = value,
					Provisional = provisional
				};
			}

			[HarmonyPatch(typeof(Humanoid), "Pickup")]
			[HarmonyPostfix]
			private static void AfterPickup(Humanoid __instance, Pickup __state)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0076: Unknown result type (might be due to invalid IL or missing references)
				Receipt receipt = __state.Receipt;
				if (receipt == null)
				{
					return;
				}
				bool flag = Count(__instance, receipt) > receipt.Before;
				if (flag)
				{
					if (Pending.Remove(__state.Id))
					{
						Dictionary<string, string> customData = Player.m_localPlayer.m_customData;
						customData.TryGetValue(receipt.Key, out var value);
						customData[receipt.Key] = FishingLoopRules.Record(value, receipt.Quality);
					}
				}
				else if (!FishingLoopRules.RetainPending(__state.Provisional, flag))
				{
					Pending.Remove(__state.Id);
				}
			}

			[HarmonyPatch(typeof(Player), "SetLocalPlayer")]
			[HarmonyPostfix]
			private static void Changed()
			{
				Lines.Clear();
				Pending.Clear();
			}

			[HarmonyPatch(typeof(Fish), "RPC_Pickup")]
			[HarmonyPrefix]
			private static void LegacyBefore(Fish __instance, out Pickup __state)
			{
				//IL_001c: 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_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				__state = default(Pickup);
				Player localPlayer = Player.m_localPlayer;
				if (!((Object)(object)localPlayer == (Object)null) && Pending.TryGetValue(__instance.GetZDOID(), out var value))
				{
					if (Time.time > value.Until)
					{
						Pending.Remove(__instance.GetZDOID());
						return;
					}
					value.Before = Count((Humanoid)(object)localPlayer, value);
					__state = new Pickup
					{
						Id = __instance.GetZDOID(),
						Receipt = value
					};
				}
			}

			[HarmonyPatch(typeof(Fish), "RPC_Pickup")]
			[HarmonyPostfix]
			private static void LegacyAfter(Pickup __state)
			{
				if ((Object)(object)Player.m_localPlayer != (Object)null)
				{
					AfterPickup((Humanoid)(object)Player.m_localPlayer, __state);
				}
			}
		}

		private static readonly Dictionary<FishingFloat, Line> Lines = new Dictionary<FishingFloat, Line>();

		private static readonly Dictionary<ZDOID, Receipt> Pending = new Dictionary<ZDOID, Receipt>();

		internal static void Init()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			Harmony harmony = new Harmony("expdare.meadworks.skills.fishing");
			harmony.PatchAll(typeof(Patches));
			LedgerTrack.Patch(harmony, "fishing loop");
			KitHostStrip.Register("catch_log", Lang.T("skills.catch_log", "Catch log"), "fish", (Action<RectTransform>)Build, (Action)null, (Func<bool>)(() => (Object)(object)Player.m_localPlayer != (Object)null), 290, (Func<bool>)null, (Func<int>)null, (Func<bool>)null, 620f, (Func<bool>)null);
			Ledger.Add("fishing loop", (Action)delegate
			{
				Lines.Clear();
				Pending.Clear();
				harmony.UnpatchSelf();
			});
		}

		private static int Count(Humanoid player, Receipt receipt)
		{
			int num = 0;
			foreach (ItemData allItem in player.GetInventory().GetAllItems())
			{
				if (allItem.m_shared.m_name == receipt.Item && allItem.m_quality == receipt.Quality)
				{
					num += allItem.m_stack;
				}
			}
			return num;
		}

		private static void Build(RectTransform body)
		{
			//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)
			Rect rect = body.rect;
			KitList val = Kit.List((Transform)(object)body, Mathf.Max(200f, ((Rect)(ref rect)).height - 20f));
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			List<string> list = new List<string>(localPlayer.m_customData.Keys);
			list.Sort(StringComparer.Ordinal);
			foreach (string item in list)
			{
				if (item.StartsWith("mw.skills.catch.v1.", StringComparison.Ordinal) && FishingLoopRules.Read(localPlayer.m_customData[item], out var count, out var best))
				{
					ZNetScene instance = ZNetScene.instance;
					GameObject val2 = ((instance != null) ? instance.GetPrefab(item.Substring("mw.skills.catch.v1.".Length)) : null);
					ItemDrop val3 = (((Object)(object)val2 == (Object)null) ? null : val2.GetComponent<ItemDrop>());
					string text = (((Object)(object)val3 == (Object)null) ? item.Substring("mw.skills.catch.v1.".Length) : Localization.instance.Localize(val3.m_itemData.m_shared.m_name));
					val.AddRow(text).Meta = Lang.T("skills.catch_record", "{0} · best {1}", new object[2] { count, best });
				}
			}
		}
	}
	public static class FishingLoopRules
	{
		public const string CatchPrefix = "mw.skills.catch.v1.";

		public static bool ArmProvisional(bool waiting, bool hooked)
		{
			return !waiting && hooked;
		}

		public static bool RetainPending(bool provisional, bool grew)
		{
			if (!provisional)
			{
				return !grew;
			}
			return false;
		}

		public static float Tension(float held, float dt, bool reeling, bool escaping, int quality, float skill)
		{
			if (!SkillPerkRules.Finite(held) || !SkillPerkRules.Finite(dt) || dt <= 0f)
			{
				return 0f;
			}
			quality = Math.Max(1, Math.Min(quality, 5));
			skill = (SkillPerkRules.Finite(skill) ? Math.Max(0f, Math.Min(skill, 1f)) : 0f);
			float num = ((!reeling) ? (-0.3f) : (escaping ? (0.2f * (1f + (float)(quality - 1) * 0.15f) * (1f - skill * 0.5f)) : 0.025f));
			return Math.Max(0f, Math.Min(1f, held + num * Math.Min(dt, 0.1f)));
		}

		public static string Record(string previous, int quality)
		{
			if (quality < 1 || quality > 100)
			{
				return previous;
			}
			int count = 0;
			int best = 0;
			if (!string.IsNullOrEmpty(previous) && !Read(previous, out count, out best))
			{
				return previous;
			}
			return Math.Min(1000000, count + 1).ToString(CultureInfo.InvariantCulture) + ":" + Math.Max(best, quality).ToString(CultureInfo.InvariantCulture);
		}

		public static bool Read(string text, out int count, out int best)
		{
			count = (best = 0);
			if (text == null)
			{
				return false;
			}
			string[] array = text.Split(new char[1] { ':' });
			if (array.Length == 2 && int.TryParse(array[0], NumberStyles.None, CultureInfo.InvariantCulture, out count) && int.TryParse(array[1], NumberStyles.None, CultureInfo.InvariantCulture, out best) && count >= 1 && count <= 1000000 && best >= 1)
			{
				return best <= 100;
			}
			return false;
		}
	}
	public static class LegacyAttunement
	{
		private static readonly Dictionary<string, string> Powers = new Dictionary<string, string>
		{
			{ "eikthyr_passive", "GP_Eikthyr" },
			{ "elder_passive", "GP_TheElder" },
			{ "bonemass_passive", "GP_Bonemass" },
			{ "moder_passive", "GP_Moder" },
			{ "yagluth_passive", "GP_Yagluth" },
			{ "queen_passive", "GP_Queen" },
			{ "fader_passive", "GP_Fader" },
			{ "north_passive", "GP_DeepNorth" }
		};

		private static readonly ConfigDefinition Input = new ConfigDefinition("Migration", "passive_switches_v1");

		public static string[] Capture(ConfigFile config)
		{
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			if (!(typeof(ConfigFile).GetProperty("OrphanedEntries", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(config, null) is Dictionary<ConfigDefinition, string> dictionary))
			{
				throw new InvalidOperationException("Cannot retain legacy Skills attunement preferences");
			}
			dictionary.TryGetValue(Input, out var value);
			HashSet<string> hashSet = new HashSet<string>((value ?? "").Split(new char[1] { ',' }), StringComparer.Ordinal);
			SortedSet<string> sortedSet = new SortedSet<string>(StringComparer.Ordinal);
			foreach (KeyValuePair<string, string> power in Powers)
			{
				if (hashSet.Contains(power.Value) || (dictionary.TryGetValue(new ConfigDefinition("Settings", power.Key), out var value2) && bool.TryParse(value2, out var result) && !result))
				{
					sortedSet.Add(power.Value);
				}
			}
			string[] array = new List<string>(sortedSet).ToArray();
			if (array.Length != 0)
			{
				dictionary[Input] = string.Join(",", array);
				config.Save();
			}
			return array;
		}
	}
	public static class PassivePowerRules
	{
		public const float DefaultRange = 50f;

		public const float MinRange = 10f;

		public const float MaxRange = 200f;

		public static bool PlayPowerStart(bool restoringPassive)
		{
			return !restoringPassive;
		}

		public static float ClampRange(float range)
		{
			if (float.IsNaN(range))
			{
				return 50f;
			}
			if (!(range < 10f))
			{
				if (!(range > 200f))
				{
					return range;
				}
				return 200f;
			}
			return 10f;
		}

		public static bool AcceptServer(long sender, long server)
		{
			if (server != 0L)
			{
				return sender == server;
			}
			return false;
		}

		public static string FightKey(string bossKey)
		{
			if (!string.IsNullOrEmpty(bossKey))
			{
				return "MW_Fought_" + bossKey.ToLowerInvariant();
			}
			return null;
		}

		public static string EarnedKey(IEnumerable<BossLink> links, string prefab, string bossKey, float distanceSquared, float range = 50f)
		{
			range = ClampRange(range);
			if (links == null || string.IsNullOrEmpty(prefab) || string.IsNullOrEmpty(bossKey) || !(distanceSquared >= 0f) || !(distanceSquared <= range * range))
			{
				return null;
			}
			foreach (BossLink link in links)
			{
				if (link != null && link.Prefab == prefab && link.Key == bossKey && !string.IsNullOrEmpty(link.Power) && link.Power.StartsWith("GP_", StringComparison.Ordinal))
				{
					return FightKey(link.Key);
				}
			}
			return null;
		}

		public static List<string> Unlocked(IEnumerable<BossLink> links, IEnumerable<string> playerKeys)
		{
			HashSet<string> hashSet = new HashSet<string>(playerKeys ?? new string[0], StringComparer.Ordinal);
			HashSet<string> hashSet2 = new HashSet<string>(StringComparer.Ordinal);
			if (links != null)
			{
				foreach (BossLink link in links)
				{
					if (link != null && !string.IsNullOrEmpty(link.Power) && link.Power.StartsWith("GP_", StringComparison.Ordinal) && ((!string.IsNullOrEmpty(link.Key) && hashSet.Contains(FightKey(link.Key))) || hashSet.Contains(link.Power)))
					{
						hashSet2.Add(link.Power);
					}
				}
			}
			List<string> list = new List<string>(hashSet2);
			list.Sort(StringComparer.Ordinal);
			return list;
		}
	}
	public static class PassivePowers
	{
		private sealed class OwnedEffect
		{
			public StatusEffect Effect;

			public float Ttl;

			public float Cooldown;

			public bool Added;

			public PowerMasteryEffects Mastery;
		}

		private static class Patches
		{
			[HarmonyPatch(typeof(StatusEffect), "Setup")]
			[HarmonyPrefix]
			private static bool SetupStart(StatusEffect __instance, Character character, bool __runOriginal = true)
			{
				if (!__runOriginal)
				{
					return false;
				}
				if (PassivePowerRules.PlayPowerStart(AddingPassive))
				{
					return true;
				}
				__instance.m_character = character;
				return false;
			}

			[HarmonyPatch(typeof(StatusEffect), "ResetTime")]
			[HarmonyPostfix]
			private static void PowerReset(StatusEffect __instance)
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				if (Owns(__instance) && PassivePowerRules.PlayPowerStart(AddingPassive))
				{
					if (!string.IsNullOrEmpty(__instance.m_startMessage))
					{
						__instance.m_character.Message(__instance.m_startMessageType, __instance.m_startMessage, 0, (Sprite)null, false);
					}
					__instance.TriggerStartEffects();
				}
			}

			[HarmonyPatch(typeof(SE_Stats), "ModifyAttack")]
			[HarmonyPostfix]
			private static void PassiveDamage(SE_Stats __instance, ref HitData hitData)
			{
				try
				{
					if (Owns((StatusEffect)(object)__instance) && hitData != null)
					{
						((DamageTypes)(ref hitData.m_damage)).Modify(1f + PowerMasteryRules.Total(((Object)__instance).name, OwnedLevel((StatusEffect)(object)__instance), MasteryStat.Damage, PowerTuning.Strength(((Object)__instance).name)));
					}
				}
				catch (Exception)
				{
				}
			}

			[HarmonyPatch(typeof(SE_Stats), "UpdateStatusEffect")]
			[HarmonyPostfix]
			private static void PassiveEitr(SE_Stats __instance, float dt)
			{
				try
				{
					if (Owns((StatusEffect)(object)__instance))
					{
						float num = PowerMasteryRules.EitrOverTime(((Object)__instance).name, OwnedLevel((StatusEffect)(object)__instance), dt, PowerTuning.Strength(((Object)__instance).name));
						if (num > 0f)
						{
							((Character)_player).AddEitr(num);
						}
					}
				}
				catch (Exception)
				{
				}
			}

			[HarmonyPatch(typeof(SE_Stats), "ModifyStaminaRegen")]
			[HarmonyPostfix]
			private static void ColdRegen(SE_Stats __instance, ref float staminaRegen)
			{
				try
				{
					if (Owns((StatusEffect)(object)__instance))
					{
						SEMan sEMan = ((Character)_player).GetSEMan();
						bool cold = sEMan.HaveStatusEffect(SEMan.s_statusEffectCold) || sEMan.HaveStatusEffect(SEMan.s_statusEffectFreezing);
						staminaRegen += PowerMasteryRules.ColdStaminaRegen(((Object)__instance).name, OwnedLevel((StatusEffect)(object)__instance), cold, PowerTuning.Strength(((Object)__instance).name));
					}
				}
				catch (Exception)
				{
				}
			}

			[HarmonyPatch(typeof(ZNet), "Update")]
			[HarmonyPostfix]
			private static void ServerTick()
			{
				try
				{
					ConfirmDeaths();
				}
				catch (Exception)
				{
				}
			}

			[HarmonyPatch(typeof(ZRoutedRpc), "RPC_RoutedRPC")]
			[HarmonyPrefix]
			private static void Arriving(ZRoutedRpc __instance, ZRpc rpc, ZPackage pkg)
			{
				try
				{
					_arriving = false;
					long num = default(long);
					if (Deaths.Count != 0 && __instance.m_server && RoutedSender.TryPeek(pkg, (ISet<int>)DeathEvidence, ref _arrivalMethod, ref num))
					{
						_arrivalPeer = RoutedSender.ArrivalPeer(__instance, rpc);
						_arriving = true;
					}
				}
				catch (Exception)
				{
					_arriving = false;
				}
			}

			[HarmonyPatch(typeof(ZRoutedRpc), "RPC_RoutedRPC")]
			[HarmonyFinalizer]
			private static void Arrived()
			{
				_arriving = false;
			}

			[HarmonyPatch(typeof(ZoneSystem), "RPC_SetGlobalKey")]
			[HarmonyPrefix]
			private static void DefeatKey(string name)
			{
				try
				{
					if (Deaths.Count != 0 && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer())
					{
						Deaths.DefeatKeySet(Actor(DefeatKeyMethod), name);
					}
				}
				catch (Exception)
				{
				}
			}

			[HarmonyPatch(typeof(ZDO), "SetOwnerInternal")]
			[HarmonyPrefix]
			private static void OwnerChange(ZDO __instance, long uid)
			{
				if (!_watchOwners || !BossPrefabs.Contains(__instance.GetPrefab()))
				{
					return;
				}
				try
				{
					OwnerChanging(__instance, uid);
				}
				catch (Exception)
				{
				}
			}

			[HarmonyPatch(typeof(ZNet), "Awake")]
			[HarmonyPostfix]
			private static void NetworkStarted()
			{
				try
				{
					RegisterRpc();
				}
				catch (Exception)
				{
				}
			}

			[HarmonyPatch(typeof(Character), "OnDeath")]
			[HarmonyPrefix]
			private static void BossDied(Character __instance)
			{
				try
				{
					ReportDeath(__instance);
				}
				catch (Exception)
				{
				}
			}

			private static void ReportDeath(Character __instance)
			{
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_0084: Unknown result type (might be due to invalid IL or missing references)
				//IL_008b: Expected O, but got Unknown
				//IL_008f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
				if (!__instance.m_boss || string.IsNullOrEmpty(__instance.m_defeatSetGlobalKey))
				{
					return;
				}
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner())
				{
					return;
				}
				string prefabName = Utils.GetPrefabName(((Component)__instance).gameObject);
				string defeatSetGlobalKey = __instance.m_defeatSetGlobalKey;
				Vector3 position = ((Component)__instance).transform.position;
				if (PassivePowerRules.EarnedKey(BossDiscovery.Links(), prefabName, defeatSetGlobalKey, 0f) != null)
				{
					RegisterRpc();
					if (_rpc != null)
					{
						ZDO zDO = component.GetZDO();
						ZPackage val = new ZPackage();
						val.Write(zDO.m_uid);
						val.Write(prefabName);
						val.Write(defeatSetGlobalKey);
						val.Write(position);
						val.Write(zDO.OwnerRevision);
						_rpc.InvokeRoutedRPC(_rpc.GetServerPeerID(), "MW_Skills_FoughtBoss", new object[1] { val });
					}
				}
			}

			[HarmonyPatch(typeof(Player), "UpdateGuardianPower")]
			[HarmonyPostfix]
			private static void Update(Player __instance, float dt)
			{
				if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
				{
					return;
				}
				if (_player != __instance)
				{
					_wait = 0f;
				}
				_wait -= dt;
				if (_wait > 0f)
				{
					return;
				}
				_wait = 1f;
				try
				{
					Reconcile(__instance);
				}
				catch (Exception)
				{
				}
			}
		}

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

		private static Setting<bool> _on;

		private static Setting<float> _range;

		private static Setting<float> _limit;

		private static string[] _legacyDisabled = new string[0];

		private static Player _player;

		private static float _wait;

		private static float _bonus;

		private static bool _progressive;

		private const string FightRpc = "MW_Skills_FoughtBoss";

		private const string MasteryRpc = "MW_Skills_Mastery.v1";

		private static ZRoutedRpc _rpc;

		private static readonly BossDeathLedger Deaths = new BossDeathLedger();

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

		private static ZNetScene _bossScene;

		private static bool _watchOwners;

		private static readonly int DefeatKeyMethod = StringExtensionMethods.GetStableHashCode("SetGlobalKey");

		private static readonly int DestroyMethod = StringExtensionMethods.GetStableHashCode("DestroyZDO");

		private static readonly HashSet<int> DeathEvidence = new HashSet<int> { DefeatKeyMethod, DestroyMethod };

		private static ZDOMan _watched;

		private static bool _arriving;

		private static long _arrivalPeer;

		private static int _arrivalMethod;

		internal static bool AddingPassive { get; private set; }

		public static int AttuneLimit => AttunementRules.Limit((_limit == null) ? 3f : _limit.Value);

		public static void Init(SettingsPage page, string[] legacyDisabled)
		{
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			_legacyDisabled = legacyDisabled;
			_on = page.Toggle("passive_powers", "Passive Forsaken powers", true, (SettingPolicy)0, false);
			_range = page.Slider("passive_kill_range", "Kill credit range", 50f, 10f, 200f, 5f, (SettingPolicy)1, true);
			_limit = page.Slider("attune_limit", "Attuned power limit", 3f, 0f, 9f, 1f, (SettingPolicy)1, true);
			((Setting)_on).Changed += Refresh;
			((Setting)_limit).Changed += Refresh;
			Harmony val = new Harmony("expdare.meadworks.skills.passivepowers");
			val.PatchAll(typeof(Patches));
			LedgerTrack.Patch(val, "skills passive powers");
			PowerMasteryAdapters.Init();
			RegisterRpc();
			Ledger.Add("skills passive powers state", (Action)delegate
			{
				((Setting)_on).Changed -= Refresh;
				((Setting)_limit).Changed -= Refresh;
				if (_rpc != null)
				{
					_rpc.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Skills_FoughtBoss"));
				}
				if (_rpc != null)
				{
					_rpc.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Skills_FoughtBoss.Result"));
				}
				if (_rpc != null)
				{
					_rpc.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Skills_Mastery.v1"));
				}
				ResetDeaths();
				if (_watched != null)
				{
					ZDOMan watched = _watched;
					watched.m_onZDODestroyed = (Action<ZDO>)Delegate.Remove(watched.m_onZDODestroyed, new Action<ZDO>(OnZdoDestroyed));
				}
				_watched = null;
				_rpc = null;
				Restore();
				_on = null;
				_range = null;
				_limit = null;
				_legacyDisabled = new string[0];
				_player = null;
				_wait = 0f;
			});
		}

		private static void RegisterRpc()
		{
			ZRoutedRpc instance = ZRoutedRpc.instance;
			WatchDestroyed();
			if (instance != null && instance != _rpc)
			{
				if (_rpc != null)
				{
					_rpc.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Skills_FoughtBoss"));
					_rpc.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Skills_FoughtBoss.Result"));
					_rpc.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Skills_Mastery.v1"));
				}
				ResetDeaths();
				RoutedRpcGuard.Register(new string[3] { "MW_Skills_FoughtBoss", "MW_Skills_FoughtBoss.Result", "MW_Skills_Mastery.v1" });
				instance.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Skills_FoughtBoss"));
				instance.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Skills_FoughtBoss.Result"));
				instance.Register<ZPackage>("MW_Skills_FoughtBoss", (Action<long, ZPackage>)OnBossDeath);
				instance.Register<string, string, Vector3>("MW_Skills_FoughtBoss.Result", (Action<long, string, string, Vector3>)OnValidatedDeath);
				instance.m_functions.Remove(StringExtensionMethods.GetStableHashCode("MW_Skills_Mastery.v1"));
				instance.Register<ZPackage>("MW_Skills_Mastery.v1", (Action<long, ZPackage>)OnMasteryDeath);
				_rpc = instance;
			}
		}

		private static void ResetDeaths()
		{
			Deaths.Clear();
			BossPrefabs.Clear();
			_bossScene = null;
			_watchOwners = false;
			_arriving = false;
			_arrivalPeer = 0L;
		}

		private static BossId Key(ZDOID id)
		{
			return new BossId(((ZDOID)(ref id)).UserID, ((ZDOID)(ref id)).ID);
		}

		private static void OnBossDeath(long sender, ZPackage pkg)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || pkg == null || pkg.Size() > 1024)
			{
				return;
			}
			try
			{
				ZDOID id = pkg.ReadZDOID();
				string text = pkg.ReadString();
				string bossKey = pkg.ReadString();
				Vector3 val = pkg.ReadVector3();
				int ownerRevision = ((pkg.GetPos() < pkg.Size()) ? pkg.ReadUShort() : (-1));
				if (PassivePowerRules.EarnedKey(BossDiscovery.Links(), text, bossKey, 0f) != null)
				{
					DeathReport deathReport = Deaths.Report(Time.realtimeSinceStartup, sender, Key(id), text, StringExtensionMethods.GetStableHashCode(text), bossKey, val.x, val.y, val.z, Reachable(sender, val), ownerRevision);
					if (deathReport == DeathReport.SenderFull || deathReport == DeathReport.QueueFull)
					{
						MwLog.Debug((object)("skills boss death report dropped: " + deathReport));
					}
				}
			}
			catch (Exception)
			{
			}
		}

		private static bool Reachable(long sender, Vector3 position)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			if (_rpc != null && sender == _rpc.m_id)
			{
				return true;
			}
			try
			{
				ZNetPeer peer = ZNet.instance.GetPeer(sender);
				if (peer == null)
				{
					return false;
				}
				Vector3 refPos = peer.GetRefPos();
				float dx = position.x - refPos.x;
				float dz = position.z - refPos.z;
				SimulationDistance syncedSimulationDistance = ZNet.instance.GetSyncedSimulationDistance();
				return BossDeathLedger.WithinReach(dx, dz, ((SimulationDistance)(ref syncedSimulationDistance)).NearSimulationDistance);
			}
			catch (Exception)
			{
				return false;
			}
		}

		private static void WatchOwners()
		{
			ZNetScene instance = ZNetScene.instance;
			if (instance == _bossScene)
			{
				return;
			}
			_bossScene = instance;
			BossPrefabs.Clear();
			if ((Object)(object)instance != (Object)null)
			{
				foreach (BossLink item in BossDiscovery.Links())
				{
					BossPrefabs.Add(StringExtensionMethods.GetStableHashCode(item.Prefab));
				}
			}
			_watchOwners = BossPrefabs.Count > 0;
		}

		private static void OwnerChanging(ZDO zdo, long next)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			long owner = zdo.GetOwner();
			if (owner != 0L && owner != next)
			{
				Deaths.OwnerLeft(Time.realtimeSinceStartup, Key(zdo.m_uid), owner);
			}
		}

		private static long Actor(int method)
		{
			if (_arriving && _arrivalMethod == method)
			{
				return _arrivalPeer;
			}
			if (ZRoutedRpc.instance != null)
			{
				return ZRoutedRpc.instance.m_id;
			}
			return 0L;
		}

		private static void WatchDestroyed()
		{
			ZDOMan instance = ZDOMan.instance;
			if (instance != _watched)
			{
				if (_watched != null)
				{
					ZDOMan watched = _watched;
					watched.m_onZDODestroyed = (Action<ZDO>)Delegate.Remove(watched.m_onZDODestroyed, new Action<ZDO>(OnZdoDestroyed));
				}
				_watched = instance;
				if (instance != null)
				{
					instance.m_onZDODestroyed = (Action<ZDO>)Delegate.Combine(instance.m_onZDODestroyed, new Action<ZDO>(OnZdoDestroyed));
				}
			}
		}

		private static void OnZdoDestroyed(ZDO zdo)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			if (Deaths.Count == 0 || zdo == null)
			{
				return;
			}
			try
			{
				if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer())
				{
					Vector3 position = zdo.GetPosition();
					DeathCredit credit;
					DeathVerdict deathVerdict = Deaths.Destroyed(Time.realtimeSinceStartup, Actor(DestroyMethod), Key(zdo.m_uid), zdo.GetOwner(), zdo.OwnerRevision, zdo.GetPrefab(), position.x, position.y, position.z, out credit);
					if (deathVerdict != DeathVerdict.Credit && deathVerdict != DeathVerdict.NoReport)
					{
						MwLog.Debug((object)("skills boss death report dropped: " + deathVerdict));
					}
				}
			}
			catch (Exception)
			{
			}
		}

		private static void ConfirmDeaths()
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || _rpc == null)
			{
				if (_watchOwners || !Deaths.Idle)
				{
					ResetDeaths();
				}
				return;
			}
			WatchOwners();
			if (!Deaths.Idle)
			{
				Deaths.SendDue(CreditBossDeath, delegate(DeathCredit credit, Exception e)
				{
					MwLog.Warn((object)("skills boss death credit not sent: " + e.Message));
				});
				if (Deaths.Expire(Time.realtimeSinceStartup) > 0)
				{
					MwLog.Debug((object)"skills boss death report dropped: the game's own death never followed it");
				}
			}
		}

		private static void CreditBossDeath(DeathCredit credit)
		{
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(credit.X, credit.Y, credit.Z);
			if (PowerMasteryRules.CountsKill(PowerMasteryRules.Power(BossDiscovery.Links(), credit.Prefab, credit.BossKey), credit.Prefab))
			{
				ZPackage val2 = new ZPackage();
				val2.Write(new ZDOID(credit.Id.User, credit.Id.Id));
				val2.Write(credit.Prefab);
				val2.Write(credit.BossKey);
				val2.Write(val);
				_rpc.InvokeRoutedRPC(0L, "MW_Skills_Mastery.v1", new object[1] { val2 });
			}
			_rpc.InvokeRoutedRPC(0L, "MW_Skills_FoughtBoss.Result", new object[3] { credit.Prefab, credit.BossKey, val });
		}

		private static void OnValidatedDeath(long sender, string prefab, string bossKey, Vector3 position)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GrantDeath(sender, prefab, bossKey, position, null);
			}
			catch (Exception)
			{
			}
		}

		private unsafe static void OnMasteryDeath(long sender, ZPackage pkg)
		{
			//IL_0020: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!((Object)(object)ZNet.instance == (Object)null) && pkg != null && pkg.Size() <= 1024)
				{
					ZDOID val = pkg.ReadZDOID();
					string prefab = pkg.ReadString();
					string text = pkg.ReadString();
					Vector3 position = pkg.ReadVector3();
					if (PowerMasteryRules.CountsKill(PowerMasteryRules.Power(BossDiscovery.Links(), prefab, text), prefab))
					{
						string text2 = ZNet.instance.GetWorldUID().ToString(CultureInfo.InvariantCulture);
						ZDOID val2 = val;
						string receipt = text2 + ":" + ((object)(*(ZDOID*)(&val2))/*cast due to .constrained prefix*/).ToString();
						GrantDeath(sender, prefab, text, position, receipt);
					}
				}
			}
			catch (Exception)
			{
			}
		}

		private static void GrantDeath(long sender, string prefab, string bossKey, Vector3 position, string receipt)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			long server = (ZNet.instance.IsServer() ? ZNet.GetUID() : (ZNet.instance.GetServerPeer()?.m_uid ?? 0));
			if (!PassivePowerRules.AcceptServer(sender, server))
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			IList<BossLink> links = BossDiscovery.Links();
			Vector3 val = ((Component)localPlayer).transform.position - position;
			string text = PassivePowerRules.EarnedKey(links, prefab, bossKey, ((Vector3)(ref val)).sqrMagnitude, (_range == null) ? 50f : _range.Value);
			if (text == null)
			{
				return;
			}
			string text2 = PowerMasteryRules.Power(BossDiscovery.Links(), prefab, bossKey);
			bool flag = PassivePowerRules.Unlocked(BossDiscovery.Links(), localPlayer.GetUniqueKeys()).Contains(text2);
			if (receipt != null)
			{
				if (!PowerMasteryRules.RecordDeath(localPlayer.m_customData, text2, receipt, flag))
				{
					return;
				}
			}
			else if (!flag && !localPlayer.m_customData.ContainsKey("mw.ski.kills." + text2))
			{
				localPlayer.m_customData["mw.ski.kills." + text2] = "0";
			}
			PowerTooltip.Invalidate();
			if (!((Humanoid)localPlayer).HaveUniqueKey(text))
			{
				((Humanoid)localPlayer).AddUniqueKey(text);
				MwLog.Debug((object)("skills fought boss " + prefab + " key=" + text));
			}
			Reconcile(localPlayer);
		}

		public static List<string> Earned(Player player)
		{
			return PassivePowerRules.Unlocked(BossDiscovery.Links(), ((Object)(object)player == (Object)null) ? null : player.GetUniqueKeys());
		}

		public static int Level(Player player, string power)
		{
			bool flag = (Object)(object)player != (Object)null && Earned(player).Contains(power);
			return PowerMasteryRules.Level(flag, PowerMasteryRules.Kills(player?.m_customData, power, flag));
		}

		public static List<string> Active(Player player)
		{
			List<string> list = new List<string>();
			if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)_player)
			{
				return list;
			}
			foreach (OwnedEffect value in Effects.Values)
			{
				if (Owns(value.Effect) && ((Character)player).GetSEMan().GetStatusEffect(value.Effect.NameHash()) == value.Effect)
				{
					list.Add(((Object)value.Effect).name);
				}
			}
			list.Sort(StringComparer.Ordinal);
			return list;
		}

		public static void Attune(Player player, string power, bool enabled)
		{
			if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			try
			{
				AttunementMigrationRules.Apply(player.m_customData, _legacyDisabled);
				if (AttunementRules.Set(player.m_customData, Earned(player), power, enabled, AttuneLimit, Available))
				{
					Reconcile(player);
				}
			}
			catch (Exception)
			{
			}
		}

		public static bool Available(string power)
		{
			if ((Object)(object)ObjectDB.instance != (Object)null)
			{
				return (Object)(object)ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode(power)) != (Object)null;
			}
			return false;
		}

		private static bool Owns(StatusEffect effect)
		{
			if ((Object)(object)effect != (Object)null && (Object)(object)_player != (Object)null && (Object)(object)_player == (Object)(object)Player.m_localPlayer && !((Character)_player).IsDead() && _on != null && _on.Value && Effects.TryGetValue(effect.NameHash(), out var value))
			{
				return effect == value.Effect;
			}
			return false;
		}

		internal static bool IsAttuned(StatusEffect effect)
		{
			if ((Object)(object)effect != (Object)null && (Object)(object)_player != (Object)null && (Object)(object)_player == (Object)(object)Player.m_localPlayer && !((Character)_player).IsDead() && _on != null && _on.Value)
			{
				return Effects.ContainsKey(effect.NameHash());
			}
			return false;
		}

		internal static bool IsHudPassive(StatusEffect effect)
		{
			if ((Object)(object)effect != (Object)null && effect.m_ttl == 0f)
			{
				return Owns(effect);
			}
			return false;
		}

		private static int OwnedLevel(StatusEffect effect)
		{
			return PowerMasteryRules.Level(earned: true, PowerMasteryRules.Kills(_player.m_customData, ((Object)effect).name, grandfathered: true));
		}

		private static void Restore()
		{
			PowerMasteryAdapters.RestoreSpeed();
			SEMan val = (((Object)(object)_player == (Object)null) ? null : ((Character)_player).GetSEMan());
			if (val != null)
			{
				foreach (KeyValuePair<int, OwnedEffect> effect in Effects)
				{
					Restore(val, effect.Key, effect.Value);
				}
			}
			Effects.Clear();
			PowerHud.Refresh();
		}

		internal static float Bonus(MasteryStat stat)
		{
			float num = 0f;
			foreach (OwnedEffect value in Effects.Values)
			{
				if (Owns(value.Effect) && ((Character)_player).GetSEMan().GetStatusEffect(value.Effect.NameHash()) == value.Effect)
				{
					num += PowerMasteryRules.Total(((Object)value.Effect).name, OwnedLevel(value.Effect), stat, PowerTuning.Strength(((Object)value.Effect).name));
				}
			}
			return num;
		}

		private static void Restore(SEMan manager, int hash, OwnedEffect owned)
		{
			if (manager.GetStatusEffect(hash) == owned.Effect)
			{
				if (owned.Added)
				{
					manager.RemoveStatusEffect(hash, true);
					return;
				}
				owned.Effect.m_ttl = owned.Ttl;
				owned.Effect.m_cooldown = owned.Cooldown;
				owned.Mastery?.Restore();
			}
		}

		internal static void Refresh()
		{
			PowerTooltip.Invalidate();
			try
			{
				Restore();
				_wait = 0f;
				Reconcile(Player.m_localPlayer);
			}
			catch (Exception)
			{
			}
		}

		private static void Reconcile(Player player)
		{
			if (_player != player)
			{
				PowerTooltip.Invalidate();
				Restore();
				_player = player;
			}
			if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || ((Character)player).IsDead() || (Object)(object)ObjectDB.instance == (Object)null)
			{
				return;
			}
			if (_progressive != ProgressivePowers.Enabled || _bonus != ProgressivePowers.EffectBonusPercent)
			{
				Restore();
				_progressive = ProgressivePowers.Enabled;
				_bonus = ProgressivePowers.EffectBonusPercent;
			}
			List<string> earned = Earned(player);
			AttunementMigrationRules.Apply(player.m_customData, _legacyDisabled);
			List<string> list = AttunementRules.Reconcile(player.m_customData, earned, AttuneLi