Decompiled source of HallowedConceptsRework v1.2.85

HallowedConceptsRework.dll

Decompiled an hour ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal static class AdditionalHexEffects
{
	private sealed class EclipseState
	{
		internal int Count;
	}

	private static readonly ConditionalWeakTable<object, EclipseState> EclipseCounts = new ConditionalWeakTable<object, EclipseState>();

	private static readonly Dictionary<string, object> Indices = new Dictionary<string, object>();

	private static MethodInfo findItem;

	private static MethodInfo countPermanent;

	private static MethodInfo give;

	private static MethodInfo roll;

	private static PropertyInfo players;

	private static PropertyInfo connected;

	private static PropertyInfo playerMaster;

	private static PropertyInfo masterInventory;

	private static PropertyInfo runInstance;

	private static PropertyInfo pickupItem;

	private static PropertyInfo serverActive;

	private static PropertyInfo itemIndex;

	private static FieldInfo lunarItems;

	private static FieldInfo treasureRng;

	private static FieldInfo tonicAffliction;

	private static FieldInfo displayInventory;

	private static FieldInfo displayStacks;

	private static FieldInfo displayOrder;

	private static FieldInfo displayCount;

	private static EventInfo chargeRate;

	private static PropertyInfo holdoutZone;

	private static Delegate chargeHandler;

	private static Type playerController;

	private static object none;

	internal static void Install()
	{
		//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_0279: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
		Type type = AccessTools.TypeByName("RoR2.Inventory");
		Type type2 = AccessTools.TypeByName("RoR2.ItemIndex");
		Type type3 = AccessTools.TypeByName("RoR2.CharacterMaster");
		Type type4 = AccessTools.TypeByName("RoR2.Run");
		Type type5 = AccessTools.TypeByName("RoR2.ItemCatalog");
		playerController = AccessTools.TypeByName("RoR2.PlayerCharacterMasterController");
		Type type6 = AccessTools.TypeByName("RoR2.TeleporterInteraction");
		none = Enum.Parse(type2, "None");
		findItem = AccessTools.Method(type5, "FindItemIndex", new Type[1] { typeof(string) }, (Type[])null);
		MethodInfo methodInfo = AccessTools.Method(type, "GetItemCountEffective", new Type[1] { type2 }, (Type[])null);
		countPermanent = AccessTools.Method(type, "GetItemCountPermanent", new Type[1] { type2 }, (Type[])null);
		give = AccessTools.Method(type, "GiveItemPermanent", new Type[2]
		{
			type2,
			typeof(int)
		}, (Type[])null);
		players = AccessTools.Property(playerController, "instances");
		connected = AccessTools.Property(playerController, "isConnected");
		playerMaster = AccessTools.Property(playerController, "master");
		masterInventory = AccessTools.Property(type3, "inventory");
		runInstance = AccessTools.Property(type4, "instance");
		lunarItems = AccessTools.Field(type4, "availableLunarItemDropList");
		treasureRng = AccessTools.Field(type4, "treasureRng");
		roll = AccessTools.Method(treasureRng.FieldType, "RangeInt", new Type[2]
		{
			typeof(int),
			typeof(int)
		}, (Type[])null);
		pickupItem = AccessTools.Property(AccessTools.TypeByName("RoR2.PickupIndex"), "itemIndex");
		itemIndex = AccessTools.Property(AccessTools.TypeByName("RoR2.ItemDef"), "itemIndex");
		tonicAffliction = AccessTools.Field(AccessTools.TypeByName("RoR2.RoR2Content+Items"), "TonicAffliction");
		serverActive = AccessTools.Property(AccessTools.TypeByName("UnityEngine.Networking.NetworkServer"), "active");
		holdoutZone = AccessTools.Property(type6, "holdoutZoneController");
		chargeRate = holdoutZone.PropertyType.GetEvent("calcChargeRate");
		chargeHandler = Delegate.CreateDelegate(chargeRate.EventHandlerType, AccessTools.DeclaredMethod(typeof(AdditionalHexEffects), "SlowCharge", (Type[])null, (Type[])null));
		Harmony val = new Harmony("evan.weightedhexdrops.additionalhexes");
		val.Patch((MethodBase)AccessTools.DeclaredMethod(type, "HandleInventoryChanged", (Type[])null, (Type[])null), (HarmonyMethod)null, Patch("GrantLunars"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)AccessTools.DeclaredMethod(AccessTools.TypeByName("RoR2.TeamManager"), "AdjustCostForLongstandingSolitude", (Type[])null, (Type[])null), (HarmonyMethod)null, Patch("InflatePrice"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)AccessTools.DeclaredMethod(type6, "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, Patch("AttachChargeModifier"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)AccessTools.PropertySetter(type3, "luck"), Patch("ReduceLuck"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, Patch("AddAfflictions"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		Type type7 = AccessTools.TypeByName("RoR2.UI.ItemInventoryDisplay");
		displayInventory = AccessTools.Field(type7, "inventory");
		displayStacks = AccessTools.Field(type7, "itemStacks");
		displayOrder = AccessTools.Field(type7, "itemOrder");
		displayCount = AccessTools.Field(type7, "itemOrderCount");
		val.Patch((MethodBase)AccessTools.DeclaredMethod(type7, "OnInventoryChanged", (Type[])null, (Type[])null), (HarmonyMethod)null, Patch("DisplayAfflictions"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
	}

	private static HarmonyMethod Patch(string name)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Expected O, but got Unknown
		return new HarmonyMethod(typeof(AdditionalHexEffects), name, (Type[])null);
	}

	internal static int HeldStacks(object inventory, string name)
	{
		return Count(inventory, name, countPermanent);
	}

	private static int Count(object inventory, string name, MethodInfo count)
	{
		Component val = (Component)((inventory is Component) ? inventory : null);
		if (val == null || !Object.op_Implicit((Object)(object)val))
		{
			return 0;
		}
		if (!Indices.TryGetValue(name, out var value))
		{
			value = findItem.Invoke(null, new object[1] { name });
			if (object.Equals(value, none))
			{
				return 0;
			}
			Indices.Add(name, value);
		}
		return (int)count.Invoke(inventory, new object[1] { value });
	}

	internal static long TeamStacks(string name)
	{
		long num = 0L;
		foreach (object item in (IEnumerable)players.GetValue(null))
		{
			Component val = (Component)((item is Component) ? item : null);
			if (val != null && Object.op_Implicit((Object)(object)val) && (bool)connected.GetValue(val))
			{
				object? value = playerMaster.GetValue(val);
				Component val2 = (Component)((value is Component) ? value : null);
				if (val2 != null && Object.op_Implicit((Object)(object)val2))
				{
					num += Count(masterInventory.GetValue(val2), name, countPermanent);
				}
			}
		}
		return num;
	}

	private static void GrantLunars(Component __instance)
	{
		if (!(bool)serverActive.GetValue(null) || !Object.op_Implicit((Object)(object)__instance.GetComponent(playerController)))
		{
			return;
		}
		int num = Count(__instance, "WeightedHexEclipse", countPermanent);
		if (num == 0 && !EclipseCounts.TryGetValue(__instance, out var _))
		{
			return;
		}
		EclipseState orCreateValue = EclipseCounts.GetOrCreateValue(__instance);
		int num2 = num - orCreateValue.Count;
		orCreateValue.Count = num;
		if (num2 <= 0)
		{
			return;
		}
		object value2 = runInstance.GetValue(null);
		if (value2 == null || !(lunarItems.GetValue(value2) is IList { Count: not 0 } list))
		{
			return;
		}
		object value3 = treasureRng.GetValue(value2);
		for (int i = 0; i < num2; i++)
		{
			int index = (int)roll.Invoke(value3, new object[2] { 0, list.Count });
			object value4 = pickupItem.GetValue(list[index]);
			if (!object.Equals(value4, none))
			{
				give.Invoke(__instance, new object[2] { value4, 1 });
			}
		}
	}

	private static void InflatePrice(ref int __result)
	{
		if (__result > 0)
		{
			long num = TeamStacks("WeightedHexInflation");
			if (num > 0)
			{
				__result = (int)Math.Min(2147483647L, __result + (__result * num + 3) / 4);
			}
		}
	}

	private static void AttachChargeModifier(object __instance)
	{
		object? value = holdoutZone.GetValue(__instance);
		Component val = (Component)((value is Component) ? value : null);
		if (val != null && Object.op_Implicit((Object)(object)val))
		{
			chargeRate.AddEventHandler(val, chargeHandler);
		}
	}

	private static void SlowCharge(ref float rate)
	{
		if (rate > 0f)
		{
			rate *= Mathf.Max(0.01f, 1f - 0.25f * (float)TeamStacks("WeightedHexImpatience"));
		}
	}

	private static void ReduceLuck(object __instance, ref float __0)
	{
		__0 -= Count(masterInventory.GetValue(__instance), "WeightedHexMisfire", countPermanent);
	}

	private static void DisplayAfflictions(Behaviour __instance)
	{
		if (!__instance.isActiveAndEnabled)
		{
			return;
		}
		int num = HeldStacks(displayInventory.GetValue(__instance), "WeightedHexWithdrawal");
		object value = tonicAffliction.GetValue(null);
		if (num != 0 && value != null)
		{
			object value2 = itemIndex.GetValue(value);
			int[] array = (int[])displayStacks.GetValue(__instance);
			int num2 = Convert.ToInt32(value2);
			Array array2 = (Array)displayOrder.GetValue(__instance);
			int num3 = (int)displayCount.GetValue(__instance);
			if (Array.IndexOf(array2, value2, 0, num3) < 0 && num3 < array2.Length)
			{
				array2.SetValue(value2, num3);
				displayCount.SetValue(__instance, num3 + 1);
			}
			array[num2] = (int)Math.Min(2147483647L, array[num2] + 3L * (long)num);
		}
	}

	private static void AddAfflictions(Component __instance, object __0, ref int __result)
	{
		object value = tonicAffliction.GetValue(null);
		if (value != null && object.Equals(__0, itemIndex.GetValue(value)))
		{
			int num = Count(__instance, "WeightedHexWithdrawal", countPermanent);
			__result = (int)Math.Min(2147483647L, __result + 3L * (long)num);
		}
	}
}
internal static class HexDescriptions
{
	internal static readonly Dictionary<string, string> Text = new Dictionary<string, string>
	{
		["WeightedHexCreepPickup"] = "<style=cDeath>Longer equipment cooldowns</style>.",
		["WeightedHexCreepDescription"] = "Equipment cooldowns increase by " + Loss("100%") + " " + Stack("+100% per stack") + ".",
		["WeightedHexEclipsePickup"] = "Gain a random <style=cIsLunar>lunar item</style>.",
		["WeightedHexEclipseDescription"] = "Gain " + Loss("1") + " " + Stack("+1 per stack") + " permanent lunar item. Lunar equipment is excluded.",
		["WeightedHexInflationPickup"] = "<style=cDeath>Higher interactable prices</style>.",
		["WeightedHexInflationDescription"] = "Interactable prices increase by " + Loss("25%") + " " + Stack("+25% per stack") + ".",
		["WeightedHexImpatiencePickup"] = "The Teleporter <style=cDeath>charges more slowly</style>.",
		["WeightedHexImpatienceDescription"] = "The Teleporter charges " + Loss("25% slower") + " " + Stack("−25% per stack") + ", down to 1% of normal charge speed.",
		["WeightedHexCalamityPickup"] = "<style=cDeath>Random catastrophes</style> during the Teleporter event.",
		["WeightedHexCalamityDescription"] = "The Teleporter receives " + Loss("1") + " " + Stack("+1 per stack") + " random lesser catastrophe.",
		["WeightedHexMisfirePickup"] = "<style=cDeath>Reduced luck</style>.",
		["WeightedHexMisfireDescription"] = "Lose " + Loss("1 luck") + " " + Stack("−1 per stack") + ".",
		["WeightedHexDisorientationPickup"] = "Your <style=cDeath>loadout changes</style> periodically.",
		["WeightedHexDisorientationDescription"] = "Randomize skills and selectable passives on pickup and every " + Loss("30 seconds") + ". Randomization frequency increases " + Stack("+25% per stack") + ".",
		["WeightedHexRegressionPickup"] = "<style=cDeath>Reduced stat gains</style> from levels.",
		["WeightedHexRegressionDescription"] = "Reduce level-up stat bonuses by " + Loss("20%") + " " + Stack("−20% per stack") + ". Effective level cannot fall below 1.",
		["WeightedHexEvolutionPickup"] = "Enemies can <style=cDeath>spawn as elites</style> for free.",
		["WeightedHexEvolutionDescription"] = "Basic enemies have a " + Loss("30% chance") + " " + Stack("+20% per stack") + " to spawn as elites at no extra director cost. Minibosses have half the chance. Major bosses have a " + Loss("10% chance") + ". Tier 2 elites become more likely with more stacks.",
		["WeightedHexWithdrawalPickup"] = "Suffer <style=cDeath>Tonic Afflictions</style>.",
		["WeightedHexWithdrawalDescription"] = "Suffer " + Loss("3 Tonic Afflictions") + " " + Stack("+3 per stack") + " while carrying this Hex.",
		["WeightedHexImpersonationPickup"] = "<style=cDeath>Vengeance doppelgangers</style> hunt you.",
		["WeightedHexImpersonationDescription"] = "Summon a doppelganger on pickup and every " + Loss("5 minutes") + " " + Stack("−25% per stack") + ". The timer pauses in safe areas.",
		["WeightedHexResurrectionPickup"] = "Defeated enemies can <style=cDeath>return at full health</style>.",
		["WeightedHexResurrectionDescription"] = "Defeated enemies have a " + Loss("40% chance") + " " + Stack("+20% per stack") + " to return once at full health. Minibosses have half the chance. Each major boss phase has a " + Loss("20% chance") + " to return."
	};

	private static string Loss(string value)
	{
		return "<style=cDeath>" + value + "</style>";
	}

	private static string Stack(string value)
	{
		return "<style=cStack>(" + value + ")</style>";
	}
}
internal static class HexExchange
{
	private const float DrainInterval = 0.35f;

	private const float OrbTravelTime = 1.5f;

	private static readonly int[] Prices = new int[3] { 3, 3, 2 };

	private static readonly string[] TierNames = new string[5] { "Tier1", "Tier2", "Tier3", "Boss", "Cursed" };

	private static readonly string[] PoolFields = new string[5] { "availableTier1DropList", "availableTier2DropList", "availableTier3DropList", "availableBossDropList", "availableCursedTierDropList" };

	private static readonly double[][] RewardWeights = new double[3][]
	{
		new double[5] { 0.8, 0.2, 0.0, 0.0, 0.0 },
		new double[5] { 0.0, 0.8, 0.2, 0.0, 0.0 },
		new double[5] { 0.0, 0.0, 1.0, 1.0, 1.0 }
	};

	private static readonly HashSet<Component> Busy = new HashSet<Component>();

	private static ManualLogSource log;

	private static MonoBehaviour coroutineHost;

	private static MethodInfo createTakenOrb;

	private static MethodInfo closeNode;

	private static MethodInfo openNode;

	private static Type bodyType;

	private static Type runType;

	private static Type pickerType;

	private static Type optionType;

	private static Type infoType;

	private static Type pickupType;

	private static Type nodeType;

	private static PropertyInfo serverActive;

	private static MethodInfo findItem;

	private static MethodInfo getItem;

	private static MethodInfo countItem;

	private static MethodInfo removeItem;

	private static MethodInfo giveItem;

	private static MethodInfo findTierPickup;

	private static MethodInfo spawnDroplet;

	private static ConstructorInfo makePickup;

	private static object[] tierPickups;

	private static readonly int[] DisplayTiers = new int[3] { 0, 1, 4 };

	private static object conditionsNotMet;

	private static object available;

	public static void Install(Harmony harmony, ManualLogSource logger, MonoBehaviour host)
	{
		//IL_035d: Unknown result type (might be due to invalid IL or missing references)
		//IL_036b: Expected O, but got Unknown
		//IL_0372: Unknown result type (might be due to invalid IL or missing references)
		//IL_037f: Expected O, but got Unknown
		//IL_03a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b5: Expected O, but got Unknown
		log = logger;
		coroutineHost = host;
		Type type = RequireType("RoR2.DrainItemsAndDropMultiChoicePotentialController");
		Type type2 = RequireType("RoR2.Inventory");
		Type type3 = RequireType("RoR2.ItemIndex");
		Type type4 = RequireType("RoR2.ItemCatalog");
		Type type5 = RequireType("RoR2.PickupIndex");
		Type itemTier = RequireType("RoR2.ItemTier");
		nodeType = RequireType("HallowingShrineSplitNode");
		closeNode = RequireMethod(nodeType, "Close");
		openNode = RequireMethod(nodeType, "Open");
		createTakenOrb = RequireMethod(RequireType("RoR2.PurchaseInteraction"), "CreateItemTakenOrb", typeof(Vector3), typeof(GameObject), type3);
		bodyType = RequireType("RoR2.CharacterBody");
		runType = RequireType("RoR2.Run");
		pickerType = RequireType("RoR2.PickupPickerController");
		optionType = RequireType("RoR2.PickupPickerController+Option");
		infoType = RequireType("RoR2.GenericPickupController+CreatePickupInfo");
		pickupType = RequireType("RoR2.UniquePickup");
		serverActive = AccessTools.Property(RequireType("UnityEngine.Networking.NetworkServer"), "active");
		findItem = RequireMethod(type4, "FindItemIndex", typeof(string));
		getItem = RequireMethod(type4, "GetItemDef", type3);
		countItem = RequireMethod(type2, "GetItemCountPermanent", type3);
		removeItem = RequireMethod(type2, "RemoveItemPermanent", type3, typeof(int));
		giveItem = RequireMethod(type2, "GiveItemPermanent", type3, typeof(int));
		findTierPickup = RequireMethod(RequireType("RoR2.PickupCatalog"), "FindPickupIndex", itemTier);
		spawnDroplet = RequireMethod(RequireType("RoR2.PickupDropletController"), "CreatePickupDroplet", infoType, typeof(Vector3), typeof(Vector3));
		makePickup = pickupType.GetConstructor(new Type[1] { type5 }) ?? throw new MissingMethodException(pickupType.FullName, ".ctor(PickupIndex)");
		tierPickups = TierNames.Select((string name) => Enum.Parse(itemTier, name)).ToArray();
		Type type6 = RequireType("RoR2.Interactor");
		MethodInfo methodInfo = RequireMethod(type, "GetInteractability", type6);
		available = Enum.Parse(methodInfo.ReturnType, "Available");
		conditionsNotMet = Enum.Parse(methodInfo.ReturnType, "ConditionsNotMet");
		MethodInfo methodInfo2 = RequireMethod(type, "OnInteractionBegin", type6);
		MethodInfo methodInfo3 = AccessTools.Method(typeof(HexExchange), "CheckEligibility", (Type[])null, (Type[])null).MakeGenericMethod(methodInfo.ReturnType);
		harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(AccessTools.Method(typeof(HexExchange), "Exchange", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo3), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		harmony.Patch((MethodBase)RequireMethod(type, "GetContextString", type6), (HarmonyMethod)null, new HarmonyMethod(typeof(HexExchange), "DescribeTrade", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		log.LogInfo((object)"Hand of Life exchange installed (3 common / 3 uncommon / 2 rare).");
	}

	private static void CheckEligibility<T>(Component __instance, Component __0, ref T __result)
	{
		if (IsHexShrine(__instance) && !(__result.ToString() == "Disabled"))
		{
			Component inventory = GetInventory(__0);
			if (!Busy.Contains(__instance) && Object.op_Implicit((Object)(object)inventory) && (HasNormalPayment(ReadPayment(inventory)) || ReincarnationTrade.CanPay(inventory)))
			{
				__result = (T)available;
			}
			else
			{
				__result = (T)conditionsNotMet;
			}
		}
	}

	private static void DescribeTrade(Component __instance, Component __0, ref string __result)
	{
		if (!IsHexShrine(__instance))
		{
			return;
		}
		Component inventory = GetInventory(__0);
		if (Object.op_Implicit((Object)(object)inventory) && !HasNormalPayment(ReadPayment(inventory)))
		{
			int num = ReincarnationTrade.CountOfferings(inventory);
			if (num > 0)
			{
				__result = ((num >= 2) ? "Offer 2 Hexes of Reincarnation" : "Hexes of Reincarnation (1/2)");
			}
		}
	}

	private static bool HasNormalPayment(List<object>[] payment)
	{
		return payment.Where((List<object> stacks, int rarity) => stacks.Count >= Prices[rarity]).Any();
	}

	private static bool Exchange(Component __instance, Component __0)
	{
		if (!IsHexShrine(__instance))
		{
			return true;
		}
		if (!(bool)serverActive.GetValue(null) || !Busy.Add(__instance))
		{
			return false;
		}
		coroutineHost.StartCoroutine(RunTrade(__instance, __0));
		return false;
	}

	private static IEnumerator RunTrade(Component shrine, Component activator)
	{
		using IEnumerator<float> trade = ExecuteTrade(shrine, activator);
		try
		{
			while (true)
			{
				float current;
				try
				{
					if (!trade.MoveNext())
					{
						break;
					}
					current = trade.Current;
				}
				catch (Exception ex)
				{
					log.LogError((object)("Hand of Life exchange failed: " + ex.GetBaseException()));
					break;
				}
				yield return (object)new WaitForSeconds(current);
			}
		}
		finally
		{
			Busy.Remove(shrine);
		}
	}

	private static IEnumerator<float> ExecuteTrade(Component shrine, Component activator)
	{
		object obj = Get(shrine, "stateMachine");
		if (!(bool)Get(shrine, "Available") || obj == null || !(bool)RequireMethod(obj.GetType(), "IsInMainState").Invoke(obj, null))
		{
			yield break;
		}
		Component inventory = GetInventory(activator);
		if ((Object)(object)inventory == (Object)null)
		{
			yield break;
		}
		List<object>[] payment = ReadPayment(inventory);
		if (!HasNormalPayment(payment))
		{
			using (IEnumerator<float> special = ReincarnationTrade.Exchange(activator.GetComponent(bodyType), inventory, shrine))
			{
				while (special.MoveNext())
				{
					yield return special.Current;
				}
				yield break;
			}
		}
		GameObject prefab = (GameObject)Get(shrine, "potentialPrefab");
		Transform origin = (Transform)Get(shrine, "dropOrigin");
		object run = AccessTools.Property(runType, "instance").GetValue(null);
		if (!Object.op_Implicit((Object)(object)prefab) || !Object.op_Implicit((Object)(object)prefab.GetComponent(pickerType)) || !Object.op_Implicit((Object)(object)origin) || run == null)
		{
			throw new InvalidOperationException("The shrine reward prefab, drop origin, or run is unavailable.");
		}
		object rng = Get(run, "treasureRng");
		PropertyInfo next = AccessTools.Property(rng.GetType(), "nextNormalizedFloat");
		Func<double> roll = () => (float)next.GetValue(rng);
		object[][] pools = PoolFields.Select((string field) => ((IEnumerable)Get(run, field)).Cast<object>().Distinct().ToArray()).ToArray();
		Vector3 velocity = origin.TransformDirection((Vector3)Get(shrine, "dropVelocity"));
		Component body = activator.GetComponent(bodyType);
		Component node = shrine.GetComponent(nodeType);
		int[] rewarded = new int[Prices.Length];
		closeNode.Invoke(node, null);
		try
		{
			for (int rarity = 0; rarity < Prices.Length; rarity++)
			{
				int price = Prices[rarity];
				int offset = 0;
				while (offset + price <= payment[rarity].Count)
				{
					if (!CanContinue(shrine, body, inventory, run))
					{
						yield break;
					}
					object[] array = payment[rarity].Skip(offset).Take(price).ToArray();
					if ((from index in array
						group index by index).Any((IGrouping<object, object> group) => Count(inventory, group.Key) < group.Count()))
					{
						break;
					}
					object[] array2 = RollOptions(pools, RewardWeights[rarity], roll);
					if (array2 == null)
					{
						log.LogWarning((object)("Hand of Life could not make three distinct choices for rarity " + rarity + "."));
						break;
					}
					object info = CreateReward(prefab, origin.position, rarity, array2);
					int num = rewarded.Sum();
					float num2 = ((num % 2 == 1) ? 1f : (-1f)) * (float)((num + 1) / 2) * 16f;
					Vector3 launch = Quaternion.AngleAxis(num2, origin.up) * velocity;
					List<object> paid = new List<object>(price);
					bool dispensed = false;
					try
					{
						object[] array3 = array;
						foreach (object obj2 in array3)
						{
							if (!CanContinue(shrine, body, inventory, run))
							{
								yield break;
							}
							int num4 = Count(inventory, obj2);
							if (num4 == 0)
							{
								break;
							}
							removeItem.Invoke(inventory, new object[2] { obj2, 1 });
							if (Count(inventory, obj2) != num4 - 1)
							{
								throw new InvalidOperationException("The inventory did not pay the expected Hex.");
							}
							paid.Add(obj2);
							createTakenOrb.Invoke(null, new object[3]
							{
								Get(body, "corePosition"),
								shrine.gameObject,
								obj2
							});
							yield return (paid.Count == price) ? 1.5f : 0.35f;
						}
						if (!CanContinue(shrine, body, inventory, run) || !Object.op_Implicit((Object)(object)origin))
						{
							yield break;
						}
						if (paid.Count == price)
						{
							spawnDroplet.Invoke(null, new object[3] { info, origin.position, launch });
							dispensed = true;
							rewarded[rarity]++;
							goto IL_06c2;
						}
					}
					finally
					{
						if (!dispensed && Object.op_Implicit((Object)(object)inventory))
						{
							foreach (object item in paid)
							{
								giveItem.Invoke(inventory, new object[2] { item, 1 });
							}
						}
					}
					break;
					IL_06c2:
					yield return 0.35f;
					offset += price;
				}
			}
		}
		finally
		{
			if (Object.op_Implicit((Object)(object)node))
			{
				openNode.Invoke(node, null);
			}
			if (rewarded.Sum() > 0)
			{
				if (Object.op_Implicit((Object)(object)shrine) && Object.op_Implicit((Object)(object)activator))
				{
					object obj3 = Get(shrine, "OnInteractServer");
					if (obj3 != null)
					{
						RequireMethod(obj3.GetType(), "Invoke", RequireType("RoR2.Interactor")).Invoke(obj3, new object[1] { activator });
					}
				}
				log.LogInfo((object)("Hand of Life rewards (common/uncommon/rare): " + string.Join("/", rewarded)));
			}
		}
	}

	private static bool CanContinue(Component shrine, Component body, Component inventory, object run)
	{
		if (Object.op_Implicit((Object)(object)shrine) && Object.op_Implicit((Object)(object)body) && Object.op_Implicit((Object)(object)inventory))
		{
			return object.Equals(run, AccessTools.Property(runType, "instance").GetValue(null));
		}
		return false;
	}

	private static object[] RollOptions(object[][] pools, double[] weights, Func<double> roll)
	{
		List<object>[] array = pools.Select((object[] pool) => pool.ToList()).ToArray();
		object[] array2 = new object[3];
		for (int num = 0; num < array2.Length; num++)
		{
			double num2 = 0.0;
			for (int num3 = 0; num3 < weights.Length; num3++)
			{
				if (array[num3].Count > 0)
				{
					num2 += weights[num3];
				}
			}
			if (num2 <= 0.0)
			{
				return null;
			}
			double num4 = roll() * num2;
			int num5 = -1;
			for (int num6 = 0; num6 < weights.Length; num6++)
			{
				if (!(weights[num6] <= 0.0) && array[num6].Count != 0)
				{
					num5 = num6;
					num4 -= weights[num6];
					if (num4 < 0.0)
					{
						break;
					}
				}
			}
			List<object> list = array[num5];
			int index = Math.Min(list.Count - 1, (int)(roll() * (double)list.Count));
			object item = (array2[num] = list[index]);
			List<object>[] array3 = array;
			for (int num7 = 0; num7 < array3.Length; num7++)
			{
				array3[num7].Remove(item);
			}
		}
		return array2;
	}

	private static object CreateReward(GameObject prefab, Vector3 position, int rarity, object[] options)
	{
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		Array array = Array.CreateInstance(optionType, options.Length);
		for (int i = 0; i < options.Length; i++)
		{
			object obj = Activator.CreateInstance(optionType);
			SetField(obj, "pickup", makePickup.Invoke(new object[1] { options[i] }));
			SetField(obj, "available", true);
			array.SetValue(obj, i);
		}
		object obj2 = Activator.CreateInstance(infoType);
		object obj3 = makePickup.Invoke(new object[1] { findTierPickup.Invoke(null, new object[1] { tierPickups[DisplayTiers[rarity]] }) });
		SetField(obj3, "ignoreArtifactBasedPickupReplacements", true);
		AccessTools.Property(infoType, "pickup").SetValue(obj2, obj3);
		SetField(obj2, "position", position);
		SetField(obj2, "rotation", Quaternion.identity);
		SetField(obj2, "prefabOverride", prefab);
		SetField(obj2, "pickerOptions", array);
		SetField(obj2, "maxOptionCount", 1);
		return obj2;
	}

	private static List<object>[] ReadPayment(Component inventory)
	{
		List<object>[] array = new List<object>[3]
		{
			new List<object>(),
			new List<object>(),
			new List<object>()
		};
		foreach (KeyValuePair<string, int> item in HallowedConceptsRework.Rarity.OrderBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> pair) => pair.Key, StringComparer.Ordinal))
		{
			object obj = findItem.Invoke(null, new object[1] { item.Key });
			object? obj2 = getItem.Invoke(null, new object[1] { obj });
			Object val = (Object)((obj2 is Object) ? obj2 : null);
			if (Object.op_Implicit(val) && (bool)Get(val, "canRemove"))
			{
				int num = Count(inventory, obj);
				for (int num2 = 0; num2 < num; num2++)
				{
					array[item.Value].Add(obj);
				}
			}
		}
		return array;
	}

	private static int Count(Component inventory, object index)
	{
		return (int)countItem.Invoke(inventory, new object[1] { index });
	}

	private static Component GetInventory(Component activator)
	{
		Component val = (Object.op_Implicit((Object)(object)activator) ? activator.GetComponent(bodyType) : null);
		if (!Object.op_Implicit((Object)(object)val))
		{
			return null;
		}
		object obj = Get(val, "inventory");
		return (Component)((obj is Component) ? obj : null);
	}

	private static bool IsHexShrine(Component shrine)
	{
		return Object.op_Implicit((Object)(object)shrine.GetComponent(nodeType));
	}

	private static Type RequireType(string name)
	{
		return AccessTools.TypeByName(name) ?? throw new TypeLoadException(name);
	}

	private static MethodInfo RequireMethod(Type type, string name, params Type[] parameters)
	{
		return AccessTools.Method(type, name, parameters, (Type[])null) ?? throw new MissingMethodException(type.FullName, name);
	}

	private static object Get(object target, string name)
	{
		Type type = target.GetType();
		FieldInfo fieldInfo = AccessTools.Field(type, name);
		if (!(fieldInfo != null))
		{
			return AccessTools.Property(type, name).GetValue(target);
		}
		return fieldInfo.GetValue(target);
	}

	private static void SetField(object target, string name, object value)
	{
		AccessTools.Field(target.GetType(), name).SetValue(target, value);
	}
}
internal static class HexOfCalamity
{
	private sealed class Selection
	{
		public int Count;

		public bool Major;
	}

	internal const string InternalName = "WeightedHexCalamity";

	private static readonly ConditionalWeakTable<Component, Selection> Selections = new ConditionalWeakTable<Component, Selection>();

	private static FieldInfo instance;

	private static FieldInfo effects;

	private static FieldInfo queue;

	private static FieldInfo weight;

	private static FieldInfo majorCompatible;

	private static MethodInfo spawn;

	private static MethodInfo randomValue;

	private static MethodInfo enqueue;

	private static MethodInfo startEffects;

	private static PropertyInfo serverActive;

	private static Type controller;

	internal static void Install()
	{
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Expected O, but got Unknown
		//IL_014a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0158: Expected O, but got Unknown
		Type type = AccessTools.TypeByName("RoR2.DLC4CatastropheProvider");
		controller = AccessTools.TypeByName("RoR2.DLC4LesserCatastropheController");
		instance = AccessTools.Field(type, "_lesserCatastropheInstance");
		effects = AccessTools.Field(controller, "_effects");
		Type? elementType = effects.FieldType.GetElementType();
		weight = AccessTools.Field(elementType, "weight");
		majorCompatible = AccessTools.Field(elementType, "isMajorCatastropheValid");
		queue = AccessTools.Field(controller, "_queuedEffects");
		enqueue = AccessTools.Method(queue.FieldType, "Enqueue", (Type[])null, (Type[])null);
		spawn = AccessTools.Method(type, "SpawnLesserCatastrophesServer", (Type[])null, (Type[])null);
		randomValue = AccessTools.Method(controller, "GetNormalizedFloatServer", (Type[])null, (Type[])null);
		startEffects = AccessTools.Method(controller, "SetMachinesToMain", (Type[])null, (Type[])null);
		serverActive = AccessTools.Property(AccessTools.TypeByName("UnityEngine.Networking.NetworkServer"), "active");
		Harmony val = new Harmony("evan.weightedhexdrops.calamity");
		val.Patch((MethodBase)AccessTools.Method(type, "HandleLesserCatastrophesServer", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(HexOfCalamity), "AddCatastrophes", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)AccessTools.Method(controller, "BeginCatastrophesServer", (Type[])null, (Type[])null), new HarmonyMethod(typeof(HexOfCalamity), "SelectCatastrophes", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
	}

	private static void AddCatastrophes(Component __instance, object __0)
	{
		if (!(bool)serverActive.GetValue(null))
		{
			return;
		}
		int num = (int)Math.Min(2147483647L, AdditionalHexEffects.TeamStacks("WeightedHexCalamity"));
		if (num == 0)
		{
			return;
		}
		object? value = instance.GetValue(__instance);
		GameObject val = (GameObject)((value is GameObject) ? value : null);
		if (val == null || !Object.op_Implicit((Object)(object)val))
		{
			spawn.Invoke(__instance, new object[2] { num, false });
		}
		object? value2 = instance.GetValue(__instance);
		GameObject val2 = (GameObject)((value2 is GameObject) ? value2 : null);
		if (val2 != null && Object.op_Implicit((Object)(object)val2))
		{
			Component component = val2.GetComponent(controller);
			if (component != null && !Selections.TryGetValue(component, out var _))
			{
				Selections.Add(component, new Selection
				{
					Count = num,
					Major = (__0?.GetType().Namespace == "EntityStates.TeleporterCatastrophe.DLC4.Teleporter")
				});
			}
		}
	}

	private static bool SelectCatastrophes(MonoBehaviour __instance)
	{
		if (!Selections.TryGetValue((Component)(object)__instance, out var value))
		{
			return true;
		}
		List<(object, float)> list = new List<(object, float)>();
		foreach (object item in (Array)effects.GetValue(__instance))
		{
			float num = (float)weight.GetValue(item);
			if (num > 0f && (!value.Major || (bool)majorCompatible.GetValue(item)))
			{
				list.Add((item, num));
			}
		}
		if (list.Count == 0)
		{
			return false;
		}
		List<(object, float)> list2 = new List<(object, float)>();
		object value2 = queue.GetValue(__instance);
		for (int i = 0; i < value.Count; i++)
		{
			if (list2.Count == 0)
			{
				list2.AddRange(list);
			}
			float num2 = 0f;
			foreach (var item2 in list2)
			{
				num2 += item2.Item2;
			}
			float num3 = (float)randomValue.Invoke(__instance, null) * num2;
			int j;
			for (j = 0; j < list2.Count - 1; j++)
			{
				num3 -= list2[j].Item2;
				if (num3 < 0f)
				{
					break;
				}
			}
			enqueue.Invoke(value2, new object[1] { list2[j].Item1 });
			list2.RemoveAt(j);
		}
		__instance.StartCoroutine((IEnumerator)startEffects.Invoke(__instance, null));
		return false;
	}
}
internal static class HexOfCreep
{
	internal const string InternalName = "WeightedHexCreep";

	private static MethodInfo findItem;

	private static MethodInfo countItem;

	private static object creepIndex;

	private static object invalidIndex;

	internal static void Install()
	{
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Expected O, but got Unknown
		Type type = AccessTools.TypeByName("RoR2.Inventory");
		Type type2 = AccessTools.TypeByName("RoR2.ItemCatalog");
		Type type3 = AccessTools.TypeByName("RoR2.ItemIndex");
		findItem = AccessTools.Method(type2, "FindItemIndex", new Type[1] { typeof(string) }, (Type[])null) ?? throw new MissingMethodException("ItemCatalog.FindItemIndex");
		countItem = AccessTools.Method(type, "GetItemCountEffective", new Type[1] { type3 }, (Type[])null) ?? throw new MissingMethodException("Inventory.GetItemCountEffective");
		invalidIndex = Enum.Parse(type3, "None");
		MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "CalculateEquipmentCooldownScale", (Type[])null, (Type[])null) ?? throw new MissingMethodException("Inventory.CalculateEquipmentCooldownScale");
		new Harmony("evan.weightedhexdrops.creep").Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(HexOfCreep), "ScaleCooldown", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
	}

	private static void ScaleCooldown(object __instance, ref float __result)
	{
		if (creepIndex == null)
		{
			object objA = findItem.Invoke(null, new object[1] { "WeightedHexCreep" });
			if (object.Equals(objA, invalidIndex))
			{
				return;
			}
			creepIndex = objA;
		}
		int num = (int)countItem.Invoke(__instance, new object[1] { creepIndex });
		__result *= 1f + (float)num;
	}
}
internal static class HexOfDisorientation
{
	private sealed class PlayerState
	{
		public object Original;

		public float Progress;

		public int Stacks;
	}

	internal const string InternalName = "WeightedHexDisorientation";

	private const float BaseInterval = 30f;

	private static readonly ConditionalWeakTable<Component, PlayerState> States = new ConditionalWeakTable<Component, PlayerState>();

	private static Type playerController;

	private static PropertyInfo serverActive;

	private static PropertyInfo players;

	private static PropertyInfo master;

	private static PropertyInfo inventory;

	private static PropertyInfo family;

	private static PropertyInfo locator;

	private static PropertyInfo allSkills;

	private static PropertyInfo baseSkill;

	private static FieldInfo masterLoadout;

	private static FieldInfo bodyLoadouts;

	private static FieldInfo variants;

	private static FieldInfo bodyIndex;

	private static FieldInfo variantSkill;

	private static MethodInfo getBody;

	private static MethodInfo copyLoadout;

	private static MethodInfo getSlots;

	private static MethodInfo getVariant;

	private static MethodInfo setVariant;

	private static MethodInfo applyMaster;

	private static MethodInfo applyBody;

	private static MethodInfo setBaseSkill;

	internal static void Install()
	{
		//IL_0281: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c5: Expected O, but got Unknown
		//IL_02c5: Expected O, but got Unknown
		Type type = AccessTools.TypeByName("UnityEngine.Networking.NetworkServer");
		Type type2 = (playerController = AccessTools.TypeByName("RoR2.PlayerCharacterMasterController"));
		Type type3 = AccessTools.TypeByName("RoR2.CharacterMaster");
		Type type4 = AccessTools.TypeByName("RoR2.CharacterBody");
		Type type5 = AccessTools.TypeByName("RoR2.Loadout");
		Type type6 = AccessTools.TypeByName("RoR2.BodyCatalog");
		serverActive = AccessTools.Property(type, "active");
		players = AccessTools.Property(type2, "instances");
		master = AccessTools.Property(type2, "master");
		inventory = AccessTools.Property(type3, "inventory");
		bodyIndex = AccessTools.Field(type4, "bodyIndex");
		masterLoadout = AccessTools.Field(type3, "loadout");
		bodyLoadouts = AccessTools.Field(type5, "bodyLoadoutManager");
		getBody = AccessTools.Method(type3, "GetBody", (Type[])null, (Type[])null);
		copyLoadout = AccessTools.Method(type5, "Copy", new Type[1] { type5 }, (Type[])null);
		getSlots = AccessTools.Method(type6, "GetBodyPrefabSkillSlots", new Type[1] { bodyIndex.FieldType }, (Type[])null);
		family = AccessTools.Property(getSlots.ReturnType.GetElementType(), "skillFamily");
		variants = AccessTools.Field(family.PropertyType, "variants");
		getVariant = AccessTools.Method(bodyLoadouts.FieldType, "GetSkillVariant", new Type[2]
		{
			bodyIndex.FieldType,
			typeof(int)
		}, (Type[])null);
		setVariant = AccessTools.Method(bodyLoadouts.FieldType, "SetSkillVariant", new Type[3]
		{
			bodyIndex.FieldType,
			typeof(int),
			typeof(uint)
		}, (Type[])null);
		applyMaster = AccessTools.Method(type3, "SetLoadoutServer", new Type[1] { type5 }, (Type[])null);
		applyBody = AccessTools.Method(type4, "SetLoadoutServer", new Type[1] { type5 }, (Type[])null);
		locator = AccessTools.Property(type4, "skillLocator");
		allSkills = AccessTools.Property(locator.PropertyType, "AllSkills");
		baseSkill = AccessTools.Property(getSlots.ReturnType.GetElementType(), "baseSkill");
		variantSkill = AccessTools.Field(variants.FieldType.GetElementType(), "skillDef");
		setBaseSkill = AccessTools.Method(getSlots.ReturnType.GetElementType(), "SetBaseSkill", (Type[])null, (Type[])null);
		new Harmony("evan.weightedhexdrops.disorientation").Patch((MethodBase)AccessTools.DeclaredMethod(type3, "OnDeserialize", (Type[])null, (Type[])null), new HarmonyMethod(typeof(HexOfDisorientation), "CaptureClientLoadout", (Type[])null), new HarmonyMethod(typeof(HexOfDisorientation), "SyncClientSkills", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		AccessTools.TypeByName("RoR2.RoR2Application").GetEvent("onFixedUpdate").AddEventHandler(null, new Action(Update));
	}

	private static void Update()
	{
		bool authoritative = (bool)serverActive.GetValue(null);
		foreach (object item in (IEnumerable)players.GetValue(null))
		{
			Component val = (Component)((item is Component) ? item : null);
			if (val != null && Object.op_Implicit((Object)(object)val))
			{
				object? value = master.GetValue(item);
				Component val2 = (Component)((value is Component) ? value : null);
				if (val2 != null && Object.op_Implicit((Object)(object)val2))
				{
					UpdatePlayer(val2, AdditionalHexEffects.HeldStacks(inventory.GetValue(val2), "WeightedHexDisorientation"), authoritative);
				}
			}
		}
	}

	private static void UpdatePlayer(Component owner, int stacks, bool authoritative)
	{
		if (stacks == 0)
		{
			if (States.TryGetValue(owner, out var value))
			{
				if (value.Original != null)
				{
					object? obj = getBody.Invoke(owner, null);
					Apply(owner, (Component)((obj is Component) ? obj : null), value.Original);
				}
				States.Remove(owner);
			}
			return;
		}
		PlayerState orCreateValue = States.GetOrCreateValue(owner);
		if (stacks > orCreateValue.Stacks)
		{
			orCreateValue.Progress = 1f;
		}
		orCreateValue.Stacks = stacks;
		orCreateValue.Progress += Time.fixedDeltaTime / Interval(stacks);
		if (orCreateValue.Progress < 1f)
		{
			return;
		}
		object? obj2 = getBody.Invoke(owner, null);
		Component val = (Component)((obj2 is Component) ? obj2 : null);
		if (val == null || !Object.op_Implicit((Object)(object)val))
		{
			return;
		}
		orCreateValue.Progress = 0f;
		if (!authoritative)
		{
			return;
		}
		object value2 = masterLoadout.GetValue(owner);
		object loadout = Clone(value2);
		if (Reroll(loadout, bodyIndex.GetValue(val)))
		{
			if (orCreateValue.Original == null)
			{
				orCreateValue.Original = Clone(value2);
			}
			Apply(owner, val, loadout);
		}
	}

	private static float Interval(int stacks)
	{
		return 30f / (1f + 0.25f * (float)(stacks - 1));
	}

	internal static string Countdown(Component owner)
	{
		if (!States.TryGetValue(owner, out var value))
		{
			return null;
		}
		int num = Mathf.CeilToInt(Mathf.Clamp01(1f - value.Progress) * Interval(value.Stacks));
		return $"Next loadout reroll: {num / 60}:{num % 60:00}";
	}

	private static object Clone(object source)
	{
		object obj = Activator.CreateInstance(masterLoadout.FieldType);
		copyLoadout.Invoke(source, new object[1] { obj });
		return obj;
	}

	private static bool Reroll(object loadout, object index)
	{
		Array array = (Array)getSlots.Invoke(null, new object[1] { index });
		if (array == null)
		{
			return false;
		}
		object value = bodyLoadouts.GetValue(loadout);
		bool result = false;
		for (int i = 0; i < array.Length; i++)
		{
			object? value2 = array.GetValue(i);
			Component val = (Component)((value2 is Component) ? value2 : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				continue;
			}
			object? value3 = family.GetValue(val);
			ScriptableObject val2 = (ScriptableObject)((value3 is ScriptableObject) ? value3 : null);
			if (val2 != null && Object.op_Implicit((Object)(object)val2) && variants.GetValue(val2) is Array { Length: >=2 } array2)
			{
				uint num = (uint)getVariant.Invoke(value, new object[2] { index, i });
				int num2 = Random.Range(0, array2.Length);
				if (num2 != num)
				{
					setVariant.Invoke(value, new object[3]
					{
						index,
						i,
						(uint)num2
					});
					result = true;
				}
			}
		}
		return result;
	}

	private static void CaptureClientLoadout(Component __instance, out object __state)
	{
		__state = ((!(bool)serverActive.GetValue(null) && Object.op_Implicit((Object)(object)__instance.GetComponent(playerController))) ? Clone(masterLoadout.GetValue(__instance)) : null);
	}

	private static void SyncClientSkills(Component __instance, object __state)
	{
		if (__state == null)
		{
			return;
		}
		object? obj = getBody.Invoke(__instance, null);
		Component val = (Component)((obj is Component) ? obj : null);
		if (val == null || !Object.op_Implicit((Object)(object)val))
		{
			return;
		}
		object? value = locator.GetValue(val);
		Component val2 = (Component)((value is Component) ? value : null);
		if (val2 == null || !Object.op_Implicit((Object)(object)val2))
		{
			return;
		}
		object value2 = bodyLoadouts.GetValue(__state);
		object value3 = bodyLoadouts.GetValue(masterLoadout.GetValue(__instance));
		object value4 = bodyIndex.GetValue(val);
		Array array = (Array)allSkills.GetValue(val2);
		for (int i = 0; i < array.Length; i++)
		{
			object[] parameters = new object[2] { value4, i };
			uint num = (uint)getVariant.Invoke(value2, parameters);
			uint num2 = (uint)getVariant.Invoke(value3, parameters);
			if (num == num2)
			{
				continue;
			}
			object? value5 = array.GetValue(i);
			Component val3 = (Component)((value5 is Component) ? value5 : null);
			if (val3 == null || !Object.op_Implicit((Object)(object)val3))
			{
				continue;
			}
			object value6 = family.GetValue(val3);
			if (value6 != null && variants.GetValue(value6) is Array array2 && num2 < array2.Length)
			{
				object value7 = variantSkill.GetValue(array2.GetValue((int)num2));
				if (value7 != null && !object.Equals(baseSkill.GetValue(val3), value7))
				{
					setBaseSkill.Invoke(val3, new object[1] { value7 });
				}
			}
		}
	}

	private static void Apply(Component owner, Component body, object loadout)
	{
		applyMaster.Invoke(owner, new object[1] { loadout });
		if (Object.op_Implicit((Object)(object)body))
		{
			applyBody.Invoke(body, new object[1] { loadout });
		}
	}
}
internal static class HexOfEvolution
{
	internal const string InternalName = "WeightedHexEvolution";

	private static FieldInfo requestedElite;

	private static FieldInfo eliteTiers;

	private static FieldInfo eliteTypes;

	private static FieldInfo eliteEquipment;

	private static FieldInfo team;

	private static FieldInfo halcyonSpawn;

	private static FieldInfo bossDirector;

	private static FieldInfo cardPrefab;

	private static FieldInfo spawnCard;

	private static FieldInfo bodyPrefab;

	private static FieldInfo healthBoost;

	private static FieldInfo damageBoost;

	private static FieldInfo boostHp;

	private static FieldInfo boostDamage;

	private static object monsterTeam;

	private static object noEquipment;

	private static Type masterType;

	private static PropertyInfo teleporter;

	private static PropertyInfo inventory;

	private static PropertyInfo isElite;

	private static PropertyInfo equipmentIndex;

	private static PropertyInfo activeEquipment;

	private static PropertyInfo equipmentLocation;

	private static PropertyInfo teamForMaster;

	private static MethodInfo getBody;

	private static MethodInfo giveItem;

	private static MethodInfo setEquipment;

	[ThreadStatic]
	private static int scriptedSpawnDepth;

	internal static void Install()
	{
		//IL_02af: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b5: Expected O, but got Unknown
		Type type = AccessTools.TypeByName("RoR2.CombatDirector");
		Type type2 = AccessTools.TypeByName("RoR2.CombatDirector+SpawnArgs");
		requestedElite = AccessTools.Field(type2, "eliteDef");
		eliteTiers = AccessTools.Field(type, "eliteTiers");
		eliteTypes = AccessTools.Field(eliteTiers.FieldType.GetElementType(), "eliteTypes");
		eliteEquipment = AccessTools.Field(requestedElite.FieldType, "eliteEquipmentDef");
		team = AccessTools.Field(type, "teamIndex");
		halcyonSpawn = AccessTools.Field(type, "isHalcyonShrineSpawn");
		monsterTeam = Enum.Parse(team.FieldType, "Monster");
		Type type3 = AccessTools.TypeByName("RoR2.TeleporterInteraction");
		teleporter = AccessTools.Property(type3, "instance");
		bossDirector = AccessTools.Field(type3, "bossDirector");
		masterType = AccessTools.TypeByName("RoR2.CharacterMaster");
		getBody = AccessTools.Method(masterType, "GetBody", (Type[])null, (Type[])null);
		teamForMaster = AccessTools.Property(masterType, "teamIndex");
		spawnCard = AccessTools.Field(type2, "spawnCard");
		cardPrefab = AccessTools.Field(spawnCard.FieldType, "prefab");
		bodyPrefab = AccessTools.Field(masterType, "bodyPrefab");
		inventory = AccessTools.Property(masterType, "inventory");
		isElite = AccessTools.Property(getBody.ReturnType, "isElite");
		equipmentIndex = AccessTools.Property(eliteEquipment.FieldType, "equipmentIndex");
		activeEquipment = AccessTools.Property(inventory.PropertyType, "currentEquipmentIndex");
		equipmentLocation = AccessTools.Property(inventory.PropertyType, "activeEquipmentLocation");
		noEquipment = Enum.Parse(equipmentIndex.PropertyType, "None");
		setEquipment = AccessTools.Method(inventory.PropertyType, "SetEquipmentIndex", new Type[2]
		{
			equipmentIndex.PropertyType,
			equipmentLocation.PropertyType.MakeByRefType()
		}, (Type[])null);
		Type type4 = AccessTools.TypeByName("RoR2.RoR2Content+Items");
		boostHp = AccessTools.Field(type4, "BoostHp");
		boostDamage = AccessTools.Field(type4, "BoostDamage");
		giveItem = AccessTools.Method(inventory.PropertyType, "GiveItemPermanent", new Type[2]
		{
			boostHp.FieldType,
			typeof(int)
		}, (Type[])null);
		healthBoost = AccessTools.Field(requestedElite.FieldType, "healthBoostCoefficient");
		damageBoost = AccessTools.Field(requestedElite.FieldType, "damageBoostCoefficient");
		Harmony val = new Harmony("evan.weightedhexdrops.evolution");
		val.Patch((MethodBase)AccessTools.DeclaredMethod(type, "Spawn", new Type[1] { type2 }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, Patch("ChooseSpawnElite"), (HarmonyMethod)null, (HarmonyMethod)null);
		Type type5 = AccessTools.TypeByName("RoR2.ScriptedCombatEncounter");
		val.Patch((MethodBase)AccessTools.DeclaredMethod(type5, "Spawn", (Type[])null, (Type[])null), Patch("BeginScriptedSpawn"), (HarmonyMethod)null, (HarmonyMethod)null, Patch("EndScriptedSpawn"), (HarmonyMethod)null);
		val.Patch((MethodBase)AccessTools.DeclaredMethod(AccessTools.TypeByName("RoR2.DirectorCore"), "TrySpawnObject", (Type[])null, (Type[])null), (HarmonyMethod)null, Patch("ConvertScriptedBoss"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
	}

	private static HarmonyMethod Patch(string name)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Expected O, but got Unknown
		return new HarmonyMethod(typeof(HexOfEvolution), name, (Type[])null);
	}

	private static void BeginScriptedSpawn()
	{
		scriptedSpawnDepth++;
	}

	private static void EndScriptedSpawn()
	{
		scriptedSpawnDepth--;
	}

	private static void ConvertScriptedBoss(GameObject __result)
	{
		if (scriptedSpawnDepth == 0 || !Object.op_Implicit((Object)(object)__result))
		{
			return;
		}
		Component component = __result.GetComponent(masterType);
		if (component == null || !object.Equals(teamForMaster.GetValue(component), monsterTeam))
		{
			return;
		}
		object? obj = getBody.Invoke(component, null);
		Component val = (Component)((obj is Component) ? obj : null);
		if (!Object.op_Implicit((Object)(object)val) || (bool)isElite.GetValue(val))
		{
			return;
		}
		object value = inventory.GetValue(component);
		if (value == null || !object.Equals(activeEquipment.GetValue(value), noEquipment))
		{
			return;
		}
		bool flag = HexOfResurrection.IsMajorBoss(((Object)val).name);
		if (flag || ((Object)val).name.StartsWith("SuperRoboBallBoss", StringComparison.Ordinal))
		{
			ScriptableObject val2 = SelectElite(flag, !flag);
			if (Object.op_Implicit((Object)(object)val2))
			{
				object value2 = equipmentIndex.GetValue(eliteEquipment.GetValue(val2));
				setEquipment.Invoke(value, new object[2]
				{
					value2,
					equipmentLocation.GetValue(value)
				});
				giveItem.Invoke(value, new object[2]
				{
					boostHp.GetValue(null),
					Mathf.RoundToInt(((float)healthBoost.GetValue(val2) - 1f) * 10f)
				});
				giveItem.Invoke(value, new object[2]
				{
					boostDamage.GetValue(null),
					Mathf.RoundToInt(((float)damageBoost.GetValue(val2) - 1f) * 10f)
				});
			}
		}
	}

	private static IEnumerable<CodeInstruction> ChooseSpawnElite(IEnumerable<CodeInstruction> instructions)
	{
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Expected O, but got Unknown
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Expected O, but got Unknown
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Expected O, but got Unknown
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Expected O, but got Unknown
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Expected O, but got Unknown
		List<CodeInstruction> list = instructions.ToList();
		int num = list.FindIndex((CodeInstruction instruction) => instruction.opcode == OpCodes.Ldfld && object.Equals(instruction.operand, requestedElite));
		if (num < 0)
		{
			throw new InvalidOperationException("Could not find the elite definition read in CombatDirector.Spawn.");
		}
		list.InsertRange(num + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[5]
		{
			new CodeInstruction(OpCodes.Ldarg_0, (object)null),
			new CodeInstruction(OpCodes.Ldarga_S, (object)(byte)1),
			new CodeInstruction(OpCodes.Ldfld, (object)spawnCard),
			new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(HexOfEvolution), "RollElite", (Type[])null, (Type[])null)),
			new CodeInstruction(OpCodes.Castclass, (object)requestedElite.FieldType)
		});
		return list;
	}

	private static ScriptableObject RollElite(ScriptableObject original, Component director, ScriptableObject card)
	{
		if (Object.op_Implicit((Object)(object)original) || !object.Equals(team.GetValue(director), monsterTeam) || (bool)halcyonSpawn.GetValue(director))
		{
			return original;
		}
		object? value = teleporter.GetValue(null);
		Component val = (Component)((value is Component) ? value : null);
		GameObject val2 = (GameObject)(Object.op_Implicit((Object)(object)card) ? /*isinst with value type is only supported in some contexts*/: null);
		Component val3 = (Object.op_Implicit((Object)(object)val2) ? val2.GetComponent(masterType) : null);
		GameObject val4 = (GameObject)(Object.op_Implicit((Object)(object)val3) ? /*isinst with value type is only supported in some contexts*/: null);
		bool major = Object.op_Implicit((Object)(object)val4) && HexOfResurrection.IsMajorBoss(((Object)val4).name);
		bool miniboss = (Object.op_Implicit((Object)(object)val) && object.Equals(bossDirector.GetValue(val), director)) || (Object.op_Implicit((Object)(object)val4) && ((Object)val4).name.StartsWith("SuperRoboBallBoss", StringComparison.Ordinal));
		return SelectElite(major, miniboss);
	}

	private static ScriptableObject SelectElite(bool major, bool miniboss)
	{
		long num = AdditionalHexEffects.TeamStacks("WeightedHexEvolution");
		if (num <= 0)
		{
			return null;
		}
		double num2 = 1.0 - 0.7 * Math.Pow(0.8, num - 1);
		if ((double)Random.value >= (major ? 0.1 : (miniboss ? (num2 * 0.5) : num2)))
		{
			return null;
		}
		bool flag = num >= 3 || Random.value < ((num == 1) ? 0.4f : 0.7f);
		Array tiers = (Array)eliteTiers.GetValue(null);
		if (tiers == null)
		{
			return null;
		}
		ScriptableObject[] array = ((!flag) ? new int[3] { 1, 4, 6 } : new int[1] { 5 }).Where((int index) => index < tiers.Length && tiers.GetValue(index) != null).SelectMany((int index) => ((Array)eliteTypes.GetValue(tiers.GetValue(index))).Cast<ScriptableObject>()).Where(delegate(ScriptableObject elite)
		{
			if (Object.op_Implicit((Object)(object)elite))
			{
				object? value = eliteEquipment.GetValue(elite);
				ScriptableObject val = (ScriptableObject)((value is ScriptableObject) ? value : null);
				if (val != null)
				{
					return Object.op_Implicit((Object)(object)val);
				}
			}
			return false;
		})
			.Distinct()
			.ToArray();
		if (array.Length != 0)
		{
			return array[Random.Range(0, array.Length)];
		}
		return null;
	}
}
internal static class HexOfImpersonation
{
	private sealed class Timer
	{
		public int Stacks;

		public double Progress;

		public float Retry;
	}

	internal const string InternalName = "WeightedHexImpersonation";

	private static readonly ConditionalWeakTable<Component, Timer> Timers = new ConditionalWeakTable<Component, Timer>();

	private static PropertyInfo players;

	private static PropertyInfo playerMaster;

	private static PropertyInfo connected;

	private static PropertyInfo inventory;

	private static PropertyInfo health;

	private static PropertyInfo alive;

	private static PropertyInfo server;

	private static PropertyInfo sceneInstance;

	private static PropertyInfo sceneDef;

	private static PropertyInfo trialState;

	private static PropertyInfo footPosition;

	private static FieldInfo sceneType;

	private static FieldInfo requestCard;

	private static FieldInfo placement;

	private static FieldInfo target;

	private static FieldInfo position;

	private static FieldInfo descriptorMaster;

	private static FieldInfo descriptorSource;

	private static FieldInfo descriptorType;

	private static FieldInfo trackerSource;

	private static FieldInfo placementMode;

	private static FieldInfo spawnPosition;

	private static MethodInfo getBody;

	private static MethodInfo createClone;

	private static MethodInfo findTrials;

	private static ConstructorInfo makeRng;

	private static Type trialType;

	private static Type spawnCardType;

	private static Type sourceType;

	private static Type trackerType;

	private static Type disorientationTracker;

	private static bool paused;

	private static Component invasionBody;

	private static bool cloneSpawned;

	private static bool useDirectPlacement;

	private static object directPlacement;

	internal static void Install()
	{
		//IL_0322: Unknown result type (might be due to invalid IL or missing references)
		//IL_0329: Expected O, but got Unknown
		Type type = AccessTools.TypeByName("RoR2.PlayerCharacterMasterController");
		players = AccessTools.Property(type, "instances");
		playerMaster = AccessTools.Property(type, "master");
		connected = AccessTools.Property(type, "isConnected");
		inventory = AccessTools.Property(playerMaster.PropertyType, "inventory");
		getBody = AccessTools.Method(playerMaster.PropertyType, "GetBody", (Type[])null, (Type[])null);
		health = AccessTools.Property(getBody.ReturnType, "healthComponent");
		alive = AccessTools.Property(health.PropertyType, "alive");
		footPosition = AccessTools.Property(getBody.ReturnType, "footPosition");
		server = AccessTools.Property(AccessTools.TypeByName("UnityEngine.Networking.NetworkServer"), "active");
		Type type2 = AccessTools.TypeByName("RoR2.SceneInfo");
		sceneInstance = AccessTools.Property(type2, "instance");
		sceneDef = AccessTools.Property(type2, "sceneDef");
		sceneType = AccessTools.Field(sceneDef.PropertyType, "sceneType");
		trialType = AccessTools.TypeByName("RoR2.TrialController");
		trialState = AccessTools.Property(trialType, "trialControllerState");
		findTrials = AccessTools.Method(AccessTools.TypeByName("RoR2.InstanceTracker"), "FindInstancesEnumerable", new Type[1] { typeof(Type) }, (Type[])null);
		createClone = AccessTools.DeclaredMethod(AccessTools.TypeByName("RoR2.Artifacts.DoppelgangerInvasionManager"), "CreateDoppelganger", (Type[])null, (Type[])null);
		makeRng = createClone.GetParameters()[1].ParameterType.GetConstructor(new Type[1] { typeof(ulong) });
		spawnCardType = AccessTools.TypeByName("RoR2.Artifacts.DoppelgangerSpawnCard");
		Type type3 = AccessTools.TypeByName("RoR2.DirectorSpawnRequest");
		requestCard = AccessTools.Field(type3, "spawnCard");
		placement = AccessTools.Field(type3, "placementRule");
		target = AccessTools.Field(placement.FieldType, "spawnOnTarget");
		position = AccessTools.Field(placement.FieldType, "position");
		placementMode = AccessTools.Field(placement.FieldType, "placementMode");
		directPlacement = Enum.Parse(placementMode.FieldType, "Direct");
		Type type4 = AccessTools.TypeByName("RoR2.DirectorCore");
		MethodInfo methodInfo = AccessTools.DeclaredMethod(type4, "TryGetSpawnPosition", (Type[])null, (Type[])null);
		spawnPosition = AccessTools.Field(methodInfo.GetParameters()[1].ParameterType.GetElementType(), "position");
		Type type5 = AccessTools.TypeByName("RoR2.UI.ObjectivePanelController");
		Type nestedType = type5.GetNestedType("ObjectiveTracker");
		sourceType = type5.GetNestedType("ObjectiveSourceDescriptor");
		descriptorMaster = AccessTools.Field(sourceType, "master");
		descriptorSource = AccessTools.Field(sourceType, "source");
		descriptorType = AccessTools.Field(sourceType, "objectiveType");
		trackerSource = AccessTools.Field(nestedType, "sourceDescriptor");
		trackerType = type5.GetNestedType("FinishTeleporterObjectiveTracker", BindingFlags.NonPublic);
		disorientationTracker = type5.GetNestedType("DefeatSolusWing", BindingFlags.NonPublic);
		Harmony val = new Harmony("evan.weightedhexdrops.impersonation");
		val.Patch((MethodBase)AccessTools.Method(type4, "TrySpawnObject", new Type[1] { type3 }, (Type[])null), Patch("PlaceNearPlayer"), Patch("RecordSpawn"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, Patch("RejectDistantNode"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)AccessTools.DeclaredMethod(type5, "GetObjectiveSources", (Type[])null, (Type[])null), (HarmonyMethod)null, Patch("AddObjective"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)AccessTools.DeclaredMethod(nestedType, "GetString", (Type[])null, (Type[])null), (HarmonyMethod)null, Patch("ShowCountdown"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		AccessTools.TypeByName("RoR2.RoR2Application").GetEvent("onFixedUpdate").AddEventHandler(null, new Action(Tick));
	}

	private static HarmonyMethod Patch(string name)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Expected O, but got Unknown
		return new HarmonyMethod(typeof(HexOfImpersonation), name, (Type[])null);
	}

	private static bool IsSafe()
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		object? value = sceneInstance.GetValue(null);
		Component val = (Component)((value is Component) ? value : null);
		if (val != null && Object.op_Implicit((Object)(object)val))
		{
			object? value2 = sceneDef.GetValue(val);
			ScriptableObject val2 = (ScriptableObject)((value2 is ScriptableObject) ? value2 : null);
			if (val2 != null && Object.op_Implicit((Object)(object)val2))
			{
				Scene scene = val.gameObject.scene;
				string name = ((Scene)(ref scene)).name;
				if (name == "bazaar" || name == "computationalexchange" || sceneType.GetValue(val2).ToString() == "Intermission")
				{
					return true;
				}
				if (findTrials.Invoke(null, new object[1] { trialType }) is IEnumerable enumerable)
				{
					foreach (object item in enumerable)
					{
						Component val3 = (Component)((item is Component) ? item : null);
						if (val3 != null && Object.op_Implicit((Object)(object)val3) && val3.gameObject.scene == val.gameObject.scene)
						{
							string text = trialState.GetValue(val3).ToString();
							if (text == "MissionComplete" || text == "MissionFailure")
							{
								return true;
							}
						}
					}
				}
				return false;
			}
		}
		return true;
	}

	private static double Interval(int stacks)
	{
		return 300.0 * Math.Pow(0.75, stacks - 1);
	}

	private static void Tick()
	{
		bool flag = (bool)server.GetValue(null);
		bool flag2 = false;
		foreach (object item in (IEnumerable)players.GetValue(null))
		{
			Component val = (Component)((item is Component) ? item : null);
			if (val == null || !Object.op_Implicit((Object)(object)val) || !(bool)connected.GetValue(val))
			{
				continue;
			}
			object? value = playerMaster.GetValue(val);
			Component val2 = (Component)((value is Component) ? value : null);
			if (val2 == null || !Object.op_Implicit((Object)(object)val2))
			{
				continue;
			}
			int num = AdditionalHexEffects.HeldStacks(inventory.GetValue(val2), "WeightedHexImpersonation");
			if (num == 0)
			{
				Timers.Remove(val2);
				continue;
			}
			if (!flag2)
			{
				paused = IsSafe();
				flag2 = true;
			}
			Timer orCreateValue = Timers.GetOrCreateValue(val2);
			if (num > orCreateValue.Stacks)
			{
				orCreateValue.Progress = 1.0;
				orCreateValue.Retry = 0f;
			}
			orCreateValue.Stacks = num;
			if (paused)
			{
				continue;
			}
			object? obj = getBody.Invoke(val2, null);
			Component val3 = (Component)((obj is Component) ? obj : null);
			if (val3 == null || !Object.op_Implicit((Object)(object)val3))
			{
				continue;
			}
			object? value2 = health.GetValue(val3);
			Component val4 = (Component)((value2 is Component) ? value2 : null);
			if (val4 == null || !Object.op_Implicit((Object)(object)val4) || !(bool)alive.GetValue(val4))
			{
				continue;
			}
			orCreateValue.Progress = Math.Min(1.0, orCreateValue.Progress + (double)Time.fixedDeltaTime / Interval(num));
			orCreateValue.Retry -= Time.fixedDeltaTime;
			if (!(orCreateValue.Progress < 1.0) && !(orCreateValue.Retry > 0f))
			{
				if (!flag || Spawn(val2, val3))
				{
					orCreateValue.Progress = 0.0;
				}
				else
				{
					orCreateValue.Retry = 1f;
				}
			}
		}
	}

	private static bool Spawn(Component owner, Component body)
	{
		invasionBody = body;
		cloneSpawned = false;
		try
		{
			object obj = makeRng.Invoke(new object[1] { (ulong)Random.Range(1, int.MaxValue) });
			createClone.Invoke(null, new object[2] { owner, obj });
			if (!cloneSpawned)
			{
				useDirectPlacement = true;
				createClone.Invoke(null, new object[2] { owner, obj });
			}
			return cloneSpawned;
		}
		finally
		{
			invasionBody = null;
			useDirectPlacement = false;
		}
	}

	private static bool IsInvasionRequest(object request)
	{
		if (Object.op_Implicit((Object)(object)invasionBody))
		{
			return spawnCardType.IsInstanceOfType(requestCard.GetValue(request));
		}
		return false;
	}

	private static void PlaceNearPlayer(object __0)
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		if (IsInvasionRequest(__0))
		{
			object value = placement.GetValue(__0);
			Vector3 val = (Vector3)footPosition.GetValue(invasionBody);
			target.SetValue(value, null);
			position.SetValue(value, val);
			if (useDirectPlacement)
			{
				placementMode.SetValue(value, directPlacement);
			}
		}
	}

	private static void RejectDistantNode(object __0, object __1, ref bool __result)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: 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_003a: 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)
		if (__result && !useDirectPlacement && IsInvasionRequest(__0))
		{
			Vector3 val = (Vector3)footPosition.GetValue(invasionBody);
			Vector3 val2 = (Vector3)spawnPosition.GetValue(__1) - val;
			if (((Vector3)(ref val2)).sqrMagnitude > 64f)
			{
				__result = false;
			}
		}
	}

	private static void RecordSpawn(object __0, GameObject __result)
	{
		if (Object.op_Implicit((Object)(object)__result) && IsInvasionRequest(__0))
		{
			cloneSpawned = true;
		}
	}

	private static void AddObjective(Component __0, IList __1)
	{
		if (Object.op_Implicit((Object)(object)__0))
		{
			if (Timers.TryGetValue(__0, out var _))
			{
				AddObjectiveRow(__0, __1, trackerType);
			}
			if (HexOfDisorientation.Countdown(__0) != null)
			{
				AddObjectiveRow(__0, __1, disorientationTracker);
			}
		}
	}

	private static void AddObjectiveRow(Component owner, IList rows, Type tracker)
	{
		object obj = Activator.CreateInstance(sourceType);
		descriptorMaster.SetValue(obj, owner);
		descriptorSource.SetValue(obj, owner);
		descriptorType.SetValue(obj, tracker);
		rows.Add(obj);
	}

	private static void ShowCountdown(object __instance, ref string __result)
	{
		Type type = __instance.GetType();
		if (type != trackerType && type != disorientationTracker)
		{
			return;
		}
		object? value = descriptorMaster.GetValue(trackerSource.GetValue(__instance));
		Component val = (Component)((value is Component) ? value : null);
		if (val == null || !object.Equals(descriptorSource.GetValue(trackerSource.GetValue(__instance)), val))
		{
			return;
		}
		Timer value2;
		if (type == disorientationTracker)
		{
			__result = HexOfDisorientation.Countdown(val) ?? string.Empty;
		}
		else if (Timers.TryGetValue(val, out value2))
		{
			double num = Math.Ceiling((1.0 - value2.Progress) * Interval(value2.Stacks));
			__result = $"Next Vengeance invasion: {Math.Floor(num / 60.0):0}:{num % 60.0:00}";
			if (paused)
			{
				__result += " (paused)";
			}
		}
	}
}
internal static class HexOfRegression
{
	private sealed class LevelDisplay
	{
		internal bool WasRichText;

		internal Component EffectiveLabel;
	}

	internal const string InternalName = "WeightedHexRegression";

	private static MethodInfo getLevel;

	private static PropertyInfo inventory;

	private static PropertyInfo text;

	private static PropertyInfo richText;

	private static FieldInfo source;

	private static FieldInfo targetText;

	private static readonly ConditionalWeakTable<Component, LevelDisplay> Displays = new ConditionalWeakTable<Component, LevelDisplay>();

	internal static void Install()
	{
		//IL_008d: 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_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Expected O, but got Unknown
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ea: Expected O, but got Unknown
		Type type = AccessTools.TypeByName("RoR2.CharacterBody");
		getLevel = AccessTools.PropertyGetter(type, "level");
		inventory = AccessTools.Property(type, "inventory");
		Type type2 = AccessTools.TypeByName("RoR2.UI.LevelText");
		source = AccessTools.Field(type2, "source");
		targetText = AccessTools.Field(type2, "targetText");
		text = AccessTools.Property(targetText.FieldType, "text");
		richText = AccessTools.Property(targetText.FieldType, "richText");
		Harmony val = new Harmony("evan.weightedhexdrops.regression");
		val.Patch((MethodBase)AccessTools.DeclaredMethod(type, "RecalculateStats", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(HexOfRegression), "ScaleLevelGrowth", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)AccessTools.DeclaredMethod(type2, "Update", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(HexOfRegression), "UpdateLevelText", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
	}

	private static IEnumerable<CodeInstruction> ScaleLevelGrowth(IEnumerable<CodeInstruction> instructions)
	{
		List<CodeInstruction> list = instructions.ToList();
		MethodInfo operand = AccessTools.DeclaredMethod(typeof(HexOfRegression), "LevelForStatGrowth", (Type[])null, (Type[])null);
		int num = 0;
		for (int i = 0; i + 2 < list.Count; i++)
		{
			if (CodeInstructionExtensions.Calls(list[i], getLevel) && !(list[i + 1].opcode != OpCodes.Ldc_R4) && object.Equals(list[i + 1].operand, 1f) && !(list[i + 2].opcode != OpCodes.Sub))
			{
				list[i].opcode = OpCodes.Call;
				list[i].operand = operand;
				num++;
			}
		}
		if (num != 2)
		{
			throw new InvalidOperationException($"Expected two level growth calculations, found {num}.");
		}
		return list;
	}

	private static float LevelForStatGrowth(Component body)
	{
		float num = (float)getLevel.Invoke(body, null);
		int num2 = AdditionalHexEffects.HeldStacks(inventory.GetValue(body), "WeightedHexRegression");
		if (num2 <= 0)
		{
			return num;
		}
		return EffectiveLevel(num, num2);
	}

	private static float EffectiveLevel(float actual, int stacks)
	{
		return 1f + Mathf.Max(0f, actual - 1f) * Mathf.Pow(0.8f, (float)stacks);
	}

	private static void UpdateLevelText(Component __instance)
	{
		object? value = targetText.GetValue(__instance);
		Component val = (Component)((value is Component) ? value : null);
		if (val == null || !Object.op_Implicit((Object)(object)val))
		{
			return;
		}
		object? value2 = source.GetValue(__instance);
		Component val2 = (Component)((value2 is Component) ? value2 : null);
		int num = (Object.op_Implicit((Object)(object)val2) ? AdditionalHexEffects.HeldStacks(inventory.GetValue(val2), "WeightedHexRegression") : 0);
		if (num == 0)
		{
			if (Displays.TryGetValue(val, out var value3))
			{
				richText.SetValue(val, value3.WasRichText);
				string value4 = (Object.op_Implicit((Object)(object)val2) ? Mathf.Floor((float)getLevel.Invoke(val2, null)).ToString("0", CultureInfo.InvariantCulture) : string.Empty);
				HexOfRegression.text.SetValue(val, value4);
				if (Object.op_Implicit((Object)(object)value3.EffectiveLabel))
				{
					Object.Destroy((Object)(object)value3.EffectiveLabel.gameObject);
				}
				Displays.Remove(val);
			}
			return;
		}
		LevelDisplay value5 = Displays.GetValue(val, delegate(Component key)
		{
			//IL_003a: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			Component val3 = Object.Instantiate<Component>(key, key.transform.parent, false);
			Component component = val3.GetComponent(((object)__instance).GetType());
			Behaviour val4 = (Behaviour)(object)((component is Behaviour) ? component : null);
			if (val4 != null)
			{
				val4.enabled = false;
			}
			RectTransform val5 = (RectTransform)val3.transform;
			val5.anchoredPosition += new Vector2(0f, 15f);
			richText.SetValue(val3, true);
			return new LevelDisplay
			{
				WasRichText = (bool)richText.GetValue(key),
				EffectiveLabel = val3
			};
		});
		float num2 = (float)getLevel.Invoke(val2, null);
		string text = Mathf.Floor(num2).ToString("0", CultureInfo.InvariantCulture);
		string text2 = EffectiveLevel(num2, num).ToString("0.#", CultureInfo.InvariantCulture);
		SetText(val, "<s>" + text + "</s>");
		SetText(value5.EffectiveLabel, "<color=#C9EF50>" + text2 + "</color>");
	}

	private static void SetText(Component label, string value)
	{
		if (!object.Equals(text.GetValue(label), value))
		{
			richText.SetValue(label, true);
			text.SetValue(label, value);
		}
	}
}
internal static class HexOfResurrection
{
	private sealed class Phase
	{
		public Component Encounter;

		public bool MultipleMembers;

		public bool Replayed;
	}

	internal const string InternalName = "WeightedHexResurrection";

	private static readonly ConditionalWeakTable<Component, object> Revived = new ConditionalWeakTable<Component, object>();

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

	private static readonly ConditionalWeakTable<Component, Phase> Phases = new ConditionalWeakTable<Component, Phase>();

	private static Component replayingGroup;

	private static Type deathRewardsType;

	private static Type encounterType;

	private static FieldInfo victim;

	private static FieldInfo victimBody;

	private static FieldInfo victimMaster;

	private static FieldInfo victimTeam;

	private static FieldInfo bossGroup;

	private static FieldInfo flags;

	private static FieldInfo deathProcChance;

	private static FieldInfo soulSurge;

	private static FieldInfo eventManager;

	private static PropertyInfo health;

	private static PropertyInfo shield;

	private static PropertyInfo maxHealth;

	private static PropertyInfo alive;

	private static PropertyInfo teleporter;

	private static PropertyInfo squad;

	private static PropertyInfo memberCount;

	private static MethodInfo awardDeath;

	private static MethodInfo awardBoss;

	private static MethodInfo deathProc;

	private static MethodInfo containsMember;

	private static MethodInfo hasBuff;

	private static MethodInfo forceSpawn;

	private static MethodInfo getBody;

	private static PropertyInfo getBodyHealth;

	private static object buddha;

	private static MethodInfo loadReviveEffect;

	private static MethodInfo spawnEffect;

	private static GameObject reviveEffect;

	internal static void Install()
	{
		//IL_031d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0324: Expected O, but got Unknown
		Type type = AccessTools.TypeByName("RoR2.GlobalEventManager");
		Type type2 = AccessTools.TypeByName("RoR2.DamageReport");
		Type type3 = AccessTools.TypeByName("RoR2.HealthComponent");
		Type type4 = AccessTools.TypeByName("RoR2.CharacterBody");
		Type type5 = AccessTools.TypeByName("RoR2.BossGroup");
		Type type6 = AccessTools.TypeByName("RoR2.TeleporterInteraction");
		deathRewardsType = AccessTools.TypeByName("RoR2.DeathRewards");
		victim = AccessTools.Field(type2, "victim");
		victimBody = AccessTools.Field(type2, "victimBody");
		victimMaster = AccessTools.Field(type2, "victimMaster");
		victimTeam = AccessTools.Field(type2, "victimTeamIndex");
		health = AccessTools.Property(type3, "Networkhealth");
		shield = AccessTools.Property(type3, "Networkshield");
		maxHealth = AccessTools.Property(type3, "fullHealth");
		alive = AccessTools.Property(type3, "alive");
		deathProcChance = AccessTools.Field(type3, "globalDeathEventChanceCoefficient");
		flags = AccessTools.Field(type4, "bodyFlags");
		buddha = Enum.Parse(flags.FieldType, "Buddha");
		soulSurge = AccessTools.Field(AccessTools.TypeByName("RoR2.DLC2Content+Buffs"), "SoulSurge");
		hasBuff = AccessTools.Method(type4, "HasBuff", new Type[1] { soulSurge.FieldType }, (Type[])null);
		teleporter = AccessTools.Property(type6, "instance");
		bossGroup = AccessTools.Field(type6, "bossGroup");
		squad = AccessTools.Property(type5, "combatSquad");
		memberCount = AccessTools.Property(squad.PropertyType, "memberCount");
		containsMember = AccessTools.Method(squad.PropertyType, "ContainsMember", (Type[])null, (Type[])null);
		awardDeath = AccessTools.Method(deathRewardsType, "OnKilledServer", (Type[])null, (Type[])null);
		awardBoss = AccessTools.DeclaredMethod(type5, "OnMemberDefeatedServer", (Type[])null, (Type[])null);
		deathProc = AccessTools.DeclaredMethod(type, "TriggerCharacterDeathProc", (Type[])null, (Type[])null);
		eventManager = AccessTools.Field(type, "instance");
		encounterType = AccessTools.TypeByName("RoR2.ScriptedCombatEncounter");
		forceSpawn = AccessTools.Method(encounterType, "ForceSpawn", new Type[1] { typeof(int) }, (Type[])null);
		getBody = AccessTools.Method(AccessTools.TypeByName("RoR2.CharacterMaster"), "GetBody", (Type[])null, (Type[])null);
		getBodyHealth = AccessTools.Property(type4, "healthComponent");
		loadReviveEffect = (AccessTools.TypeByName("RoR2.LegacyResourcesAPI") ?? AccessTools.TypeByName("LegacyResourcesAPI"))?.GetMethods().FirstOrDefault((MethodInfo method) => method.Name == "Load" && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 1 && method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(string))?.MakeGenericMethod(typeof(GameObject));
		spawnEffect = AccessTools.Method(AccessTools.TypeByName("RoR2.EffectManager"), "SimpleEffect", new Type[4]
		{
			typeof(GameObject),
			typeof(Vector3),
			typeof(Quaternion),
			typeof(bool)
		}, (Type[])null);
		Harmony val = new Harmony("evan.weightedhexdrops.resurrection");
		val.Patch((MethodBase)AccessTools.DeclaredMethod(type, "ServerDamageDealt", (Type[])null, (Type[])null), (HarmonyMethod)null, Patch("TryResurrect"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)awardDeath, Patch("SkipRepeatRewards"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)deathProc, Patch("SkipRepeatRewards"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)awardBoss, Patch("SkipRepeatBossRewards"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		val.Patch((MethodBase)AccessTools.DeclaredMethod(type5, "OnMemberAddedServer", (Type[])null, (Type[])null), (HarmonyMethod)null, Patch("TrackPhaseMember"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		string[] array = new string[3] { "EntityStates.Missions.BrotherEncounter.BrotherEncounterPhaseBaseState", "EntityStates.Missions.ProvidenceBossEncounter.ProvidenceBossEncounterPhaseBaseState", "EntityStates.MeridianEvent.FSBFPhaseBaseState" };
		for (int num = 0; num < array.Length; num++)
		{
			Type type7 = AccessTools.TypeByName(array[num]);
			if (type7 != null && AccessTools.Field(type7, "phaseBossGroup") != null)
			{
				val.Patch((MethodBase)AccessTools.DeclaredMethod(type7, "OnEnter", (Type[])null, (Type[])null), (HarmonyMethod)null, Patch("RegisterPhase"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}
	}

	private static HarmonyMethod Patch(string method)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Expected O, but got Unknown
		return new HarmonyMethod(typeof(HexOfResurrection), method, (Type[])null);
	}

	private static void RegisterPhase(object __instance)
	{
		object? value = AccessTools.Field(__instance.GetType(), "phaseBossGroup").GetValue(__instance);
		Component val = (Component)((value is Component) ? value : null);
		if (val != null && Object.op_Implicit((Object)(object)val) && !MajorGroups.Contains(val))
		{
			MajorGroups.Add(val);
			Phase orCreateValue = Phases.GetOrCreateValue(val);
			orCreateValue.Encounter = val.GetComponent(encounterType);
			orCreateValue.MultipleMembers = (int)memberCount.GetValue(squad.GetValue(val)) > 1;
		}
	}

	private static void TrackPhaseMember(Component __instance, Component __0)
	{
		if (!Phases.TryGetValue(__instance, out var value))
		{
			return;
		}
		if ((Object)(object)__instance == (Object)(object)replayingGroup)
		{
			object? obj = getBody.Invoke(__0, null);
			Component val = (Component)((obj is Component) ? obj : null);
			if (val != null && Object.op_Implicit((Object)(object)val))
			{
				object? value2 = getBodyHealth.GetValue(val);
				Component val2 = (Component)((value2 is Component) ? value2 : null);
				if (val2 != null && Object.op_Implicit((Object)(object)val2))
				{
					RestoreFullHealth(val2);
				}
			}
		}
		else if ((int)memberCount.GetValue(squad.GetValue(__instance)) > 1)
		{
			value.MultipleMembers = true;
		}
	}

	private static void TryResurrect(object __0)
	{
		object? value = victim.GetValue(__0);
		Component val = (Component)((value is Component) ? value : null);
		if (val == null || !Object.op_Implicit((Object)(object)val) || (bool)alive.GetValue(val))
		{
			return;
		}
		object? value2 = victimBody.GetValue(__0);
		Component val2 = (Component)((value2 is Component) ? value2 : null);
		if (val2 == null || !Object.op_Implicit((Object)(object)val2) || Revived.TryGetValue(val, out var _))
		{
			return;
		}
		string text = victimTeam.GetValue(__0).ToString();
		if (text != "Monster" && text != "Lunar" && text != "Void")
		{
			return;
		}
		long num = AdditionalHexEffects.TeamStacks("WeightedHexResurrection");
		if (num == 0L || (Convert.ToUInt64(flags.GetValue(val2)) & Convert.ToUInt64(buddha)) != 0L)
		{
			return;
		}
		object value4 = soulSurge.GetValue(null);
		if (value4 != null && (bool)hasBuff.Invoke(val2, new object[1] { value4 }))
		{
			return;
		}
		Component master = default(Component);
		ref Component reference = ref master;
		object? value5 = victimMaster.GetValue(__0);
		reference = (Component)((value5 is Component) ? value5 : null);
		MajorGroups.RemoveAll((Component group) => !Object.op_Implicit((Object)(object)group));
		Component val3 = MajorGroups.Find((Component group) => Contains(group, master));
		object? value6 = teleporter.GetValue(null);
		Component val4 = (Component)((value6 is Component) ? value6 : null);
		Component val5 = (Component)(Object.op_Implicit((Object)(object)val4) ? /*isinst with value type is only supported in some contexts*/: null);
		bool flag = Object.op_Implicit((Object)(object)val3) || IsMajorBoss(((Object)val2).name);
		Phase value7 = null;
		if (Object.op_Implicit((Object)(object)val3) && ((Phases.TryGetValue(val3, out value7) && value7.Replayed) || (int)memberCount.GetValue(squad.GetValue(val3)) > 1))
		{
			return;
		}
		double num2 = 1.0 - 0.6 * Math.Pow(0.8, num - 1);
		bool flag2 = Contains(val5, master) || ((Object)val2).name.StartsWith("SuperRoboBallBoss", StringComparison.Ordinal);
		if ((double)Random.value >= (flag ? 0.2 : (flag2 ? (num2 * 0.5) : num2)))
		{
			return;
		}
		if (value7 != null)
		{
			value7.Replayed = true;
			if (value7.MultipleMembers && Object.op_Implicit((Object)(object)value7.Encounter))
			{
				replayingGroup = val3;
				try
				{
					forceSpawn.Invoke(value7.Encounter, new object[1] { int.MaxValue });
				}
				finally
				{
					replayingGroup = null;
				}
				if ((int)memberCount.GetValue(squad.GetValue(val3)) > 1)
				{
					return;
				}
			}
		}
		Component component = val2.GetComponent(deathRewardsType);
		if (component != null && Object.op_Implicit((Object)(object)component))
		{
			awardDeath.Invoke(component, new object[1] { __0 });
		}
		Component val6 = (Object.op_Implicit((Object)(object)val3) ? val3 : ((flag2 && Contains(val5, master)) ? val5 : null));
		if (Object.op_Implicit((Object)(object)val6))
		{
			awardBoss.Invoke(val6, new object[2] { master, __0 });
		}
		if (Random.value < (float)deathProcChance.GetValue(val))
		{
			object? value8 = eventManager.GetValue(null);
			Component val7 = (Component)((value8 is Component) ? value8 : null);
			if (val7 != null && Object.op_Implicit((Object)(object)val7))
			{
				deathProc.Invoke(val7, new object[1] { __0 });
			}
		}
		RestoreFullHealth(val);
	}

	private static void RestoreFullHealth(Component hp)
	{
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		Revived.GetValue(hp, (Component key) => new object());
		health.SetValue(hp, Mathf.Max(1f, (float)maxHealth.GetValue(hp)));
		shield.SetValue(hp, 0f);
		if (!Object.op_Implicit((Object)(object)reviveEffect))
		{
			object? obj = loadReviveEffect?.Invoke(null, new object[1] { "Prefabs/Effects/HippoRezEffect" });
			reviveEffect = (GameObject)((obj is GameObject) ? obj : null);
		}
		if (Object.op_Implicit((Object)(object)reviveEffect))
		{
			spawnEffect?.Invoke(null, new object[4]
			{
				reviveEffect,
				hp.transform.position,
				hp.transform.rotation,
				true
			});
		}
	}

	private static bool Contains(Component group, Component master)
	{
		if (Object.op_Implicit((Object)(object)group) && Object.op_Implicit((Object)(object)master))
		{
			object? value = squad.GetValue(group);
			Component val = (Component)((value is Component) ? value : null);
			if (val != null && Object.op_Implicit((Object)(object)val))
			{
				return (bool)containsMember.Invoke(val, new object[1] { master });
			}
		}
		return false;
	}

	internal static bool IsMajorBoss(string name)
	{
		if (!name.StartsWith("Brother", StringComparison.Ordinal) && !name.StartsWith("TitanGoldBody", StringComparison.Ordinal) && !name.StartsWith("MiniVoidRaidCrabBody", StringComparison.Ordinal) && !name.StartsWith("VoidRaidCrabBody", StringComparison.Ordinal) && !name.StartsWith("FalseSonBossBody", StringComparison.Ordinal) && !name.StartsWith("SolusWingBody", StringComparison.Ordinal) && !name.StartsWith("SolusHeartBody", StringComparison.Ordinal) && !name.StartsWith("ReaperBoss", StringComparison.Ordinal))
		{
			if (name.StartsWith("Providence", StringComparison.Ordinal))
			{
				return name.IndexOf("ShadowClone", StringComparison.Ordinal) < 0;
			}
			return false;
		}
		return true;
	}

	private static bool SkipRepeatRewards(object __0)
	{
		object? value = victim.GetValue(__0);
		Component val = (Component)((value is Component) ? value : null);
		object value2;
		if (val != null)
		{
			return !Revived.TryGetValue(val, out value2);
		}
		return true;
	}

	private static bool SkipRepeatBossRewards(object __1)
	{
		return SkipRepeatRewards(__1);
	}
}
internal static class HexRarityColors
{
	private static object commonColor;

	private static object rareColor;

	private static object reincarnationColor;

	private static MethodInfo getItemDef;

	private static MethodInfo getColor;

	private static FieldInfo asyncImage;

	private static FieldInfo renderer;

	private static FieldInfo spriteReference;

	private static PropertyInfo iconItemIndex;

	private static PropertyInfo texture;

	private static PropertyInfo spriteResult;

	private static Type iconType;

	private static ManualLogSource logger;

	private static Type imageType;

	private static Type childLocatorType;

	private static MethodInfo findChild;

	private static MethodInfo getPickupDef;

	private static FieldInfo entryPickup;

	private static FieldInfo pickupItemIndex;

	private static FieldInfo entryColor;

	private static FieldInfo entryBackground;

	private static FieldInfo pageImage;

	private static PropertyInfo commonBackground;

	private static PropertyInfo rareBackground;

	private static MethodInfo getTierDef;

	private static FieldInfo tierBackground;

	private static object bossTier;

	private static readonly ConditionalWeakTable<Component, object> LogbookColors = new ConditionalWeakTable<Component, object>();

	private static readonly Dictionary<(Texture2D, object), Texture2D> RecoloredIcons = new Dictionary<(Texture2D, object), Texture2D>();

	internal static void Install(ManualLogSource log)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Expected O, but got Unknown
		//IL_0221: Unknown result type (might be due to invalid IL or missing references)
		//IL_022e: Expected O, but got Unknown
		//IL_0252: Unknown result type (might be due to invalid IL or missing references)
		//IL_025f: Expected O, but got Unknown
		logger = log;
		Harmony val = new Harmony("evan.weightedhexdrops.raritycolors");
		try
		{
			Type type = AccessTools.TypeByName("RoR2.ItemDef");
			MethodInfo methodInfo = AccessTools.PropertyGetter(type, "colorIndex");
			MethodInfo methodInfo2 = AccessTools.PropertyGetter(type, "darkColorIndex");
			commonColor = Enum.Parse(methodInfo.ReturnType, "Tier1Item");
			rareColor = Enum.Parse(methodInfo.ReturnType, "Tier3Item");
			reincarnationColor = Enum.Parse(methodInfo.ReturnType, "BossItem");
			HarmonyMethod val2 = new HarmonyMethod(AccessTools.Method(typeof(HexRarityColors), "ApplyColor", (Type[])null, (Type[])null).MakeGenericMethod(methodInfo.ReturnType));
			val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		catch (Exception ex)
		{
			val.UnpatchSelf();
			log.LogWarning((object)("Could not install Hex rarity colors: " + ex.GetBaseException()));
			return;
		}
		try
		{
			iconType = AccessTools.TypeByName("RoR2.UI.ItemIcon");
			Type type2 = AccessTools.TypeByName("RoR2.UI.ItemIcon+SetItemIndexArgs");
			iconItemIndex = AccessTools.Property(iconType, "itemIndex");
			asyncImage = AccessTools.Field(iconType, "asyncRawImage");
			imageType = asyncImage.FieldType;
			renderer = AccessTools.Field(imageType, "renderer");
			texture = AccessTools.Property(renderer.FieldType, "texture");
			spriteReference = AccessTools.Field(imageType, "spriteAoDR");
			spriteResult = AccessTools.Property(spriteReference.FieldType, "Result");
			getItemDef = AccessTools.Method(AccessTools.TypeByName("RoR2.ItemCatalog"), "GetItemDef", new Type[1] { iconItemIndex.PropertyType }, (Type[])null);
			getColor = AccessTools.Method(AccessTools.TypeByName("RoR2.ColorCatalog"), "GetColor", new Type[1] { commonColor.GetType() }, (Type[])null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(iconType, "SetItemIndex", new Type[1] { type2 }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(HexRarityColors), "ApplyInventoryOutline", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(imageType, "OnSpriteFound", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(HexRarityColors), "ApplyLoadedOutline", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			InstallLogbook();
		}
		catch (Exception ex2)
		{
			log.LogWarning((object)("Could not install Hex inventory outlines: " + ex2.GetBaseException()));
		}
	}

	private static void InstallLogbook()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ae: Expected O, but got Unknown
		//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dc: Expected O, but got Unknown
		//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_020a: Expected O, but got Unknown
		Harmony val = new Harmony("evan.weightedhexdrops.logbookcolors");
		try
		{
			Type type = AccessTools.TypeByName("RoR2.UI.LogBook.LogBookController");
			Type type2 = AccessTools.Inner(type, "CommonAssets");
			Type type3 = AccessTools.TypeByName("RoR2.UI.LogBook.Entry");
			Type type4 = AccessTools.TypeByName("RoR2.UI.LogBook.CategoryDef");
			Type type5 = AccessTools.TypeByName("RoR2.UI.LogBook.LogBookPage");
			Type type6 = AccessTools.TypeByName("RoR2.PickupIndex");
			getPickupDef = AccessTools.Method(AccessTools.TypeByName("RoR2.PickupCatalog"), "GetPickupDef", new Type[1] { type6 }, (Type[])null);
			pickupItemIndex = AccessTools.Field(getPickupDef.ReturnType, "itemIndex");
			entryPickup = AccessTools.Field(type3, "extraData");
			entryColor = AccessTools.Field(type3, "color");
			entryBackground = AccessTools.Field(type3, "bgTexture");
			commonBackground = AccessTools.Property(type2, "tier1BgIcon");
			rareBackground = AccessTools.Property(type2, "tier3BgIcon");
			Type type7 = AccessTools.TypeByName("RoR2.ItemTier");
			bossTier = Enum.Parse(type7, "Boss");
			getTierDef = AccessTools.Method(AccessTools.TypeByName("RoR2.ItemTierCatalog"), "GetItemTierDef", new Type[1] { type7 }, (Type[])null);
			tierBackground = AccessTools.Field(getTierDef.ReturnType, "bgIconTexture");
			childLocatorType = AccessTools.TypeByName("ChildLocator");
			findChild = AccessTools.Method(childLocatorType, "FindChild", new Type[1] { typeof(string) }, (Type[])null);
			pageImage = AccessTools.Field(type5, "asyncIconImage");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(type, "BuildPickupEntries", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(HexRarityColors), "ColorLogbookEntries", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(type4, "InitializeDefault", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(HexRarityColors), "ColorLogbookTile", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(type5, "SetEntry", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(HexRarityColors), "ColorLogbookPage", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		catch (Exception ex)
		{
			val.UnpatchSelf();
			logger.LogWarning((object)("Could not install Hex logbook colors: " + ex.GetBaseException()));
		}
	}

	private static ScriptableObject GetEntryItem(object entry)
	{
		object obj = ((entry == null) ? null : entryPickup.GetValue(entry));
		if (obj == null || obj.GetType() != getPickupDef.GetParameters()[0].ParameterType)
		{
			return null;
		}
		object obj2 = getPickupDef.Invoke(null, new object[1] { obj });
		if (obj2 == null)
		{
			return null;
		}
		object? obj3 = getItemDef.Invoke(null, new object[1] { pickupItemIndex.GetValue(obj2) });
		return (ScriptableObject)((obj3 is ScriptableObject) ? obj3 : null);
	}

	private static object GetEntryColor(object entry)
	{
		ScriptableObject entryItem = GetEntryItem(entry);
		if (!Object.op_Implicit((Object)(object)entryItem))
		{
			return null;
		}
		return GetRarityColor(entryItem);
	}

	private static void ColorLogbookEntries(Array __result)
	{
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		foreach (object item in __result)
		{
			ScriptableObject entryItem = GetEntryItem(item);
			if (Object.op_Implicit((Object)(object)entryItem) && ((Object)entryItem).name == "WeightedHexDropsReincarnation")
			{
				entryColor.SetValue(item, Color32.op_Implicit((Color32)getColor.Invoke(null, new object[1] { reincarnationColor })));
				object? obj = getTierDef.Invoke(null, new object[1] { bossTier });
				ScriptableObject val = (ScriptableObject)((obj is ScriptableObject) ? obj : null);
				if (Object.op_Implicit((Object)(object)val))
				{
					object? value = tierBackground.GetValue(val);
					Texture val2 = (Texture)((value is Texture) ? value : null);
					if (val2 != null && Object.op_Implicit((Object)(object)val2))
					{
						entryBackground.SetValue(item, val2);
					}
				}
				continue;
			}
			object obj2 = (Object.op_Implicit((Object)(object)entryItem) ? GetRarityColor(entryItem) : null);
			if (obj2 != null)
			{
				entryColor.SetValue(item, Color32.op_Implicit((Color32)getColor.Invoke(null, new object[1] { obj2 })));
				object? value2 = (object.Equals(obj2, commonColor) ? commonBackground : rareBackground).GetValue(null);
				Texture val3 = (Texture