Decompiled source of BuminFixes v1.46.0

plugins/PathOfBuminFixes.dll

Decompiled 5 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using PassiveTree;
using PassiveTree.Gear;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.TextCore;
using UnityEngine.TextCore.LowLevel;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace PathOfBuminFixes;

internal static class AnvilFlash
{
	private const string WardFx = "fx_guardstone";

	private const float FxHeight = 0.85f;

	private const float NearAnvil = 1.5f;

	private const float SteadyIntensity = 0.35f;

	private const float SteadyPerStage = 0.22f;

	private static ConfigEntry<float> _strength;

	private static FieldInfo _light;

	private static FieldInfo _shown;

	private static FieldInfo _glow;

	private static FieldInfo _flickerBase;

	private static FieldInfo _lodRange;

	private static readonly List<Component> Anvils = new List<Component>();

	private static int _replaced;

	internal static void Apply(Harmony harmony, ConfigFile config, ManualLogSource log)
	{
		//IL_016b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Expected O, but got Unknown
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d2: Expected O, but got Unknown
		//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f9: Expected O, but got Unknown
		//IL_0214: Unknown result type (might be due to invalid IL or missing references)
		//IL_0221: Expected O, but got Unknown
		//IL_023c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0249: Expected O, but got Unknown
		Type type = AccessTools.TypeByName("PassiveTree.RunicCraft.Anvil");
		Type type2 = AccessTools.TypeByName("PassiveTree.RunicCraft.AnvilLook");
		MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "Make", (Type[])null, (Type[])null));
		MethodInfo methodInfo2 = ((type2 == null) ? null : AccessTools.Method(type2, "Flash", (Type[])null, (Type[])null));
		MethodInfo methodInfo3 = ((type2 == null) ? null : AccessTools.Method(type2, "Start", (Type[])null, (Type[])null));
		MethodInfo methodInfo4 = AccessTools.Method(typeof(ZNetScene), "CreateObject", new Type[1] { typeof(ZDO) }, (Type[])null);
		_light = ((type2 == null) ? null : AccessTools.Field(type2, "light"));
		_shown = ((type2 == null) ? null : AccessTools.Field(type2, "shown"));
		_glow = ((type2 == null) ? null : AccessTools.Field(type2, "Glow"));
		if (methodInfo == null || methodInfo2 == null || methodInfo3 == null || methodInfo4 == null || _light == null || _shown == null || _glow == null)
		{
			log.LogWarning((object)"Runic Anvil flash: Path of Valheiman's anvil effects have changed; nothing changed.");
			return;
		}
		_strength = config.Bind<float>("Path of Valheiman", "Runic Anvil flash strength", 0.35f, new ConfigDescription("Strength of the ward-like flash and the light pulse when you forge, upgrade, repair or put items in at a Runic Anvil. 1: Path of Valheiman's own look. 0: no flash, only the sparks and sounds. Whatever the value, the anvil's light no longer builds up with every item put in. Applies at once.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[0]));
		_flickerBase = AccessTools.Field(typeof(LightFlicker), "m_baseIntensity");
		_lodRange = AccessTools.Field(typeof(LightLod), "m_baseRange");
		harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(AnvilFlash).GetMethod("Transpiler", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null);
		harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(AnvilFlash).GetMethod("FlashPrefix", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(AnvilFlash).GetMethod("AnvilStarted", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		harmony.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, new HarmonyMethod(typeof(AnvilFlash).GetMethod("Created", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		log.LogInfo((object)("Runic Anvil flash follows [Path of Valheiman] Runic Anvil flash strength (" + _replaced + " of 2 spawns caught)."));
	}

	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Expected O, but got Unknown
		List<CodeInstruction> list = new List<CodeInstruction>(instructions);
		MethodInfo method = typeof(AnvilFlash).GetMethod("Spawn", BindingFlags.Static | BindingFlags.NonPublic);
		for (int i = 0; i < list.Count; i++)
		{
			MethodInfo methodInfo = list[i].operand as MethodInfo;
			if (!(methodInfo == null) && !(methodInfo.Name != "Instantiate") && !(methodInfo.DeclaringType != typeof(Object)) && methodInfo.GetParameters().Length == 3 && !(methodInfo.ReturnType != typeof(GameObject)))
			{
				CodeInstruction val = new CodeInstruction(OpCodes.Call, (object)method);
				val.labels.AddRange(list[i].labels);
				val.blocks.AddRange(list[i].blocks);
				list[i] = val;
				_replaced++;
			}
		}
		return list;
	}

	private static GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = Object.Instantiate<GameObject>(prefab, position, rotation);
		if ((Object)(object)prefab != (Object)null && ((Object)prefab).name.StartsWith("fx_guardstone"))
		{
			Tone(val);
		}
		return val;
	}

	private static void FlashPrefix(MonoBehaviour __instance, ref float power)
	{
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		power *= _strength.Value;
		__instance.StopAllCoroutines();
		object? value = _light.GetValue(__instance);
		Light val = (Light)((value is Light) ? value : null);
		if (!((Object)(object)val == (Object)null))
		{
			int num = Mathf.Max(0, (int)_shown.GetValue(__instance));
			val.color = (Color)_glow.GetValue(null);
			val.intensity = 0.35f + 0.22f * (float)num;
		}
	}

	private static void AnvilStarted(Component __instance)
	{
		Anvils.Add(__instance);
	}

	private static void Created(GameObject __result)
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: 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_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)__result == (Object)null || !((Object)__result).name.StartsWith("fx_guardstone"))
		{
			return;
		}
		Vector3 position = __result.transform.position;
		for (int num = Anvils.Count - 1; num >= 0; num--)
		{
			if ((Object)(object)Anvils[num] == (Object)null)
			{
				Anvils.RemoveAt(num);
			}
			else if (Vector3.Distance(Anvils[num].transform.position + Vector3.up * 0.85f, position) < 1.5f)
			{
				Tone(__result);
				break;
			}
		}
	}

	private static void Tone(GameObject fx)
	{
		//IL_015b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		//IL_0184: Unknown result type (might be due to invalid IL or missing references)
		//IL_018a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: Unknown result type (might be due to invalid IL or missing references)
		//IL_019b: Unknown result type (might be due to invalid IL or missing references)
		float num = Mathf.Clamp01(_strength.Value);
		if ((Object)(object)fx == (Object)null || num > 0.999f)
		{
			return;
		}
		float num2 = Mathf.Sqrt(num);
		Light[] componentsInChildren = fx.GetComponentsInChildren<Light>(true);
		Light[] array = componentsInChildren;
		foreach (Light val in array)
		{
			val.intensity *= num;
			val.range *= Mathf.Max(num2, 0.3f);
			LightFlicker component = ((Component)val).GetComponent<LightFlicker>();
			if ((Object)(object)component != (Object)null && _flickerBase != null)
			{
				_flickerBase.SetValue(component, (float)_flickerBase.GetValue(component) * num);
			}
			LightLod component2 = ((Component)val).GetComponent<LightLod>();
			if ((Object)(object)component2 != (Object)null && _lodRange != null)
			{
				_lodRange.SetValue(component2, (float)_lodRange.GetValue(component2) * Mathf.Max(num2, 0.3f));
			}
			if (num < 0.001f)
			{
				((Behaviour)val).enabled = false;
			}
		}
		ParticleSystem[] componentsInChildren2 = fx.GetComponentsInChildren<ParticleSystem>(true);
		ParticleSystem[] array2 = componentsInChildren2;
		foreach (ParticleSystem val2 in array2)
		{
			if (num < 0.001f)
			{
				ParticleSystemRenderer component3 = ((Component)val2).GetComponent<ParticleSystemRenderer>();
				if ((Object)(object)component3 != (Object)null)
				{
					((Renderer)component3).enabled = false;
				}
				continue;
			}
			MainModule main = val2.main;
			((MainModule)(ref main)).startSizeMultiplier = ((MainModule)(ref main)).startSizeMultiplier * num2;
			((MainModule)(ref main)).startSpeedMultiplier = ((MainModule)(ref main)).startSpeedMultiplier * num2;
			((MainModule)(ref main)).startColor = Fade(((MainModule)(ref main)).startColor, num2);
			ShapeModule shape = val2.shape;
			if (((ShapeModule)(ref shape)).enabled)
			{
				((ShapeModule)(ref shape)).radius = ((ShapeModule)(ref shape)).radius * num2;
			}
		}
	}

	private static MinMaxGradient Fade(MinMaxGradient g, float a)
	{
		//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)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Expected I4, but got Unknown
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//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)
		//IL_0051: 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_009b: Unknown result type (might be due to invalid IL or missing references)
		ParticleSystemGradientMode mode = ((MinMaxGradient)(ref g)).mode;
		switch ((int)mode)
		{
		case 0:
			return new MinMaxGradient(Fade(((MinMaxGradient)(ref g)).color, a));
		case 2:
			return new MinMaxGradient(Fade(((MinMaxGradient)(ref g)).colorMin, a), Fade(((MinMaxGradient)(ref g)).colorMax, a));
		case 1:
		case 4:
		{
			MinMaxGradient result = default(MinMaxGradient);
			((MinMaxGradient)(ref result))..ctor(Fade(((MinMaxGradient)(ref g)).gradient, a));
			((MinMaxGradient)(ref result)).mode = ((MinMaxGradient)(ref g)).mode;
			return result;
		}
		case 3:
			return new MinMaxGradient(Fade(((MinMaxGradient)(ref g)).gradientMin, a), Fade(((MinMaxGradient)(ref g)).gradientMax, a));
		default:
			return g;
		}
	}

	private static Color Fade(Color c, float a)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		c.a *= a;
		return c;
	}

	private static Gradient Fade(Gradient g, float a)
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Expected O, but got Unknown
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		if (g == null)
		{
			return null;
		}
		GradientAlphaKey[] alphaKeys = g.alphaKeys;
		for (int i = 0; i < alphaKeys.Length; i++)
		{
			ref GradientAlphaKey reference = ref alphaKeys[i];
			reference.alpha *= a;
		}
		Gradient val = new Gradient();
		val.mode = g.mode;
		val.SetKeys(g.colorKeys, alphaKeys);
		return val;
	}
}
internal static class AnvilQuickStack
{
	internal const string QuickStackGuid = "goldenrevolver.quick_stack_store";

	private static ConfigEntry<bool> _enabled;

	private static MethodInfo _is;

	private static MethodInfo _isCache;

	private static MethodInfo _canWrite;

	private static MethodInfo _deposit;

	private static MethodInfo _do;

	private static MethodInfo _stockable;

	private static MethodInfo _count;

	private static Type _store;

	private static Container _forced;

	private static readonly FieldInfo CurrentContainer = AccessTools.Field(typeof(InventoryGui), "m_currentContainer");

	private static readonly FieldInfo ContainerView = AccessTools.Field(typeof(Container), "m_nview");

	internal static void Apply(Harmony harmony, ConfigFile config, ManualLogSource log)
	{
		//IL_0324: Unknown result type (might be due to invalid IL or missing references)
		//IL_0331: Expected O, but got Unknown
		//IL_034b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0359: Expected O, but got Unknown
		//IL_0373: Unknown result type (might be due to invalid IL or missing references)
		//IL_038e: Unknown result type (might be due to invalid IL or missing references)
		//IL_039b: Expected O, but got Unknown
		//IL_039b: Expected O, but got Unknown
		if (Chainloader.PluginInfos.ContainsKey("goldenrevolver.quick_stack_store"))
		{
			_enabled = config.Bind<bool>("Quick Stack Store", "Quick stack into Runic Anvils", true, "Quick stack also puts Glyph Alloys, Azurite Dust and the other items a Path of Valheiman Runic Anvil stocks into the open anvil, or into anvils in Quick Stack Store's range. An anvil that already holds the item comes first. An anvil another player stands at is left alone. Applies at once.");
			Type type = AccessTools.TypeByName("PassiveTree.RunicCraft.Anvil");
			Type type2 = AccessTools.TypeByName("PassiveTree.RunicCraft.Defs");
			Type type3 = AccessTools.TypeByName("QuickStackStore.QuickStackModule");
			_store = AccessTools.TypeByName("PassiveTree.RunicCraft.Anvil+Store");
			_is = ((type == null) ? null : AccessTools.Method(type, "Is", new Type[1] { typeof(Container) }, (Type[])null));
			_isCache = ((type == null) ? null : AccessTools.Method(type, "IsCache", new Type[1] { typeof(Container) }, (Type[])null));
			_canWrite = ((type == null) ? null : AccessTools.Method(type, "CanWrite", new Type[2]
			{
				typeof(Container),
				typeof(Player)
			}, (Type[])null));
			_deposit = ((type == null) ? null : AccessTools.Method(type, "Deposit", new Type[4]
			{
				typeof(Container),
				typeof(Inventory),
				typeof(ItemData),
				typeof(int)
			}, (Type[])null));
			_do = ((type == null) ? null : AccessTools.Method(type, "Do", new Type[2]
			{
				typeof(Container),
				typeof(Action)
			}, (Type[])null));
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "Viewing", new Type[1] { typeof(Container) }, (Type[])null));
			_stockable = ((type2 == null) ? null : AccessTools.Method(type2, "Stockable", new Type[1] { typeof(string) }, (Type[])null));
			_count = ((_store == null) ? null : AccessTools.Method(_store, "Count", new Type[1] { typeof(string) }, (Type[])null));
			MethodInfo methodInfo2 = ((type3 == null) ? null : AccessTools.Method(type3, "QuickStackIntoThisContainer", (Type[])null, (Type[])null));
			MethodInfo methodInfo3 = ((type3 == null) ? null : AccessTools.Method(type3, "QuickStackIntoMultipleContainers", (Type[])null, (Type[])null));
			if (_is == null || _isCache == null || _canWrite == null || _deposit == null || _do == null || methodInfo == null || _stockable == null || _store == null || methodInfo2 == null || methodInfo3 == null)
			{
				log.LogError((object)"Path of Valheiman's Runic Anvil or Quick Stack Store's quick stack was not found. Quick stack leaves the anvils alone.");
				return;
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(AnvilQuickStack), "ForceViewing", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(AccessTools.Method(typeof(AnvilQuickStack), "IntoOpenAnvil", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(AccessTools.Method(typeof(AnvilQuickStack), "IntoNearAnvils", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.Method(typeof(AnvilQuickStack), "AddNearCount", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			log.LogInfo((object)"Quick Stack Store puts Runic Anvil items into anvils ([Quick Stack Store] Quick stack into Runic Anvils).");
		}
	}

	private static bool Call(MethodInfo method, params object[] args)
	{
		try
		{
			return (bool)method.Invoke(null, args);
		}
		catch (Exception)
		{
			return false;
		}
	}

	private static bool IsAnvil(Container container)
	{
		if ((Object)(object)container != (Object)null && Call(_is, container))
		{
			return !Call(_isCache, container);
		}
		return false;
	}

	private static bool Stockable(ItemData item)
	{
		if (item != null && (Object)(object)item.m_dropPrefab != (Object)null && !item.m_equipped)
		{
			return Call(_stockable, ((Object)item.m_dropPrefab).name);
		}
		return false;
	}

	private static long Stock(Container container, string id)
	{
		try
		{
			Component component = ((Component)container).GetComponent(_store);
			return ((Object)(object)component == (Object)null || _count == null) ? 0 : Convert.ToInt64(_count.Invoke(component, new object[1] { id }));
		}
		catch (Exception)
		{
			return 0L;
		}
	}

	private static void ForceViewing(Container c, ref bool __result)
	{
		if (!__result && (Object)(object)c != (Object)null && (Object)(object)c == (Object)(object)_forced)
		{
			__result = true;
		}
	}

	private static int Fill(Container anvil, Inventory bag, List<ItemData> items, Func<ItemData, bool> wanted)
	{
		int num = 0;
		_forced = anvil;
		try
		{
			for (int num2 = items.Count - 1; num2 >= 0; num2--)
			{
				ItemData val = items[num2];
				if (Stockable(val) && bag.ContainsItem(val) && (wanted == null || wanted(val)) && Call(_deposit, anvil, bag, val, val.m_stack))
				{
					items.RemoveAt(num2);
					num++;
				}
			}
			return num;
		}
		finally
		{
			_forced = null;
		}
	}

	private static bool IntoOpenAnvil(object[] __args, ref int __result)
	{
		if (!_enabled.Value || (Object)(object)InventoryGui.instance == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null)
		{
			return true;
		}
		Container anvil = default(Container);
		ref Container reference = ref anvil;
		object? value = CurrentContainer.GetValue(InventoryGui.instance);
		reference = (Container)((value is Container) ? value : null);
		object obj = __args[3];
		Inventory val = (Inventory)((obj is Inventory) ? obj : null);
		if (!IsAnvil(anvil) || val == null || anvil.GetInventory() != val)
		{
			return true;
		}
		List<ItemData> list = __args[1] as List<ItemData>;
		Inventory bag = default(Inventory);
		ref Inventory reference2 = ref bag;
		object obj2 = __args[2];
		reference2 = (Inventory)((obj2 is Inventory) ? obj2 : null);
		__result = 0;
		if (list == null || bag == null)
		{
			return false;
		}
		List<ItemData> picked = new List<ItemData>();
		foreach (ItemData item in list)
		{
			if (Stockable(item))
			{
				picked.Add(item);
			}
		}
		if (picked.Count == 0)
		{
			return false;
		}
		if (anvil.IsOwner())
		{
			__result = Fill(anvil, bag, list, null);
			return false;
		}
		Call(_do, anvil, (Action)delegate
		{
			Fill(anvil, bag, picked, null);
		});
		return false;
	}

	private static void IntoNearAnvils(object[] __args, out int __state)
	{
		//IL_0109: 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)
		__state = 0;
		List<ItemData> list = __args[1] as List<ItemData>;
		object obj = __args[2];
		Player val = (Player)((obj is Player) ? obj : null);
		List<Container> list2 = __args[3] as List<Container>;
		if (!_enabled.Value || list == null || (Object)(object)val == (Object)null || (Object)(object)val != (Object)(object)Player.m_localPlayer || list2 == null)
		{
			return;
		}
		List<Container> list3 = new List<Container>();
		for (int num = list2.Count - 1; num >= 0; num--)
		{
			if (IsAnvil(list2[num]))
			{
				if (Call(_canWrite, list2[num], val))
				{
					list3.Add(list2[num]);
				}
				list2.RemoveAt(num);
			}
		}
		bool flag = false;
		foreach (ItemData item in list)
		{
			if (Stockable(item))
			{
				flag = true;
				break;
			}
		}
		if (!flag || list3.Count == 0)
		{
			return;
		}
		Vector3 here = ((Component)val).transform.position;
		list3.Sort((Container a, Container b) => Vector3.Distance(here, ((Component)a).transform.position).CompareTo(Vector3.Distance(here, ((Component)b).transform.position)));
		Inventory inventory = ((Humanoid)val).GetInventory();
		List<Container> list4 = new List<Container>();
		foreach (Container item2 in list3)
		{
			object? value = ContainerView.GetValue(item2);
			ZNetView val2 = (ZNetView)((value is ZNetView) ? value : null);
			if (!item2.IsOwner() && (Object)(object)val2 != (Object)null && val2.IsValid())
			{
				val2.ClaimOwnership();
			}
			if (item2.IsOwner())
			{
				list4.Add(item2);
			}
		}
		foreach (Container item3 in list4)
		{
			Container each = item3;
			__state += Fill(each, inventory, list, (ItemData item) => Stock(each, ((Object)item.m_dropPrefab).name) > 0);
		}
		if (list4.Count > 0)
		{
			__state += Fill(list4[0], inventory, list, null);
		}
	}

	private static void AddNearCount(int __state, ref int __result)
	{
		__result += __state;
	}
}
[BepInPlugin("__pathofbumin.fixes.early", "Path of Bumin Fixes Early", "1.46.0")]
public class BarheimFont : BaseUnityPlugin
{
	private const string Guid = "__pathofbumin.fixes.early";

	private static readonly string[] Files = new string[2] { "Caudex-Regular.ttf", "OFL-caudex.txt" };

	private void Awake()
	{
		try
		{
			string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "fonts");
			string[] files = Directory.GetFiles(Paths.PluginPath, "HPBarheim.dll", SearchOption.AllDirectories);
			string[] array = files;
			foreach (string path2 in array)
			{
				string[] files2 = Files;
				string[] array2 = files2;
				foreach (string text in array2)
				{
					string text2 = Path.Combine(path, text);
					string text3 = Path.Combine(Path.GetDirectoryName(path2), text);
					if (File.Exists(text2) && !File.Exists(text3))
					{
						File.Copy(text2, text3);
						((BaseUnityPlugin)this).Logger.LogInfo((object)("Copied " + text + " to HP Barheim."));
					}
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Could not copy the Caudex font to HP Barheim: " + ex));
		}
	}
}
internal static class BarheimPovIcons
{
	private static ManualLogSource _log;

	private static MethodInfo _on;

	private static MethodInfo _each;

	private static MethodInfo _icon;

	private static MethodInfo _tile;

	private static MethodInfo _getPov;

	private static MethodInfo _maybe;

	private static MethodInfo _iconSet;

	private static FieldInfo _byGroupField;

	private static FieldInfo _tried;

	private static FieldInfo _ready;

	private static Type _modType;

	private static bool _told;

	private static bool _failed;

	private static readonly Dictionary<long, int> Ids = new Dictionary<long, int>();

	private static readonly List<long> Masks = new List<long> { 0L };

	private static readonly Dictionary<int, Sprite[]>[] Cache = new Dictionary<int, Sprite[]>[2]
	{
		new Dictionary<int, Sprite[]>(),
		new Dictionary<int, Sprite[]>()
	};

	internal static void Apply(Harmony harmony, ManualLogSource log)
	{
		//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f1: Expected O, but got Unknown
		//IL_030b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0319: Expected O, but got Unknown
		//IL_0333: Unknown result type (might be due to invalid IL or missing references)
		//IL_0341: Expected O, but got Unknown
		//IL_0365: Unknown result type (might be due to invalid IL or missing references)
		//IL_0373: Expected O, but got Unknown
		Type type = AccessTools.TypeByName("HPBarheim.Compat.PathOfValheimanModifiers");
		Type type2 = AccessTools.TypeByName("PassiveTree.RarityMods");
		Type type3 = AccessTools.TypeByName("PassiveTree.IconMap");
		Type type4 = AccessTools.TypeByName("PassiveTree.UI.UiKit");
		if (type == null || type2 == null)
		{
			return;
		}
		_log = log;
		_on = AccessTools.Method(type2, "On", new Type[1] { typeof(Character) }, (Type[])null);
		_modType = ((_on == null) ? null : _on.ReturnType);
		if (_modType == null || !_modType.IsEnum)
		{
			log.LogWarning((object)"Path of Valheiman's creature modifiers were not found; HP Barheim's modifier icons stay as they are.");
			return;
		}
		if (Enum.GetUnderlyingType(_modType) == typeof(int))
		{
			log.LogInfo((object)"Path of Valheiman's creature modifiers fit HP Barheim again; its own modifier icons are used.");
			return;
		}
		_each = AccessTools.Method(type2, "Each", new Type[1] { _modType }, (Type[])null);
		_icon = AccessTools.Method(type2, "Icon", new Type[1] { _modType }, (Type[])null);
		_tile = ((type4 == null) ? null : AccessTools.Method(type4, "Tile", new Type[1] { typeof(int) }, (Type[])null));
		_byGroupField = ((type3 == null) ? null : AccessTools.Field(type3, "ByGroup"));
		_getPov = AccessTools.Method("HPBarheim.Hud.ModifierIconSprite:GetPov", new Type[1] { typeof(string) }, (Type[])null);
		_maybe = AccessTools.Method("PassiveTree.UI.IconRegistry:Maybe", new Type[1] { typeof(string) }, (Type[])null);
		_iconSet = AccessTools.PropertyGetter(type, "IconSet");
		_tried = AccessTools.Field(type, "_tried");
		_ready = AccessTools.Field(type, "_ready");
		MethodInfo methodInfo = AccessTools.Method(type, "Bind", (Type[])null, (Type[])null);
		MethodInfo methodInfo2 = AccessTools.Method(type, "ReadMask", new Type[1] { typeof(Character) }, (Type[])null);
		MethodInfo methodInfo3 = AccessTools.Method(type, "Sprites", (Type[])null, (Type[])null);
		MethodInfo methodInfo4 = AccessTools.Method(type, "ParseList", (Type[])null, (Type[])null);
		if (_each == null || _icon == null || _tile == null || _byGroupField == null || _iconSet == null || _tried == null || _ready == null || methodInfo == null || methodInfo2 == null || methodInfo3 == null)
		{
			log.LogWarning((object)"HP Barheim's or Path of Valheiman's modifier parts were not found; HP Barheim's modifier icons stay off.");
			return;
		}
		harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(BarheimPovIcons), "Bind", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(AccessTools.Method(typeof(BarheimPovIcons), "ReadMask", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(AccessTools.Method(typeof(BarheimPovIcons), "Sprites", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		if (methodInfo4 != null)
		{
			harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(AccessTools.Method(typeof(BarheimPovIcons), "ParseList", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		log.LogInfo((object)("HP Barheim reads Path of Valheiman's " + Enum.GetNames(_modType).Length + " creature modifiers (64 bit) and draws their icons."));
	}

	private static int Intern(long mask)
	{
		if (mask == 0)
		{
			return 0;
		}
		if (!Ids.TryGetValue(mask, out var value))
		{
			value = Masks.Count;
			Masks.Add(mask);
			Ids[mask] = value;
		}
		return value;
	}

	private static bool Bind()
	{
		_tried.SetValue(null, true);
		_ready.SetValue(null, !_failed);
		return false;
	}

	private static bool ReadMask(Character c, ref int __result)
	{
		__result = 0;
		if ((Object)(object)c == (Object)null || _failed)
		{
			return false;
		}
		try
		{
			__result = Intern(Convert.ToInt64(_on.Invoke(null, new object[1] { c })));
		}
		catch (Exception e)
		{
			Fail(e);
		}
		return false;
	}

	private static bool ParseList(string list, ref int mask, ref int __result)
	{
		mask = 0;
		__result = 0;
		if (string.IsNullOrEmpty(list))
		{
			return false;
		}
		long num = 0L;
		string[] array = list.Split(',', ';', ' ');
		string[] array2 = array;
		foreach (string text in array2)
		{
			string text2 = text.Trim();
			if (text2.Length == 0)
			{
				continue;
			}
			try
			{
				long num2 = Convert.ToInt64(Enum.Parse(_modType, text2, ignoreCase: true));
				if (num2 != 0 && (num2 & (num2 - 1)) == 0 && (num & num2) == 0)
				{
					num |= num2;
					__result++;
				}
			}
			catch (Exception)
			{
			}
		}
		mask = Intern(num);
		return false;
	}

	private static bool Sprites(int mask, Sprite[] buf, ref int total, ref int __result)
	{
		total = 0;
		__result = 0;
		if (mask <= 0 || mask >= Masks.Count || buf == null || _failed)
		{
			return false;
		}
		int num = 0;
		try
		{
			num = (((int)_iconSet.Invoke(null, null) != 0) ? 1 : 0);
		}
		catch (Exception)
		{
		}
		if (!Cache[num].TryGetValue(mask, out var value) || Destroyed(value))
		{
			value = Build(Masks[mask], num == 0);
			if (value.Length > 0)
			{
				Cache[num][mask] = value;
			}
		}
		total = value.Length;
		int num2 = Math.Min(value.Length, buf.Length);
		for (int i = 0; i < num2; i++)
		{
			buf[i] = value[i];
		}
		__result = num2;
		return false;
	}

	private static bool Destroyed(Sprite[] list)
	{
		foreach (Sprite val in list)
		{
			if ((Object)(object)val == (Object)null)
			{
				return true;
			}
		}
		return false;
	}

	private static Sprite[] Build(long mask, bool own)
	{
		List<Sprite> list = new List<Sprite>();
		try
		{
			Dictionary<string, int> dictionary = _byGroupField.GetValue(null) as Dictionary<string, int>;
			if (!(_each.Invoke(null, new object[1] { Enum.ToObject(_modType, mask) }) is IEnumerable enumerable))
			{
				return list.ToArray();
			}
			foreach (object item in enumerable)
			{
				if (list.Count < 32)
				{
					Sprite val = null;
					if (own && _getPov != null)
					{
						object? obj = _getPov.Invoke(null, new object[1] { item.ToString() });
						val = (Sprite)((obj is Sprite) ? obj : null);
					}
					string text = (((Object)(object)val == (Object)null) ? (_icon.Invoke(null, new object[1] { item }) as string) : null);
					if ((Object)(object)val == (Object)null && _maybe != null && !string.IsNullOrEmpty(text))
					{
						object? obj2 = _maybe.Invoke(null, new object[1] { text });
						val = (Sprite)((obj2 is Sprite) ? obj2 : null);
					}
					if ((Object)(object)val == (Object)null && dictionary != null && !string.IsNullOrEmpty(text) && dictionary.TryGetValue(text, out var value))
					{
						object? obj3 = _tile.Invoke(null, new object[1] { value });
						val = (Sprite)((obj3 is Sprite) ? obj3 : null);
					}
					if ((Object)(object)val != (Object)null)
					{
						list.Add(val);
					}
					continue;
				}
				break;
			}
			if (!_told && list.Count > 0)
			{
				_told = true;
				_log.LogInfo((object)string.Concat("HP Barheim draws Path of Valheiman modifier icons (first: ", Enum.ToObject(_modType, mask), ")."));
			}
		}
		catch (Exception e)
		{
			Fail(e);
		}
		return list.ToArray();
	}

	private static void Fail(Exception e)
	{
		if (!_failed)
		{
			_failed = true;
			_ready.SetValue(null, false);
			_log.LogWarning((object)("HP Barheim's Path of Valheiman modifier icons are switched off after an error: " + (e.InnerException ?? e).Message));
		}
	}
}
internal static class BaseProperties
{
	internal const string SouthsilGuid = "southsil.SouthsilArmor";

	internal const string WarriorGloryGuid = "Dreanegade.Warrior_Glory";

	internal const string TraderGuid = "p0kahontazz.immersivetrader";

	private static List<FieldInfo> _traderSets;

	private static readonly Regex TraderPiece;

	private static readonly string[] TraderSlots;

	private static readonly int[][] Ranges;

	private static readonly string[] BiomeNames;

	private static readonly string[] Bows;

	private static readonly string[] MediumChest;

	private static readonly string[] MediumLegs;

	private static readonly string[] MediumHelmet;

	private static readonly string[] HeavyChest;

	private static readonly string[] HeavyLegs;

	private static readonly string[] HeavyHelmet;

	private static readonly string[] MageChest;

	private static readonly string[] MageLegs;

	private static readonly string[] MageHelmet;

	private static readonly string[] Capes;

	private static readonly string[] Trinkets;

	private static readonly string[] QuiverKinds;

	private static readonly Regex SetPiece;

	private static readonly Dictionary<string, object> QuiverDefs;

	private static readonly Dictionary<string, int[]> QuiverSpans;

	private static HashSet<string> _registered;

	private static readonly Dictionary<string, string> Owners;

	private static readonly Dictionary<string, string> Overrides;

	private static bool _quiversBroken;

	private static bool _registryBroken;

	private static readonly Dictionary<string, int> Materials;

	private static ConfigEntry<bool> _enabled;

	private static ConfigEntry<bool> _allMods;

	private static ConfigEntry<string> _overrides;

	private static ManualLogSource _log;

	private static MethodInfo _inherit;

	private static MethodInfo _register;

	private static IDictionary _bases;

	private static IDictionary _bySharedData;

	private static Type _defs;

	private static readonly HashSet<string> Done;

	private static readonly HashSet<string> Unknown;

	private static readonly Dictionary<string, int> DonorBiome;

	private static Dictionary<string, List<Recipe>> _recipes;

	private static Dictionary<string, int> _memo;

	private static bool _jotunnBroken;

	private static Type _jotunn;

	private static int _lastBiome;

	static BaseProperties()
	{
		TraderPiece = new Regex("^(IT_[A-Za-z]+?)(Helmet|Helm|Hood|Hat|Chest|Jerkin|Legs)$");
		TraderSlots = new string[7] { "Helmet", "Helm", "Hood", "Hat", "Chest", "Jerkin", "Legs" };
		Ranges = new int[9][]
		{
			null,
			new int[2] { 5, 8 },
			new int[2] { 6, 10 },
			new int[2] { 8, 12 },
			new int[2] { 9, 15 },
			new int[2] { 11, 18 },
			new int[2] { 12, 20 },
			new int[2] { 15, 24 },
			new int[2] { 17, 28 }
		};
		BiomeNames = new string[9] { "?", "Meadows", "Black Forest", "Swamp", "Mountain", "Plains", "Mistlands", "Ashlands", "Deep North" };
		Bows = new string[9] { null, "Bow", "BowFineWood", "BowHuntsman", "BowDraugrFang", "BowDraugrFang", "BowSpineSnap", "BowAshlands", "BowGold" };
		MediumChest = new string[9] { null, "ArmorLeatherChest", "ArmorTrollLeatherChest", "ArmorRootChest", "ArmorWolfChest", "ArmorLoxChest", "ArmorCarapaceChest", "ArmorAshlandsMediumChest", "ArmorDeepNorthMediumChest" };
		MediumLegs = new string[9] { null, "ArmorLeatherLegs", "ArmorTrollLeatherLegs", "ArmorRootLegs", "ArmorWolfLegs", "ArmorLoxLegs", "ArmorCarapaceLegs", "ArmorAshlandsMediumlegs", "ArmorDeepNorthMediumlegs" };
		MediumHelmet = new string[9] { null, "HelmetLeather", "HelmetTrollLeather", "HelmetRoot", "HelmetDrake", "HelmetLox", "HelmetCarapace", "HelmetAshlandsMediumHood", "HelmetDNMediumHood" };
		HeavyChest = new string[9] { null, "ArmorLeatherChest", "ArmorBronzeChest", "ArmorIronChest", "ArmorWolfChest", "ArmorPaddedCuirass", "ArmorCarapaceChest", "ArmorFlametalChest", "ArmorDeepNorthHeavyChest" };
		HeavyLegs = new string[9] { null, "ArmorLeatherLegs", "ArmorBronzeLegs", "ArmorIronLegs", "ArmorWolfLegs", "ArmorPaddedGreaves", "ArmorCarapaceLegs", "ArmorFlametalLegs", "ArmorDeepNorthHeavylegs" };
		HeavyHelmet = new string[9] { null, "HelmetLeather", "HelmetBronze", "HelmetIron", "HelmetDrake", "HelmetPadded", "HelmetCarapace", "HelmetFlametal", "HelmetDNHeavy" };
		MageChest = new string[9] { null, "ArmorRagsChest", null, null, null, null, "ArmorMageChest", "ArmorMageChest_Ashlands", "ArmorDeepNorthMageChest" };
		MageLegs = new string[9] { null, "ArmorRagsLegs", null, null, null, null, "ArmorMageLegs", "ArmorMageLegs_Ashlands", "ArmorDeepNorthMagelegs" };
		MageHelmet = new string[9] { null, null, null, null, null, null, "HelmetMage", "HelmetMage_Ashlands", "HelmetDNMage" };
		Capes = new string[9] { null, "CapeDeerHide", "CapeTrollHide", "CapeTrollHide", "CapeWolf", "CapeLinen", "CapeFeather", "CapeAsksvin", "CapeDeepNorth" };
		Trinkets = new string[9] { null, "TrinketBronzeStamina", "TrinketBronzeStamina", "TrinketIronStamina", "TrinketSilverDamage", "TrinketBlackStamina", "TrinketScaleStaminaDamage", "TrinketFlametalStaminaHealth", "TrinketBloodGoldStamina" };
		QuiverKinds = new string[9] { null, "PoV_QuiverLeather", "PoV_QuiverTroll", "PoV_QuiverTroll", "PoV_QuiverSilver", "PoV_QuiverSilver", "PoV_QuiverMist", "PoV_QuiverAsh", "PoV_QuiverAsh" };
		SetPiece = new Regex("^(.+?)(Quiver|Trinket|Belt|Bag|Cape|Utility)_DO$");
		QuiverDefs = new Dictionary<string, object>();
		QuiverSpans = new Dictionary<string, int[]>();
		Owners = new Dictionary<string, string>();
		Overrides = new Dictionary<string, string>(StringComparer.Ordinal);
		Materials = new Dictionary<string, int>();
		Done = new HashSet<string>();
		Unknown = new HashSet<string>();
		DonorBiome = new Dictionary<string, int>();
		Add(1, "Wood", "Stone", "Flint", "LeatherScraps", "DeerHide", "Resin", "Feathers", "Raspberry", "Mushroom", "Honey", "Dandelion", "HardAntler", "TrophyEikthyr", "TrophyDeer", "TrophyBoar", "TrophyNeck");
		Add(2, "Copper", "CopperOre", "CopperScrap", "Tin", "TinOre", "Bronze", "BronzeNails", "RoundLog", "FineWood", "TrollHide", "GreydwarfEye", "AncientSeed", "SurtlingCore", "BoneFragments", "Thistle", "Blueberries", "CryptKey", "Coal", "Chitin", "TrophyTheElder", "TrophyGreydwarf", "TrophyGreydwarfBrute", "TrophyGreydwarfShaman", "TrophyTroll", "TrophySkeleton", "TrophyFrostTroll");
		Add(3, "Iron", "IronScrap", "IronOre", "IronNails", "Chain", "ElderBark", "Guck", "Bloodbag", "Root", "WitheredBone", "Ooze", "Entrails", "Wishbone", "SerpentScale", "TrophyBonemass", "TrophyDraugr", "TrophyDraugrElite", "TrophyAbomination", "TrophyBlob", "TrophyLeech", "TrophySerpent", "TrophyWraith");
		Add(4, "Silver", "SilverOre", "WolfPelt", "WolfFang", "WolfClaw", "Obsidian", "FreezeGland", "DragonTear", "Crystal", "JuteRed", "FenrisHair", "FenrisClaw", "DragonEgg", "Onion", "TrophyDragonQueen", "TrophyWolf", "TrophyCultist", "TrophyHatchling", "TrophySGolem", "TrophyUlv", "TrophyFenring");
		Add(5, "BlackMetal", "BlackMetalScrap", "LinenThread", "Flax", "Barley", "Needle", "LoxPelt", "Tar", "GoblinTotem", "YagluthDrop", "Cloudberry", "TrophyGoblinKing", "TrophyGoblin", "TrophyGoblinBrute", "TrophyGoblinShaman", "TrophyLox", "TrophyDeathsquito", "TrophyGrowth");
		Add(6, "Eitr", "Carapace", "BlackMarble", "YggdrasilWood", "Sap", "ScaleHide", "Mandible", "BlackCore", "RoyalJelly", "DvergrNeedle", "JuteBlue", "Softtissue", "Bilebag", "Wisp", "GiantBloodSack", "QueenDrop", "DvergrKeyFragment", "MechanicalSpring", "TrophySeekerQueen", "TrophySeeker", "TrophySeekerBrute", "TrophyTick", "TrophyGjall", "TrophyDvergr", "TrophyHare");
		Add(7, "Flametal", "FlametalNew", "FlametalOre", "FlametalOreNew", "AskHide", "AskBladder", "CharredBone", "CharcoalResin", "MoltenCore", "Grausten", "MorgenSinew", "MorgenHeart", "AsksvinCarrionNeck", "AsksvinCarrionPelvic", "AsksvinCarrionRibcage", "AsksvinCarrionSkull", "BellFragment", "CelestialFeather", "Blackwood", "ProustitePowder", "SulfurStone", "GemstoneRed", "GemstoneBlue", "GemstoneGreen", "FaderDrop", "BonemawSerpentScale", "BonemawSerpentTooth", "CharredCogwheel", "DyrnwynBladeFragment", "DyrnwynHiltFragment", "DyrnwynTipFragment", "Fiddleheadfern", "Vineberry", "VoltureEgg", "TrophyFader", "TrophyCharredMelee", "TrophyCharredArcher", "TrophyCharredMage", "TrophyMorgen", "TrophyAsksvin", "TrophyVolture", "TrophyFallenValkyrie", "TrophyBonemawSerpent");
		string[][] array = new string[12][]
		{
			Bows, MediumChest, MediumLegs, MediumHelmet, HeavyChest, HeavyLegs, HeavyHelmet, MageChest, MageLegs, MageHelmet,
			Capes, Trinkets
		};
		string[][] array2 = array;
		foreach (string[] array3 in array2)
		{
			for (int j = 1; j < array3.Length; j++)
			{
				if (array3[j] != null && !DonorBiome.ContainsKey(array3[j]))
				{
					DonorBiome[array3[j]] = j;
				}
			}
		}
	}

	private static void Add(int biome, params string[] names)
	{
		foreach (string key in names)
		{
			Materials[key] = biome;
		}
	}

	internal static void Apply(Harmony harmony, ConfigFile config, ManualLogSource log)
	{
		//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0201: Expected O, but got Unknown
		_log = log;
		_enabled = config.Bind<bool>("Path of Valheiman", "Base properties for modded gear", true, "Gives Hunter Legacy, Valheim Armory and Southsil Armor weapons, armour, capes, bags and trinkets a Path of Valheiman base property like the vanilla item of the same kind from the same biome (for example a Swamp bow gets the Huntsman bow's arrow chain chance). Hunter Legacy quivers get the base property of the Path of Valheiman quiver of their biome. Warrior's Glory and ImmersiveTrader gear is covered too; every piece of an ImmersiveTrader armour set gets the same biome. Off: they have none, as before. Restart the game after a change.");
		_allMods = config.Bind<bool>("Path of Valheiman", "Base properties for all mods", true, "Also gives the weapons, armour, shields, capes and trinkets of every other mod (items registered through ItemManager or Jotunn) a base property the same way, when Path of Valheiman has none for them. Items Path of Valheiman defines are never changed. Off: only Hunter Legacy, Valheim Armory, Southsil Armor, Warrior's Glory and ImmersiveTrader. Restart the game after a change.");
		_overrides = config.Bind<string>("Path of Valheiman", "Base property overrides", "", "Per item choice that wins over the automatic one, as PrefabName=VanillaPrefab, separated by commas. The item copies the base property of that vanilla item (for example ScytheHeavyIron_DO=Battleaxe). PrefabName=none gives the item none. The game log lists the prefab names and the donor picked for each item. Restart the game after a change.");
		if (_enabled.Value)
		{
			ReadOverrides(_overrides.Value);
			Type type = AccessTools.TypeByName("PassiveTree.Implicits");
			Type type2 = AccessTools.TypeByName("PassiveTree.Implicits+Def");
			_defs = AccessTools.TypeByName("PassiveTree.BaseImplicits");
			_inherit = ((type == null) ? null : AccessTools.Method(type, "Inherit", new Type[2]
			{
				typeof(string),
				typeof(string)
			}, (Type[])null));
			_register = ((type == null || type2 == null) ? null : AccessTools.Method(type, "Register", new Type[4]
			{
				typeof(string),
				type2,
				typeof(int),
				typeof(int)
			}, (Type[])null));
			FieldInfo fieldInfo = ((type == null) ? null : AccessTools.Field(type, "bases"));
			FieldInfo fieldInfo2 = ((type == null) ? null : AccessTools.Field(type, "bySharedData"));
			_bases = ((fieldInfo == null) ? null : (fieldInfo.GetValue(null) as IDictionary));
			_bySharedData = ((fieldInfo2 == null) ? null : (fieldInfo2.GetValue(null) as IDictionary));
			if (_inherit == null || _register == null || _bases == null || _defs == null)
			{
				log.LogError((object)"Path of Valheiman's base properties (Implicits) were not found. Modded gear keeps no base property.");
				return;
			}
			HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeof(BaseProperties), "Run", (Type[])null, (Type[])null));
			val.priority = 0;
			HarmonyMethod val2 = val;
			harmony.Patch((MethodBase)AccessTools.Method(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(ObjectDB), "CopyOtherDB", (Type[])null, (Type[])null), (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Player), "OnSpawned", (Type[])null, (Type[])null), (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			log.LogInfo((object)("Modded gear gets Path of Valheiman base properties ([Path of Valheiman] Base properties for modded gear, all mods: " + _allMods.Value + ", overrides: " + Overrides.Count + ")."));
		}
	}

	private static void ReadOverrides(string text)
	{
		Overrides.Clear();
		if (string.IsNullOrEmpty(text))
		{
			return;
		}
		string[] array = text.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
		string[] array2 = array;
		foreach (string text2 in array2)
		{
			string[] array3 = text2.Split(new char[1] { '=' });
			if (array3.Length != 2 || array3[0].Trim().Length == 0 || array3[1].Trim().Length == 0)
			{
				_log.LogWarning((object)("Base property override \"" + text2.Trim() + "\" is not PrefabName=VanillaPrefab; it is ignored."));
			}
			else
			{
				Overrides[array3[0].Trim()] = array3[1].Trim();
			}
		}
	}

	private static bool GiveOverride(string name)
	{
		string text = Overrides[name];
		if (string.Equals(text, "none", StringComparison.OrdinalIgnoreCase))
		{
			if (Unknown.Add(name))
			{
				_log.LogInfo((object)("Base property: " + name + " gets none ([Base property overrides])."));
			}
			return true;
		}
		if (!_bases.Contains(text) || Modded(text))
		{
			if (Unknown.Add(name))
			{
				_log.LogWarning((object)("Base property override " + name + "=" + text + ": " + text + " has no Path of Valheiman base property; the override is ignored."));
			}
			return false;
		}
		_inherit.Invoke(null, new object[2] { name, text });
		_log.LogInfo((object)("Base property: " + name + " like " + text + " ([Base property overrides]): " + Describe(name)));
		return true;
	}

	private static void Run()
	{
		ObjectDB instance = ObjectDB.instance;
		if ((Object)(object)instance == (Object)null || instance.m_items == null || instance.m_items.Count == 0 || ((Object)(object)ZNetScene.instance == (Object)null && (Object)(object)Player.m_localPlayer == (Object)null))
		{
			return;
		}
		try
		{
			_inherit.Invoke(null, new object[2] { "__buminfixes", null });
			_recipes = null;
			_memo = new Dictionary<string, int>();
			LoadRegistry();
			int num = 0;
			foreach (GameObject item in instance.m_items)
			{
				if (!((Object)(object)item == (Object)null) && !Done.Contains(((Object)item).name) && !_bases.Contains(((Object)item).name) && (Modded(((Object)item).name) || Overrides.ContainsKey(((Object)item).name)))
				{
					ItemDrop component = item.GetComponent<ItemDrop>();
					if (!((Object)(object)component == (Object)null) && component.m_itemData != null && component.m_itemData.m_shared != null && (Overrides.ContainsKey(((Object)item).name) ? GiveOverride(((Object)item).name) : (((Object)item).name.ToLowerInvariant().Contains("quiver") ? GiveQuiver(((Object)item).name) : Give(((Object)item).name, component.m_itemData.m_shared))))
					{
						Done.Add(((Object)item).name);
						num++;
					}
				}
			}
			if (num > 0)
			{
				if (_bySharedData != null)
				{
					_bySharedData.Clear();
				}
				_log.LogInfo((object)("Base properties given to " + num + " modded items (all so far by mod: " + Summary() + ")."));
			}
		}
		catch (Exception ex)
		{
			_log.LogError((object)("Could not give modded gear base properties: " + ex));
		}
	}

	private static bool Modded(string name)
	{
		if (!name.EndsWith("_DO", StringComparison.Ordinal) && (!name.StartsWith("VA", StringComparison.Ordinal) || name.Length <= 2))
		{
			if (_registered != null)
			{
				return _registered.Contains(name);
			}
			return false;
		}
		return true;
	}

	private static string Summary()
	{
		Dictionary<string, int> dictionary = new Dictionary<string, int>();
		foreach (string item in Done)
		{
			if (!Owners.TryGetValue(item, out var value))
			{
				value = ((!item.EndsWith("_DO", StringComparison.Ordinal)) ? (item.StartsWith("VA", StringComparison.Ordinal) ? "Valheim Armory" : "override") : "Dreanegade");
			}
			dictionary.TryGetValue(value, out var value2);
			dictionary[value] = value2 + 1;
		}
		List<string> list = new List<string>();
		foreach (KeyValuePair<string, int> item2 in dictionary)
		{
			list.Add(item2.Key + " " + item2.Value);
		}
		return string.Join(", ", list.ToArray());
	}

	private static bool Known(string guid)
	{
		if (!(guid == "southsil.SouthsilArmor") && !(guid == "p0kahontazz.immersivetrader"))
		{
			return guid == "Dreanegade.Warrior_Glory";
		}
		return true;
	}

	private static void AddTraderSets(Assembly assembly, string owner)
	{
		if (_traderSets == null)
		{
			_traderSets = new List<FieldInfo>();
			Type[] types;
			try
			{
				types = assembly.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				types = ex.Types;
			}
			Type[] array = types;
			foreach (Type type in array)
			{
				if (!(type == null) && type.Namespace == "ImmersiveTrader.Armor")
				{
					FieldInfo field = type.GetField("built", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					if (field != null && typeof(IDictionary).IsAssignableFrom(field.FieldType))
					{
						_traderSets.Add(field);
					}
				}
			}
			_log.LogInfo((object)("ImmersiveTrader: " + _traderSets.Count + " armour sets outside Jotunn are read for base properties."));
		}
		foreach (FieldInfo traderSet in _traderSets)
		{
			if (!(traderSet.GetValue(null) is IDictionary dictionary))
			{
				continue;
			}
			foreach (object value in dictionary.Values)
			{
				GameObject val = (GameObject)((value is GameObject) ? value : null);
				if ((Object)(object)val != (Object)null && (Object)(object)val.GetComponent<ItemDrop>() != (Object)null && _registered.Add(((Object)val).name))
				{
					Owners[((Object)val).name] = owner;
				}
			}
		}
	}

	private static int TraderSetBiome(string name, int biome)
	{
		Match match = TraderPiece.Match(name);
		if (!match.Success || NameHint(name) > 0)
		{
			return biome;
		}
		string[] traderSlots = TraderSlots;
		foreach (string text in traderSlots)
		{
			string text2 = match.Groups[1].Value + text;
			if (text2 == name)
			{
				continue;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text2);
			ItemDrop val = (((Object)(object)itemPrefab == (Object)null) ? null : itemPrefab.GetComponent<ItemDrop>());
			if (!((Object)(object)val == (Object)null) && val.m_itemData != null && val.m_itemData.m_shared != null)
			{
				int num = BiomeOf(text2, 0);
				if (num <= 0)
				{
					num = NearestBiome(text2, val.m_itemData.m_shared);
				}
				biome = Math.Max(biome, num);
			}
		}
		return biome;
	}

	private static void LoadRegistry()
	{
		_registered = new HashSet<string>();
		Owners.Clear();
		if (_registryBroken)
		{
			return;
		}
		try
		{
			Assembly assembly = _defs.Assembly;
			HashSet<string> hashSet = new HashSet<string>();
			HashSet<Assembly> hashSet2 = new HashSet<Assembly>();
			foreach (PluginInfo value in Chainloader.PluginInfos.Values)
			{
				if (value == null || (Object)(object)value.Instance == (Object)null || value.Metadata == null)
				{
					continue;
				}
				Assembly assembly2 = ((object)value.Instance).GetType().Assembly;
				if (assembly2 == assembly || assembly2 == typeof(BaseProperties).Assembly)
				{
					hashSet.Add(value.Metadata.GUID);
				}
				else
				{
					if (!hashSet2.Add(assembly2) || (!_allMods.Value && !Known(value.Metadata.GUID)))
					{
						continue;
					}
					if (value.Metadata.GUID == "p0kahontazz.immersivetrader")
					{
						AddTraderSets(assembly2, value.Metadata.Name);
					}
					Type type;
					try
					{
						type = assembly2.GetType("ItemManager.Item", throwOnError: false);
					}
					catch (Exception)
					{
						continue;
					}
					FieldInfo fieldInfo = ((type == null) ? null : AccessTools.Field(type, "registeredItems"));
					FieldInfo fieldInfo2 = ((type == null) ? null : AccessTools.Field(type, "Prefab"));
					IEnumerable enumerable = ((fieldInfo == null || !fieldInfo.IsStatic) ? null : (fieldInfo.GetValue(null) as IEnumerable));
					if (enumerable == null || fieldInfo2 == null)
					{
						continue;
					}
					foreach (object item in enumerable)
					{
						GameObject val = (GameObject)((item == null) ? null : /*isinst with value type is only supported in some contexts*/);
						if ((Object)(object)val != (Object)null && _registered.Add(((Object)val).name))
						{
							Owners[((Object)val).name] = value.Metadata.Name;
						}
					}
				}
			}
			if (!_jotunnBroken)
			{
				LoadJotunn(hashSet);
			}
		}
		catch (Exception ex2)
		{
			_registryBroken = true;
			_log.LogError((object)("The item lists of other mods could not be read; only Hunter Legacy and Valheim Armory names are covered: " + ex2));
		}
	}

	private static void LoadJotunn(HashSet<string> skip)
	{
		try
		{
			if (_jotunn == null)
			{
				if (!Chainloader.PluginInfos.TryGetValue("com.jotunn.jotunn", out var value) || (Object)(object)value.Instance == (Object)null)
				{
					return;
				}
				_jotunn = ((object)value.Instance).GetType().Assembly.GetType("Jotunn.Managers.ItemManager", throwOnError: false);
				if (_jotunn == null)
				{
					return;
				}
			}
			PropertyInfo propertyInfo = AccessTools.Property(_jotunn, "Instance");
			FieldInfo fieldInfo = AccessTools.Field(_jotunn, "Items");
			object obj = ((propertyInfo == null) ? null : propertyInfo.GetValue(null, null));
			IDictionary dictionary = ((obj == null || fieldInfo == null) ? null : (fieldInfo.GetValue(obj) as IDictionary));
			if (dictionary == null)
			{
				return;
			}
			PropertyInfo propertyInfo2 = null;
			PropertyInfo propertyInfo3 = null;
			foreach (DictionaryEntry item in dictionary)
			{
				object value2 = item.Value;
				if (value2 == null)
				{
					continue;
				}
				if (propertyInfo2 == null)
				{
					propertyInfo2 = AccessTools.Property(value2.GetType(), "ItemPrefab");
					propertyInfo3 = AccessTools.Property(value2.GetType(), "SourceMod");
					if (propertyInfo2 == null)
					{
						throw new MissingMemberException("CustomItem.ItemPrefab");
					}
				}
				object? value3 = propertyInfo2.GetValue(value2, null);
				GameObject val = (GameObject)((value3 is GameObject) ? value3 : null);
				BepInPlugin val2 = (BepInPlugin)((propertyInfo3 == null) ? null : /*isinst with value type is only supported in some contexts*/);
				if ((_allMods.Value || (val2 != null && Known(val2.GUID))) && !((Object)(object)val == (Object)null) && (val2 == null || !skip.Contains(val2.GUID)) && _registered.Add(((Object)val).name))
				{
					Owners[((Object)val).name] = ((val2 == null) ? "Jotunn" : val2.Name);
				}
			}
		}
		catch (Exception ex)
		{
			_jotunnBroken = true;
			_log.LogError((object)("Jotunn's item list could not be read; Jotunn mods keep no base property unless named above: " + ex));
		}
	}

	private static bool GiveQuiver(string name)
	{
		int num = BiomeOf(name, 0);
		if (num <= 0)
		{
			num = SetBiome(name);
		}
		if (num <= 0)
		{
			Skip(name, "its biome is unknown");
			return false;
		}
		num = Math.Min(8, num);
		string text = QuiverKinds[num];
		object obj = QuiverDef(text);
		if (obj == null)
		{
			return false;
		}
		int[] array = QuiverSpans[text];
		_register.Invoke(null, new object[4]
		{
			name,
			obj,
			array[0],
			array[1]
		});
		_log.LogInfo((object)("Base property: " + name + " (" + BiomeNames[num] + ") like " + text + ": " + Describe(name)));
		return true;
	}

	private static object QuiverDef(string id)
	{
		if (QuiverDefs.TryGetValue(id, out var value))
		{
			return value;
		}
		if (_quiversBroken)
		{
			return null;
		}
		try
		{
			Type type = AccessTools.TypeByName("PassiveTree.Quivers");
			Type type2 = AccessTools.TypeByName("PassiveTree.Quivers+Kind");
			Type type3 = AccessTools.TypeByName("PassiveTree.Implicits+Def");
			Array array = ((type == null) ? null : (AccessTools.Field(type, "Kinds").GetValue(null) as Array));
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "ForAmmo", (Type[])null, (Type[])null));
			FieldInfo fieldInfo = ((type3 == null) ? null : AccessTools.Field(type3, "Grants"));
			if (array == null || type2 == null || methodInfo == null || fieldInfo == null || AccessTools.Field(type2, "Grants").FieldType != fieldInfo.FieldType)
			{
				throw new MissingMemberException("Quivers.Kinds, Quivers.ForAmmo or Implicits.Def.Grants");
			}
			object obj = null;
			foreach (object item in array)
			{
				if (item != null && AccessTools.Field(type2, "Id").GetValue(item) as string == id)
				{
					obj = item;
				}
			}
			if (obj == null)
			{
				throw new MissingMemberException("Path of Valheiman quiver " + id);
			}
			object value2 = AccessTools.Field(type2, "Implicit").GetValue(obj);
			Array array2 = AccessTools.Field(type2, "Range").GetValue(obj) as Array;
			object value3 = array2.GetValue(0);
			object value4 = array2.GetValue(array2.Length - 1);
			int num = (int)value3.GetType().GetField("Item1").GetValue(value3);
			int num2 = (int)value4.GetType().GetField("Item2").GetValue(value4);
			Type returnType = methodInfo.ReturnType;
			Delegate obj2 = Delegate.CreateDelegate(typeof(Func<, >).MakeGenericType(returnType, returnType), methodInfo);
			object value5 = AccessTools.Method(typeof(BaseProperties), "Chain", (Type[])null, (Type[])null).MakeGenericMethod(returnType).Invoke(null, new object[2]
			{
				AccessTools.Field(type2, "Grants").GetValue(obj),
				obj2
			});
			object obj3 = Activator.CreateInstance(type3);
			AccessTools.Field(type3, "Id").SetValue(obj3, "buminfixes_" + id);
			AccessTools.Field(type3, "Text").SetValue(obj3, AccessTools.Field(type3, "Text").GetValue(value2));
			AccessTools.Field(type3, "Min").SetValue(obj3, num);
			AccessTools.Field(type3, "Max").SetValue(obj3, num2);
			fieldInfo.SetValue(obj3, value5);
			QuiverDefs[id] = obj3;
			QuiverSpans[id] = new int[2] { num, num2 };
			return obj3;
		}
		catch (Exception ex)
		{
			_quiversBroken = true;
			_log.LogError((object)("Path of Valheiman's quiver base properties could not be read. Hunter Legacy quivers keep none: " + ex));
			return null;
		}
	}

	private static Func<int, T> Chain<T>(Func<int, T> grants, Func<T, T> ammo)
	{
		return (int v) => ammo(grants(v));
	}

	private static int SetBiome(string name)
	{
		Match match = SetPiece.Match(name);
		if (!match.Success)
		{
			return 0;
		}
		string[] array = new string[3] { "Chest", "Legs", "Helmet" };
		string[] array2 = array;
		foreach (string text in array2)
		{
			string text2 = match.Groups[1].Value + text + "_DO";
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text2);
			ItemDrop val = (((Object)(object)itemPrefab == (Object)null) ? null : itemPrefab.GetComponent<ItemDrop>());
			if (!((Object)(object)val == (Object)null) && val.m_itemData != null && val.m_itemData.m_shared != null)
			{
				int num = BiomeOf(text2, 0);
				if (num <= 0)
				{
					num = NearestBiome(text2, val.m_itemData.m_shared);
				}
				if (num > 0)
				{
					return num;
				}
			}
		}
		return 0;
	}

	private static void Skip(string name, string why)
	{
		if ((Object)(object)Player.m_localPlayer != (Object)null && Unknown.Add(name))
		{
			_log.LogInfo((object)("Base property: " + name + " skipped, " + why + "."));
		}
	}

	private static string FirstPresent(string[] table, int biome)
	{
		for (int num = Math.Min(biome, table.Length - 1); num >= 1; num--)
		{
			if (table[num] != null && _bases.Contains(table[num]))
			{
				return table[num];
			}
		}
		return null;
	}

	private static bool Give(string name, SharedData s)
	{
		if (!Plan(name, s, out var donor, out var family, out var min, out var max))
		{
			return false;
		}
		if (donor != null)
		{
			if (!_bases.Contains(donor))
			{
				return false;
			}
			_inherit.Invoke(null, new object[2] { name, donor });
			_log.LogInfo((object)("Base property: " + name + " (" + BiomeNames[_lastBiome] + ") like " + donor + ": " + Describe(name)));
			return true;
		}
		FieldInfo fieldInfo = AccessTools.Field(_defs, "D_" + family);
		object obj = ((fieldInfo == null) ? null : fieldInfo.GetValue(null));
		if (obj == null)
		{
			return false;
		}
		_register.Invoke(null, new object[4] { name, obj, min, max });
		_log.LogInfo((object)("Base property: " + name + " (" + BiomeNames[_lastBiome] + "): " + Describe(name)));
		return true;
	}

	private static string Describe(string name)
	{
		if (!(_bases[name] is IList { Count: not 0 } list))
		{
			return "?";
		}
		object obj = list[0];
		Type type = obj.GetType();
		object value = type.GetField("Item1").GetValue(obj);
		string text = ((value == null) ? null : (value.GetType().GetField("Text").GetValue(value) as string));
		object value2 = type.GetField("Item2").GetValue(obj);
		object value3 = type.GetField("Item3").GetValue(obj);
		return (text ?? "?").Replace("{0}", string.Concat(value2, "-", value3));
	}

	private static bool Plan(string name, SharedData s, out string donor, out string family, out int min, out int max)
	{
		//IL_000f: 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_003a: 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_0059: Invalid comparison between Unknown and I4
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Invalid comparison between Unknown and I4
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Invalid comparison between Unknown and I4
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Invalid comparison between Unknown and I4
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Invalid comparison between Unknown and I4
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Invalid comparison between Unknown and I4
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Invalid comparison between Unknown and I4
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Invalid comparison between Unknown and I4
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Invalid comparison between Unknown and I4
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Invalid comparison between Unknown and I4
		//IL_0136: 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_0163: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Invalid comparison between Unknown and I4
		//IL_016b: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Invalid comparison between Unknown and I4
		//IL_0219: Unknown result type (might be due to invalid IL or missing references)
		//IL_021c: Invalid comparison between Unknown and I4
		//IL_0252: Unknown result type (might be due to invalid IL or missing references)
		//IL_0257: Unknown result type (might be due to invalid IL or missing references)
		//IL_0259: Unknown result type (might be due to invalid IL or missing references)
		//IL_025c: Unknown result type (might be due to invalid IL or missing references)
		//IL_029a: Expected I4, but got Unknown
		//IL_04a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ee: Invalid comparison between Unknown and I4
		donor = null;
		family = null;
		min = 0;
		max = 0;
		ItemType itemType = s.m_itemType;
		string text = name.ToLowerInvariant();
		if (text.Contains("quiver"))
		{
			return false;
		}
		string[] array = null;
		if (text.Contains("trinket") || ((object)itemType).ToString() == "Trinket")
		{
			array = Trinkets;
		}
		bool flag = (int)itemType == 6 || (int)itemType == 7 || (int)itemType == 11 || (int)itemType == 17;
		bool flag2 = (int)itemType == 3 || (int)itemType == 14 || (int)itemType == 22 || (int)itemType == 4 || (int)itemType == 5 || (int)itemType == 9 || text.Contains("throwing") || text.Contains("shuriken");
		if (array == null && !flag && !flag2)
		{
			return false;
		}
		int num = BiomeOf(name, 0);
		if (num <= 0)
		{
			num = NearestBiome(name, s);
		}
		if (num <= 0)
		{
			num = SetBiome(name);
		}
		if (flag && name.StartsWith("IT_", StringComparison.Ordinal))
		{
			num = TraderSetBiome(name, num);
		}
		if (num <= 0)
		{
			Skip(name, "its biome is unknown");
			return false;
		}
		num = (_lastBiome = Math.Min(8, num));
		min = Ranges[num][0];
		max = Ranges[num][1];
		if (array != null || flag)
		{
			donor = ((array != null) ? FirstPresent(array, num) : ArmourDonor(itemType, s, num));
			if (donor == null)
			{
				Skip(name, "no Path of Valheiman item of its kind to copy");
			}
			return donor != null;
		}
		ItemType val = itemType;
		if ((int)val == 9)
		{
			string text2 = Element(s);
			family = text2 switch
			{
				"poison" => "poison_arrow", 
				"frost" => "frost_arrow", 
				"fire" => "fire_arrow", 
				_ => "stagger_buildup", 
			};
			int num2 = ((num > 3) ? ((num <= 5) ? 4 : 6) : 2);
			min = ((text2 == null) ? Ranges[num2][0] : 9);
			max = ((text2 == null) ? Ranges[num2][1] : 15);
			return true;
		}
		int num3 = (((int)val == 14 || (int)itemType == 22) ? 1 : 0);
		bool flag3 = (byte)num3 != 0;
		bool flag4 = text.Contains("dual") || text.Contains("_2h");
		SkillType skillType = s.m_skillType;
		switch (skillType - 1)
		{
		case 0:
			family = ((flag3 && !flag4) ? "attack_area" : "break_buildup");
			return true;
		case 1:
			family = "ailment_buildup";
			return true;
		case 2:
			family = ((flag3 && !flag4) ? "slam_area" : "stagger_buildup");
			return true;
		case 3:
			family = "stagger_buildup";
			return true;
		case 4:
			family = "bleed_buildup";
			return true;
		case 6:
			family = ((flag3 && !flag4) ? "break_buildup" : "bleed_buildup");
			return true;
		case 10:
			family = "attack_cost";
			return true;
		case 11:
			family = "tool_cost";
			return true;
		case 5:
		{
			string text4 = ((!text.Contains("buckler")) ? (text.Contains("tower") ? "block_cost" : "block_stamina") : "parry_stamina");
			family = text4;
			return true;
		}
		case 7:
			if (text.Contains("slingshot"))
			{
				family = "projectile_speed";
				return true;
			}
			donor = FirstPresent(Bows, num);
			return donor != null;
		case 13:
			if (num >= 8)
			{
				donor = "CrossbowGold";
			}
			else
			{
				switch (num)
				{
				case 7:
					donor = "CrossbowRipper";
					break;
				case 6:
					donor = "CrossbowArbalest";
					break;
				default:
					family = "bolt_stagger";
					break;
				}
			}
			return true;
		case 8:
		case 9:
		{
			string text5 = Element(s);
			if (text5 == null)
			{
				text5 = (text.Contains("fire") ? "fire" : ((text.Contains("ice") || text.Contains("frost")) ? "frost" : ((!text.Contains("poison")) ? (text.Contains("lightning") ? "lightning" : null) : "poison")));
			}
			family = text5 switch
			{
				"lightning" => "shock_buildup", 
				"poison" => "poison_buildup", 
				"frost" => "chill_buildup", 
				"fire" => "fire_area", 
				_ => "projectile_speed", 
			};
			return true;
		}
		default:
			if (!Enum.IsDefined(typeof(SkillType), s.m_skillType))
			{
				family = NamedFamily(text) ?? DamageFamily(s, flag3 && !flag4);
				if (family == null)
				{
					Skip(name, "its skill is the mod's own and it deals no damage to compare");
				}
				return family != null;
			}
			if ((int)itemType == 5)
			{
				string text3 = ((!text.Contains("buckler")) ? (text.Contains("tower") ? "block_cost" : "block_stamina") : "parry_stamina");
				family = text3;
				return true;
			}
			return false;
		}
	}

	private static string NamedFamily(string lower)
	{
		if (lower.Contains("throwing") || lower.Contains("shuriken"))
		{
			return "ailment_buildup";
		}
		if (lower.Contains("chakram"))
		{
			return "bleed_buildup";
		}
		if (!lower.Contains("scythe"))
		{
			return null;
		}
		return "attack_area";
	}

	private static string DamageFamily(SharedData s, bool two)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		DamageTypes damages = s.m_damages;
		if (damages.m_blunt > 0f && damages.m_blunt >= damages.m_slash && damages.m_blunt >= damages.m_pierce)
		{
			if (!two)
			{
				return "stagger_buildup";
			}
			return "slam_area";
		}
		if (damages.m_pierce > 0f && damages.m_pierce > damages.m_slash)
		{
			return "bleed_buildup";
		}
		if (damages.m_slash > 0f)
		{
			if (!two)
			{
				return "break_buildup";
			}
			return "attack_area";
		}
		return Element(s) switch
		{
			"lightning" => "shock_buildup", 
			"poison" => "poison_buildup", 
			"frost" => "chill_buildup", 
			"fire" => "fire_area", 
			_ => null, 
		};
	}

	private static string ArmourDonor(ItemType type, SharedData s, int biome)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0003: Invalid comparison between Unknown and I4
		//IL_0046: 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_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Invalid comparison between Unknown and I4
		//IL_00b9: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: Invalid comparison between Unknown and I4
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Invalid comparison between Unknown and I4
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Invalid comparison between Unknown and I4
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Invalid comparison between Unknown and I4
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Invalid comparison between Unknown and I4
		if ((int)type == 17)
		{
			if (!(s.m_eitrRegenModifier > 0f) || biome < 8 || !_bases.Contains("CapeDeepNorthMage"))
			{
				return FirstPresent(Capes, biome);
			}
			return "CapeDeepNorthMage";
		}
		string[] array2;
		if (s.m_eitrRegenModifier > 0f)
		{
			string[] array = (((int)type == 7) ? MageChest : (((int)type == 11) ? MageLegs : MageHelmet));
			array2 = array;
			if (array2[biome] != null && _bases.Contains(array2[biome]))
			{
				return array2[biome];
			}
		}
		if (s.m_movementModifier <= -0.04f)
		{
			string[] array3 = (((int)type == 7) ? HeavyChest : (((int)type == 11) ? HeavyLegs : HeavyHelmet));
			array2 = array3;
		}
		else
		{
			string[] array4 = (((int)type == 7) ? MediumChest : (((int)type == 11) ? MediumLegs : MediumHelmet));
			array2 = array4;
		}
		return FirstPresent(array2, biome);
	}

	private static string Element(SharedData s)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		DamageTypes damages = s.m_damages;
		float num = damages.m_damage + damages.m_blunt + damages.m_slash + damages.m_pierce;
		float best = 0f;
		string element = null;
		Pick(damages.m_fire, "fire", ref best, ref element);
		Pick(damages.m_frost, "frost", ref best, ref element);
		Pick(damages.m_poison, "poison", ref best, ref element);
		Pick(damages.m_lightning, "lightning", ref best, ref element);
		Pick(damages.m_spirit, "spirit", ref best, ref element);
		if (!(best > 0f) || !(best * 3f >= num))
		{
			return null;
		}
		return element;
	}

	private static void Pick(float value, string name, ref float best, ref string element)
	{
		if (value > best)
		{
			best = value;
			element = name;
		}
	}

	private static int NameHint(string name)
	{
		string text = name.ToLowerInvariant();
		if (text.Contains("deepnorth"))
		{
			return 8;
		}
		if (text.Contains("ashland"))
		{
			return 7;
		}
		if (text.Contains("mistland"))
		{
			return 6;
		}
		if (text.Contains("plains"))
		{
			return 5;
		}
		if (text.Contains("mountain"))
		{
			return 4;
		}
		if (text.Contains("swamp"))
		{
			return 3;
		}
		if (text.Contains("blackforest"))
		{
			return 2;
		}
		if (!text.Contains("meadows"))
		{
			return MetalHint(name, text);
		}
		return 1;
	}

	private static int MetalHint(string name, string lower)
	{
		if (!Modded(name))
		{
			return 0;
		}
		if (lower.Contains("flametal"))
		{
			return 7;
		}
		if (lower.Contains("blackmetal"))
		{
			return 5;
		}
		if (lower.Contains("silver"))
		{
			return 4;
		}
		if (lower.Contains("iron"))
		{
			return 3;
		}
		if (lower.Contains("bronze") || lower.Contains("copper"))
		{
			return 2;
		}
		return 0;
	}

	private static int VanillaBiome(string name)
	{
		if (DonorBiome.TryGetValue(name, out var value))
		{
			return value;
		}
		if (!(_bases[name] is IList { Count: not 0 } list))
		{
			return 0;
		}
		object obj = list[0];
		Type type = obj.GetType();
		int num = (int)type.GetField("Item2").GetValue(obj);
		int num2 = (int)type.GetField("Item3").GetValue(obj);
		for (int i = 1; i < Ranges.Length; i++)
		{
			if (Ranges[i][0] == num && Ranges[i][1] == num2)
			{
				return i;
			}
		}
		return 0;
	}

	private static int BiomeOf(string name, int depth)
	{
		if (_memo.TryGetValue(name, out var value))
		{
			return value;
		}
		value = NameHint(name);
		if (value == 0 && !Modded(name) && _bases.Contains(name))
		{
			value = VanillaBiome(name);
		}
		if (value == 0 && !Materials.TryGetValue(name, out value))
		{
			value = 0;
		}
		_memo[name] = value;
		if (value > 0 || depth > 5)
		{
			return value;
		}
		if (Recipes().TryGetValue(name, out var value2))
		{
			foreach (Recipe item in value2)
			{
				if (item.m_resources == null)
				{
					continue;
				}
				int num = 0;
				Requirement[] resources = item.m_resources;
				Requirement[] array = resources;
				foreach (Requirement val in array)
				{
					if (val != null && (Object)(object)val.m_resItem != (Object)null)
					{
						num = Math.Max(num, BiomeOf(((Object)((Component)val.m_resItem).gameObject).name, depth + 1));
					}
				}
				if (num > 0 && (value == 0 || num < value))
				{
					value = num;
				}
			}
		}
		_memo[name] = value;
		return value;
	}

	private static Dictionary<string, List<Recipe>> Recipes()
	{
		if (_recipes != null)
		{
			return _recipes;
		}
		_recipes = new Dictionary<string, List<Recipe>>();
		foreach (Recipe recipe in ObjectDB.instance.m_recipes)
		{
			if (!((Object)(object)recipe == (Object)null) && !((Object)(object)recipe.m_item == (Object)null) && recipe.m_enabled)
			{
				string name = ((Object)((Component)recipe.m_item).gameObject).name;
				if (!_recipes.TryGetValue(name, out var value))
				{
					List<Recipe> list = (_recipes[name] = new List<Recipe>());
					value = list;
				}
				value.Add(recipe);
			}
		}
		return _recipes;
	}

	private static int NearestBiome(string name, SharedData s)
	{
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
		float num = Stat(s);
		if (num <= 0f)
		{
			return 0;
		}
		float num2 = float.MaxValue;
		int result = 0;
		foreach (object key in _bases.Keys)
		{
			if (!(key is string text) || Modded(text))
			{
				continue;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text);
			ItemDrop val = (((Object)(object)itemPrefab == (Object)null) ? null : itemPrefab.GetComponent<ItemDrop>());
			if ((Object)(object)val == (Object)null || val.m_itemData == null || val.m_itemData.m_shared == null)
			{
				continue;
			}
			SharedData shared = val.m_itemData.m_shared;
			if (shared.m_itemType == s.m_itemType && shared.m_skillType == s.m_skillType)
			{
				int num3 = VanillaBiome(text);
				float num4 = Math.Abs(Stat(shared) - num);
				if (num3 > 0 && num4 < num2)
				{
					num2 = num4;
					result = num3;
				}
			}
		}
		return result;
	}

	private static float Stat(SharedData s)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Invalid comparison between Unknown and I4
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Invalid comparison between Unknown and I4
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Invalid comparison between Unknown and I4
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Invalid comparison between Unknown and I4
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Invalid comparison between Unknown and I4
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		if ((int)s.m_itemType == 6 || (int)s.m_itemType == 7 || (int)s.m_itemType == 11 || (int)s.m_itemType == 17)
		{
			return s.m_armor;
		}
		if ((int)s.m_itemType == 5)
		{
			return s.m_blockPower;
		}
		DamageTypes damages = s.m_damages;
		return damages.m_damage + damages.m_blunt + damages.m_slash + damages.m_pierce + damages.m_fire + damages.m_frost + damages.m_lightning + damages.m_poison + damages.m_spirit;
	}
}
internal static class BiomeGear
{
	internal enum BiomeSource
	{
		KillPlace,
		CreatureLevel
	}

	private const string Section = "PoV Biome Gear";

	private static readonly HashSet<string> KillSources = new HashSet<string> { "creature", "elite", "boss" };

	private static readonly HashSet<string> ChestSources = new HashSet<string> { "chest", "dungeon-chest" };

	private static readonly Biome[] Ladder = (Biome[])(object)new Biome[8]
	{
		(Biome)1,
		(Biome)8,
		(Biome)2,
		(Biome)4,
		(Biome)16,
		(Biome)512,
		(Biome)32,
		(Biome)64
	};

	private static readonly Dictionary<string, Biome> Names = new Dictionary<string, Biome>
	{
		{
			"meadows",
			(Biome)1
		},
		{
			"cayir",
			(Biome)1
		},
		{
			"blackforest",
			(Biome)8
		},
		{
			"forest",
			(Biome)8
		},
		{
			"karaorman",
			(Biome)8
		},
		{
			"swamp",
			(Biome)2
		},
		{
			"bataklik",
			(Biome)2
		},
		{
			"mountain",
			(Biome)4
		},
		{
			"mountains",
			(Biome)4
		},
		{
			"dag",
			(Biome)4
		},
		{
			"daglar",
			(Biome)4
		},
		{
			"plains",
			(Biome)16
		},
		{
			"ova",
			(Biome)16
		},
		{
			"ovalar",
			(Biome)16
		},
		{
			"mistlands",
			(Biome)512
		},
		{
			"sisli",
			(Biome)512
		},
		{
			"sislitopraklar",
			(Biome)512
		},
		{
			"sisdiyari",
			(Biome)512
		},
		{
			"ashlands",
			(Biome)32
		},
		{
			"kul",
			(Biome)32
		},
		{
			"kuldiyari",
			(Biome)32
		},
		{
			"kultopraklari",
			(Biome)32
		},
		{
			"deepnorth",
			(Biome)64
		},
		{
			"kuzey",
			(Biome)64
		},
		{
			"derinkuzey",
			(Biome)64
		}
	};

	private static ConfigEntry<bool> _enabled;

	private static ConfigEntry<BiomeSource> _from;

	private static ConfigEntry<bool> _chests;

	private static ConfigEntry<bool> _lower;

	private static ConfigEntry<string> _overrides;

	private static ConfigEntry<bool> _logDrops;

	private static ManualLogSource _log;

	private static FieldInfo _ctxSource;

	private static FieldInfo _ctxBiome;

	private static FieldInfo _ctxLevel;

	private static Func<string, int> _craftLevel;

	private static Func<int, Biome> _biomeAt;

	private static Func<Biome, int> _biomeLevel;

	private static readonly Dictionary<string, Biome> ItemBiomes = new Dictionary<string, Biome>();

	private static ObjectDB _itemBiomesOf;

	private static Dictionary<string, Biome> _overrideMap = new Dictionary<string, Biome>();

	private static string _overrideText;

	private static ObjectDB _tableOf;

	private static bool _warned;

	internal static void Apply(Harmony harmony, ConfigFile config, ManualLogSource log)
	{
		//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bf: Expected O, but got Unknown
		_log = log;
		_enabled = config.Bind<bool>("PoV Biome Gear", "Enabled", false, "Path of Valheiman equipment drops follow the biome: a creature drops only weapons, armour, shields and accessories of its biome (Meadows gear in the Meadows, Black Forest gear in the Black Forest, and so on). How often gear drops, its rarity and its properties stay Path of Valheiman's own; materials, food, currency, gems, rings from the ring roll and unique items are not changed. Each player rolls their own drops on their own computer, so this works for every player who has it on. Applies at once.");
		_from = config.Bind<BiomeSource>("PoV Biome Gear", "Biome from", BiomeSource.KillPlace, "KillPlace: the biome where the creature died, so a troll killed in the Meadows drops Meadows gear. CreatureLevel: the biome whose level band the creature's Path of Valheiman level falls in, so that troll drops Black Forest gear, a raid drops the gear of the biome it came from, and creatures near a biome's far edge after its boss can drop the next biome's gear. A kill at sea always uses the creature's level.");
		_chests = config.Bind<bool>("PoV Biome Gear", "Chests too", true, "Gear from world and dungeon chests follows the chest's biome too. Off: chests keep Path of Valheiman's usual pool.");
		_lower = config.Bind<bool>("PoV Biome Gear", "Lower biome when none", true, "When no gear of that biome may drop for you yet (Path of Valheiman's Equipment drop gate holds it back until its recipe is open), drop gear of the nearest biome below it. Off: drop from Path of Valheiman's usual pool in that case.");
		_overrides = config.Bind<string>("PoV Biome Gear", "Item biomes", "", "Sets the biome of single items, as Prefab:Biome pairs split by commas, such as SwordIron:Swamp, ArmorWolfChest:Mountain. Biome names: Meadows, BlackForest, Swamp, Mountain, Plains, Mistlands, AshLands, DeepNorth, or Cayir, KaraOrman, Bataklik, Dag, Ova, Sisli, Kul, Kuzey. An item without an entry takes the biome of its Path of Valheiman crafting level: the highest biome among its crafting station and materials. Applies at once.");
		_logDrops = config.Bind<bool>("PoV Biome Gear", "Log drops", false, "Writes each gear drop's biome and pool size to the BepInEx log, and once per game the number of items in each biome.");
		Type type = AccessTools.TypeByName("PassiveTree.Loot.LootDrops");
		Type type2 = ((type == null) ? null : AccessTools.Inner(type, "Context"));
		MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "GearReward", (Type[])null, (Type[])null));
		Type type3 = AccessTools.TypeByName("PassiveTree.Loot.CraftLevel");
		Type type4 = AccessTools.TypeByName("PassiveTree.BiomeLevels");
		MethodInfo methodInfo2 = ((type3 == null) ? null : AccessTools.Method(type3, "OfPrefab", new Type[1] { typeof(string) }, (Type[])null));
		MethodInfo methodInfo3 = ((type4 == null) ? null : AccessTools.Method(type4, "BiomeAt", new Type[1] { typeof(int) }, (Type[])null));
		MethodInfo methodInfo4 = ((type4 == null) ? null : AccessTools.Method(type4, "Of", new Type[1] { typeof(Biome) }, (Type[])null));
		_ctxSource = ((type2 == null) ? null : AccessTools.Field(type2, "Source"));
		_ctxBiome = ((type2 == null) ? null : AccessTools.Field(type2, "Biome"));
		_ctxLevel = ((type2 == null) ? null : AccessTools.Field(type2, "Level"));
		if (methodInfo == null || methodInfo2 == null || methodInfo3 == null || methodInfo4 == null || _ctxSource == null || _ctxBiome == null || _ctxLevel == null)
		{
			log.LogWarning((object)"Path of Valheiman's gear drop code was not found (written for 6.0.1). Biome gear drops are off.");
			return;
		}
		_craftLevel = (Func<string, int>)Delegate.CreateDelegate(typeof(Func<string, int>), methodInfo2);
		_biomeAt = (Func<int, Biome>)Delegate.CreateDelegate(typeof(Func<int, Biome>), methodInfo3);
		_biomeLevel = (Func<Biome, int>)Delegate.CreateDelegate(typeof(Func<Biome, int>), methodInfo4);
		harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(BiomeGear).GetMethod("Cut", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		log.LogInfo((object)("Biome gear drops ready (" + (_enabled.Value ? "on" : "off") + ")."));
	}

	private static void Cut(object ctx, ref List<GameObject> pool)
	{
		//IL_005d: 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_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		if (!_enabled.Value || ctx == null || pool == null || pool.Count == 0)
		{
			return;
		}
		try
		{
			if (!(_ctxSource.GetValue(ctx) is string text) || (!KillSources.Contains(text) && (!_chests.Value || !ChestSources.Contains(text))))
			{
				return;
			}
			Biome val = TargetOf(ctx);
			if ((int)val != 0)
			{
				LogTable();
				Biome chosen;
				List<GameObject> list = Pool(pool, val, out chosen);
				if (_logDrops.Value)
				{
					_log.LogInfo((object)string.Concat("Biome gear drop (", text, "): ", val, " -> ", (list == null) ? "usual pool" : ((object)chosen).ToString(), ", ", pool.Count, " -> ", list?.Count ?? pool.Count, " items."));
				}
				if (list != null)
				{
					pool = list;
				}
			}
		}
		catch (Exception ex)
		{
			if (!_warned)
			{
				_warned = true;
				_log.LogWarning((object)("Biome gear drops failed; this drop uses Path of Valheiman's usual pool: " + ex));
			}
		}
	}

	private static Biome TargetOf(object ctx)
	{
		//IL_0001: 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_001e: 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_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: 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)
		Biome val = (Biome)0;
		if (_from.Value == BiomeSource.KillPlace)
		{
			val = Parse(_ctxBiome.GetValue(ctx) as string);
		}
		if ((int)val == 0)
		{
			val = _biomeAt((int)_ctxLevel.GetValue(ctx));
		}
		if (Array.IndexOf(Ladder, val) < 0)
		{
			return (Biome)0;
		}
		return val;
	}

	private static Biome Parse(string name)
	{
		//IL_0038: 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_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		if (string.IsNullOrEmpty(name))
		{
			return (Biome)0;
		}
		try
		{
			Biome val = (Biome)Enum.Parse(typeof(Biome), name, ignoreCase: true);
			return (Biome)((Array.IndexOf(Ladder, val) >= 0) ? ((int)val) : 0);
		}
		catch (ArgumentException)
		{
			return (Biome)0;
		}
	}

	private static List<GameObject> Pool(List<GameObject> pool, Biome target, out Biome chosen)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0003: Expected I4, but got Unknown
		//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_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: 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_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: Expected I4, but got Unknown
		chosen = (Biome)(int)target;
		Dictionary<Biome, List<GameObject>> dictionary = new Dictionary<Biome, List<GameObject>>();
		foreach (GameObject item in pool)
		{
			if (!((Object)(object)item == (Object)null))
			{
				Biome key = BiomeOf(((Object)item).name);
				if (!dictionary.TryGetValue(key, out var value))
				{
					List<GameObject> list = (dictionary[key] = new List<GameObject>());
					value = list;
				}
				value.Add(item);
			}
		}
		if (dictionary.TryGetValue(target, out var value2))
		{
			return value2;
		}
		if (!_lower.Value)
		{
			return null;
		}
		int num = _biomeLevel(target);
		int num2 = int.MinValue;
		List<GameObject> result = null;
		foreach (KeyValuePair<Biome, List<GameObject>> item2 in dictionary)
		{
			int num3 = _biomeLevel(item2.Key);
			if (num3 <= num && num3 > num2)
			{
				num2 = num3;
				result = item2.Value;
				chosen = (Biome)(int)item2.Key;
			}
		}
		return result;
	}

	private static Biome BiomeOf(string prefab)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		ReadOverrides();
		if (_overrideMap.TryGetValue(prefab, out var value))
		{
			return value;
		}
		if ((Object)(object)_itemBiomesOf != (Object)(object)ObjectDB.instance)
		{
			ItemBiomes.Clear();
			_itemBiomesOf = ObjectDB.instance;
		}
		if (!ItemBiomes.TryGetValue(prefab, out value))
		{
			value = _biomeAt(_craftLevel(prefab));
			ItemBiomes[prefab] = value;
		}
		return value;
	}

	private static void ReadOverrides()
	{
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		string text = _overrides.Value ?? "";
		if (text == _overrideText)
		{
			return;
		}
		_overrideText = text;
		Dictionary<string, Biome> dictionary = new Dictionary<string, Biome>();
		string[] array = text.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
		string[] array2 = array;
		foreach (string text2 in array2)
		{
			int num = text2.IndexOf(':');
			if (num > 0)
			{
				string text3 = text2.Substring(0, num).Trim();
				if (text3.Length > 0 && Names.TryGetValue(Plain(text2.Substring(num + 1)), out var value))
				{
					dictionary[text3] = value;
				}
				else
				{
					_log.LogWarning((object)("Item biomes: could not read \"" + text2.Trim() + "\"."));
				}
			}
		}
		_overrideMap = dictionary;
	}

	private static string Plain(string s)
	{
		StringBuilder stringBuilder = new StringBuilder();
		string text = s.Trim().ToLowerInvariant();
		string text2 = text;
		foreach (char c in text2)
		{
			switch (c)
			{
			case 'ç':
				stringBuilder.Append('c');
				break;
			case 'ğ':
				stringBuilder.Append('g');
				break;
			case 'ı':
				stringBuilder.Append('i');
				break;
			case 'ö':
				stringBuilder.Append('o');
				break;
			case 'ş':
				stringBuilder.Append('s');
				break;
			case 'ü':
				stringBuilder.Append('u');
				break;
			default:
				stringBuilder.Append(c);
				break;
			case ' ':
			case '-':
			case '_':
			case '\u0307':
				break;
			}
		}
		return stringBuilder.ToString();
	}

	private static void LogTable()
	{
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: 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_0121: Unknown result type (might be due to invalid IL or missing references)
		if (!_logDrops.Value || (Object)(object)ObjectDB.instance == (Object)null || (Object)(object)_tableOf == (Object)(object)ObjectDB.instance)
		{
			return;
		}
		_tableOf = ObjectDB.instance;
		Type type = AccessTools.TypeByName("PassiveTree.Loot.LootDrops");
		MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "GearCandidates", (Type[])null, (Type[])null));
		if (methodInfo == null || !(methodInfo.Invoke(null, new object[2] { null, true }) is List<GameObject> list))
		{
			return;
		}
		Dictionary<Biome, int> dictionary = new Dictionary<Biome, int>();
		foreach (GameObject item in list)
		{
			if (!((Object)(object)item == (Object)null))
			{
				Biome key = BiomeOf(((Object)item).name);
				dictionary.TryGetValue(key, out var value);
				dictionary[key] = value + 1;
			}
		}
		StringBuilder stringBuilder = new StringBuilder("Biome gear items:");
		Biome[] ladder = Ladder;
		Biome[] array = ladder;
		foreach (Biome val in array)
		{
			dictionary.TryGetValue(val, out var value2);
			stringBuilder.Append(' ').Append(val).Append(' ')
				.Append(value2)
				.Append(',');
		}
		_log.LogInfo((object)stringBuilder.ToString().TrimEnd(new char[1] { ',' }));
	}
}
internal static class BossStarCap
{
	private const string Section = "Path of Valheiman Bosses";

	private static ConfigEntry<int> _stars;

	private static ConfigEntry<int> _mods;

	private static int _depth;

	private static bool _toldStars;

	private static bool _toldMods;

	private static bool _failed;

	private static ManualLogSource _log;

	internal static void Apply(Harmony harmony, ConfigFile config, ManualLogSource log)
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Expected O, but got Unknown
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Expected O, but got Unknown
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Expected O, but got Unknown
		//IL_0207: Unknown result type (might be due to invalid IL or missing references)
		//IL_0224: Unknown result type (might be due to invalid IL or missing references)
		//IL_022f: Expected O, but got Unknown
		//IL_022f: Expected O, but got Unknown
		//IL_025c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0269: Expected O, but got Unknown
		//IL_0328: Unknown result type (might be due to invalid IL or missing references)
		//IL_032f: Expected O, but got Unknown
		_log = log;
		Type type = AccessTools.TypeByName("PassiveTree.BossStars");
		if (type == null)
		{
			return;
		}
		_stars = config.Bind<int>("Path of Valheiman Bosses", "Boss max stars", 5, new ConfigDescription("Most stars a boss can get from Path of Valheiman (altar summons, the Great Rune of Awakening, Hall of Oaths and monolith bosses). Other creatures keep Path of Valheiman's Max stars. How often a boss gets stars still follows Path of Valheiman's Boss star chance, Boss two-star chance and Chance of each star above two. 0 = Path of Valheiman's own limit (Max stars). In multiplayer the boss's owner rolls, so give every player the same value. Bosses already in the world keep their stars.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), new object[0]));
		_mods = config.Bind<int>("Path of Valheiman Bosses", "Boss max modifiers", 1, new ConfigDescription("Most modifiers a boss can get, whatever its stars, Boss modifiers per star and [Path of Valheiman Creature Modifiers] say. -1 = no limit of our own.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-1, 10), new object[0]));
		MethodInfo methodInfo = AccessTools.PropertyGetter(type, "Cap");
		if (methodInfo == null)
		{
			log.LogWarning((object)"Path of Valheiman's boss star limit was not found; Boss max stars does nothing.");
		}
		else
		{
			HarmonyMethod prefix = new HarmonyMethod(AccessTools.Method(typeof(BossStarCap), "Enter", (Type[])null, (Type[])null));
			HarmonyMethod finalizer = new HarmonyMethod(AccessTools.Method(typeof(BossStarCap), "Leave", (Type[])null, (Type[])null));
			int num = 0;
			num += Wrap(harmony, AccessTools.Method(type, "Roll", new Type[1] { typeof(Character) }, (Type[])null), prefix, finalizer);
			num += Wrap(harmony, AccessTools.Method(type, "Give", new Type[2]
			{
				typeof(Character),
				typeof(int)
			}, (Type[])null), prefix, finalizer);
			num += Wrap(harmony, AccessTools.Method(type, "Stars", Type.EmptyTypes, (Type[])null), prefix, finalizer);
			num += Wrap(harmony, AccessTools.Method(type, "Further", new Type[1] { typeof(int) }, (Type[])null), prefix, finalizer);
			Type type2 = AccessTools.TypeByName("PassiveTree.Encounters.HallMaps.HallMapBossRules");
			MethodInfo methodInfo2 = ((type2 == null) ? null : AccessTools.Method(type2, "Stars", new Type[2]
			{
				typeof(Character),
				typeof(int)
			}, (Type[])null));
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(AccessTools.Method(typeof(BossStarCap), "HallEnter", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(BossStarCap), "HallLeave", (Type[])null, (Type[])null)), (HarmonyMethod)null);
				num++;
			}
			else
			{
				log.LogWarning((object)"Path of Valheiman's Hall of Oaths boss stars were not found; Hall of Oaths bosses keep Max stars.");
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(BossStarCap), "Cap", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			log.LogInfo((object)("Path of Valheiman boss stars: up to " + StarText() + " (" + num + " of 5 boss star steps found)."));
		}
		Type type3 = AccessTools.TypeByName("PassiveTree.RarityMods");
		MethodInfo methodInfo3 = ((type3 == null) ? null : AccessTools.Method(type3, "Fill", new Type[2]
		{
			typeof(Character),
			typeof(int)
		}, (Type[])null));
		if (methodInfo3 == null)
		{
			log.LogWarning((object)"Path of Valheiman's modifier roll was not found; Boss max modifiers does nothing.");
			return;
		}
		HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeof(BossStarCap), "Mods", (Type[])null, (Type[])null));
		val.priority = 0;
		harmony.Patch((MethodBase)methodInfo3, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		log.LogInfo((object)("Path of Valheiman boss modifiers: at most " + ((_mods.Value < 0) ? "Path of Valheiman's own count" : _mods.Value.ToString()) + "."));
	}

	private static int Wrap(Harmony harmony, MethodInfo method, HarmonyMethod prefix, HarmonyMethod finalizer)
	{
		if (method ==