Decompiled source of FreyrsVorpalSword v1.0.3

FreyrsVorpalSword.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using EpicLoot;
using EpicLoot.GatedItemType;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("FreyrsVorpalSword")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+3f49a655a9ceb15b134110176cfe4fd82934a562")]
[assembly: AssemblyProduct("FreyrsVorpalSword")]
[assembly: AssemblyTitle("FreyrsVorpalSword")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace VorpalBlade
{
	internal class GiveCommand : ConsoleCommand
	{
		public override string Name => "vorpal_give";

		public override string Help => "Give a sword. Usage: vorpal_give [1|2|3|freyr|blood|lightning|nature]  (numbers = Vorpal Sword level; a given Freyr's has no world serial, so it is a duplicate and reverts within seconds)";

		public override void Run(string[] args)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				Console.instance.Print("Load into a world first.");
				return;
			}
			string arg = ((args.Length != 0) ? args[0].ToLowerInvariant() : "1");
			int num = 1;
			string text;
			if (int.TryParse(arg, out var result))
			{
				text = "SwordVorpal";
				num = Mathf.Clamp(result, 1, 3);
			}
			else if (arg == "freyr")
			{
				text = "SwordFreyrsVorpal";
			}
			else
			{
				Variants.Gem gem = Variants.Gems.FirstOrDefault((Variants.Gem g) => g.Suffix.ToLowerInvariant() == arg);
				if (gem == null)
				{
					Console.instance.Print(((ConsoleCommand)this).Help);
					return;
				}
				text = gem.Prefab;
			}
			ItemData val = ((Humanoid)localPlayer).GetInventory().AddItem(text, 1, num, 0, 0L, "", false, false);
			Console.instance.Print((val != null) ? $"Gave {text} L{num}." : "Inventory full or item missing - check LogOutput.log.");
			Diag.Log(string.Format("vorpal_give {0} L{1}: {2}", text, num, (val != null) ? "ok" : "FAILED"));
		}
	}
	internal class MatsCommand : ConsoleCommand
	{
		public override string Name => "vorpal_mats";

		public override string Help => "Give materials. Usage: vorpal_mats [1|2|3|freyr|gems]  (blank = everything; swords themselves are not given, use vorpal_give)";

		public override void Run(string[] args)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				Console.instance.Print("Load into a world first.");
				return;
			}
			string text = ((args.Length != 0) ? args[0].ToLowerInvariant() : "all");
			Inventory inv = ((Humanoid)localPlayer).GetInventory();
			for (int i = 1; i <= 3; i++)
			{
				if (!(text == "all") && !(text == i.ToString()))
				{
					continue;
				}
				foreach (KeyValuePair<string, int> item in Costs.Parse(Costs.SpecFor(i)))
				{
					Give("L" + i, item.Key, item.Value);
				}
			}
			if (text == "all" || text == "freyr")
			{
				foreach (KeyValuePair<string, int> item2 in Costs.Parse(Plugin.FreyrCost.Value))
				{
					Give("freyr", item2.Key, item2.Value);
				}
			}
			if ((text == "all" || text == "gems") && (Object)(object)ObjectDB.instance != (Object)null)
			{
				foreach (Recipe item3 in ObjectDB.instance.m_recipes.Where((Recipe r) => (Object)(object)r?.m_item != (Object)null && Variants.PrefabNames.Contains(((Object)r.m_item).name)))
				{
					foreach (Requirement item4 in item3.m_resources.Where((Requirement q) => (Object)(object)q.m_resItem != (Object)null))
					{
						Give(((Object)item3.m_item).name, ((Object)item4.m_resItem).name, item4.m_amount);
					}
				}
			}
			Console.instance.Print("Gave materials (" + text + "). See LogOutput.log for details.");
			void Give(string label, string prefab, int amount)
			{
				if (!Diag.IsOurPrefabName(prefab))
				{
					bool flag = inv.AddItem(prefab, amount, 1, 0, 0L, "", false, false) != null;
					Diag.Log(string.Format("vorpal_mats {0} {1} x{2}: {3}", label, prefab, amount, flag ? "ok" : "FAILED (full inventory or bad prefab name)"));
				}
			}
		}
	}
	internal class StatusCommand : ConsoleCommand
	{
		public override string Name => "vorpal_status";

		public override string Help => "Write a full status report to LogOutput.log.";

		public override void Run(string[] args)
		{
			Diag.DumpStatus("vorpal_status command");
			foreach (string item in Diag.AllOurPrefabs())
			{
				Diag.DumpHierarchy(((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab(item) : null, item);
			}
			Console.instance.Print("Status written to LogOutput.log.");
		}
	}
	internal class LockCommand : ConsoleCommand
	{
		public override string Name => "vorpal_lock";

		public override string Help => "Show the world's one Freyr's Vorpal Sword lock. Usage: vorpal_lock [reset]  (reset: test only, world host only)";

		public override void Run(string[] args)
		{
			if ((Object)(object)ZNet.instance == (Object)null || (Object)(object)ZoneSystem.instance == (Object)null)
			{
				Console.instance.Print("Load into a world first.");
				return;
			}
			if (args.Length != 0 && args[0].ToLowerInvariant() == "reset")
			{
				if (!ZNet.instance.IsServer())
				{
					Console.instance.Print("Only the world's host can reset (test only).");
					return;
				}
				ZoneSystem.instance.RemoveGlobalKey("freyrsvorpal_serial");
				Console.instance.Print("Lock cleared. Every existing Freyr's Vorpal Sword is now a duplicate and will revert.");
				Plugin.Log.LogInfo((object)"[Vorpal] vorpal_lock reset: world lock cleared (test command).");
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			string text = (((Object)(object)localPlayer == (Object)null) ? "" : string.Join(", ", from i in ((Humanoid)localPlayer).GetInventory().GetAllItems().Where(Diag.IsFreyr)
				select Diag.Label(i) + " serial " + (OnlyOne.SerialOf(i) ?? "none") + (OnlyOne.IsCurrent(i) ? " (true)" : " (duplicate)")));
			List<string> list = OnlyOne.WorldSerials();
			string text2 = string.Format("World: {0} of {1} forged ({2}){3}. Server={4}, ", list.Count, OnlyOne.Max, OnlyOne.Describe(list), (list.Count < OnlyOne.Max) ? ", one can be forged" : ", full", ZNet.instance.IsServer()) + $"server has mod={OnlyOne.ServerHasMod}, keys received={OnlyOne.KeysReceived}, can judge={OnlyOne.CanJudge}. " + "Carried: " + ((text.Length > 0) ? text : "no Freyr's");
			Console.instance.Print(text2);
			Plugin.Log.LogInfo((object)("[Vorpal] vorpal_lock: " + text2));
		}
	}
	internal class SwordsCommand : ConsoleCommand
	{
		public override string Name => "vorpal_swords";

		public override string Help => "Write every vanilla sword's damage, block and parry per level to LogOutput.log, with the Vorpal swords for comparison.";

		private static bool IsVanilla(string prefab)
		{
			if (prefab == "SwordCheat")
			{
				return false;
			}
			try
			{
				return ModQuery.GetPrefab(prefab) == null;
			}
			catch
			{
				return true;
			}
		}

		private static string Damage(DamageTypes d)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: 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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			List<string> parts = new List<string>();
			Add("slash", d.m_slash);
			Add("blunt", d.m_blunt);
			Add("pierce", d.m_pierce);
			Add("fire", d.m_fire);
			Add("frost", d.m_frost);
			Add("lightning", d.m_lightning);
			Add("poison", d.m_poison);
			Add("spirit", d.m_spirit);
			float num = d.m_damage + d.m_blunt + d.m_slash + d.m_pierce + d.m_fire + d.m_frost + d.m_lightning + d.m_poison + d.m_spirit;
			return string.Format("total {0:0.#} ({1})", num, string.Join(", ", parts));
			void Add(string n, float v)
			{
				if (v > 0f)
				{
					parts.Add($"{n} {v:0.#}");
				}
			}
		}

		public override void Run(string[] args)
		{
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			ObjectDB instance = ObjectDB.instance;
			if ((Object)(object)instance == (Object)null)
			{
				Console.instance.Print("Load into a world first.");
				return;
			}
			var list = (from i in instance.m_items
				where (Object)(object)i != (Object)null
				select new
				{
					name = ((Object)i).name,
					drop = i.GetComponent<ItemDrop>()
				} into x
				where (Object)(object)x.drop != (Object)null && (int)x.drop.m_itemData.m_shared.m_skillType == 1
				where Diag.IsOurPrefabName(x.name) || IsVanilla(x.name)
				orderby Diag.IsOurPrefabName(x.name), x.drop.m_itemData.m_shared.m_damages.m_slash
				select x).ToList();
			Plugin.Log.LogInfo((object)$"[Vorpal] vorpal_swords: {list.Count} swords (vanilla, then ours):");
			foreach (var item in list)
			{
				SharedData shared = item.drop.m_itemData.m_shared;
				for (int num = 1; num <= Mathf.Max(1, shared.m_maxQuality); num++)
				{
					DamageTypes d = ((DamageTypes)(ref shared.m_damages)).Clone();
					((DamageTypes)(ref d)).Add(shared.m_damagesPerLevel, num - 1);
					Plugin.Log.LogInfo((object)$"[Vorpal]   {item.name} ({shared.m_itemType}) L{num}: {Damage(d)}, block {shared.m_blockPower + shared.m_blockPowerPerLevel * (float)(num - 1):0.#}, parry x{shared.m_timedBlockBonus}");
				}
			}
			Console.instance.Print($"{list.Count} swords written to LogOutput.log.");
		}
	}
	internal static class Costs
	{
		private static Dictionary<string, int[]> _table = new Dictionary<string, int[]>();

		private static readonly HashSet<Requirement> OurRequirements = new HashSet<Requirement>();

		private static readonly Dictionary<string, CraftingStation> StationCache = new Dictionary<string, CraftingStation>();

		internal static Dictionary<string, int> Parse(string spec)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			if (string.IsNullOrWhiteSpace(spec))
			{
				return dictionary;
			}
			string[] array = spec.Split(new char[1] { ',' });
			foreach (string text in array)
			{
				string[] array2 = text.Split(new char[1] { ':' });
				if (array2.Length != 2 || !int.TryParse(array2[1].Trim(), out var result) || result <= 0)
				{
					Plugin.Log.LogWarning((object)("[Vorpal] Ignoring bad cost entry '" + text.Trim() + "' (want Prefab:amount)"));
					continue;
				}
				string key = array2[0].Trim();
				dictionary[key] = (dictionary.TryGetValue(key, out var value) ? (value + result) : result);
			}
			return dictionary;
		}

		private static string[] VorpalSpecs()
		{
			return new string[3]
			{
				Plugin.CraftCost.Value,
				Plugin.Upgrade2Cost.Value,
				Plugin.Upgrade3Cost.Value
			};
		}

		internal static string SpecFor(int quality)
		{
			if (quality < 4)
			{
				return VorpalSpecs()[Math.Max(1, Math.Min(3, quality)) - 1];
			}
			return Plugin.FreyrCost.Value;
		}

		internal static IEnumerable<string> AllItemNames()
		{
			return VorpalSpecs().Concat(new string[2]
			{
				Plugin.FreyrCost.Value,
				Plugin.FreyrUpgradeCost.Value
			}).Concat(Variants.Gems.Select((Variants.Gem g) => g.ExtraCost?.Value ?? "")).SelectMany((string s) => Parse(s).Keys)
				.Distinct();
		}

		internal static string StationFor(int quality)
		{
			return quality switch
			{
				2 => Plugin.Upgrade2Station.Value.Trim(), 
				3 => Plugin.Upgrade3Station.Value.Trim(), 
				_ => Plugin.Station.Value.Trim(), 
			};
		}

		internal static IEnumerable<string> AllStationNames()
		{
			return Enumerable.Range(1, 3).Select(StationFor).Concat(new string[1] { Plugin.FreyrStation.Value.Trim() })
				.Distinct();
		}

		internal static IEnumerable<string> ExtraUpgradeStations()
		{
			return from s in Enumerable.Range(2, 2).Select(StationFor).Distinct()
				where s != StationFor(1)
				select s;
		}

		internal static bool IsExtraRecipe(Recipe r)
		{
			if ((Object)(object)r != (Object)null)
			{
				return ((Object)r).name.StartsWith("Recipe_SwordVorpal_Upgrade_");
			}
			return false;
		}

		internal static string ExtraRecipeName(string station)
		{
			return "Recipe_SwordVorpal_Upgrade_" + station;
		}

		internal static CraftingStation CachedStation(string prefabName)
		{
			if (string.IsNullOrEmpty(prefabName))
			{
				return null;
			}
			if (!StationCache.TryGetValue(prefabName, out var value) || (Object)(object)value == (Object)null)
			{
				GameObject prefab = PrefabManager.Instance.GetPrefab(prefabName);
				value = (StationCache[prefabName] = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<CraftingStation>() : null));
			}
			return value;
		}

		internal static bool IsVorpalRecipe(Recipe r)
		{
			if ((Object)(object)r != (Object)null && (Object)(object)r.m_item != (Object)null)
			{
				return ((Object)r.m_item).name == "SwordVorpal";
			}
			return false;
		}

		internal static bool IsFreyrRecipe(Recipe r)
		{
			if ((Object)(object)r != (Object)null && (Object)(object)r.m_item != (Object)null)
			{
				return ((Object)r.m_item).name == "SwordFreyrsVorpal";
			}
			return false;
		}

		internal static bool IsOurRecipe(Recipe r)
		{
			if ((Object)(object)r != (Object)null && (Object)(object)r.m_item != (Object)null)
			{
				return Diag.IsOurPrefabName(((Object)r.m_item).name);
			}
			return false;
		}

		internal static int StationLevelFor(int quality)
		{
			return quality switch
			{
				2 => Plugin.Upgrade2StationLevel.Value, 
				3 => Plugin.Upgrade3StationLevel.Value, 
				_ => Plugin.CraftStationLevel.Value, 
			};
		}

		private static void BuildTable()
		{
			Dictionary<string, int[]> dictionary = new Dictionary<string, int[]>();
			string[] array = VorpalSpecs();
			for (int i = 1; i <= 3; i++)
			{
				foreach (KeyValuePair<string, int> item in Parse(array[i - 1]))
				{
					if (!dictionary.TryGetValue(item.Key, out var value))
					{
						value = (dictionary[item.Key] = new int[4]);
					}
					value[i] = item.Value;
				}
			}
			_table = dictionary;
		}

		internal static Requirement Req(ObjectDB db, string prefab, int amount, int perLevel, bool recover)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: 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_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			GameObject itemPrefab = db.GetItemPrefab(prefab);
			ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)("[Vorpal] Cost item '" + prefab + "' not found in ObjectDB - skipped."));
				return null;
			}
			bool flag = prefab.StartsWith("Upgrader");
			return new Requirement
			{
				m_resItem = val,
				m_amount = amount,
				m_amountPerLevel = ((!flag) ? perLevel : 0),
				m_recover = (recover && !flag),
				m_upgraderResource = flag
			};
		}

		internal static void RebuildRecipes()
		{
			StationCache.Clear();
			RebuildVorpal();
			RebuildFreyr();
			Variants.RebuildRecipes();
			LogVanillaReference();
			Diag.DumpRecipes();
		}

		private static void RebuildVorpal()
		{
			try
			{
				BuildTable();
				ObjectDB instance = ObjectDB.instance;
				if ((Object)(object)instance == (Object)null)
				{
					return;
				}
				List<Recipe> list = instance.m_recipes.Where(IsVorpalRecipe).ToList();
				if (list.Count == 0)
				{
					Plugin.Log.LogWarning((object)"[Vorpal] No Vorpal Sword recipes found in ObjectDB.");
					return;
				}
				OurRequirements.Clear();
				foreach (Recipe item in list)
				{
					bool flag = !IsExtraRecipe(item);
					string text = (flag ? StationFor(1) : (((Object)(object)item.m_craftingStation != (Object)null) ? ((Object)item.m_craftingStation).name : "?"));
					CraftingStation val = CachedStation(text);
					if ((Object)(object)val != (Object)null)
					{
						item.m_craftingStation = val;
						item.m_repairStation = CachedStation(StationFor(1)) ?? val;
					}
					else
					{
						Plugin.Log.LogWarning((object)("[Vorpal] Station '" + text + "' for " + ((Object)item).name + " not found."));
					}
					item.m_minStationLevel = ((!flag) ? 1 : Plugin.CraftStationLevel.Value);
					item.m_noCraftOnlyUpgrade = !flag;
					List<Requirement> list2 = new List<Requirement>();
					foreach (KeyValuePair<string, int[]> item2 in _table)
					{
						Requirement val2 = Req(instance, item2.Key, item2.Value[1], item2.Value.Skip(2).Max(), item2.Key != "SwordSilver");
						if (val2 != null)
						{
							list2.Add(val2);
							OurRequirements.Add(val2);
						}
					}
					item.m_resources = list2.ToArray();
				}
				Diag.Log("Vorpal cost table: " + string.Join("; ", _table.Select((KeyValuePair<string, int[]> kv) => $"{kv.Key} craft {kv.Value[1]} / L2 {kv.Value[2]} / L3 {kv.Value[3]}")) + $". Benches: craft {StationFor(1)} {StationLevelFor(1)}, L2 {StationFor(2)} {StationLevelFor(2)}, L3 {StationFor(3)} {StationLevelFor(3)}");
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[Vorpal] RebuildVorpal failed: {arg}");
			}
		}

		private static void RebuildFreyr()
		{
			try
			{
				ObjectDB db = ObjectDB.instance;
				if ((Object)(object)db == (Object)null)
				{
					return;
				}
				Recipe val = ((IEnumerable<Recipe>)db.m_recipes).FirstOrDefault((Func<Recipe, bool>)IsFreyrRecipe);
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Log.LogWarning((object)"[Vorpal] Freyr's Vorpal Sword recipe not found in ObjectDB.");
					return;
				}
				CraftingStation val2 = CachedStation(Plugin.FreyrStation.Value.Trim());
				if ((Object)(object)val2 != (Object)null)
				{
					val.m_craftingStation = val2;
					val.m_repairStation = val2;
				}
				else
				{
					Plugin.Log.LogWarning((object)("[Vorpal] Freyr station '" + Plugin.FreyrStation.Value + "' not found."));
				}
				val.m_minStationLevel = Plugin.FreyrStationLevel.Value;
				Dictionary<string, int> craft = Parse(Plugin.FreyrCost.Value);
				Dictionary<string, int> perLevel = Parse(Plugin.FreyrUpgradeCost.Value);
				val.m_resources = (from n in craft.Keys.Concat(perLevel.Keys).Distinct()
					select Req(db, n, craft.TryGetValue(n, out var value) ? value : 0, (!(n == "SwordVorpal")) ? (perLevel.TryGetValue(n, out var value2) ? value2 : 0) : 0, n != "SwordVorpal") into q
					where q != null
					select q).ToArray();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[Vorpal] RebuildFreyr failed: {arg}");
			}
		}

		private static void LogVanillaReference()
		{
			if (!Diag.On || (Object)(object)ObjectDB.instance == (Object)null)
			{
				return;
			}
			foreach (Recipe item in ObjectDB.instance.m_recipes.Where((Recipe r) => (Object)(object)r != (Object)null && (Object)(object)r.m_item != (Object)null && (((Object)r.m_item).name.StartsWith("SwordNiedhogg") || ((Object)r.m_item).name.StartsWith("SwordDyrnwyn") || ((Object)r.m_item).name.StartsWith("SwordMistwalker") || ((Object)r.m_item).name == "SwordSilver")))
			{
				string[] obj = new string[7]
				{
					$"Vanilla reference: {((Object)item).name} -> {((Object)item.m_item).name} (\"{item.m_item.m_itemData.m_shared.m_name}\", maxQ {item.m_item.m_itemData.m_shared.m_maxQuality}) ",
					null,
					null,
					null,
					null,
					null,
					null
				};
				object[] array = new object[4];
				CraftingStation craftingStation = item.m_craftingStation;
				array[0] = ((craftingStation != null) ? ((Object)craftingStation).name : null);
				array[1] = item.m_minStationLevel;
				array[2] = item.m_noCraftOnlyUpgrade;
				array[3] = item.m_requireOnlyOneIngredient;
				obj[1] = string.Format("at '{0}' level {1}, upgradeOnly={2}, oneIngredient={3}, needs: ", array);
				obj[2] = string.Join(", ", item.m_resources.Select(delegate(Requirement q)
				{
					object[] array2 = new object[5];
					ItemDrop resItem = q.m_resItem;
					array2[0] = ((resItem != null) ? ((Object)resItem).name : null);
					array2[1] = q.m_amount;
					array2[2] = q.m_amountPerLevel;
					array2[3] = q.m_recover;
					array2[4] = (q.m_upgraderResource ? ", upgrader" : "");
					return string.Format("{0} x{1} (+{2}/lvl, recover {3}{4})", array2);
				}));
				obj[3] = ". Stats: ";
				obj[4] = Diag.StatsAt(item.m_item.m_itemData.m_shared, 1);
				obj[5] = " ... ";
				obj[6] = Diag.StatsAt(item.m_item.m_itemData.m_shared, item.m_item.m_itemData.m_shared.m_maxQuality);
				Diag.Log(string.Concat(obj));
			}
		}

		internal static bool TryGetAmount(Requirement req, int quality, out int amount)
		{
			amount = 0;
			if (!OurRequirements.Contains(req) || (Object)(object)req.m_resItem == (Object)null)
			{
				return false;
			}
			if (!_table.TryGetValue(((Object)req.m_resItem).name, out var value))
			{
				return false;
			}
			amount = ((quality >= 1 && quality <= 3) ? value[quality] : 0);
			return true;
		}
	}
	[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
	{
		typeof(Recipe),
		typeof(bool),
		typeof(int),
		typeof(int)
	})]
	internal static class DiscoveryPatch
	{
		private static bool Prefix(Player __instance, Recipe recipe, bool discover, ref bool __result)
		{
			if (!discover || !Costs.IsOurRecipe(recipe))
			{
				return true;
			}
			__result = false;
			ObjectDB instance = ObjectDB.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			string[] array = Plugin.DiscoverBy.Value.Split(new char[1] { ',' });
			foreach (string text in array)
			{
				GameObject itemPrefab = instance.GetItemPrefab(text.Trim());
				ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val != (Object)null && __instance.IsMaterialKnown(val.m_itemData.m_shared.m_name))
				{
					__result = true;
					if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && !__instance.IsRecipeKnown(recipe.m_item.m_itemData.m_shared.m_name))
					{
						Diag.Log("Discovered " + ((Object)recipe).name + " because '" + text.Trim() + "' is known");
					}
					break;
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Requirement), "GetAmount")]
	internal static class RequirementAmountPatch
	{
		private static void Postfix(Requirement __instance, int qualityLevel, ref int __result)
		{
			if (Costs.TryGetAmount(__instance, qualityLevel, out var amount))
			{
				__result = amount;
			}
		}
	}
	[HarmonyPatch(typeof(Recipe), "GetRequiredStation")]
	internal static class StationPatch
	{
		private static void Postfix(Recipe __instance, int quality, ref CraftingStation __result)
		{
			if (!Costs.IsVorpalRecipe(__instance))
			{
				return;
			}
			if (quality <= 1)
			{
				__result = __instance.m_craftingStation;
				return;
			}
			CraftingStation val = Costs.CachedStation(Costs.StationFor(quality));
			if ((Object)(object)val != (Object)null)
			{
				__result = val;
			}
		}
	}
	[HarmonyPatch(typeof(Recipe), "GetRequiredStationLevel")]
	internal static class StationLevelPatch
	{
		private static void Postfix(Recipe __instance, int quality, ref int __result)
		{
			if (Costs.IsVorpalRecipe(__instance))
			{
				if (quality <= 1 && Costs.IsExtraRecipe(__instance))
				{
					__result = 1;
				}
				else
				{
					__result = Math.Max(1, Costs.StationLevelFor(quality));
				}
			}
		}
	}
	internal static class Diag
	{
		internal static bool On
		{
			get
			{
				if (Plugin.VerboseLogging != null)
				{
					return Plugin.VerboseLogging.Value;
				}
				return false;
			}
		}

		internal static void Log(string msg)
		{
			if (On)
			{
				Plugin.Log.LogInfo((object)("[Vorpal] " + msg));
			}
		}

		internal static bool IsOurPrefabName(string prefab)
		{
			if (!(prefab == "SwordVorpal") && !(prefab == "SwordFreyrsVorpal"))
			{
				return Variants.PrefabNames.Contains(prefab);
			}
			return true;
		}

		internal static bool IsVorpal(ItemData item)
		{
			if (item != null)
			{
				if (!((Object)(object)item.m_dropPrefab != (Object)null) || !(((Object)item.m_dropPrefab).name == "SwordVorpal"))
				{
					if (item.m_shared != null)
					{
						return item.m_shared.m_name == "$item_vorpalsword";
					}
					return false;
				}
				return true;
			}
			return false;
		}

		internal static bool IsFreyr(ItemData item)
		{
			if (item != null)
			{
				if (!((Object)(object)item.m_dropPrefab != (Object)null) || (!(((Object)item.m_dropPrefab).name == "SwordFreyrsVorpal") && !Variants.PrefabNames.Contains(((Object)item.m_dropPrefab).name)))
				{
					if (item.m_shared != null)
					{
						return item.m_shared.m_name == "$item_freyrsvorpalsword";
					}
					return false;
				}
				return true;
			}
			return false;
		}

		internal static bool IsOurs(ItemData item)
		{
			if (!IsVorpal(item))
			{
				return IsFreyr(item);
			}
			return true;
		}

		internal static string Label(ItemData item)
		{
			if (item != null)
			{
				GameObject dropPrefab = item.m_dropPrefab;
				return $"{((dropPrefab != null) ? ((Object)dropPrefab).name : null) ?? item.m_shared.m_name} L{item.m_quality}";
			}
			return "nothing";
		}

		internal static ItemData RightItem(Humanoid h)
		{
			if (!((Object)(object)h != (Object)null))
			{
				return null;
			}
			return Traverse.Create((object)h).Field<ItemData>("m_rightItem").Value;
		}

		internal static bool LocalHolding(out ItemData item)
		{
			item = (((Object)(object)Player.m_localPlayer != (Object)null) ? RightItem((Humanoid)(object)Player.m_localPlayer) : null);
			return IsOurs(item);
		}

		internal static string Path(Transform t)
		{
			StringBuilder stringBuilder = new StringBuilder(((Object)t).name);
			Transform parent = t.parent;
			while ((Object)(object)parent != (Object)null)
			{
				stringBuilder.Insert(0, ((Object)parent).name + "/");
				parent = parent.parent;
			}
			return stringBuilder.ToString();
		}

		internal static void DumpHierarchy(GameObject go, string label)
		{
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			if (!On || (Object)(object)go == (Object)null)
			{
				return;
			}
			StringBuilder stringBuilder = new StringBuilder("[Vorpal] Hierarchy of " + label + " (" + ((Object)go).name + "):\n");
			Transform[] componentsInChildren = go.GetComponentsInChildren<Transform>(true);
			foreach (Transform val in componentsInChildren)
			{
				int num = 0;
				Transform val2 = val;
				while ((Object)(object)val2 != (Object)(object)go.transform)
				{
					num++;
					val2 = val2.parent;
				}
				string value = string.Join(", ", from c in ((Component)val).GetComponents<Component>()
					where (Object)(object)c != (Object)null && !(c is Transform)
					select ((object)c).GetType().Name);
				stringBuilder.Append(new string(' ', num * 2)).Append("- ").Append(((Object)val).name)
					.Append(((Component)val).gameObject.activeSelf ? "" : " (inactive)")
					.Append(" [")
					.Append(value)
					.Append("]\n");
				Renderer component = ((Component)val).GetComponent<Renderer>();
				if ((Object)(object)component == (Object)null)
				{
					continue;
				}
				Material[] sharedMaterials = component.sharedMaterials;
				foreach (Material val3 in sharedMaterials)
				{
					if ((Object)(object)val3 == (Object)null)
					{
						stringBuilder.Append(new string(' ', num * 2 + 4)).Append("material: null\n");
						continue;
					}
					StringBuilder stringBuilder2 = stringBuilder.Append(new string(' ', num * 2 + 4));
					string name = ((Object)val3).name;
					Shader shader = val3.shader;
					stringBuilder2.Append(string.Format("material '{0}' shader '{1}' _EmissionColor={2}", name, (shader != null) ? ((Object)shader).name : null, val3.HasProperty("_EmissionColor"))).Append(val3.HasProperty("_Color") ? string.Format(" _Color={0}", val3.GetColor("_Color")) : "").Append(val3.HasProperty("_EmissionColor") ? string.Format(" emission={0}", val3.GetColor("_EmissionColor")) : "")
						.Append(" keywords=[" + string.Join(" ", val3.shaderKeywords) + "]\n");
				}
			}
			Plugin.Log.LogInfo((object)stringBuilder.ToString());
		}

		internal static void CheckEffectPrefab(string name, params string[] hints)
		{
			if (!On)
			{
				return;
			}
			try
			{
				if ((Object)(object)PrefabManager.Instance.GetPrefab(name) != (Object)null)
				{
					Log("Effect prefab '" + name + "': found");
					return;
				}
				List<string> list = (from n in (((Object)(object)ZNetScene.instance != (Object)null) ? (from p in ZNetScene.instance.m_prefabs
						where (Object)(object)p != (Object)null
						select ((Object)p).name) : (from g in Resources.FindObjectsOfTypeAll<GameObject>()
						where (Object)(object)g.transform.parent == (Object)null
						select ((Object)g).name)).Where((string n) => (n.StartsWith("fx_") || n.StartsWith("vfx_")) && hints.Any((string h) => n.IndexOf(h, StringComparison.OrdinalIgnoreCase) >= 0)).Distinct()
					orderby n
					select n).Take(40).ToList();
				Log("Effect prefab '" + name + "': NOT FOUND. Candidates: " + ((list.Count > 0) ? string.Join(", ", list) : "none"));
			}
			catch (Exception ex)
			{
				Log("Effect prefab check failed: " + ex.Message);
			}
		}

		internal static string StatsAt(SharedData s, int q)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			int num = q - 1;
			DamageTypes damages = s.m_damages;
			string arg = string.Join("", from x in new(string, float)[6]
				{
					("fire", damages.m_fire),
					("frost", damages.m_frost),
					("lightning", damages.m_lightning),
					("poison", damages.m_poison),
					("blunt", damages.m_blunt),
					("pierce", damages.m_pierce)
				}
				where x.Item2 > 0f
				select $", {x.Item1} {x.Item2}");
			return $"L{q}: slash {damages.m_slash + s.m_damagesPerLevel.m_slash * (float)num}, " + $"spirit {damages.m_spirit + s.m_damagesPerLevel.m_spirit * (float)num}{arg}, " + $"block {s.m_blockPower + s.m_blockPowerPerLevel * (float)num}, parry x{s.m_timedBlockBonus}";
		}

		internal static void DumpRecipes()
		{
			if (!On || (Object)(object)ObjectDB.instance == (Object)null)
			{
				return;
			}
			foreach (Recipe item in ObjectDB.instance.m_recipes.Where(Costs.IsOurRecipe))
			{
				string text = string.Join(", ", item.m_resources.Select((Requirement r) => string.Format("{0} x{1} (+{2}/lvl)", ((Object)(object)r.m_resItem != (Object)null) ? ((Object)r.m_resItem).name : "MISSING ITEM", r.m_amount, r.m_amountPerLevel)));
				Log("Recipe " + ((Object)item).name + " -> " + ((Object)item.m_item).name + ": station '" + (((Object)(object)item.m_craftingStation != (Object)null) ? ((Object)item.m_craftingStation).name : "NONE") + "' " + $"level {item.m_minStationLevel}, upgradeOnly={item.m_noCraftOnlyUpgrade}, enabled={item.m_enabled}, needs: {text}");
			}
		}

		internal static IEnumerable<string> AllOurPrefabs()
		{
			return new string[2] { "SwordVorpal", "SwordFreyrsVorpal" }.Concat(Variants.PrefabNames);
		}

		internal static void DumpStatus(string reason)
		{
			if (!On)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			StringBuilder stringBuilder = new StringBuilder("[Vorpal] Status (" + reason + "):\n");
			foreach (string item in AllOurPrefabs())
			{
				GameObject val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab(item) : null);
				SharedData val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>().m_itemData.m_shared : null);
				if (val2 == null)
				{
					stringBuilder.Append("  " + item + ": not in ObjectDB!\n");
					continue;
				}
				for (int i = 1; i <= val2.m_maxQuality; i++)
				{
					stringBuilder.Append("  " + item + " ").Append(StatsAt(val2, i)).Append('\n');
				}
			}
			if ((Object)(object)localPlayer != (Object)null)
			{
				ItemData val3 = RightItem((Humanoid)(object)localPlayer);
				stringBuilder.Append("  Right hand: " + ((val3 != null) ? (val3.m_shared.m_name + " Q" + val3.m_quality + " dur " + val3.m_durability.ToString("0")) : "empty") + "\n");
				stringBuilder.Append($"  Body armor: {((Character)localPlayer).GetBodyArmor():0.#}\n");
				stringBuilder.Append($"  Blocking skill: {((Character)localPlayer).GetSkillLevel((SkillType)6):0.#} (includes buff if active)\n");
				IEnumerable<string> values = from e in ((Character)localPlayer).GetSEMan().GetStatusEffects()
					select ((Object)e).name;
				stringBuilder.Append("  Status effects: " + string.Join(", ", values) + "\n");
				VisEquipment component = ((Component)localPlayer).GetComponent<VisEquipment>();
				if ((Object)(object)component != (Object)null)
				{
					GameObject value = Traverse.Create((object)component).Field<GameObject>("m_rightItemInstance").Value;
					GameObject value2 = Traverse.Create((object)component).Field<GameObject>("m_rightBackItemInstance").Value;
					stringBuilder.Append("  Visual in hand: " + (((Object)(object)value != (Object)null) ? (((Object)value).name + " glow=" + ((Object)(object)value.GetComponent<GlowMarker>() != (Object)null)) : "none") + ", on back: " + (((Object)(object)value2 != (Object)null) ? ((Object)value2).name : "none") + "\n");
				}
			}
			Plugin.Log.LogInfo((object)stringBuilder.ToString());
			DumpRecipes();
		}

		internal static void LogThrowNumbers()
		{
			if (!On)
			{
				return;
			}
			try
			{
				ObjectDB instance = ObjectDB.instance;
				object obj;
				if (instance == null)
				{
					obj = null;
				}
				else
				{
					GameObject itemPrefab = instance.GetItemPrefab("SpearFlint");
					obj = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
				}
				Attack val = ((ItemDrop)(obj?)).m_itemData.m_shared.m_secondaryAttack;
				if (val == null)
				{
					Log("Throw numbers: SpearFlint not found");
					return;
				}
				Projectile val2 = (((Object)(object)val.m_attackProjectile != (Object)null) ? val.m_attackProjectile.GetComponent<Projectile>() : null);
				GameObject attackProjectile = val.m_attackProjectile;
				Log($"Throw (SpearFlint secondary): projectile '{((attackProjectile != null) ? ((Object)attackProjectile).name : null)}', speed {val.m_projectileVelMin}-{val.m_projectileVel}, " + $"accuracy {val.m_projectileAccuracyMin}-{val.m_projectileAccuracy}, stamina {val.m_attackStamina}" + (((Object)(object)val2 != (Object)null) ? $", gravity {val2.m_gravity}, lifetime {val2.m_ttl}s" : ""));
			}
			catch (Exception ex)
			{
				Log("Throw numbers unavailable: " + ex.Message);
			}
		}

		internal static IEnumerator DelayedStatus(string reason)
		{
			yield return (object)new WaitForSeconds(0.5f);
			DumpStatus(reason);
		}
	}
	[HarmonyPatch(typeof(Humanoid), "EquipItem")]
	internal static class EquipLog
	{
		private static void Postfix(Humanoid __instance, ItemData item, bool __result)
		{
			if (Diag.On && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && Diag.IsOurs(item))
			{
				Diag.Log($"Equipped {Diag.Label(item)} (result {__result}). {Diag.StatsAt(item.m_shared, item.m_quality)}");
				Dictionary<string, string> customData = item.m_customData;
				Diag.Log((customData == null || customData.Count == 0) ? "Item custom data: none (not enchanted)" : ("Item custom data: " + string.Join("; ", customData.Select((KeyValuePair<string, string> kv) => kv.Key + " = " + ((kv.Value != null && kv.Value.Length > 300) ? (kv.Value.Substring(0, 300) + "...") : kv.Value)))));
				((MonoBehaviour)Plugin.Instance).StartCoroutine(Diag.DelayedStatus("after equip"));
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "UnequipItem")]
	internal static class UnequipLog
	{
		private static void Postfix(Humanoid __instance, ItemData item)
		{
			if (Diag.On && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && Diag.IsOurs(item))
			{
				Diag.Log("Unequipped " + Diag.Label(item));
				((MonoBehaviour)Plugin.Instance).StartCoroutine(Diag.DelayedStatus("after unequip"));
			}
		}
	}
	[HarmonyPatch(typeof(Character), "Damage")]
	internal static class HitLog
	{
		private static void Prefix(Character __instance, HitData hit)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			if (Diag.On && hit != null && !((Object)(object)hit.GetAttacker() != (Object)(object)Player.m_localPlayer) && Diag.LocalHolding(out var item))
			{
				Diag.Log($"HIT {__instance.m_name} (lvl {__instance.GetLevel()}): slash {hit.m_damage.m_slash:0.#}, spirit {hit.m_damage.m_spirit:0.#}, " + $"total {hit.GetTotalDamage():0.#}, skill raise type {hit.m_skill}, Q{item.m_quality}, durability {item.m_durability:0}");
			}
		}
	}
	[HarmonyPatch(typeof(Character), "ApplyDamage")]
	internal static class ApplyLog
	{
		private static void Prefix(Character __instance, HitData hit, DamageModifier mod)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			if (Diag.On && hit != null)
			{
				Character attacker = hit.GetAttacker();
				if ((Object)(object)attacker == (Object)(object)Player.m_localPlayer && Diag.LocalHolding(out var item))
				{
					Diag.Log($"APPLIED to {__instance.m_name}: {hit.GetTotalDamage():0.#} (modifier {mod}), target HP {__instance.GetHealth():0}/{__instance.GetMaxHealth():0}");
				}
				else if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && Diag.LocalHolding(out item))
				{
					Diag.Log(string.Format("TOOK {0:0.#} from {1} (modifier {2}), armor {3:0.#}, HP {4:0}", hit.GetTotalDamage(), ((Object)(object)attacker != (Object)null) ? attacker.m_name : "?", mod, ((Character)Player.m_localPlayer).GetBodyArmor(), __instance.GetHealth()));
				}
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "BlockAttack")]
	internal static class BlockLog
	{
		private static void Prefix(Humanoid __instance, HitData hit, out float __state)
		{
			__state = ((hit != null) ? hit.GetTotalBlockableDamage() : 0f);
		}

		private static void Postfix(Humanoid __instance, HitData hit, Character attacker, bool __result, float __state)
		{
			if (Diag.On && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
			{
				ItemData value = Traverse.Create((object)__instance).Method("GetCurrentBlocker", Array.Empty<object>()).GetValue<ItemData>();
				if (Diag.IsOurs(value))
				{
					Diag.Log(string.Format("BLOCK vs {0}: blocked={1}, blockable before {2:0.#}, after {3:0.#}, ", ((Object)(object)attacker != (Object)null) ? attacker.m_name : "?", __result, __state, hit.GetTotalBlockableDamage()) + $"blocker {value.m_shared.m_name} Q{value.m_quality} blockPower {value.m_shared.m_blockPower + value.m_shared.m_blockPowerPerLevel * (float)(value.m_quality - 1):0.#}, " + $"blocking skill {((Character)__instance).GetSkillLevel((SkillType)6):0.#}");
				}
			}
		}
	}
	internal static class EpicLootIntegration
	{
		public const string EpicLootGuid = "randyknapp.mods.epicloot";

		public const string LegendaryId = "FreyrsVorpalSword";

		public const string LegendaryNameToken = "$mod_freyrsvorpal_l_freyrsvorpalsword";

		public const string LegendaryDescToken = "$mod_freyrsvorpal_l_freyrsvorpalsword_desc";

		internal static bool Active;

		private static Type _helper;

		internal const float FreyrSelectionWeight = 1000000f;

		private static string LegendaryJson()
		{
			return "{\"ID\":\"FreyrsVorpalSword\",\"Name\":\"$mod_freyrsvorpal_l_freyrsvorpalsword\",\"Description\":\"$mod_freyrsvorpal_l_freyrsvorpalsword_desc\",\"Rarities\":[\"Legendary\",\"Mythic\",\"Ancient\"],\"Requirements\":{\"AllowedItemNames\":[\"$item_freyrsvorpalsword\"]}," + $"\"GuaranteedEffectCount\":{Plugin.LegendaryEffectCount.Value}," + "\"GuaranteedMagicEffects\":[{\"Type\":\"AddPoisonDamage\"},{\"Type\":\"AddFrostDamage\"},{\"Type\":\"FreyrFightsOnItsOwn\"}" + (Plugin.NativeThrowEnabled.Value ? "" : ",{\"Type\":\"Throwable\"},{\"Type\":\"RecallWeapon\"}") + "]}";
		}

		internal static void Init(Harmony harmony)
		{
			if (!Plugin.EpicLootEnabled.Value)
			{
				Diag.Log("EpicLoot integration disabled in config.");
				return;
			}
			Type type = AccessTools.TypeByName("EpicLoot.API");
			if (type == null)
			{
				Diag.Log("EpicLoot not installed: integration skipped (sword works normally).");
				return;
			}
			try
			{
				object arg = AccessTools.Method(type, "GetApiVersion", (Type[])null, (Type[])null)?.Invoke(null, null);
				object arg2 = AccessTools.Method(type, "GetPluginVersion", (Type[])null, (Type[])null)?.Invoke(null, null);
				Plugin.Log.LogInfo((object)$"[Vorpal] EpicLoot {arg2} detected (API v{arg}).");
				MethodInfo methodInfo = AccessTools.Method(type, "add_OnError", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					methodInfo.Invoke(null, new object[1] { (Action<string>)delegate(string msg)
					{
						Plugin.Log.LogWarning((object)("[Vorpal] EpicLoot API error: " + msg));
					} });
				}
				RegisterOwnEffects();
				MethodInfo methodInfo2 = AccessTools.Method(type, "AddLegendaryItem", new Type[2]
				{
					typeof(string),
					typeof(string)
				}, (Type[])null);
				if (methodInfo2 == null)
				{
					Plugin.Log.LogWarning((object)"[Vorpal] EpicLoot API has no AddLegendaryItem; Freyr's Sword not registered.");
					return;
				}
				string text = LegendaryJson();
				object obj = methodInfo2.Invoke(null, new object[2] { "Legendary", text });
				if (obj == null)
				{
					Plugin.Log.LogWarning((object)("[Vorpal] EpicLoot rejected the Freyr's Sword legendary. JSON: " + text));
					return;
				}
				Diag.Log(string.Format("Registered EpicLoot unique '{0}' (key {1}). JSON: {2}", "FreyrsVorpalSword", obj, text));
				object obj2 = AccessTools.Method(type, "GetLegendaryInfoJson", (Type[])null, (Type[])null)?.Invoke(null, new object[1] { "FreyrsVorpalSword" });
				Diag.Log("EpicLoot reports Freyr's Sword as: " + (obj2 ?? "null"));
				Type type2 = AccessTools.TypeByName("EpicLoot.LegendarySystem.UniqueLegendaryHelper");
				if (type2 == null)
				{
					Plugin.Log.LogWarning((object)"[Vorpal] UniqueLegendaryHelper not found; Freyr's Sword may not be forced.");
				}
				else
				{
					_helper = type2;
					EventInfo eventInfo = type2.GetEvent("OnSetupLegendaryItemConfig");
					if (eventInfo != null)
					{
						eventInfo.AddEventHandler(null, new Action(ApplyExclusions));
					}
					else
					{
						Plugin.Log.LogWarning((object)"[Vorpal] EpicLoot has no OnSetupLegendaryItemConfig; exclusions apply once now and not after a config reload.");
					}
					ApplyExclusions();
				}
				if (Plugin.NativeThrowEnabled.Value)
				{
					InitNativeThrow(harmony);
				}
				else
				{
					Diag.Log("Native throw disabled in config (the unique gets EpicLoot's Throwable + Recall instead).");
				}
				InitFightsOnItsOwn(harmony);
				InitOnlyOne(harmony);
				Active = true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("[Vorpal] EpicLoot integration failed (sword still works): " + ex));
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void InitNativeThrow(Harmony harmony)
		{
			try
			{
				NativeThrow.Init(harmony);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("[Vorpal] Native throw setup failed (swords still work, just not throwable): " + ex));
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void RegisterOwnEffects()
		{
			try
			{
				FightsOnItsOwn.RegisterEffect();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("[Vorpal] Registering 'Fights on Its Own' failed: " + ex));
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void InitFightsOnItsOwn(Harmony harmony)
		{
			try
			{
				FightsOnItsOwn.Init(harmony);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("[Vorpal] 'Fights on Its Own' setup failed: " + ex));
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void InitOnlyOne(Harmony harmony)
		{
			try
			{
				OnlyOneEpicLoot.Init(harmony);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("[Vorpal] Keeping Freyr's Vorpal Sword out of EpicLoot loot failed: " + ex));
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static void AfterForge(ItemData created)
		{
			try
			{
				OnlyOneEpicLoot.AfterForge(created);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Vorpal] EpicLoot re-roll after forging failed: " + ex.Message));
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static void AfterRevert(ItemData vorpal)
		{
			try
			{
				OnlyOneEpicLoot.AfterRevert(vorpal);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Vorpal] EpicLoot re-roll after reverting failed: " + ex.Message));
			}
		}

		private static string IdOf(object legendaryInfo)
		{
			try
			{
				return Traverse.Create(legendaryInfo).Field<string>("ID").Value;
			}
			catch
			{
				return null;
			}
		}

		private static void ApplyExclusions()
		{
			try
			{
				if (_helper == null)
				{
					return;
				}
				string[] array = new string[2] { "$item_vorpalsword", "$item_freyrsvorpalsword" };
				object obj = AccessTools.Method(_helper, "GetCFG", (Type[])null, (Type[])null)?.Invoke(null, null);
				List<IEnumerable> list = new List<IEnumerable>();
				if (obj != null)
				{
					string[] array2 = new string[2] { "LegendaryItems", "MythicItems" };
					foreach (string text in array2)
					{
						if (Traverse.Create(obj).Field(text).GetValue() is IEnumerable item)
						{
							list.Add(item);
						}
					}
				}
				if (AccessTools.Field(_helper, "AllUniques")?.GetValue(null) is IDictionary dictionary)
				{
					list.Add(dictionary.Values);
				}
				HashSet<object> hashSet = new HashSet<object>();
				int num = 0;
				int num2 = 0;
				foreach (IEnumerable item3 in list)
				{
					foreach (object item4 in item3)
					{
						if (item4 == null || !hashSet.Add(item4))
						{
							continue;
						}
						Traverse val = Traverse.Create(item4);
						if (IdOf(item4) == "FreyrsVorpalSword")
						{
							val.Field("SelectionWeight").SetValue((object)1000000f);
							num2++;
							continue;
						}
						object obj2 = val.Field("Requirements").GetValue();
						if (obj2 == null)
						{
							Type type = AccessTools.Field(item4.GetType(), "Requirements")?.FieldType;
							if (type == null)
							{
								continue;
							}
							obj2 = Activator.CreateInstance(type);
							val.Field("Requirements").SetValue(obj2);
						}
						Traverse val2 = Traverse.Create(obj2).Field("ExcludedItemNames");
						List<string> list2 = val2.GetValue() as List<string>;
						if (list2 == null)
						{
							list2 = new List<string>();
							val2.SetValue((object)list2);
						}
						bool flag = false;
						string[] array2 = array;
						foreach (string item2 in array2)
						{
							if (!list2.Contains(item2))
							{
								list2.Add(item2);
								flag = true;
							}
						}
						if (flag)
						{
							num++;
						}
					}
				}
				Diag.Log(string.Format("EpicLoot: our swords excluded from {0} other unique(s)/set piece(s); Freyr's Sword weight {1} on {2} entr{3}", num, 1000000f, num2, (num2 == 1) ? "y" : "ies"));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Vorpal] EpicLoot exclusions failed: " + ex));
			}
		}
	}
	internal static class FightsOnItsOwn
	{
		private class SplashInfo
		{
			public float Radius;

			public Character Owner;

			public bool Done;
		}

		public const string EffectType = "FreyrFightsOnItsOwn";

		public const string DisplayToken = "$mod_freyrsvorpal_me_fightsonitsown_display";

		public const string DescToken = "$mod_freyrsvorpal_me_fightsonitsown_desc";

		private static readonly ConditionalWeakTable<Projectile, SplashInfo> Splash = new ConditionalWeakTable<Projectile, SplashInfo>();

		internal static void RegisterEffect()
		{
			string text = "{\"Type\":\"FreyrFightsOnItsOwn\",\"DisplayText\":\"$mod_freyrsvorpal_me_fightsonitsown_display\",\"Description\":\"$mod_freyrsvorpal_me_fightsonitsown_desc\",\"CanBeAugmented\":false,\"CanBeDisenchanted\":false,\"CanBeRunified\":false,\"SelectionWeight\":0,\"Requirements\":{\"AllowedItemNames\":[\"$item_vorpalsword\",\"$item_freyrsvorpalsword\"],\"AllowedRarities\":[\"Legendary\",\"Mythic\",\"Ancient\"]},\"ValuesPerRarity\":{\"Legendary\":{\"MinValue\":3,\"MaxValue\":4,\"Increment\":0.5},\"Mythic\":{\"MinValue\":4,\"MaxValue\":5,\"Increment\":0.5},\"Ancient\":{\"MinValue\":5,\"MaxValue\":6,\"Increment\":0.5}}}";
			string text2 = API.AddMagicEffect(text);
			if (text2 == null)
			{
				Plugin.Log.LogWarning((object)("[Vorpal] EpicLoot rejected the 'Fights on Its Own' effect. JSON: " + text));
			}
			else
			{
				Diag.Log("Registered EpicLoot effect FreyrFightsOnItsOwn (key " + text2 + ")");
			}
		}

		internal static void Init(Harmony harmony)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_0081: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(Projectile), "Setup", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(FightsOnItsOwn), "SetupPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Projectile), "OnHit", (Type[])null, (Type[])null), new HarmonyMethod(typeof(FightsOnItsOwn), "OnHitPrefix", (Type[])null), new HarmonyMethod(typeof(FightsOnItsOwn), "OnHitPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Diag.Log("'Fights on Its Own' armed (impact effect is checked once the game's prefabs load).");
		}

		private static void SetupPostfix(Projectile __instance, Character owner, ItemData item)
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Expected O, but got Unknown
			try
			{
				if (item == null || !Diag.IsOurs(item))
				{
					return;
				}
				Player val = (Player)(object)((owner is Player) ? owner : null);
				if (val == null)
				{
					return;
				}
				float totalActiveMagicEffectValueForWeapon = API.GetTotalActiveMagicEffectValueForWeapon(val, item, "FreyrFightsOnItsOwn", 1f);
				if (!(totalActiveMagicEffectValueForWeapon <= 0f))
				{
					Splash.Remove(__instance);
					Splash.Add(__instance, new SplashInfo
					{
						Radius = totalActiveMagicEffectValueForWeapon,
						Owner = (Character)(object)val
					});
					GameObject prefab = PrefabManager.Instance.GetPrefab(Plugin.FightsVfx.Value);
					if ((Object)(object)prefab != (Object)null)
					{
						EffectList val2 = (EffectList)(((object)__instance.m_hitEffects) ?? ((object)new EffectList()));
						List<EffectData> list = ((IEnumerable<EffectData>)(((object)val2.m_effectPrefabs) ?? ((object)new EffectData[0]))).ToList();
						list.Add(new EffectData
						{
							m_prefab = prefab,
							m_enabled = true
						});
						val2.m_effectPrefabs = list.ToArray();
						__instance.m_hitEffects = val2;
					}
					Diag.Log($"Fights on Its Own: thrown {Diag.Label(item)} will strike every other enemy within {totalActiveMagicEffectValueForWeapon:0.#} m of impact " + $"for {Plugin.FightsSplashDamage.Value:P0} of the throw's damage");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Vorpal] Fights on Its Own: " + ex.Message));
			}
		}

		private static void OnHitPrefix(Projectile __instance, out DamageTypes __state)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			__state = __instance.m_damage;
		}

		private static void OnHitPostfix(Projectile __instance, Collider collider, Vector3 hitPoint, bool water, DamageTypes __state)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Expected O, but got Unknown
			try
			{
				if (!Splash.TryGetValue(__instance, out var value) || value.Done || water)
				{
					return;
				}
				value.Done = true;
				Character owner = value.Owner;
				if ((Object)(object)owner == (Object)null)
				{
					return;
				}
				Character val = (((Object)(object)collider != (Object)null) ? ((Component)collider).GetComponentInParent<Character>() : null);
				DamageTypes damage = __state;
				((DamageTypes)(ref damage)).Modify(Mathf.Clamp(Plugin.FightsSplashDamage.Value, 0f, 1f));
				int num = 0;
				foreach (Character allCharacter in Character.GetAllCharacters())
				{
					if (!((Object)(object)allCharacter == (Object)null) && !((Object)(object)allCharacter == (Object)(object)val) && !((Object)(object)allCharacter == (Object)(object)owner) && !allCharacter.IsDead() && BaseAI.IsEnemy(owner, allCharacter) && !(Vector3.Distance(((Component)allCharacter).transform.position, hitPoint) > value.Radius))
					{
						Vector3 val2 = ((Component)allCharacter).transform.position - hitPoint;
						val2.y = 0f;
						HitData val3 = new HitData
						{
							m_damage = damage,
							m_point = allCharacter.GetCenterPoint(),
							m_dir = ((((Vector3)(ref val2)).sqrMagnitude > 0.01f) ? ((Vector3)(ref val2)).normalized : Vector3.forward),
							m_pushForce = __instance.m_attackForce * 0.5f,
							m_ranged = true,
							m_skill = __instance.m_skill,
							m_hitType = (HitType)2
						};
						val3.SetAttacker(owner);
						allCharacter.Damage(val3);
						num++;
					}
				}
				Diag.Log(string.Format("Fights on Its Own: struck {0} other enem{1} within {2:0.#} m for {3:P0} (total {4:0})", num, (num == 1) ? "y" : "ies", value.Radius, Plugin.FightsSplashDamage.Value, ((DamageTypes)(ref damage)).GetTotalDamage()));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Vorpal] Fights on Its Own splash: " + ex.Message));
			}
		}
	}
	internal static class Forging
	{
		internal class Spec
		{
			public string Source;

			public int MinQuality;
		}

		internal static ItemData PendingSource;

		internal static string PendingResult;

		internal static bool SourceConsumed;

		internal static HashSet<ItemData> ResultsBefore;

		internal static Spec For(string resultPrefab)
		{
			if (resultPrefab == "SwordFreyrsVorpal")
			{
				return new Spec
				{
					Source = "SwordVorpal",
					MinQuality = Plugin.FreyrNeedsVorpalQuality.Value
				};
			}
			if (Variants.PrefabNames.Contains(resultPrefab))
			{
				return new Spec
				{
					Source = "SwordFreyrsVorpal",
					MinQuality = 1
				};
			}
			return null;
		}

		internal static bool IsPrefab(ItemData item, string prefab)
		{
			if (item != null && (Object)(object)item.m_dropPrefab != (Object)null)
			{
				return ((Object)item.m_dropPrefab).name == prefab;
			}
			return false;
		}

		internal static bool IsBookkeeping(string key)
		{
			return key.StartsWith("valheim.epiclootprogressionfix.recall", StringComparison.Ordinal);
		}

		internal static bool HasEnchantData(ItemData i)
		{
			if (i.m_customData != null)
			{
				return i.m_customData.Keys.Any((string k) => !IsBookkeeping(k) && k != "valheim.freyrsvorpalsword.serial");
			}
			return false;
		}

		internal static Dictionary<string, string> CarriedData(ItemData i)
		{
			return i.m_customData?.Where((KeyValuePair<string, string> kv) => !IsBookkeeping(kv.Key)).ToDictionary((KeyValuePair<string, string> kv) => kv.Key, (KeyValuePair<string, string> kv) => kv.Value) ?? new Dictionary<string, string>();
		}

		internal static ItemData PickSource(Player player, Spec spec)
		{
			return (from i in ((Humanoid)player).GetInventory().GetAllItems()
				where IsPrefab(i, spec.Source) && i.m_quality >= spec.MinQuality
				where spec.Source != "SwordFreyrsVorpal" || !OnlyOne.CanJudge || OnlyOne.IsCurrent(i)
				select i).ToList().OrderByDescending(HasEnchantData).ThenByDescending((ItemData i) => i.m_equipped)
				.ThenByDescending((ItemData i) => i.m_quality)
				.ThenByDescending((ItemData i) => i.m_durability)
				.FirstOrDefault();
		}
	}
	[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
	{
		typeof(Recipe),
		typeof(bool),
		typeof(int),
		typeof(int)
	})]
	internal static class ForgeRequirementPatch
	{
		private static void Postfix(Player __instance, Recipe recipe, bool discover, int qualityLevel, ref bool __result)
		{
			if (discover || !__result || (Object)(object)recipe?.m_item == (Object)null || qualityLevel > 1)
			{
				return;
			}
			Forging.Spec spec = Forging.For(((Object)recipe.m_item).name);
			if (spec != null)
			{
				if (((Object)recipe.m_item).name == "SwordFreyrsVorpal" && OnlyOne.Taken)
				{
					__result = false;
				}
				else if (Forging.PickSource(__instance, spec) == null)
				{
					__result = false;
				}
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "AddRecipeToList")]
	internal static class UpgradeRowPatch
	{
		[HarmonyPriority(800)]
		private static bool Prefix(Recipe recipe, ItemData item)
		{
			if (item == null || (Object)(object)recipe?.m_item == (Object)null || !Costs.IsOurRecipe(recipe) || (Object)(object)item.m_dropPrefab == (Object)null)
			{
				return true;
			}
			return ((Object)item.m_dropPrefab).name == ((Object)recipe.m_item).name;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
	internal static class ForgeCraftPatch
	{
		private static void Prefix(InventoryGui __instance, Player player)
		{
			Forging.PendingSource = null;
			Forging.PendingResult = null;
			Forging.SourceConsumed = false;
			Forging.ResultsBefore = null;
			try
			{
				Recipe recipe = Traverse.Create((object)__instance).Field<Recipe>("m_craftRecipe").Value;
				ItemData value = Traverse.Create((object)__instance).Field<ItemData>("m_craftUpgradeItem").Value;
				if ((Object)(object)recipe?.m_item == (Object)null || value != null)
				{
					return;
				}
				Forging.Spec spec = Forging.For(((Object)recipe.m_item).name);
				if (spec == null)
				{
					return;
				}
				ItemData val = Forging.PickSource(player, spec);
				if (val == null)
				{
					((Character)player).Message((MessageType)2, string.Format("Needs a level {0} {1}", spec.MinQuality, (spec.Source == "SwordVorpal") ? "Vorpal Sword" : "Freyr's Vorpal Sword"), 0, (Sprite)null, false);
					return;
				}
				Forging.PendingSource = val;
				Forging.PendingResult = ((Object)recipe.m_item).name;
				Forging.ResultsBefore = new HashSet<ItemData>(from i in ((Humanoid)player).GetInventory().GetAllItems()
					where Forging.IsPrefab(i, ((Object)recipe.m_item).name)
					select i);
				Diag.Log(string.Format("Forging {0} from {1} L{2} (custom data keys: {3})", ((Object)recipe.m_item).name, spec.Source, val.m_quality, (val.m_customData == null) ? "none" : string.Join(", ", val.m_customData.Keys)));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Vorpal] Forge prefix: " + ex.Message));
			}
		}

		private static void Postfix(Player player)
		{
			try
			{
				if (Forging.PendingSource == null)
				{
					return;
				}
				ItemData val = ((IEnumerable<ItemData>)((Humanoid)player).GetInventory().GetAllItems()).FirstOrDefault((Func<ItemData, bool>)((ItemData i) => Forging.IsPrefab(i, Forging.PendingResult) && !Forging.ResultsBefore.Contains(i)));
				bool flag = Forging.PendingResult == "SwordFreyrsVorpal";
				if (val == null)
				{
					Diag.Log($"Forge: no new {Forging.PendingResult} found (craft didn't happen?). Source consumed: {Forging.SourceConsumed}");
					if (flag)
					{
						OnlyOne.FinishForge(null);
					}
					return;
				}
				if (!Forging.SourceConsumed && ((Humanoid)player).GetInventory().ContainsItem(Forging.PendingSource))
				{
					ItemData pendingSource = Forging.PendingSource;
					if (pendingSource.m_equipped)
					{
						((Humanoid)player).UnequipItem(pendingSource, false);
					}
					((Humanoid)player).GetInventory().RemoveItem(pendingSource);
					Forging.SourceConsumed = true;
					Diag.Log("Forge: the game didn't consume the source (nocost?); removed " + Diag.Label(pendingSource) + " ourselves.");
				}
				if (!Forging.SourceConsumed)
				{
					Plugin.Log.LogWarning((object)"[Vorpal] Forge: the chosen source sword is gone but wasn't consumed by the forge; enchantment not carried over.");
				}
				else
				{
					Dictionary<string, string> dictionary = Forging.CarriedData(Forging.PendingSource);
					if (dictionary.Count > 0)
					{
						val.m_customData = dictionary;
						Diag.Log("Forge: carried over custom data to " + Forging.PendingResult + ": " + string.Join(", ", val.m_customData.Keys));
					}
					else
					{
						Diag.Log("Forge: " + Forging.PendingResult + " created; source had nothing to carry over.");
					}
				}
				if (flag)
				{
					OnlyOne.FinishForge(val);
					if (EpicLootIntegration.Active)
					{
						EpicLootIntegration.AfterForge(val);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Vorpal] Forge postfix: " + ex.Message));
			}
			finally
			{
				Forging.PendingSource = null;
				Forging.PendingResult = null;
				Forging.ResultsBefore = null;
			}
		}
	}
	[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
	{
		typeof(string),
		typeof(int),
		typeof(int),
		typeof(bool)
	})]
	internal static class ForgeConsumePatch
	{
		private static bool Prefix(Inventory __instance, string name, int amount)
		{
			ItemData pendingSource = Forging.PendingSource;
			if (pendingSource == null || Forging.SourceConsumed || amount != 1 || pendingSource.m_shared.m_name != name)
			{
				return true;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Humanoid)localPlayer).GetInventory() != __instance || !__instance.ContainsItem(pendingSource))
			{
				return true;
			}
			if (pendingSource.m_equipped)
			{
				((Humanoid)localPlayer).UnequipItem(pendingSource, false);
			}
			__instance.RemoveItem(pendingSource);
			Forging.SourceConsumed = true;
			GameObject dropPrefab = pendingSource.m_dropPrefab;
			Diag.Log($"Forge: consumed the chosen {((dropPrefab != null) ? ((Object)dropPrefab).name : null)} L{pendingSource.m_quality}");
			return false;
		}
	}
	internal static class Glow
	{
		private static bool _loggedMaterials;

		internal static void Apply(GameObject instance, Color color)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.GetComponent<GlowMarker>() != (Object)null)
			{
				return;
			}
			instance.AddComponent<GlowMarker>();
			Color val = color * Plugin.GlowIntensity.Value;
			Renderer[] componentsInChildren = instance.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val2 in componentsInChildren)
			{
				if (val2 is ParticleSystemRenderer)
				{
					continue;
				}
				Material[] materials = val2.materials;
				BladeSubmesh component = ((Component)val2).GetComponent<BladeSubmesh>();
				for (int j = 0; j < materials.Length; j++)
				{
					Material val3 = materials[j];
					if (!((Object)(object)component != (Object)null) || j == component.Index)
					{
						if (!_loggedMaterials)
						{
							Plugin.Log.LogInfo((object)string.Format("Vorpal renderer '{0}' material '{1}' shader '{2}' hasEmission={3}", ((Object)val2).name, ((Object)val3).name, ((Object)val3.shader).name, val3.HasProperty("_EmissionColor")));
						}
						if (val3.HasProperty("_EmissionColor"))
						{
							val3.EnableKeyword("_EMISSION");
							val3.SetColor("_EmissionColor", val);
							val3.globalIlluminationFlags = (MaterialGlobalIlluminationFlags)1;
						}
					}
				}
				val2.materials = materials;
			}
			_loggedMaterials = true;
			GameObject val4 = new GameObject("VorpalLight");
			val4.transform.SetParent(instance.transform, false);
			val4.transform.localPosition = new Vector3(0f, 0f, 0.6f);
			Light obj = val4.AddComponent<Light>();
			obj.type = (LightType)2;
			obj.color = color;
			obj.range = Plugin.LightRange.Value;
			obj.intensity = Plugin.LightIntensity.Value;
			obj.shadows = (LightShadows)0;
		}

		internal static bool ColorForHash(int hash, out Color color)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			color = Plugin.GlowColor.Value;
			if (hash == Plugin.VorpalHash || hash == Plugin.FreyrHash)
			{
				return true;
			}
			Variants.Gem[] gems = Variants.Gems;
			foreach (Variants.Gem gem in gems)
			{
				if (hash == gem.Hash)
				{
					color = gem.GlowColor.Value;
					return true;
				}
			}
			return false;
		}

		internal static Sprite LoadEmbeddedIcon(string name = "icon_item")
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				using Stream stream = typeof(Glow).Assembly.GetManifestResourceStream("VorpalBlade." + name + ".png");
				if (stream == null)
				{
					Plugin.Log.LogWarning((object)"Embedded icon not found, falling back to tinted silver sword icon.");
					return null;
				}
				byte[] array = new byte[stream.Length];
				stream.Read(array, 0, array.Length);
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				MethodInfo methodInfo = Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule")?.GetMethod("LoadImage", new Type[2]
				{
					typeof(Texture2D),
					typeof(byte[])
				});
				if (methodInfo == null || !(bool)methodInfo.Invoke(null, new object[2] { val, array }))
				{
					Plugin.Log.LogWarning((object)"ImageConversion.LoadImage unavailable or failed; using tinted silver sword icon.");
					return null;
				}
				((Object)val).name = "FreyrsVorpalSwordIcon";
				((Texture)val).wrapMode = (TextureWrapMode)1;
				Diag.Log($"Loaded embedded icon {((Texture)val).width}x{((Texture)val).height}");
				return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Embedded icon failed to load: " + ex.Message));
				return null;
			}
		}

		internal static Sprite TintIcon(Sprite src, Color tint)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)src == (Object)null)
			{
				return null;
			}
			RenderTexture val = null;
			RenderTexture active = RenderTexture.active;
			try
			{
				Texture2D texture = src.texture;
				Rect textureRect = src.textureRect;
				val = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)0);
				Graphics.Blit((Texture)(object)texture, val);
				RenderTexture.active = val;
				int num = (int)((Rect)(ref textureRect)).width;
				int num2 = (int)((Rect)(ref textureRect)).height;
				Texture2D val2 = new Texture2D(num, num2, (TextureFormat)4, false);
				val2.ReadPixels(new Rect(((Rect)(ref textureRect)).x, ((Rect)(ref textureRect)).y, (float)num, (float)num2), 0, 0);
				Color[] pixels = val2.GetPixels();
				Color val4 = default(Color);
				for (int i = 0; i < pixels.Length; i++)
				{
					Color val3 = pixels[i];
					float num3 = val3.r * 0.3f + val3.g * 0.59f + val3.b * 0.11f;
					((Color)(ref val4))..ctor(tint.r * num3 * 1.3f, tint.g * num3 * 1.3f, tint.b * num3 * 1.3f, val3.a);
					pixels[i] = Color.Lerp(val3, val4, 0.65f);
					pixels[i].a = val3.a;
				}
				val2.SetPixels(pixels);
				val2.Apply();
				((Object)val2).name = "VorpalBladeIcon";
				return Sprite.Create(val2, new Rect(0f, 0f, (float)num, (float)num2), new Vector2(0.5f, 0.5f), src.pixelsPerUnit);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Icon tint failed, using the silver sword icon: " + ex.Message));
				return null;
			}
			finally
			{
				RenderTexture.active = active;
				if ((Object)(object)val != (Object)null)
				{
					RenderTexture.ReleaseTemporary(val);
				}
			}
		}
	}
	internal class GlowMarker : MonoBehaviour
	{
	}
	internal class BladeSubmesh : MonoBehaviour
	{
		public int Index = 1;
	}
	internal static class BladeSplit
	{
		private static Mesh _split;

		private static Mesh _source;

		private const string SplitSuffix = "_VorpalBladeSplit";

		internal static void Prepare(GameObject prefab)
		{
			try
			{
				MeshFilter val = ((IEnumerable<MeshFilter>)prefab.GetComponentsInChildren<MeshFilter>(true)).FirstOrDefault((Func<MeshFilter, bool>)((MeshFilter m) => (Object)(object)m.sharedMesh != (Object)null && (Object)(object)((Component)m).GetComponent<MeshRenderer>() != (Object)null));
				if ((Object)(object)val == (Object)null)
				{
					Diag.Log("Blade split " + ((Object)prefab).name + ": no sword mesh found - whole sword glows");
					return;
				}
				MeshRenderer component = ((Component)val).GetComponent<MeshRenderer>();
				Mesh sharedMesh = val.sharedMesh;
				if (((Object)sharedMesh).name.EndsWith("_VorpalBladeSplit"))
				{
					return;
				}
				if ((Object)(object)_source != (Object)(object)sharedMesh)
				{
					_source = sharedMesh;
					_split = null;
					if (!sharedMesh.isReadable)
					{
						Diag.Log("Blade split: mesh '" + ((Object)sharedMesh).name + "' is not readable - whole sword glows");
					}
					else if (sharedMesh.subMeshCount != 1)
					{
						Diag.Log($"Blade split: mesh '{((Object)sharedMesh).name}' already has {sharedMesh.subMeshCount} submeshes - whole sword glows");
					}
					else
					{
						_split = Build(sharedMesh);
					}
				}
				if (!((Object)(object)_split == (Object)null))
				{
					val.sharedMesh = _split;
					Material sharedMaterial = ((Renderer)component).sharedMaterial;
					((Renderer)component).sharedMaterials = (Material[])(object)new Material[2] { sharedMaterial, sharedMaterial };
					if ((Object)(object)((Component)val).GetComponent<BladeSubmesh>() == (Object)null)
					{
						((Component)val).gameObject.AddComponent<BladeSubmesh>().Index = 1;
					}
					Diag.Log("Blade split " + ((Object)prefab).name + ": '" + ((Object)val).name + "' glows on the blade only");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[Vorpal] Blade split " + ((Object)prefab).name + " failed (whole sword glows): " + ex.Message));
			}
		}

		private static Mesh Build(Mesh mesh)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] vertices = mesh.vertices;
			int[] triangles = mesh.triangles;
			Bounds bounds = mesh.bounds;
			int axis = ((!(((Bounds)(ref bounds)).size.x >= ((Bounds)(ref bounds)).size.y) || !(((Bounds)(ref bounds)).size.x >= ((Bounds)(ref bounds)).size.z)) ? ((((Bounds)(ref bounds)).size.y >= ((Bounds)(ref bounds)).size.z) ? 1 : 2) : 0);
			Vector3 val = ((Bounds)(ref bounds)).min;
			float num = ((Vector3)(ref val))[axis];
			val = ((Bounds)(ref bounds)).size;
			float num2 = ((Vector3)(ref val))[axis];
			Vector3[] lo = (Vector3[])(object)new Vector3[50];
			Vector3[] hi = (Vector3[])(object)new Vector3[50];
			bool[] has = new bool[50];
			Vector3[] array = vertices;
			for (int i = 0; i < array.Length; i++)
			{
				Vector3 val2 = array[i];
				int num3 = Mathf.Clamp((int)((((Vector3)(ref val2))[axis] - num) / num2 * 50f), 0, 49);
				if (!has[num3])
				{
					val = (lo[num3] = (hi[num3] = val2));
					has[num3] = true;
				}
				else
				{
					lo[num3] = Vector3.Min(lo[num3], val2);
					hi[num3] = Vector3.Max(hi[num3], val2);
				}
			}
			int num4 = Enumerable.Range(0, 50).OrderByDescending(Width).First();
			bool flag = num4 < 25;
			float num5 = Width(num4);
			int j;
			for (j = num4 + (flag ? 1 : (-1)); j > 0 && j < 49 && Width(j) > num5 * 0.5f; j += (flag ? 1 : (-1)))
			{
			}
			float num6 = num + num2 * (float)(flag ? j : (j + 1)) / 50f;
			List<int> list = new List<int>();
			List<int> list2 = new List<int>();
			for (int k = 0; k + 2 < triangles.Length; k += 3)
			{
				float num7 = (((Vector3)(ref vertices[triangles[k]]))[axis] + ((Vector3)(ref vertices[triangles[k + 1]]))[axis] + ((Vector3)(ref vertices[triangles[k + 2]]))[axis]) / 3f;
				List<int> obj = ((flag ? (num7 >= num6) : (num7 <= num6)) ? list : list2);
				obj.Add(triangles[k]);
				obj.Add(triangles[k + 1]);
				obj.Add(triangles[k + 2]);
			}
			Diag.Log(string.Format("Blade split: mesh '{0}' {1} verts, long axis {2} length {3:0.###}, guard at slice {4}/{5} (width {6:0.###}), ", ((Object)mesh).name, vertices.Length, "xyz"[axis], num2, num4, 50, num5) + string.Format("blade on the {0} side from {1:0.###}: {2} blade / {3} other triangles", flag ? "+" : "-", num6, list.Count / 3, list2.Count / 3));
			if (list.Count == 0 || list2.Count == 0)
			{
				Diag.Log("Blade split: nothing to split - whole sword glows");
				return null;
			}
			Mesh obj2 = Object.Instantiate<Mesh>(mesh);
			((Object)obj2).name = ((Object)mesh).name + "_VorpalBladeSplit";
			obj2.subMeshCount = 2;
			obj2.SetTriangles(list2, 0);
			obj2.SetTriangles(list, 1);
			return obj2;
			float Width(int num8)
			{
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0040: 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_004c: Unknown result type (might be due to invalid IL or missing references)
				if (!has[num8])
				{
					return 0f;
				}
				Vector3 val3 = hi[num8] - lo[num8];
				((Vector3)(ref val3))[axis] = 0f;
				return Mathf.Max(val3.x, Mathf.Max(val3.y, val3.z));
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "AttachItem")]
	internal static class AttachItemPatch
	{
		[HarmonyPriority(0)]
		private static void Postfix(GameObject __result, int itemHash, bool backAttach)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			if (!Glow.ColorForHash(itemHash, out var color))
			{
				return;
			}
			Diag.Log("AttachItem: " + (backAttach ? "on BACK (no glow)" : "in HAND (glow)") + ", instance " + (((Object)(object)__result != (Object)null) ? ((Object)__result).name : "null") + ", joint " + (((Object)(object)__result != (Object)null && (Object)(object)__result.transform.parent != (Object)null) ? ((Object)__result.transform.parent).name : "?"));
			if (backAttach || (Object)(object)__result == (Object)null)
			{
				return;
			}
			try
			{
				Glow.Apply(__result, color);
				Transform obj = __result.transform.Find("VorpalLight");
				Light val = ((obj != null) ? ((Component)obj).GetComponent<Light>() : null);
				Diag.Log("Glow applied: light " + (((Object)(object)val != (Object)null) ? $"range {val.range} intensity {val.intensity} color {val.color}" : "MISSING"));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Glow failed: " + ex.Message));
			}
		}
	}
	internal static class NativeThrow
	{
		private static int _scope;

		private static bool _lastWasOurs;

		private static MagicItem _fake;

		private static readonly (string type, string method)[] ScopedMethods = new(string, string)[7]
		{
			("EpicLoot.MagicItemEffects.Throwable_Humanoid_StartAttack_Patch", "Prefix"),
			("EpicLoot.MagicItemEffects.Throwable_Attack_ProjectileAttackTriggered_Patch", "Prefix"),
			("EpicLoot.MagicItemEffects.Throwable_Attack_ProjectileAttackTriggered_Patch", "Postfix"),
			("EpicLoot.MagicItemEffects.Throwable_Attack_FireProjectileBurst_Patch", "Postfix"),
			("EpicLoot.MagicItemEffects.Throwable_Projectile_HitData_Patch", "RestoreToolTier"),
			("EpicLoot.MagicItemEffects.RecallWeapon_Projectile_SpawnOnHit_Patch", "IssueItemRecall"),
			("EpicLoot.MagicItemEffects.RecallWeapon_Projectile_SpawnOnHit_Patch", "Projectile_LateUpdate_Postfix")
		};

		private static readonly (string type, string method)[] OptionalScopedMethods = new(string, string)[2]
		{
			("EpicLootProgressionFix.RecallPriority", "Reserve"),
			("EpicLootProgressionFix.RecallRecovery", "TrackProjectile")
		};

		internal static void Init(Harmony harmony)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_00d9: Expected O, but got Unknown
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Expected O, but got Unknown
			//IL_01c4: Expected O, but got Unknown
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Expected O, but got Unknown
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Expected O, but got Unknown
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Expected O, but got Unknown
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b0: Expected O, but got Unknown
			_fake = new MagicItem();
			int num = 0;
			(string, string)[] scopedMethods = ScopedMethods;
			for (int i = 0; i < scopedMethods.Length; i++)
			{
				(string, string) tuple = scopedMethods[i];
				string item = tuple.Item1;
				string item2 = tuple.Item2;
				Type type = AccessTools.TypeByName(item);
				MethodInfo methodInfo = ((type != null) ? AccessTools.Method(type, item2, (Type[])null, (Type[])null) : null);
				if (methodInfo == null)
				{
					Plugin.Log.LogWarning((object)("[Vorpal] Native throw: EpicLoot " + item + "." + item2 + " not found (EpicLoot changed?)"));
				}
				else
				{
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(NativeThrow), "Enter", (Type[])null)
					{
						priority = 800
					}, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(NativeThrow), "Leave", (Type[])null), (HarmonyMethod)null);
					num++;
				}
			}
			int num2 = 0;
			int num3 = 0;
			scopedMethods = OptionalScopedMethods;
			for (int i = 0; i < scopedMethods.Length; i++)
			{
				(string, string) tuple2 = scopedMethods[i];
				string item3 = tuple2.Item1;
				string item4 = tuple2.Item2;
				Type type2 = AccessTools.TypeByName(item3);
				if (!(type2 == null))
				{
					num3++;
					MethodInfo methodInfo2 = AccessTools.Method(type2, item4, (Type[])null, (Type[])null);
					if (methodInfo2 == null)
					{
						Plugin.Log.LogWarning((object)("[Vorpal] Native throw: " + item3 + "." + item4 + " not found (Progression Fix changed?) - recall may not return"));
					}
					else
					{
						harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(NativeThrow), "Enter", (Type[])null)
						{
							priority = 800
						}, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(NativeThrow), "Leave", (Type[])null), (HarmonyMethod)null);
						num2++;
					}
				}
			}
			if (num3 > 0)
			{
				Diag.Log($"Native recall: {num2}/{OptionalScopedMethods.Length} EpicLoot Progression Fix recall hooks covered");
			}
			Type typeFromHandle = typeof(ItemDataExtensions);
			foreach (MethodInfo item5 in from m in AccessTools.GetDeclaredMethods(typeFromHandle)
				where m.Name == "IsMagic"
				select m)
			{
				ParameterInfo[] parameters = item5.GetParameters();
				harmony.Patch((MethodBase)item5, (HarmonyMethod)null, new HarmonyMethod(typeof(NativeThrow), (parameters.Length == 1) ? "IsMagicPostfix" : "IsMagicOutPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			harmony.Patch((MethodBase)AccessTools.Method(typeFromHandle, "GetMagicItem", new Type[1] { typeof(ItemData) }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(NativeThrow), "GetMagicItemPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			foreach (MethodInfo item6 in from m in AccessTools.GetDeclaredMethods(typeFromHandle)
				where m.Name == "HasMagicEffect"
				select m)
			{
				harmony.Patch((MethodBase)item6, (HarmonyMethod)null, new HarmonyMethod(typeof(NativeThrow), "HasMagicEffectPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			foreach (MethodInfo item7 in from m in AccessTools.GetDeclaredMethods(typeof(MagicItem))
				where m.Name == "HasEffect"
				select m)
			{
				harmony.Patch((MethodBase)item7, new HarmonyMethod(typeof(NativeThrow), "HasEffectPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			Plugin.Log.LogInfo((object)$"[Vorpal] Native throw + recall enabled through EpicLoot ({num}/{ScopedMethods.Length} EpicLoot hooks found).");
		}

		private static bool Wanted(string effectType)
		{
			if (!(effectType == MagicEffectType.Throwable))
			{
				return effectType == MagicEffectType.RecallWeapon;
			}
			return true;
		}

		private static void Enter()
		{
			_scope++;
		}

		private static Exception Leave(Exception __exception)
		{
			_scope = Math.Max(0, _scope - 1);
			if (_scope == 0)
			{
				_lastWasOurs = false;
			}
			return __exception;
		}

		private static bool Note(ItemData item)
		{
			return _lastWasOurs = Diag.IsOurs(item);
		}

		private static void IsMagicPostfix(ItemData itemData, ref bool __result)
		{
			if (_scope != 0 && Note(itemData) && !__result)
			{
				__result = true;
			}
		}

		private static void IsMagicOutPostfix(ItemData itemData, ref MagicItem magicItem, ref bool __result)
		{
			if (_scope != 0 && Note(itemData) && !__result)
			{
				__result = true;
				magicItem = _fake;
			}
		}

		private static void GetMagicItemPostfix(ItemData itemData, ref MagicItem __result)
		{
			if (_scope != 0 && Note(itemData) && __result == null)
			{
				__result = _fake;
			}
		}

		private static void HasMagicEffectPostfix(ItemData itemData, string effectType, ref bool __result)
		{
			if (!((_scope == 0) | __result) && Note(itemData) && Wanted(effectType))
			{
				__result = true;
				Diag.Log("Native " + effectType + " for " + Diag.Label(itemData));
			}
		}

		private static bool HasEffectPrefix(MagicItem __instance, string effectType, ref bool __result)
		{
			if (_scope == 0 || !Wanted(effectType))
			{
				return true;
			}
			if (__instance == _fake || _lastWasOurs)
			{
				__result = true;
				Diag.Log("Native " + effectType + " for our sword");
				return false;
			}
			return true;
		}
	}
	internal static class OnlyOne
	{
		internal const string KeyName = "freyrsvorpal_serial";

		internal const string SerialData = "valheim.freyrsvorpalsword.serial";

		internal const string FaderPrefab = "Fader";

		private const string RpcToServer = "FreyrsVorpal_ToServer";

		private const string RpcToClient = "FreyrsVorpal_ToClient";

		private const float PendingSeconds = 30f;

		private const float GrantSeconds = 25f;

		private const float CheckEvery = 2f;

		internal static bool KeysReceived;

		internal static bool ServerHasMod;

		private static string _granted;

		private static float _grantedUntil;

		private static string _forging;

		private static string _localPending;

		private static float _claimSentAt = -100f;

		private static string _offerSerial;

		private static OfferingBowl _offerBowl;

		private static float _nextCheck;

		private static bool _resume;

		private static string _pending;

		private static long _pendingPeer;

		private static float _pendingUntil;

		private static bool IsServer
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return ZNet.instance.IsServer();
				}
				return false;
			}
		}

		internal static int Max => Math.Max(1, Plugin.MaxInWorld?.Value ?? 1);

		internal static bool CanJudge
		{
			get
			{
				if ((Object)(object)ZoneSystem.instance != (Object)null && (Object)(object)ZNet.instance != (Object)null)
				{
					if (!IsServer)
					{
						if (KeysReceived)
						{
							return ServerHasMod;
						}
						return false;
					}
					return true;
				}
				return false;
			}
		}

		internal static bool Taken => WorldSerials().Count >= Max;

		internal static void ResetSession()
		{
			KeysReceived = false;
			ServerHasMod = false;
			_granted = null;
			_forging = null;
			_localPending = null;
			_offerSerial = null;
			_offerBowl = null;
			_pending = null;
			_resume = false;
		}

		internal static void RegisterRpcs()
		{
			ResetSession();
			ZRoutedRpc.instance.Register<ZPackage>("FreyrsVorpal_ToServer", (Action<long, ZPackage>)OnServer);
			ZRoutedRpc.instance.Register<ZPackage>("FreyrsVorpal_ToClient", (Action<long, ZPackage>)OnClient);
			Diag.Log($"There should be only one: RPCs registered (server={IsServer}).");
		}

		internal static List<string> WorldSerials()
		{
			string text = default(string);
			if ((Object)(object)ZoneSystem.instance == (Object)null || !ZoneSystem.instance.GetGlobalKey("freyrsvorpal_serial", ref text) || string.IsNullOrEmpty(text))
			{
				return new List<string>();
			}
			return (from x in text.Split(new char[1] { ',' })
				select x.Trim() into x
				where x.Length > 0
				select x).Distinct().ToList();
		}

		internal static string Describe(List<string> serials)
		{
			if (serials.Count != 0)
			{
				return string.Join(", ", serials);
			}
			return "none";
		}

		private static void WriteSerials(List<string> serials)
		{
			if (serials.Count == 0)
			{
				ZoneSystem.instance.RemoveGlobalKey("freyrsvorpal_serial");
			}
			else
			{
				ZoneSystem.instance.SetGlobalKey("freyrsvorpal_serial " + string.Join(",", serials));
			}
		}

		internal static string FullMessage()
		{
			if (Max != 1)
			{
				return $"All {Max} Freyr's Vorpal Swords are already in this world";
			}
			return "There is only one, and it is already in this world";
		}

		internal static string SerialOf(ItemData item)
		{
			if (item?.m_customData == null || !item.m_customData.TryGetValue("valheim.freyrsvorpalsword.serial", out var value) || string.IsNullOrEmpty(value))
			{
				return null;
			}
			return value;
		}

		internal static bool IsCurrent(ItemData item)
		{
			string text = SerialOf(item);
			if (text == null)
			{
				return false;
			}
			if (text == _localPending)
			{
				return true;
			}
			return WorldSerials().Contains(text);
		}

		internal static string ForgeBlockedReason()
		{
			if ((Object)(object)ZNet.instance == (Object)null || (Object)(object)ZoneSystem.instance == (Object)null)
			{
				return "Not in a world";
			}
			if (!IsServer && !ServerHasMod)
			{
				return "This server doesn't run Freyr's Vorpal Sword";
			}
			if (Taken)
			{
				return FullMessage();
			}
			return null;
		}

		internal static bool BeginForge(Player player)
		{
			string text = ForgeBlockedReason();
			if (text != null)
			{
				((Character)player).Message((MessageType)2, text, 0, (Sprite)null, false);
				Diag.Log("Forge refused: " + text);
				return false;
			}
			if (_granted != null && Time.time < _grantedUntil)
			{
				_forging = _granted;
				_granted = null;
				return true;
			}
			if (Time.time - _claimSentAt < 5f)
			{
				return false;
			}
			_granted = null;
			_claimSentAt = Time.time;
			Send("claim", "");
			Diag.Log($"Forge: asked the server for a Freyr's Vorpal Sword ({WorldSerials().Count} of {Max} in this world).");
			return false;
		}

		internal static void FinishForge(ItemData created)
		{
			string forging = _forging;
			_forging = null;
			if (forging != null)
			{
				if (created == null)
				{
					Send("cancel", forging);
					Diag.Log("Forge: no sword made; reservation " + forging + " released.");
					return;
				}
				created.m_customData["valheim.freyrsvorpalsword.serial"] = forging;
				_localPending = forging;
				Send("confirm", forging);
				Diag.Log("Forge: Freyr's Vorpal Sword stamped with serial " + forging + "; confirming with the server.");
			}
		}

		internal static bool IsFaderAltar(OfferingBowl bowl)
		{
			if ((Object)(object)bowl != (Object)null && (Object)(object)bowl.m_bossPrefab != (Object)null)
			{
				return ((Object)bowl.m_bossPrefab).name == "Fader";
			}
			return false;
		}

		internal static void BeginOffer(Player player, OfferingBowl bowl, ItemData item)
		{
			if (!CanJudge)
			{
				((Character)player).Message((MessageType)2, "The altar doesn't answer (server doesn't run Freyr's Vorpal Sword)", 0, (Sprite)null, false);
				return;
			}
			if (!IsCurrent(item))
			{
				((Character)player).Message((MessageType)2, "This is not a true Freyr's Vorpal Sword of this world", 0, (Sprite)null, false);
				return;
			}
			_offerSerial = SerialOf(item);
			_offerBowl = bowl;
			Send("offer", _offerSerial);
			Diag.Log("Offering Freyr's Vorpal Sword " + _offerSerial + " at Fader's altar.");
		}

		internal static void ReportDestroyed(ItemData item, string how)
		{
			string text = SerialOf(item);
			Plugin.Log.LogInfo((object)("[Vorpal] Freyr's Vorpal Sword (serial " + (text ?? "none") + ") destroyed: " + how + "."));
			if (text != null)
			{
				Send("destroyed", text);
			}
		}

		internal static void Tick(Player player)
		{
			if (_resume)
			{
				_resume = false;
				if (!ResumeCraft(player))
				{
					((Character)player).Message((MessageType)2, "The Black forge is ready: press Craft again", 0, (Sprite)null, false);
				}
			}
			if (Time.time < _nextCheck)
			{
				return;
			}
			_nextCheck = Time.time + 2f;
			if (!CanJudge)
			{
				return;
			}
			if (_granted != null && Time.time >= _grantedUntil)
			{
				_granted = null;
			}
			foreach (ItemData item in (from i in ((Humanoid)player).GetInventory().GetAllItems()
				where Diag.IsFreyr(i) && !IsCurrent(i)
				select i).ToList())
			{
				Revert(player, item);
			}
		}

		internal static void Revert(Player player, ItemData item)
		{
			//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)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Inventory inventory = ((Humanoid)player).GetInventory();
				Vector2i gridPos = item.m_gridPos;
				string text = Diag.Label(item);
				string text2 = SerialOf(item);
				Dictionary<string, string> customData = item.m_customData?.Where((KeyValuePair<string, string> kv) => kv.Key != "valheim.freyrsvorpalsword.serial" && !Forging.IsBookkeeping(kv.Key)).ToDictionary((KeyValuePair<string, string> kv) => kv.Key, (KeyValuePair<string, string> kv) => kv.Value) ?? new Dictionary<string, string>();
				if (item.m_equipped)
				{
					((Humanoid)player).UnequipItem(item, false);
				}
				inventory.RemoveItem(item);
				ItemData val = inventory.AddItem("SwordVorpal", 1, 3, 0, item.m_crafterID, item.m_crafterName, gridPos, false, false, true);
				if (val != null)
				{
					val.m_customData = customData;
					if (EpicLootIntegration.Active)
					{
						EpicLootIntegration.AfterRevert(val);