Decompiled source of RelicGear v1.0.1

RelicGear.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using Jotunn;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("RelicGear")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RelicGear")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")]
[assembly: AssemblyFileVersion("1.0.1")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
namespace RelicGear;

internal class SetQualityCommand : ConsoleCommand
{
	public override string Name => "setquality";

	public override string Help => "setquality <n>: set the quality of the item in the top-left inventory slot (testing only)";

	public override bool IsCheat => true;

	public override void Run(string[] args)
	{
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null)
		{
			Console.instance.Print("setquality: no player");
			return;
		}
		if (args.Length < 1 || !int.TryParse(args[0], out var result) || result < 1)
		{
			Console.instance.Print("usage: setquality <n>");
			return;
		}
		Inventory inventory = ((Humanoid)localPlayer).GetInventory();
		ItemData itemAt = inventory.GetItemAt(0, 0);
		if (itemAt == null)
		{
			Console.instance.Print("setquality: top-left slot is empty");
			return;
		}
		itemAt.m_quality = result;
		itemAt.m_durability = itemAt.GetMaxDurability();
		MethodInfo methodInfo = AccessTools.Method(typeof(Inventory), "Changed", (Type[])null, (Type[])null);
		if (methodInfo != null)
		{
			methodInfo.Invoke(inventory, null);
		}
		Console.instance.Print("setquality: " + itemAt.m_shared.m_name + " is now quality " + result);
	}
}
internal static class Ladders
{
	private sealed class RungDef
	{
		public string TargetSet;

		public string[] AverageOf;

		public string CostSet;
	}

	private sealed class LadderDef
	{
		public string[] Members;

		public RungDef[] Rungs;
	}

	private sealed class Rung_
	{
		public string CostSet;

		public float Total;
	}

	private sealed class PieceInfo
	{
		public string SetName;

		public int Slot;

		public float Total4;

		public List<Rung_> Rungs;
	}

	public sealed class Step
	{
		public int K;

		public float Fraction;

		public string CostSet;

		public int Slot;
	}

	private const float SetArmorPerLevel = 6f;

	private const float MinGain = 3f;

	private static readonly Dictionary<string, string[]> SetPieces = new Dictionary<string, string[]>
	{
		{
			"Leather",
			new string[3] { "HelmetLeather", "ArmorLeatherChest", "ArmorLeatherLegs" }
		},
		{
			"Troll",
			new string[3] { "HelmetTrollLeather", "ArmorTrollLeatherChest", "ArmorTrollLeatherLegs" }
		},
		{
			"Bear",
			new string[3] { "HelmetBerserkerHood", "ArmorBerserkerChest", "ArmorBerserkerLegs" }
		},
		{
			"Root",
			new string[3] { "HelmetRoot", "ArmorRootChest", "ArmorRootLegs" }
		},
		{
			"Fenris",
			new string[3] { "HelmetFenring", "ArmorFenringChest", "ArmorFenringLegs" }
		},
		{
			"Lox",
			new string[3] { "HelmetLox", "ArmorLoxChest", "ArmorLoxLegs" }
		},
		{
			"Vilebone",
			new string[3] { "HelmetBerserkerUndead", "ArmorBerserkerUndeadChest", "ArmorBerserkerUndeadLegs" }
		},
		{
			"AshlandsMedium",
			new string[3] { "HelmetAshlandsMediumHood", "ArmorAshlandsMediumChest", "ArmorAshlandsMediumlegs" }
		},
		{
			"DeepNorthMedium",
			new string[3] { "HelmetDNMediumHood", "ArmorDeepNorthMediumChest", "ArmorDeepNorthMediumlegs" }
		},
		{
			"EitrWeave",
			new string[3] { "HelmetMage", "ArmorMageChest", "ArmorMageLegs" }
		},
		{
			"EitrWeaveAsh",
			new string[3] { "HelmetMage_Ashlands", "ArmorMageChest_Ashlands", "ArmorMageLegs_Ashlands" }
		},
		{
			"DeepNorthMage",
			new string[3] { "HelmetDNMage", "ArmorDeepNorthMageChest", "ArmorDeepNorthMagelegs" }
		},
		{
			"Bronze",
			new string[3] { "HelmetBronze", "ArmorBronzeChest", "ArmorBronzeLegs" }
		},
		{
			"Iron",
			new string[3] { "HelmetIron", "ArmorIronChest", "ArmorIronLegs" }
		},
		{
			"Wolf",
			new string[3] { "HelmetDrake", "ArmorWolfChest", "ArmorWolfLegs" }
		},
		{
			"Padded",
			new string[3] { "HelmetPadded", "ArmorPaddedCuirass", "ArmorPaddedGreaves" }
		},
		{
			"Carapace",
			new string[3] { "HelmetCarapace", "ArmorCarapaceChest", "ArmorCarapaceLegs" }
		},
		{
			"Flametal",
			new string[3] { "HelmetFlametal", "ArmorFlametalChest", "ArmorFlametalLegs" }
		},
		{
			"DeepNorthHeavy",
			new string[3] { "HelmetDNHeavy", "ArmorDeepNorthHeavyChest", "ArmorDeepNorthHeavylegs" }
		}
	};

	private static readonly LadderDef[] LadderDefs = new LadderDef[3]
	{
		new LadderDef
		{
			Members = new string[8] { "Leather", "Troll", "Bear", "Root", "Fenris", "Lox", "Vilebone", "AshlandsMedium" },
			Rungs = new RungDef[7]
			{
				Rung("Troll"),
				Rung("Root"),
				Rung("Fenris"),
				Rung("Lox"),
				new RungDef
				{
					TargetSet = null,
					AverageOf = new string[2] { "Vilebone", "AshlandsMedium" },
					CostSet = "EitrWeave"
				},
				Rung("AshlandsMedium"),
				Rung("DeepNorthMedium")
			}
		},
		new LadderDef
		{
			Members = new string[2] { "EitrWeave", "EitrWeaveAsh" },
			Rungs = new RungDef[2]
			{
				Rung("EitrWeaveAsh"),
				Rung("DeepNorthMage")
			}
		},
		new LadderDef
		{
			Members = new string[6] { "Bronze", "Iron", "Wolf", "Padded", "Carapace", "Flametal" },
			Rungs = new RungDef[6]
			{
				Rung("Iron"),
				Rung("Wolf"),
				Rung("Padded"),
				Rung("Carapace"),
				Rung("Flametal"),
				Rung("DeepNorthHeavy")
			}
		}
	};

	private static readonly Dictionary<string, PieceInfo> Pieces = new Dictionary<string, PieceInfo>();

	private static readonly Dictionary<string, Requirement[]> RequirementCache = new Dictionary<string, Requirement[]>();

	private static readonly Dictionary<string, List<KeyValuePair<ItemDrop, int>>> CostCache = new Dictionary<string, List<KeyValuePair<ItemDrop, int>>>();

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

	private static bool IsExcludedResource(string prefabName)
	{
		if (!prefabName.StartsWith("Trophy", StringComparison.Ordinal) && !(prefabName == "Chain"))
		{
			return prefabName == "MorgenHeart";
		}
		return true;
	}

	private static RungDef Rung(string set)
	{
		return new RungDef
		{
			TargetSet = set,
			CostSet = set
		};
	}

	public static bool IsFixedAmount(Requirement requirement)
	{
		return FixedAmounts.Contains(requirement);
	}

	public static void Setup(ObjectDB db)
	{
		if ((Object)(object)db == (Object)null || db.m_items == null || db.m_items.Count == 0)
		{
			return;
		}
		Pieces.Clear();
		RequirementCache.Clear();
		CostCache.Clear();
		FixedAmounts.Clear();
		Dictionary<string, float> dictionary = new Dictionary<string, float>();
		foreach (KeyValuePair<string, string[]> setPiece in SetPieces)
		{
			float num = 0f;
			bool flag = true;
			string[] value = setPiece.Value;
			foreach (string text in value)
			{
				ItemDrop val = ItemDropOf(db, text);
				if ((Object)(object)val == (Object)null)
				{
					Logger.LogWarning((object)("Set '" + setPiece.Key + "' skipped, prefab not found: " + text));
					flag = false;
					break;
				}
				if (Math.Abs(val.m_itemData.m_shared.m_armorPerLevel - 2f) > 0.01f)
				{
					Logger.LogWarning((object)(text + " has armor per level " + val.m_itemData.m_shared.m_armorPerLevel + " (expected 2), k values will be off"));
				}
				SharedData shared = val.m_itemData.m_shared;
				num += shared.m_armor + 3f * shared.m_armorPerLevel;
			}
			if (flag)
			{
				dictionary[setPiece.Key] = num;
			}
		}
		LadderDef[] ladderDefs = LadderDefs;
		foreach (LadderDef ladderDef in ladderDefs)
		{
			List<Rung_> list = new List<Rung_>();
			RungDef[] rungs = ladderDef.Rungs;
			foreach (RungDef rungDef in rungs)
			{
				if (TryRungTotal(rungDef, dictionary, out var total) && dictionary.ContainsKey(rungDef.CostSet))
				{
					list.Add(new Rung_
					{
						CostSet = rungDef.CostSet,
						Total = total
					});
				}
			}
			list.Sort((Rung_ a, Rung_ b) => a.Total.CompareTo(b.Total));
			string[] value = ladderDef.Members;
			foreach (string text2 in value)
			{
				if (!dictionary.ContainsKey(text2))
				{
					continue;
				}
				float num2 = dictionary[text2];
				int num3 = 4;
				float num4 = num2;
				while (true)
				{
					Rung_ rung_ = NextRung(list, num4);
					if (rung_ == null)
					{
						break;
					}
					int num5 = StepSize(rung_.Total, num4);
					num4 += (float)num5 * 6f;
					num3 += num5;
				}
				string[] array = SetPieces[text2];
				for (int num6 = 0; num6 < array.Length; num6++)
				{
					Pieces[array[num6]] = new PieceInfo
					{
						SetName = text2,
						Slot = num6,
						Total4 = num2,
						Rungs = list
					};
					ItemDrop val2 = ItemDropOf(db, array[num6]);
					if ((Object)(object)val2 != (Object)null && num3 > val2.m_itemData.m_shared.m_maxQuality)
					{
						val2.m_itemData.m_shared.m_maxQuality = num3;
					}
				}
				Logger.LogInfo((object)("Ladder '" + text2 + "': +4 total " + num2 + ", reachable quality +" + num3));
			}
		}
	}

	private static bool TryRungTotal(RungDef def, Dictionary<string, float> totals, out float total)
	{
		total = 0f;
		if (def.AverageOf != null)
		{
			string[] averageOf = def.AverageOf;
			foreach (string key in averageOf)
			{
				if (!totals.TryGetValue(key, out var value))
				{
					return false;
				}
				total += value;
			}
			total /= def.AverageOf.Length;
			return true;
		}
		return totals.TryGetValue(def.TargetSet, out total);
	}

	private static ItemDrop ItemDropOf(ObjectDB db, string prefab)
	{
		GameObject itemPrefab = db.GetItemPrefab(prefab);
		if (!((Object)(object)itemPrefab != (Object)null))
		{
			return null;
		}
		return itemPrefab.GetComponent<ItemDrop>();
	}

	private static Rung_ NextRung(List<Rung_> rungs, float armor)
	{
		foreach (Rung_ rung in rungs)
		{
			if (rung.Total - armor >= 3f)
			{
				return rung;
			}
		}
		return null;
	}

	private static int StepSize(float target, float armor)
	{
		return Math.Max(1, (int)Math.Floor((double)((target - armor) / 6f) + 0.5));
	}

	public static bool TryGetStep(string prefab, int quality, out Step step)
	{
		step = null;
		if (quality < 4 || !Pieces.TryGetValue(prefab, out var value))
		{
			return false;
		}
		float armor = value.Total4 + (float)(quality - 4) * 6f;
		Rung_ rung_ = NextRung(value.Rungs, armor);
		if (rung_ == null)
		{
			return false;
		}
		float num = value.Total4;
		foreach (Rung_ rung in value.Rungs)
		{
			if (rung.Total < rung_.Total && rung.Total > num)
			{
				num = rung.Total;
			}
		}
		int num2 = StepSize(rung_.Total, armor);
		int num3 = StepSize(rung_.Total, num);
		step = new Step
		{
			K = num2,
			Fraction = Math.Min(1f, (float)num2 / (float)num3),
			CostSet = rung_.CostSet,
			Slot = value.Slot
		};
		return true;
	}

	public static bool IsLadderItem(string prefab)
	{
		return Pieces.ContainsKey(prefab);
	}

	private static List<KeyValuePair<ItemDrop, int>> PieceCost(string costSet, int slot)
	{
		string key = costSet + "|" + slot;
		if (CostCache.TryGetValue(key, out var value))
		{
			return value;
		}
		List<KeyValuePair<ItemDrop, int>> list = new List<KeyValuePair<ItemDrop, int>>();
		ObjectDB instance = ObjectDB.instance;
		ItemDrop val = (((Object)(object)instance != (Object)null) ? ItemDropOf(instance, SetPieces[costSet][slot]) : null);
		Recipe val2 = (((Object)(object)val != (Object)null) ? instance.GetRecipe(val.m_itemData) : null);
		if ((Object)(object)val2 == (Object)null)
		{
			return list;
		}
		Dictionary<string, int> dictionary = new Dictionary<string, int>();
		Dictionary<string, ItemDrop> dictionary2 = new Dictionary<string, ItemDrop>();
		List<string> list2 = new List<string>();
		Requirement[] resources = val2.m_resources;
		foreach (Requirement val3 in resources)
		{
			if (val3 == null || (Object)(object)val3.m_resItem == (Object)null || val3.m_upgraderResource)
			{
				continue;
			}
			string name = ((Object)val3.m_resItem).name;
			if (!IsExcludedResource(name))
			{
				int num = 0;
				for (int j = 1; j <= 4; j++)
				{
					num += val3.GetAmount(j);
				}
				if (!dictionary.ContainsKey(name))
				{
					dictionary[name] = 0;
					dictionary2[name] = val3.m_resItem;
					list2.Add(name);
				}
				dictionary[name] += num;
			}
		}
		foreach (string item in list2)
		{
			list.Add(new KeyValuePair<ItemDrop, int>(dictionary2[item], dictionary[item]));
		}
		CostCache[key] = list;
		return list;
	}

	public static bool TryGetRequirements(Recipe recipe, int qualityArg, out Requirement[] requirements, out Step step)
	{
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: 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_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Expected O, but got Unknown
		requirements = null;
		step = null;
		if ((Object)(object)recipe == (Object)null || (Object)(object)recipe.m_item == (Object)null || qualityArg < 5)
		{
			return false;
		}
		string name = ((Object)recipe.m_item).name;
		if (!TryGetStep(name, qualityArg - 1, out step))
		{
			return false;
		}
		string key = name + "|" + qualityArg;
		if (RequirementCache.TryGetValue(key, out requirements))
		{
			return true;
		}
		List<KeyValuePair<ItemDrop, int>> list = PieceCost(step.CostSet, step.Slot);
		if (list.Count == 0)
		{
			return false;
		}
		List<Requirement> list2 = new List<Requirement>();
		foreach (KeyValuePair<ItemDrop, int> item2 in list)
		{
			int amount = Math.Max(1, (int)Math.Ceiling((float)item2.Value * step.Fraction - 0.0001f));
			Requirement item = new Requirement
			{
				m_resItem = item2.Key,
				m_amount = amount,
				m_amountPerLevel = 0
			};
			FixedAmounts.Add(item);
			list2.Add(item);
		}
		requirements = list2.ToArray();
		RequirementCache[key] = requirements;
		return true;
	}
}
internal static class Util
{
	public static bool AtUpgraderStation(Player player)
	{
		CraftingStation val = (((Object)(object)player != (Object)null) ? player.GetCurrentCraftingStation() : null);
		if ((Object)(object)val != (Object)null)
		{
			return val.m_upgrader;
		}
		return false;
	}

	public static void InvokeWithDefaults(MethodInfo method, object target)
	{
		if (method == null)
		{
			return;
		}
		ParameterInfo[] parameters = method.GetParameters();
		object[] array = new object[parameters.Length];
		for (int i = 0; i < parameters.Length; i++)
		{
			ParameterInfo parameterInfo = parameters[i];
			if (parameterInfo.HasDefaultValue && parameterInfo.DefaultValue != DBNull.Value)
			{
				array[i] = parameterInfo.DefaultValue;
			}
			else if (parameterInfo.ParameterType.IsValueType)
			{
				array[i] = Activator.CreateInstance(parameterInfo.ParameterType);
			}
			else
			{
				array[i] = null;
			}
		}
		method.Invoke(target, array);
	}
}
internal static class SafeSetup
{
	public static void Run(ObjectDB db)
	{
		try
		{
			Upgrades.Setup(db);
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Upgrades.Setup failed: " + ex));
		}
	}
}
[HarmonyPatch(typeof(ObjectDB), "Awake")]
internal static class Patch_ObjectDB_Awake
{
	private static void Postfix(ObjectDB __instance)
	{
		SafeSetup.Run(__instance);
	}
}
[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
internal static class Patch_ObjectDB_CopyOtherDB
{
	private static void Postfix(ObjectDB __instance)
	{
		SafeSetup.Run(__instance);
	}
}
[HarmonyPatch(typeof(Requirement), "GetAmount")]
internal static class Patch_GetAmount
{
	private static bool Prefix(Requirement __instance, ref int __result)
	{
		if (!Upgrades.IsFixedAmount(__instance))
		{
			return true;
		}
		__result = __instance.m_amount;
		return false;
	}
}
[HarmonyPatch(typeof(Recipe), "GetRequiredStationLevel")]
internal static class Patch_GetRequiredStationLevel
{
	private static bool Prefix(Recipe __instance, int quality, ref int __result)
	{
		if ((Object)(object)__instance.m_item == (Object)null)
		{
			return true;
		}
		string name = ((Object)__instance.m_item).name;
		if (!Upgrades.IsLadderItem(name))
		{
			return true;
		}
		int num = Upgrades.VanillaMax(name);
		if (quality <= num)
		{
			return true;
		}
		if (Util.AtUpgraderStation(Player.m_localPlayer))
		{
			return true;
		}
		__result = Math.Max(1, __instance.m_minStationLevel + num - 1);
		return false;
	}
}
[HarmonyPatch(typeof(InventoryGui), "SetupRequirementList", new Type[]
{
	typeof(int),
	typeof(Player),
	typeof(bool),
	typeof(int)
})]
internal static class Patch_SetupRequirementList
{
	private static readonly FieldInfo SelectedRecipeField = AccessTools.Field(typeof(InventoryGui), "m_selectedRecipe");

	private static readonly Type RecipeDataPairType = SelectedRecipeField.FieldType;

	private static readonly FieldInfo RecipeFieldInfo = AccessTools.Field(RecipeDataPairType, "Recipe");

	private static readonly PropertyInfo RecipePropertyInfo = AccessTools.Property(RecipeDataPairType, "Recipe");

	private static Recipe GetSelectedRecipe(InventoryGui instance)
	{
		object value = SelectedRecipeField.GetValue(instance);
		if (RecipeFieldInfo != null)
		{
			object? value2 = RecipeFieldInfo.GetValue(value);
			return (Recipe)((value2 is Recipe) ? value2 : null);
		}
		if (RecipePropertyInfo != null)
		{
			object? value3 = RecipePropertyInfo.GetValue(value);
			return (Recipe)((value3 is Recipe) ? value3 : null);
		}
		return null;
	}

	private static void Prefix(InventoryGui __instance, int quality, Player player, out Requirement[] __state)
	{
		__state = null;
		if (!Util.AtUpgraderStation(player))
		{
			Recipe selectedRecipe = GetSelectedRecipe(__instance);
			if (Upgrades.TryGetRequirements(selectedRecipe, quality, out var requirements, out var _))
			{
				__state = selectedRecipe.m_resources;
				selectedRecipe.m_resources = requirements;
			}
		}
	}

	private static void Finalizer(InventoryGui __instance, Requirement[] __state)
	{
		if (__state != null)
		{
			Recipe selectedRecipe = GetSelectedRecipe(__instance);
			if ((Object)(object)selectedRecipe != (Object)null)
			{
				selectedRecipe.m_resources = __state;
			}
		}
	}
}
[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
{
	typeof(Recipe),
	typeof(bool),
	typeof(int),
	typeof(int)
})]
internal static class Patch_HaveRequirements
{
	private static void Prefix(Player __instance, Recipe recipe, int qualityLevel, out Requirement[] __state)
	{
		__state = null;
		if (!Util.AtUpgraderStation(__instance) && Upgrades.TryGetRequirements(recipe, qualityLevel, out var requirements, out var _))
		{
			__state = recipe.m_resources;
			recipe.m_resources = requirements;
		}
	}

	private static void Finalizer(Recipe recipe, Requirement[] __state)
	{
		if (__state != null && (Object)(object)recipe != (Object)null)
		{
			recipe.m_resources = __state;
		}
	}
}
[HarmonyPatch(typeof(InventoryGui), "UpdateRecipe", new Type[]
{
	typeof(Player),
	typeof(float)
})]
internal static class Patch_UpdateRecipe
{
	private static readonly Dictionary<string, string> TooltipCache = new Dictionary<string, string>();

	private static void Postfix(InventoryGui __instance, Player player)
	{
		Recipe recipe = ((RecipeDataPair)(ref __instance.m_selectedRecipe)).Recipe;
		ItemData itemData = ((RecipeDataPair)(ref __instance.m_selectedRecipe)).ItemData;
		if (!((Object)(object)recipe == (Object)null) && itemData != null && !((Object)(object)recipe.m_item == (Object)null) && !Util.AtUpgraderStation(player) && Upgrades.TryGetStepLevels(((Object)recipe.m_item).name, itemData.m_quality, out var levels))
		{
			int num = itemData.m_quality + levels;
			string key = ((Object)recipe.m_item).name + "|" + num + "|" + Game.m_worldLevel;
			if (!TooltipCache.TryGetValue(key, out var value))
			{
				value = Localization.instance.Localize(ItemData.GetTooltip(recipe.m_item.m_itemData, num, true, (float)Game.m_worldLevel, recipe.m_amount, false));
				TooltipCache[key] = value;
			}
			__instance.m_recipeDecription.text = value;
			string text = Localization.instance.Localize(itemData.m_shared.m_name);
			__instance.m_itemCraftType.text = Localization.instance.Localize("$inventory_upgrade", new string[2]
			{
				text,
				num.ToString()
			});
		}
	}
}
internal sealed class CraftState
{
	public Recipe Recipe;

	public Requirement[] OriginalResources;

	public Vector2i Position;

	public string SharedName;

	public int OldQuality;

	public int K;
}
[HarmonyPatch(typeof(InventoryGui), "DoCrafting", new Type[] { typeof(Player) })]
internal static class Patch_DoCrafting
{
	private static void Prefix(InventoryGui __instance, Player player, out CraftState __state)
	{
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		__state = null;
		ItemData craftUpgradeItem = __instance.m_craftUpgradeItem;
		Recipe craftRecipe = __instance.m_craftRecipe;
		if (craftUpgradeItem != null && !((Object)(object)craftRecipe == (Object)null) && !Util.AtUpgraderStation(player) && Upgrades.TryGetRequirements(craftRecipe, craftUpgradeItem.m_quality + 1, out var requirements, out var levels))
		{
			__state = new CraftState
			{
				Recipe = craftRecipe,
				OriginalResources = craftRecipe.m_resources,
				Position = craftUpgradeItem.m_gridPos,
				SharedName = craftUpgradeItem.m_shared.m_name,
				OldQuality = craftUpgradeItem.m_quality,
				K = levels
			};
			craftRecipe.m_resources = requirements;
		}
	}

	private static void Postfix(InventoryGui __instance, Player player, CraftState __state)
	{
		if (__state == null || (Object)(object)player == (Object)null)
		{
			return;
		}
		Inventory inventory = ((Humanoid)player).GetInventory();
		ItemData itemAt = inventory.GetItemAt(__state.Position.x, __state.Position.y);
		if (itemAt == null || itemAt.m_shared.m_name != __state.SharedName || itemAt.m_quality != __state.OldQuality + 1)
		{
			return;
		}
		itemAt.m_quality = __state.OldQuality + __state.K;
		itemAt.m_durability = itemAt.GetMaxDurability();
		MethodInfo method = AccessTools.Method(typeof(Inventory), "Changed", (Type[])null, (Type[])null);
		try
		{
			Util.InvokeWithDefaults(method, inventory);
		}
		catch (Exception ex)
		{
			Logger.LogWarning((object)("Inventory.Changed failed: " + ex.Message));
		}
		try
		{
			Util.InvokeWithDefaults(AccessTools.Method(typeof(InventoryGui), "UpdateCraftingPanel", (Type[])null, (Type[])null), __instance);
		}
		catch (Exception ex2)
		{
			Logger.LogWarning((object)("UpdateCraftingPanel failed: " + ex2.Message));
		}
	}

	private static void Finalizer(CraftState __state)
	{
		if (__state != null)
		{
			__state.Recipe.m_resources = __state.OriginalResources;
		}
	}
}
[BepInPlugin("spectorswim.relicgear", "Relic Gear", "1.0.1")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
internal class RelicGear : BaseUnityPlugin
{
	public const string PluginGUID = "spectorswim.relicgear";

	public const string PluginName = "Relic Gear";

	public const string PluginVersion = "1.0.1";

	private void Awake()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			new Harmony("spectorswim.relicgear").PatchAll();
			Logger.LogInfo((object)"Relic Gear patches applied");
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new SetQualityCommand());
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Patching failed: " + ex));
		}
	}
}
internal static class ShieldLadders
{
	private sealed class RungDef
	{
		public int Biome;

		public string Prefab;

		public float TargetE3;

		public string CostPrefab;
	}

	private sealed class ExtraMember
	{
		public string Prefab;

		public int Biome;

		public float Offset;
	}

	private sealed class ClassDef
	{
		public string Name;

		public RungDef[] Rungs;

		public ExtraMember[] Extras;
	}

	private sealed class Rung_
	{
		public string Name;

		public int Biome;

		public float E3;

		public float G;

		public int KFull;

		public string CostPrefab;
	}

	private sealed class MemberInfo
	{
		public string Prefab;

		public float E3;

		public float G;

		public float Offset;

		public int MinBiome;

		public List<Rung_> Rungs;
	}

	public sealed class Step
	{
		public int K;

		public float Fraction;

		public string CostPrefab;
	}

	public const int VanillaMax = 3;

	private const float MinGain = 3f;

	private const int Meadows = 0;

	private const int BlackForest = 1;

	private const int Swamp = 2;

	private const int Mountain = 3;

	private const int Plains = 4;

	private const int Mistlands = 5;

	private const int Ashlands = 6;

	private const int DeepNorth = 7;

	private static readonly ClassDef[] Classes = new ClassDef[3]
	{
		Class("Round", new RungDef[8]
		{
			Real(0, "ShieldWood"),
			Synth(1, 36f, "ShieldBronzeBuckler"),
			Real(2, "ShieldBanded"),
			Real(3, "ShieldSilver"),
			Real(4, "ShieldBlackmetal"),
			Real(5, "ShieldCarapace"),
			Real(6, "ShieldFlametal"),
			Real(7, "ShieldGold")
		}, Extra("ShieldRoots", 2, -6f), Extra("ShieldIronSquare", 2, -7f)),
		Class("Tower", new RungDef[8]
		{
			Real(0, "ShieldWoodTower"),
			Real(1, "ShieldBoneTower"),
			Real(2, "ShieldIronTower"),
			RealCost(3, "ShieldSerpentscale", "ShieldSilver"),
			Real(4, "ShieldBlackmetalTower"),
			Synth(5, 134f, "ShieldCarapace"),
			Real(6, "ShieldFlametalTower"),
			Real(7, "ShieldGoldTower")
		}),
		Class("Buckler", new RungDef[7]
		{
			Real(1, "ShieldBronzeBuckler"),
			Real(2, "ShieldIronBuckler"),
			Synth(3, 56f, "ShieldSilver"),
			Synth(4, 72f, "ShieldBlackmetal"),
			Real(5, "ShieldCarapaceBuckler"),
			Synth(6, 96f, "ShieldFlametal"),
			Real(7, "ShieldGoldBuckler")
		})
	};

	private static readonly Dictionary<string, string[]> Variants = new Dictionary<string, string[]> { 
	{
		"ShieldBlackmetalTower",
		new string[2] { "FW_ShieldBlackmetalTower", "SP_ShieldBlackmetalTower" }
	} };

	private static readonly Dictionary<string, MemberInfo> Members = new Dictionary<string, MemberInfo>();

	private static readonly Dictionary<string, Requirement[]> RequirementCache = new Dictionary<string, Requirement[]>();

	private static readonly Dictionary<string, List<KeyValuePair<ItemDrop, int>>> CostCache = new Dictionary<string, List<KeyValuePair<ItemDrop, int>>>();

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

	private static bool IsExcludedResource(string prefabName)
	{
		if (!prefabName.StartsWith("Trophy", StringComparison.Ordinal) && !prefabName.StartsWith("Mold", StringComparison.Ordinal) && !(prefabName == "Chain") && !(prefabName == "ScaleHide"))
		{
			return prefabName == "SerpentScale";
		}
		return true;
	}

	private static RungDef Real(int biome, string prefab)
	{
		return new RungDef
		{
			Biome = biome,
			Prefab = prefab,
			CostPrefab = prefab
		};
	}

	private static RungDef RealCost(int biome, string prefab, string costPrefab)
	{
		return new RungDef
		{
			Biome = biome,
			Prefab = prefab,
			CostPrefab = costPrefab
		};
	}

	private static RungDef Synth(int biome, float e3, string costPrefab)
	{
		return new RungDef
		{
			Biome = biome,
			Prefab = null,
			TargetE3 = e3,
			CostPrefab = costPrefab
		};
	}

	private static ExtraMember Extra(string prefab, int biome, float offset)
	{
		return new ExtraMember
		{
			Prefab = prefab,
			Biome = biome,
			Offset = offset
		};
	}

	private static ClassDef Class(string name, RungDef[] rungs, params ExtraMember[] extras)
	{
		return new ClassDef
		{
			Name = name,
			Rungs = rungs,
			Extras = extras
		};
	}

	public static bool IsFixedAmount(Requirement requirement)
	{
		return FixedAmounts.Contains(requirement);
	}

	public static bool IsLadderItem(string prefab)
	{
		return Members.ContainsKey(prefab);
	}

	private static float E(SharedData shared, int quality)
	{
		return shared.m_blockPower + (float)Math.Max(0, quality - 1) * shared.m_blockPowerPerLevel;
	}

	private static ItemDrop ItemDropOf(ObjectDB db, string prefab)
	{
		GameObject itemPrefab = db.GetItemPrefab(prefab);
		if (!((Object)(object)itemPrefab != (Object)null))
		{
			return null;
		}
		return itemPrefab.GetComponent<ItemDrop>();
	}

	private static int StepSize(float gap, float g)
	{
		if (g <= 0f)
		{
			return 1;
		}
		return Math.Max(1, (int)Math.Floor(gap / g + 0.5f));
	}

	public static void Setup(ObjectDB db)
	{
		if ((Object)(object)db == (Object)null || db.m_items == null || db.m_items.Count == 0)
		{
			return;
		}
		Members.Clear();
		RequirementCache.Clear();
		CostCache.Clear();
		FixedAmounts.Clear();
		ClassDef[] classes = Classes;
		foreach (ClassDef classDef in classes)
		{
			List<Rung_> list = BuildRungs(db, classDef);
			if (list.Count < 2)
			{
				continue;
			}
			List<ExtraMember> list2 = new List<ExtraMember>();
			for (int j = 0; j < list.Count - 1; j++)
			{
				if (list[j].Name != null)
				{
					list2.Add(new ExtraMember
					{
						Prefab = list[j].Name,
						Biome = list[j].Biome,
						Offset = 0f
					});
				}
			}
			ExtraMember[] extras = classDef.Extras;
			foreach (ExtraMember item in extras)
			{
				list2.Add(item);
			}
			foreach (ExtraMember item2 in list2)
			{
				ItemDrop val = ItemDropOf(db, item2.Prefab);
				if ((Object)(object)val == (Object)null)
				{
					Logger.LogWarning((object)("Shield '" + item2.Prefab + "' skipped, prefab not found"));
					continue;
				}
				SharedData shared = val.m_itemData.m_shared;
				MemberInfo memberInfo = new MemberInfo
				{
					Prefab = item2.Prefab,
					E3 = E(shared, 3),
					G = shared.m_blockPowerPerLevel,
					Offset = item2.Offset,
					MinBiome = item2.Biome + 1,
					Rungs = list
				};
				if (memberInfo.G <= 0f)
				{
					continue;
				}
				int endQuality = EndQuality(memberInfo);
				Register(db, item2.Prefab, memberInfo, endQuality);
				if (Variants.TryGetValue(item2.Prefab, out var value))
				{
					string[] array = value;
					foreach (string prefab in array)
					{
						Register(db, prefab, memberInfo, endQuality);
					}
				}
				Logger.LogInfo((object)("Shield ladder '" + item2.Prefab + "' (" + classDef.Name + "): +" + 3 + " E " + memberInfo.E3.ToString("0.#") + ", reachable quality +" + endQuality));
			}
		}
	}

	private static void Register(ObjectDB db, string prefab, MemberInfo info, int endQuality)
	{
		ItemDrop val = ItemDropOf(db, prefab);
		if (!((Object)(object)val == (Object)null))
		{
			Members[prefab] = info;
			if (endQuality > val.m_itemData.m_shared.m_maxQuality)
			{
				val.m_itemData.m_shared.m_maxQuality = endQuality;
			}
		}
	}

	private static List<Rung_> BuildRungs(ObjectDB db, ClassDef cls)
	{
		List<Rung_> list = new List<Rung_>();
		RungDef[] rungs = cls.Rungs;
		foreach (RungDef rungDef in rungs)
		{
			Rung_ rung_ = new Rung_
			{
				Biome = rungDef.Biome,
				CostPrefab = rungDef.CostPrefab
			};
			if (rungDef.Prefab != null)
			{
				ItemDrop val = ItemDropOf(db, rungDef.Prefab);
				if ((Object)(object)val == (Object)null)
				{
					Logger.LogWarning((object)("Shield rung '" + rungDef.Prefab + "' (" + cls.Name + ") skipped, prefab not found"));
					continue;
				}
				rung_.Name = rungDef.Prefab;
				rung_.E3 = E(val.m_itemData.m_shared, 3);
				rung_.G = val.m_itemData.m_shared.m_blockPowerPerLevel;
			}
			else
			{
				rung_.E3 = rungDef.TargetE3;
			}
			list.Add(rung_);
		}
		float g = 0f;
		foreach (Rung_ item in list)
		{
			if (item.Name != null)
			{
				g = item.G;
				break;
			}
		}
		for (int j = 0; j < list.Count; j++)
		{
			list[j].KFull = ((j == 0) ? 1 : StepSize(list[j].E3 - list[j - 1].E3, g));
			if (list[j].Name != null)
			{
				g = list[j].G;
			}
		}
		return list;
	}

	private static Rung_ NextRung(MemberInfo info, float current)
	{
		foreach (Rung_ rung in info.Rungs)
		{
			if (rung.Biome >= info.MinBiome && rung.E3 + info.Offset - current >= 3f)
			{
				return rung;
			}
		}
		return null;
	}

	private static int EndQuality(MemberInfo info)
	{
		int num = 3;
		float num2 = info.E3;
		for (int i = 0; i < 200; i++)
		{
			Rung_ rung_ = NextRung(info, num2);
			if (rung_ == null)
			{
				break;
			}
			int num3 = StepSize(rung_.E3 + info.Offset - num2, info.G);
			num2 += (float)num3 * info.G;
			num += num3;
		}
		return num;
	}

	public static bool TryGetStep(string prefab, int quality, out Step step)
	{
		step = null;
		if (quality < 3 || !Members.TryGetValue(prefab, out var value))
		{
			return false;
		}
		float num = value.E3 + (float)(quality - 3) * value.G;
		Rung_ rung_ = NextRung(value, num);
		if (rung_ == null)
		{
			return false;
		}
		int num2 = StepSize(rung_.E3 + value.Offset - num, value.G);
		step = new Step
		{
			K = num2,
			Fraction = Math.Min(1f, (float)num2 / (float)Math.Max(1, rung_.KFull)),
			CostPrefab = rung_.CostPrefab
		};
		return true;
	}

	private static List<KeyValuePair<ItemDrop, int>> RungCost(string costPrefab)
	{
		if (CostCache.TryGetValue(costPrefab, out var value))
		{
			return value;
		}
		List<KeyValuePair<ItemDrop, int>> list = new List<KeyValuePair<ItemDrop, int>>();
		ObjectDB instance = ObjectDB.instance;
		ItemDrop val = (((Object)(object)instance != (Object)null) ? ItemDropOf(instance, costPrefab) : null);
		Recipe val2 = (((Object)(object)val != (Object)null) ? instance.GetRecipe(val.m_itemData) : null);
		if ((Object)(object)val2 == (Object)null)
		{
			return list;
		}
		Dictionary<string, int> dictionary = new Dictionary<string, int>();
		Dictionary<string, ItemDrop> dictionary2 = new Dictionary<string, ItemDrop>();
		List<string> list2 = new List<string>();
		Requirement[] resources = val2.m_resources;
		foreach (Requirement val3 in resources)
		{
			if (val3 == null || (Object)(object)val3.m_resItem == (Object)null || val3.m_upgraderResource)
			{
				continue;
			}
			string name = ((Object)val3.m_resItem).name;
			if (IsExcludedResource(name))
			{
				continue;
			}
			int num = 0;
			for (int j = 1; j <= 3; j++)
			{
				num += val3.GetAmount(j);
			}
			if (num > 0)
			{
				if (!dictionary.ContainsKey(name))
				{
					dictionary[name] = 0;
					dictionary2[name] = val3.m_resItem;
					list2.Add(name);
				}
				dictionary[name] += num;
			}
		}
		foreach (string item in list2)
		{
			list.Add(new KeyValuePair<ItemDrop, int>(dictionary2[item], dictionary[item]));
		}
		CostCache[costPrefab] = list;
		return list;
	}

	public static bool TryGetRequirements(Recipe recipe, int qualityArg, out Requirement[] requirements, out Step step)
	{
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: 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_00d8: Expected O, but got Unknown
		requirements = null;
		step = null;
		if ((Object)(object)recipe == (Object)null || (Object)(object)recipe.m_item == (Object)null || qualityArg <= 3)
		{
			return false;
		}
		string name = ((Object)recipe.m_item).name;
		if (!TryGetStep(name, qualityArg - 1, out step))
		{
			return false;
		}
		string key = name + "|" + qualityArg;
		if (RequirementCache.TryGetValue(key, out requirements))
		{
			return true;
		}
		List<KeyValuePair<ItemDrop, int>> list = RungCost(step.CostPrefab);
		if (list.Count == 0)
		{
			return false;
		}
		List<Requirement> list2 = new List<Requirement>();
		foreach (KeyValuePair<ItemDrop, int> item2 in list)
		{
			int amount = Math.Max(1, (int)Math.Ceiling((float)item2.Value * step.Fraction - 0.0001f));
			Requirement item = new Requirement
			{
				m_resItem = item2.Key,
				m_amount = amount,
				m_amountPerLevel = 0
			};
			FixedAmounts.Add(item);
			list2.Add(item);
		}
		requirements = list2.ToArray();
		RequirementCache[key] = requirements;
		return true;
	}
}
internal static class Upgrades
{
	public static void Setup(ObjectDB db)
	{
		try
		{
			Ladders.Setup(db);
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Ladders.Setup (armor) failed: " + ex));
		}
		try
		{
			WeaponLadders.Setup(db);
		}
		catch (Exception ex2)
		{
			Logger.LogError((object)("WeaponLadders.Setup failed: " + ex2));
		}
		try
		{
			ShieldLadders.Setup(db);
		}
		catch (Exception ex3)
		{
			Logger.LogError((object)("ShieldLadders.Setup failed: " + ex3));
		}
	}

	public static bool IsFixedAmount(Requirement requirement)
	{
		if (!Ladders.IsFixedAmount(requirement) && !WeaponLadders.IsFixedAmount(requirement))
		{
			return ShieldLadders.IsFixedAmount(requirement);
		}
		return true;
	}

	public static bool IsLadderItem(string prefab)
	{
		if (!Ladders.IsLadderItem(prefab) && !WeaponLadders.IsLadderItem(prefab))
		{
			return ShieldLadders.IsLadderItem(prefab);
		}
		return true;
	}

	public static int VanillaMax(string prefab)
	{
		if (!ShieldLadders.IsLadderItem(prefab))
		{
			return 4;
		}
		return 3;
	}

	public static bool TryGetStepLevels(string prefab, int quality, out int levels)
	{
		levels = 0;
		if (Ladders.TryGetStep(prefab, quality, out var step))
		{
			levels = step.K;
			return true;
		}
		if (WeaponLadders.TryGetStep(prefab, quality, out var step2))
		{
			levels = step2.K;
			return true;
		}
		if (ShieldLadders.TryGetStep(prefab, quality, out var step3))
		{
			levels = step3.K;
			return true;
		}
		return false;
	}

	public static bool TryGetRequirements(Recipe recipe, int qualityArg, out Requirement[] requirements, out int levels)
	{
		levels = 0;
		if (Ladders.TryGetRequirements(recipe, qualityArg, out requirements, out var step))
		{
			levels = step.K;
			return true;
		}
		if (WeaponLadders.TryGetRequirements(recipe, qualityArg, out requirements, out var step2))
		{
			levels = step2.K;
			return true;
		}
		if (ShieldLadders.TryGetRequirements(recipe, qualityArg, out requirements, out var step3))
		{
			levels = step3.K;
			return true;
		}
		requirements = null;
		return false;
	}
}
internal static class WeaponLadders
{
	private sealed class RungDef
	{
		public int Biome;

		public string Prefab;

		public float TargetE4;

		public string CostPrefab;

		public bool Level4Cost;
	}

	private sealed class ExtraMember
	{
		public string Prefab;

		public int Biome;

		public float Offset;

		public bool StartsAtOwnBiome;

		public float Level4Multiplier;
	}

	private sealed class ClassDef
	{
		public string Name;

		public RungDef[] Rungs;

		public ExtraMember[] Extras;
	}

	private sealed class Rung_
	{
		public string Name;

		public int Biome;

		public float E4;

		public float G;

		public int KFull;

		public string CostPrefab;

		public bool Level4Cost;
	}

	private sealed class MemberInfo
	{
		public string Prefab;

		public float E4;

		public float G;

		public bool Pure;

		public float Offset;

		public int MinBiome;

		public float Level4Multiplier;

		public List<Rung_> Rungs;
	}

	public sealed class Step
	{
		public int K;

		public float Fraction;

		public float Multiplier;

		public string CostPrefab;

		public bool Level4Cost;
	}

	private const float PureBonus = 6f;

	private const float MinGain = 3f;

	private const int Meadows = 0;

	private const int BlackForest = 1;

	private const int Swamp = 2;

	private const int Mountain = 3;

	private const int Plains = 4;

	private const int Mistlands = 5;

	private const int Ashlands = 6;

	private const int DeepNorth = 7;

	private static readonly ClassDef[] Classes = new ClassDef[12]
	{
		Class("Sword1H", new RungDef[7]
		{
			Real(1, "SwordBronze"),
			Real(2, "SwordIron"),
			Real(3, "SwordSilver"),
			Real(4, "SwordBlackmetal"),
			Real(5, "SwordMistwalker"),
			Real(6, "SwordNiedhogg"),
			Real(7, "SwordGold")
		}, Extra("SwordDyrnwyn", 6, 0f)),
		Class("Sword2H", new RungDef[3]
		{
			Real(5, "THSwordKrom"),
			Real(6, "THSwordSlayer"),
			Real(7, "THSwordGold")
		}),
		Class("Axe1H", new RungDef[8]
		{
			Real(0, "AxeFlint"),
			Real(1, "AxeBronze"),
			Real(2, "AxeIron"),
			Synth(3, 95f, "SwordSilver"),
			Real(4, "AxeBlackMetal"),
			SynthLevel4(5, 136f, "AxeJotunBane"),
			Real(6, "AxeBerzerkr"),
			Real(7, "AxeGold")
		}, Extra("AxeEarly", 1, -10f), new ExtraMember
		{
			Prefab = "AxeJotunBane",
			Biome = 5,
			Offset = 0f,
			StartsAtOwnBiome = true,
			Level4Multiplier = 1.5f
		}),
		Class("Axe2H", new RungDef[6]
		{
			Real(2, "Battleaxe"),
			Real(3, "BattleaxeCrystal"),
			Real(4, "BattleaxeBlackmetal"),
			Real(5, "BattleaxeSkullSplittur"),
			Synth(6, 175f, "THSwordSlayer"),
			Real(7, "BattleaxeGold")
		}),
		Class("Mace", new RungDef[7]
		{
			Real(1, "MaceBronze"),
			Real(2, "MaceIron"),
			Real(3, "MaceSilver"),
			Real(4, "MaceNeedle"),
			Synth(5, 133f, "SwordMistwalker"),
			Real(6, "MaceEldner"),
			Real(7, "MaceGold")
		}),
		Class("Sledge", new RungDef[8]
		{
			Real(0, "SledgeStagbreaker"),
			Synth(1, 58f, "AtgeirBronze"),
			Real(2, "SledgeIron"),
			Synth(3, 103f, "BattleaxeCrystal"),
			Synth(4, 133f, "BattleaxeBlackmetal"),
			Real(5, "SledgeDemolisher"),
			Synth(6, 179f, "THSwordSlayer"),
			Real(7, "SledgeGold")
		}),
		Class("Spear", new RungDef[8]
		{
			Real(0, "SpearFlint"),
			Real(1, "SpearBronze"),
			Real(2, "SpearElderbark"),
			Real(3, "SpearWolfFang"),
			Synth(4, 113f, "SwordBlackmetal"),
			Real(5, "SpearCarapace"),
			Real(6, "SpearSplitner"),
			Real(7, "SpearGold")
		}),
		Class("Atgeir", new RungDef[7]
		{
			Real(1, "AtgeirBronze"),
			Real(2, "AtgeirIron"),
			Synth(3, 103f, "BattleaxeCrystal"),
			Real(4, "AtgeirBlackmetal"),
			Real(5, "AtgeirHimminAfl"),
			Synth(6, 170f, "THSwordSlayer"),
			Real(7, "AtgeirGold")
		}),
		Class("Knife", new RungDef[8]
		{
			Real(0, "KnifeFlint"),
			Real(1, "KnifeCopper"),
			Real(2, "KnifeChitin"),
			Real(3, "KnifeSilver"),
			Real(4, "KnifeBlackMetal"),
			Real(5, "KnifeSkollAndHati"),
			Synth(6, 106f, "SwordNiedhogg"),
			Real(7, "KnifeGold")
		}, Extra("KnifeVoid", 1, 0f)),
		Class("Bow", new RungDef[8]
		{
			Real(0, "Bow"),
			Real(1, "BowFineWood"),
			Real(2, "BowHuntsman"),
			Real(3, "BowDraugrFang"),
			Synth(4, 70f, "SwordBlackmetal"),
			Real(5, "BowSpineSnap"),
			Real(6, "BowAshlands"),
			Real(7, "BowGold")
		}),
		Class("Crossbow", new RungDef[3]
		{
			Real(5, "CrossbowArbalest"),
			Real(6, "CrossbowRipper"),
			Real(7, "CrossbowGold")
		}),
		Class("Fist", new RungDef[7]
		{
			Real(1, "FistBjornClaw"),
			Synth(2, 55f, "SwordIron"),
			Real(3, "FistFenrirClaw"),
			Real(4, "FistBjornUndeadClaw"),
			Synth(5, 99f, "SwordMistwalker"),
			Synth(6, 114f, "SwordNiedhogg"),
			Real(7, "FistGold")
		})
	};

	private static readonly Dictionary<string, string[]> Variants = new Dictionary<string, string[]>
	{
		{
			"SwordNiedhogg",
			new string[3] { "SwordNiedhoggBlood", "SwordNiedhoggLightning", "SwordNiedhoggNature" }
		},
		{
			"THSwordSlayer",
			new string[3] { "THSwordSlayerBlood", "THSwordSlayerLightning", "THSwordSlayerNature" }
		},
		{
			"AxeBerzerkr",
			new string[3] { "AxeBerzerkrBlood", "AxeBerzerkrLightning", "AxeBerzerkrNature" }
		},
		{
			"MaceEldner",
			new string[3] { "MaceEldnerBlood", "MaceEldnerLightning", "MaceEldnerNature" }
		},
		{
			"SpearSplitner",
			new string[3] { "SpearSplitner_Blood", "SpearSplitner_Lightning", "SpearSplitner_Nature" }
		},
		{
			"BowAshlands",
			new string[3] { "BowAshlandsBlood", "BowAshlandsRoot", "BowAshlandsStorm" }
		},
		{
			"CrossbowRipper",
			new string[3] { "CrossbowRipperBlood", "CrossbowRipperLightning", "CrossbowRipperNature" }
		}
	};

	private static readonly Dictionary<string, MemberInfo> Members = new Dictionary<string, MemberInfo>();

	private static readonly Dictionary<string, Requirement[]> RequirementCache = new Dictionary<string, Requirement[]>();

	private static readonly Dictionary<string, List<KeyValuePair<ItemDrop, int>>> CostCache = new Dictionary<string, List<KeyValuePair<ItemDrop, int>>>();

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

	private static bool IsExcludedResource(string prefabName)
	{
		if (!prefabName.StartsWith("Trophy", StringComparison.Ordinal) && !prefabName.StartsWith("Mold", StringComparison.Ordinal))
		{
			switch (prefabName)
			{
			default:
				return prefabName == "Needle";
			case "Chain":
			case "MorgenHeart":
			case "MorgenSinew":
			case "BarkaBranch":
			case "ScaleHide":
			case "BonemawSerpentTooth":
				break;
			}
		}
		return true;
	}

	private static RungDef Real(int biome, string prefab)
	{
		return new RungDef
		{
			Biome = biome,
			Prefab = prefab,
			CostPrefab = prefab
		};
	}

	private static RungDef Synth(int biome, float e4, string costPrefab)
	{
		return new RungDef
		{
			Biome = biome,
			Prefab = null,
			TargetE4 = e4,
			CostPrefab = costPrefab
		};
	}

	private static RungDef SynthLevel4(int biome, float e4, string costPrefab)
	{
		return new RungDef
		{
			Biome = biome,
			Prefab = null,
			TargetE4 = e4,
			CostPrefab = costPrefab,
			Level4Cost = true
		};
	}

	private static ExtraMember Extra(string prefab, int biome, float offset)
	{
		return new ExtraMember
		{
			Prefab = prefab,
			Biome = biome,
			Offset = offset,
			Level4Multiplier = 1f
		};
	}

	private static ClassDef Class(string name, RungDef[] rungs, params ExtraMember[] extras)
	{
		return new ClassDef
		{
			Name = name,
			Rungs = rungs,
			Extras = extras
		};
	}

	public static bool IsFixedAmount(Requirement requirement)
	{
		return FixedAmounts.Contains(requirement);
	}

	public static bool IsLadderItem(string prefab)
	{
		return Members.ContainsKey(prefab);
	}

	private static float Counted(DamageTypes d)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		return d.m_damage + d.m_blunt + d.m_slash + d.m_pierce + d.m_frost + d.m_lightning + d.m_fire;
	}

	private static float E(SharedData shared, int quality)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		int num = Math.Max(0, quality - 1);
		return Counted(shared.m_damages) + (float)num * Counted(shared.m_damagesPerLevel);
	}

	private static float Perlevel(SharedData shared)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		return Counted(shared.m_damagesPerLevel);
	}

	private static int CountedTypes(DamageTypes d)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: 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_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		int num = 0;
		if (d.m_damage > 0f)
		{
			num++;
		}
		if (d.m_blunt > 0f)
		{
			num++;
		}
		if (d.m_slash > 0f)
		{
			num++;
		}
		if (d.m_pierce > 0f)
		{
			num++;
		}
		if (d.m_frost > 0f)
		{
			num++;
		}
		if (d.m_lightning > 0f)
		{
			num++;
		}
		if (d.m_fire > 0f)
		{
			num++;
		}
		return num;
	}

	private static bool IsPure(SharedData shared)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: 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_00a7: 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_00bb: 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_00d7: Unknown result type (might be due to invalid IL or missing references)
		DamageTypes damages = shared.m_damages;
		DamageTypes damagesPerLevel = shared.m_damagesPerLevel;
		DamageTypes d = damages;
		d.m_damage += 3f * damagesPerLevel.m_damage;
		d.m_blunt += 3f * damagesPerLevel.m_blunt;
		d.m_slash += 3f * damagesPerLevel.m_slash;
		d.m_pierce += 3f * damagesPerLevel.m_pierce;
		d.m_frost += 3f * damagesPerLevel.m_frost;
		d.m_lightning += 3f * damagesPerLevel.m_lightning;
		d.m_fire += 3f * damagesPerLevel.m_fire;
		float num = damages.m_poison + 3f * damagesPerLevel.m_poison;
		float num2 = damages.m_spirit + 3f * damagesPerLevel.m_spirit;
		if (CountedTypes(d) == 1 && num <= 0f && num2 <= 0f)
		{
			return (Object)(object)shared.m_attackStatusEffect == (Object)null;
		}
		return false;
	}

	private static ItemDrop ItemDropOf(ObjectDB db, string prefab)
	{
		GameObject itemPrefab = db.GetItemPrefab(prefab);
		if (!((Object)(object)itemPrefab != (Object)null))
		{
			return null;
		}
		return itemPrefab.GetComponent<ItemDrop>();
	}

	private static int StepSize(float gap, float g)
	{
		if (g <= 0f)
		{
			return 1;
		}
		return Math.Max(1, (int)Math.Floor(gap / g + 0.5f));
	}

	public static void Setup(ObjectDB db)
	{
		if ((Object)(object)db == (Object)null || db.m_items == null || db.m_items.Count == 0)
		{
			return;
		}
		Members.Clear();
		RequirementCache.Clear();
		CostCache.Clear();
		FixedAmounts.Clear();
		ClassDef[] classes = Classes;
		foreach (ClassDef classDef in classes)
		{
			List<Rung_> list = BuildRungs(db, classDef);
			if (list.Count < 2)
			{
				continue;
			}
			List<ExtraMember> list2 = new List<ExtraMember>();
			for (int j = 0; j < list.Count - 1; j++)
			{
				if (list[j].Name != null)
				{
					list2.Add(new ExtraMember
					{
						Prefab = list[j].Name,
						Biome = list[j].Biome,
						Offset = 0f,
						Level4Multiplier = 1f
					});
				}
			}
			ExtraMember[] extras = classDef.Extras;
			foreach (ExtraMember item in extras)
			{
				list2.Add(item);
			}
			foreach (ExtraMember item2 in list2)
			{
				ItemDrop val = ItemDropOf(db, item2.Prefab);
				if ((Object)(object)val == (Object)null)
				{
					Logger.LogWarning((object)("Weapon '" + item2.Prefab + "' skipped, prefab not found"));
					continue;
				}
				SharedData shared = val.m_itemData.m_shared;
				MemberInfo memberInfo = new MemberInfo
				{
					Prefab = item2.Prefab,
					E4 = E(shared, 4),
					G = Perlevel(shared),
					Pure = IsPure(shared),
					Offset = item2.Offset,
					MinBiome = (item2.StartsAtOwnBiome ? item2.Biome : (item2.Biome + 1)),
					Level4Multiplier = item2.Level4Multiplier,
					Rungs = list
				};
				if (memberInfo.G <= 0f)
				{
					continue;
				}
				int endQuality = EndQuality(memberInfo);
				Register(db, item2.Prefab, memberInfo, endQuality);
				if (Variants.TryGetValue(item2.Prefab, out var value))
				{
					string[] array = value;
					foreach (string prefab in array)
					{
						Register(db, prefab, memberInfo, endQuality);
					}
				}
				Logger.LogInfo((object)("Weapon ladder '" + item2.Prefab + "': +4 E " + memberInfo.E4.ToString("0.#") + (memberInfo.Pure ? " (pure)" : "") + ", reachable quality +" + endQuality));
			}
		}
	}

	private static void Register(ObjectDB db, string prefab, MemberInfo info, int endQuality)
	{
		ItemDrop val = ItemDropOf(db, prefab);
		if (!((Object)(object)val == (Object)null))
		{
			Members[prefab] = info;
			if (endQuality > val.m_itemData.m_shared.m_maxQuality)
			{
				val.m_itemData.m_shared.m_maxQuality = endQuality;
			}
		}
	}

	private static List<Rung_> BuildRungs(ObjectDB db, ClassDef cls)
	{
		List<Rung_> list = new List<Rung_>();
		RungDef[] rungs = cls.Rungs;
		foreach (RungDef rungDef in rungs)
		{
			Rung_ rung_ = new Rung_
			{
				Biome = rungDef.Biome,
				CostPrefab = rungDef.CostPrefab,
				Level4Cost = rungDef.Level4Cost
			};
			if (rungDef.Prefab != null)
			{
				ItemDrop val = ItemDropOf(db, rungDef.Prefab);
				if ((Object)(object)val == (Object)null)
				{
					Logger.LogWarning((object)("Weapon rung '" + rungDef.Prefab + "' (" + cls.Name + ") skipped, prefab not found"));
					continue;
				}
				rung_.Name = rungDef.Prefab;
				rung_.E4 = E(val.m_itemData.m_shared, 4);
				rung_.G = Perlevel(val.m_itemData.m_shared);
			}
			else
			{
				rung_.E4 = rungDef.TargetE4;
			}
			list.Add(rung_);
		}
		float g = 0f;
		foreach (Rung_ item in list)
		{
			if (item.Name != null)
			{
				g = item.G;
				break;
			}
		}
		for (int j = 0; j < list.Count; j++)
		{
			list[j].KFull = ((j == 0) ? 1 : StepSize(list[j].E4 - list[j - 1].E4, g));
			if (list[j].Name != null)
			{
				g = list[j].G;
			}
		}
		return list;
	}

	private static float Target(MemberInfo info, Rung_ rung)
	{
		return rung.E4 + info.Offset + (info.Pure ? 6f : 0f);
	}

	private static Rung_ NextRung(MemberInfo info, float current)
	{
		foreach (Rung_ rung in info.Rungs)
		{
			if (rung.Biome >= info.MinBiome && Target(info, rung) - current >= 3f)
			{
				return rung;
			}
		}
		return null;
	}

	private static int EndQuality(MemberInfo info)
	{
		int num = 4;
		float num2 = info.E4;
		for (int i = 0; i < 200; i++)
		{
			Rung_ rung_ = NextRung(info, num2);
			if (rung_ == null)
			{
				break;
			}
			int num3 = StepSize(Target(info, rung_) - num2, info.G);
			num2 += (float)num3 * info.G;
			num += num3;
		}
		return num;
	}

	public static bool TryGetStep(string prefab, int quality, out Step step)
	{
		step = null;
		if (quality < 4 || !Members.TryGetValue(prefab, out var value))
		{
			return false;
		}
		float num = value.E4 + (float)(quality - 4) * value.G;
		Rung_ rung_ = NextRung(value, num);
		if (rung_ == null)
		{
			return false;
		}
		int num2 = StepSize(Target(value, rung_) - num, value.G);
		step = new Step
		{
			K = num2,
			Fraction = Math.Min(1f, (float)num2 / (float)Math.Max(1, rung_.KFull)),
			Multiplier = (rung_.Level4Cost ? value.Level4Multiplier : 1f),
			CostPrefab = rung_.CostPrefab,
			Level4Cost = rung_.Level4Cost
		};
		return true;
	}

	private static List<KeyValuePair<ItemDrop, int>> RungCost(string costPrefab, bool level4)
	{
		string key = costPrefab + (level4 ? "|4" : "|sum");
		if (CostCache.TryGetValue(key, out var value))
		{
			return value;
		}
		List<KeyValuePair<ItemDrop, int>> list = new List<KeyValuePair<ItemDrop, int>>();
		ObjectDB instance = ObjectDB.instance;
		ItemDrop val = (((Object)(object)instance != (Object)null) ? ItemDropOf(instance, costPrefab) : null);
		Recipe val2 = (((Object)(object)val != (Object)null) ? instance.GetRecipe(val.m_itemData) : null);
		if ((Object)(object)val2 == (Object)null)
		{
			return list;
		}
		Dictionary<string, int> dictionary = new Dictionary<string, int>();
		Dictionary<string, ItemDrop> dictionary2 = new Dictionary<string, ItemDrop>();
		List<string> list2 = new List<string>();
		Requirement[] resources = val2.m_resources;
		foreach (Requirement val3 in resources)
		{
			if (val3 == null || (Object)(object)val3.m_resItem == (Object)null || val3.m_upgraderResource)
			{
				continue;
			}
			string text = ((Object)val3.m_resItem).name;
			ItemDrop value2 = val3.m_resItem;
			if (IsExcludedResource(text))
			{
				continue;
			}
			if (costPrefab == "KnifeSkollAndHati" && text == "FineWood")
			{
				ItemDrop val4 = ItemDropOf(instance, "YggdrasilWood");
				if ((Object)(object)val4 != (Object)null)
				{
					value2 = val4;
					text = "YggdrasilWood";
				}
			}
			int num = 0;
			if (level4)
			{
				num = val3.GetAmount(4);
			}
			else
			{
				for (int j = 1; j <= 4; j++)
				{
					num += val3.GetAmount(j);
				}
			}
			if (num > 0)
			{
				if (!dictionary.ContainsKey(text))
				{
					dictionary[text] = 0;
					dictionary2[text] = value2;
					list2.Add(text);
				}
				dictionary[text] += num;
			}
		}
		foreach (string item in list2)
		{
			list.Add(new KeyValuePair<ItemDrop, int>(dictionary2[item], dictionary[item]));
		}
		CostCache[key] = list;
		return list;
	}

	public static bool TryGetRequirements(Recipe recipe, int qualityArg, out Requirement[] requirements, out Step step)
	{
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: 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_00e7: Expected O, but got Unknown
		requirements = null;
		step = null;
		if ((Object)(object)recipe == (Object)null || (Object)(object)recipe.m_item == (Object)null || qualityArg < 5)
		{
			return false;
		}
		string name = ((Object)recipe.m_item).name;
		if (!TryGetStep(name, qualityArg - 1, out step))
		{
			return false;
		}
		string key = name + "|" + qualityArg;
		if (RequirementCache.TryGetValue(key, out requirements))
		{
			return true;
		}
		List<KeyValuePair<ItemDrop, int>> list = RungCost(step.CostPrefab, step.Level4Cost);
		if (list.Count == 0)
		{
			return false;
		}
		List<Requirement> list2 = new List<Requirement>();
		foreach (KeyValuePair<ItemDrop, int> item2 in list)
		{
			int amount = Math.Max(1, (int)Math.Ceiling((float)item2.Value * step.Multiplier * step.Fraction - 0.0001f));
			Requirement item = new Requirement
			{
				m_resItem = item2.Key,
				m_amount = amount,
				m_amountPerLevel = 0
			};
			FixedAmounts.Add(item);
			list2.Add(item);
		}
		requirements = list2.ToArray();
		RequirementCache[key] = requirements;
		return true;
	}
}