Decompiled source of SLRUpgradePack v0.6.1

plugins/SLRUpgradePack.dll

Decompiled 3 weeks ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Photon.Pun;
using Photon.Realtime;
using REPOLib.Modules;
using REPOLib.Objects.Sdk;
using SLRUpgradePack.Properties;
using SLRUpgradePack.UpgradeManagers;
using Steamworks;
using TMPro;
using UnityEngine;
using UnityEngine.Events;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SolarAaron")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.6.2.0")]
[assembly: AssemblyInformationalVersion("0.6.2+c998c941a47c7ea2e56fee93fccd9a584442ed02")]
[assembly: AssemblyProduct("SLRUpgradePack")]
[assembly: AssemblyTitle("SLRUpgradePack")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.6.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SLRUpgradePack
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("SolarAaron.SLRUpgradePack", "SLRUpgradePack", "0.6.1")]
	public class SLRUpgradePack : BaseUnityPlugin
	{
		private const float StartingLevelRetryInterval = 1f;

		private static readonly FieldRef<PlayerUpgrade, Action<PlayerAvatar, int>> PlayerUpgradeStartActionRef = AccessTools.FieldRefAccess<PlayerUpgrade, Action<PlayerAvatar, int>>("StartAction");

		internal static readonly Dictionary<string, int> LimitedUse = new Dictionary<string, int>();

		private readonly HashSet<(string Upgrade, string SteamId)> _initializedStartingLevels = new HashSet<(string, string)>();

		private readonly HashSet<string> _playersWithInitializedStartingLevels = new HashSet<string>();

		private readonly HashSet<string> _startingLevelRequestsSent = new HashSet<string>();

		private readonly HashSet<string> _pendingStartingLevelInitializations = new HashSet<string>();

		private readonly Dictionary<(string Upgrade, string SteamId), int> _initializedStartActionLevels = new Dictionary<(string, string), int>();

		private readonly HashSet<string> _playersWithStartActions = new HashSet<string>();

		private bool _activePlayersStartingLevelsInitialized;

		private bool _startingLevelInitializationAllowed = true;

		private float _nextStartingLevelRetryTime;

		private static readonly NetworkedEvent StartingLevelInitializationEvent = new NetworkedEvent("SLR Starting Upgrade Levels", (Action<EventData>)HandleStartingLevelInitializationRequest);

		internal Dictionary<string, Action> Actions { get; private set; } = new Dictionary<string, Action>();

		internal static SLRUpgradePack Instance { get; private set; } = null;

		internal static ManualLogSource Logger => Instance._logger;

		internal Harmony? Harmony { get; set; }

		private ManualLogSource _logger => ((BaseUnityPlugin)this).Logger;

		public static OverchargeUpgrade? OverchargeUpgradeInstance { get; private set; }

		public static ArmorUpgrade ArmorUpgradeInstance { get; private set; } = null;

		public static ObjectValueUpgrade ObjectValueUpgradeInstance { get; private set; } = null;

		public static ObjectDurabilityUpgrade ObjectDurabilityUpgradeInstance { get; private set; } = null;

		public static ValuableDensityUpgrade ValuableDensityUpgradeInstance { get; private set; } = null;

		public static HeartOfGoldUpgrade HeartOfGoldUpgradeInstance { get; private set; } = null;

		public static RegenerationUpgrade RegenerationUpgradeInstance { get; private set; } = null;

		public static ExtraLifeUpgrade ExtraLifeUpgradeInstance { get; private set; } = null;

		public static InventorySlotUpgrade InventorySlotUpgradeInstance { get; private set; } = null;

		public static SafeTriggerUpgrade SafeTriggerUpgradeInstance { get; private set; } = null;

		private void Awake()
		{
			Instance = this;
			((Component)this).gameObject.transform.parent = null;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			_logger.LogInfo((object)"Configuring upgrade pack...");
			AssetBundle val = AssetBundle.LoadFromMemory(Resources.slr_assets);
			((Object)val).name = "slr";
			string[] allAssetNames = val.GetAllAssetNames();
			foreach (string text in allAssetNames)
			{
				_logger.LogInfo((object)("Found asset: " + text));
			}
			if (PhysGrabberPatch.Prepare())
			{
				OverchargeUpgradeInstance = new OverchargeUpgrade(enabled: true, 0.1f, exponential: false, 1.1f, ((BaseUnityPlugin)this).Config, val, 0.75f);
			}
			ArmorUpgradeInstance = new ArmorUpgrade(enabled: true, 0.1f, exponential: false, 1.1f, ((BaseUnityPlugin)this).Config, val, 1f);
			ObjectValueUpgradeInstance = new ObjectValueUpgrade(enabled: true, 0.1f, exponential: false, 1.1f, ((BaseUnityPlugin)this).Config, val, 2.5f);
			ObjectDurabilityUpgradeInstance = new ObjectDurabilityUpgrade(enabled: true, 0.1f, exponential: false, 1.1f, ((BaseUnityPlugin)this).Config, val, 2.5f);
			ValuableDensityUpgradeInstance = new ValuableDensityUpgrade(enabled: true, 0.1f, exponential: false, 1.1f, ((BaseUnityPlugin)this).Config, val, 2.5f);
			HeartOfGoldUpgradeInstance = new HeartOfGoldUpgrade(enabled: true, 0.1f, exponential: false, 1.1f, ((BaseUnityPlugin)this).Config, val, 10f, 3.5f);
			RegenerationUpgradeInstance = new RegenerationUpgrade(enabled: true, 0.1f, exponential: false, 1.1f, ((BaseUnityPlugin)this).Config, val, 0.1f, 4.5f);
			ExtraLifeUpgradeInstance = new ExtraLifeUpgrade(enabled: true, 0.1f, exponential: false, 1.1f, ((BaseUnityPlugin)this).Config, val, 5, 10f);
			InventorySlotUpgradeInstance = new InventorySlotUpgrade(enabled: true, 1, ((BaseUnityPlugin)this).Config, val, 2f);
			SafeTriggerUpgradeInstance = new SafeTriggerUpgrade(enabled: true, 0.1f, ((BaseUnityPlugin)this).Config, val, 3.5f);
			Patch();
			Logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version} has loaded!");
		}

		internal void Patch()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_0025: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony val = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
				Harmony val2 = val;
				Harmony = val;
			}
			Harmony.PatchAll();
		}

		internal void Unpatch()
		{
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private void Update()
		{
			RegenerationUpgradeInstance?.UpdateLocalPlayerRegeneration();
			if (!SemiFunc.IsMasterClientOrSingleplayer())
			{
				return;
			}
			if (_pendingStartingLevelInitializations.Count > 0 && Time.unscaledTime >= _nextStartingLevelRetryTime)
			{
				_nextStartingLevelRetryTime = Time.unscaledTime + 1f;
				foreach (string item in new List<string>(_pendingStartingLevelInitializations))
				{
					InitializeStartingLevelsForPlayer(item);
				}
			}
			if (!Object.op_Implicit((Object)(object)LevelGenerator.Instance) || !LevelGenerator.Instance.Generated)
			{
				return;
			}
			if (!_activePlayersStartingLevelsInitialized)
			{
				_activePlayersStartingLevelsInitialized = InitializeStartingLevelsForActivePlayers();
			}
			foreach (Action item2 in new List<Action>(Actions.Values))
			{
				item2();
			}
		}

		internal bool InitializeStartingLevelsForPlayer(string steamId)
		{
			if (string.IsNullOrWhiteSpace(steamId))
			{
				return false;
			}
			if (!SemiFunc.IsMasterClientOrSingleplayer())
			{
				RequestStartingLevelInitialization(steamId);
				return false;
			}
			if (!_startingLevelInitializationAllowed)
			{
				return true;
			}
			if (_playersWithInitializedStartingLevels.Contains(steamId))
			{
				_pendingStartingLevelInitializations.Remove(steamId);
				return true;
			}
			bool flag = true;
			OverchargeUpgrade overchargeUpgradeInstance = OverchargeUpgradeInstance;
			if (overchargeUpgradeInstance != null)
			{
				flag &= InitializeStartingLevel("Overcharge", overchargeUpgradeInstance, steamId);
			}
			flag &= InitializeStartingLevel("Armor", ArmorUpgradeInstance, steamId);
			flag &= InitializeStartingLevel("ObjectValue", ObjectValueUpgradeInstance, steamId);
			flag &= InitializeStartingLevel("ObjectDurability", ObjectDurabilityUpgradeInstance, steamId);
			flag &= InitializeStartingLevel("ValuableDensity", ValuableDensityUpgradeInstance, steamId);
			flag &= InitializeStartingLevel("HeartOfGold", HeartOfGoldUpgradeInstance, steamId);
			flag &= InitializeStartingLevel("Regeneration", RegenerationUpgradeInstance, steamId);
			flag &= InitializeStartingLevel("ExtraLife", ExtraLifeUpgradeInstance, steamId);
			flag &= InitializeStartingLevel("InventorySlot", InventorySlotUpgradeInstance, steamId);
			flag &= InitializeStartingLevel("SafeTrigger", SafeTriggerUpgradeInstance, steamId);
			if (flag)
			{
				_playersWithInitializedStartingLevels.Add(steamId);
				_pendingStartingLevelInitializations.Remove(steamId);
			}
			else
			{
				_pendingStartingLevelInitializations.Add(steamId);
			}
			return flag;
		}

		internal bool InitializeStartingLevelsForActivePlayers()
		{
			if (!SemiFunc.IsMasterClientOrSingleplayer())
			{
				return false;
			}
			PlayerAvatar[] array = Object.FindObjectsByType<PlayerAvatar>((FindObjectsSortMode)0);
			if (array.Length == 0)
			{
				return false;
			}
			bool flag = true;
			PlayerAvatar[] array2 = array;
			foreach (PlayerAvatar val in array2)
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					flag &= InitializeStartingLevelsForPlayer(GetUpgradePlayerId(val));
				}
			}
			return flag;
		}

		private static string GetUpgradePlayerId(PlayerAvatar player)
		{
			PhotonView photonView = player.photonView;
			string text = ((Object.op_Implicit((Object)(object)photonView) && photonView.Owner != null) ? photonView.Owner.UserId : null);
			if (string.IsNullOrWhiteSpace(text))
			{
				return SemiFunc.PlayerGetSteamID(player);
			}
			return text;
		}

		private void RequestStartingLevelInitialization(string steamId)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (!SemiFunc.IsMultiplayer() || !PhotonNetwork.InRoom || string.IsNullOrWhiteSpace(steamId))
			{
				return;
			}
			Player masterClient = PhotonNetwork.MasterClient;
			if (masterClient == null || !_startingLevelRequestsSent.Add(steamId))
			{
				return;
			}
			try
			{
				NetworkedEvent startingLevelInitializationEvent = StartingLevelInitializationEvent;
				RaiseEventOptions val = new RaiseEventOptions();
				val.TargetActors = new int[1] { masterClient.ActorNumber };
				startingLevelInitializationEvent.RaiseEvent((object)steamId, val, SendOptions.SendReliable);
				Logger.LogInfo((object)("Requested host to apply configured starting levels for player " + steamId + "."));
			}
			catch (Exception arg)
			{
				_startingLevelRequestsSent.Remove(steamId);
				Logger.LogError((object)$"Failed to request starting-level initialization for player {steamId}: {arg}");
			}
		}

		private static void HandleStartingLevelInitializationRequest(EventData eventData)
		{
			if (!SemiFunc.IsMasterClientOrSingleplayer() || !SemiFunc.IsMultiplayer() || !(eventData.CustomData is string text) || string.IsNullOrWhiteSpace(text))
			{
				return;
			}
			Player val = null;
			Player[] playerList = PhotonNetwork.PlayerList;
			foreach (Player val2 in playerList)
			{
				if (val2.ActorNumber == eventData.Sender)
				{
					val = val2;
					break;
				}
			}
			if (val == null || !string.Equals(val.UserId, text, StringComparison.Ordinal))
			{
				Logger.LogWarning((object)$"Ignoring starting-level request from actor {eventData.Sender} for mismatched player ID '{text}'.");
				return;
			}
			Logger.LogInfo((object)("Received starting-level initialization request for player " + text + "."));
			if ((Object)(object)Instance != (Object)null && !Instance.InitializeStartingLevelsForPlayer(text))
			{
				Logger.LogWarning((object)("Host could not fully initialize configured starting levels for player " + text + "; queued for retry."));
			}
		}

		private bool InitializeStartingLevel<T>(string upgradeName, UpgradeBase<T> upgrade, string steamId)
		{
			if (upgrade == null || !upgrade.UpgradeEnabled.Value)
			{
				return true;
			}
			if (upgrade.UpgradeRegister == null)
			{
				return false;
			}
			int value = upgrade.StartingAmount.Value;
			if (value <= 0)
			{
				return true;
			}
			(string, string) item = (upgradeName, steamId);
			if (_initializedStartingLevels.Contains(item))
			{
				return true;
			}
			try
			{
				int level = upgrade.UpgradeRegister.GetLevel(steamId);
				if (level >= value)
				{
					_initializedStartingLevels.Add(item);
					return true;
				}
				Logger.LogInfo((object)$"Applying configured starting level for {upgradeName} to player {steamId}: {level} -> {value}");
				upgrade.UpgradeRegister.SetLevel(steamId, value);
				if (upgrade.UpgradeRegister.GetLevel(steamId) < value)
				{
					Logger.LogWarning((object)("Configured starting level for " + upgradeName + " did not persist for player " + steamId + "; will retry."));
					return false;
				}
				_initializedStartingLevels.Add(item);
				return true;
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Failed to initialize {upgradeName} for player {steamId}: {arg}");
				return false;
			}
		}

		internal void RecordPlayerStartActions(string steamId)
		{
			if (string.IsNullOrWhiteSpace(steamId))
			{
				return;
			}
			_playersWithStartActions.Add(steamId);
			foreach (PlayerUpgrade playerUpgrade in Upgrades.PlayerUpgrades)
			{
				_initializedStartActionLevels[(playerUpgrade.UpgradeId, steamId)] = playerUpgrade.GetLevel(steamId);
			}
		}

		internal void RepairRemotePlayerStartAction(PlayerUpgrade upgrade, string steamId, int level)
		{
			if (SemiFunc.IsMasterClientOrSingleplayer() || string.IsNullOrWhiteSpace(steamId) || !_playersWithStartActions.Contains(steamId))
			{
				return;
			}
			int configuredStartingLevel = GetConfiguredStartingLevel(upgrade);
			Action<PlayerAvatar, int> action = PlayerUpgradeStartActionRef.Invoke(upgrade);
			if (configuredStartingLevel <= 0 || level < configuredStartingLevel || action == null)
			{
				return;
			}
			(string, string) key = (upgrade.UpgradeId, steamId);
			if (_initializedStartActionLevels.TryGetValue(key, out var value) && value >= configuredStartingLevel)
			{
				return;
			}
			PlayerAvatar val = SemiFunc.PlayerAvatarGetFromSteamID(steamId);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			try
			{
				action(val, upgrade.GetLevel(steamId));
				_initializedStartActionLevels[key] = upgrade.GetLevel(steamId);
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Failed to initialize synchronized {upgrade.UpgradeId} for player {steamId}: {arg}");
			}
		}

		private int GetConfiguredStartingLevel(PlayerUpgrade upgrade)
		{
			OverchargeUpgrade overchargeUpgradeInstance = OverchargeUpgradeInstance;
			if (overchargeUpgradeInstance?.UpgradeRegister == upgrade)
			{
				return overchargeUpgradeInstance.StartingAmount.Value;
			}
			if (ArmorUpgradeInstance?.UpgradeRegister == upgrade)
			{
				return ArmorUpgradeInstance.StartingAmount.Value;
			}
			if (ObjectValueUpgradeInstance?.UpgradeRegister == upgrade)
			{
				return ObjectValueUpgradeInstance.StartingAmount.Value;
			}
			if (ObjectDurabilityUpgradeInstance?.UpgradeRegister == upgrade)
			{
				return ObjectDurabilityUpgradeInstance.StartingAmount.Value;
			}
			if (ValuableDensityUpgradeInstance?.UpgradeRegister == upgrade)
			{
				return ValuableDensityUpgradeInstance.StartingAmount.Value;
			}
			if (HeartOfGoldUpgradeInstance?.UpgradeRegister == upgrade)
			{
				return HeartOfGoldUpgradeInstance.StartingAmount.Value;
			}
			if (RegenerationUpgradeInstance?.UpgradeRegister == upgrade)
			{
				return RegenerationUpgradeInstance.StartingAmount.Value;
			}
			if (ExtraLifeUpgradeInstance?.UpgradeRegister == upgrade)
			{
				return ExtraLifeUpgradeInstance.StartingAmount.Value;
			}
			if (InventorySlotUpgradeInstance?.UpgradeRegister == upgrade)
			{
				return InventorySlotUpgradeInstance.StartingAmount.Value;
			}
			if (SafeTriggerUpgradeInstance?.UpgradeRegister == upgrade)
			{
				return SafeTriggerUpgradeInstance.StartingAmount.Value;
			}
			return 0;
		}

		internal void ResetStartingLevelInitialization(bool allowStartingLevels = true)
		{
			_initializedStartingLevels.Clear();
			_playersWithInitializedStartingLevels.Clear();
			_startingLevelRequestsSent.Clear();
			_pendingStartingLevelInitializations.Clear();
			_nextStartingLevelRetryTime = 0f;
			_initializedStartActionLevels.Clear();
			_playersWithStartActions.Clear();
			_activePlayersStartingLevelsInitialized = false;
			_startingLevelInitializationAllowed = allowStartingLevels;
		}

		internal void SuppressStartingLevelInitializationForLoadedSave()
		{
			ResetStartingLevelInitialization(allowStartingLevels: false);
			Logger.LogInfo((object)"Configured starting upgrade levels are suppressed for the loaded save.");
		}
	}
	[HarmonyPatch(typeof(MenuPageSaves), "OnNewGame")]
	internal static class NewGameStartingUpgradeLevelsPatch
	{
		private static void Prefix()
		{
			SLRUpgradePack.Instance.ResetStartingLevelInitialization();
		}
	}
	[HarmonyPatch(typeof(RunManager), "ResetProgress")]
	internal static class ResetRunStartingUpgradeLevelsPatch
	{
		private static void Postfix()
		{
			if ((Object)(object)SLRUpgradePack.Instance != (Object)null)
			{
				SLRUpgradePack.Instance.ResetStartingLevelInitialization();
			}
		}
	}
	[HarmonyPatch(typeof(StatsManager), "LoadGame")]
	internal static class LoadedSaveStartingUpgradeLevelsPatch
	{
		private static void Prefix()
		{
			if ((Object)(object)SLRUpgradePack.Instance != (Object)null)
			{
				SLRUpgradePack.Instance.SuppressStartingLevelInitializationForLoadedSave();
			}
		}
	}
	[HarmonyPatch(typeof(Upgrades), "InvokeStartActions")]
	internal static class InitializeStartingUpgradeLevelsPatch
	{
		private static void Prefix(string steamId)
		{
			if ((Object)(object)SLRUpgradePack.Instance != (Object)null)
			{
				SLRUpgradePack.Instance.InitializeStartingLevelsForPlayer(steamId);
			}
		}

		private static void Postfix(string steamId)
		{
			if ((Object)(object)SLRUpgradePack.Instance != (Object)null)
			{
				SLRUpgradePack.Instance.RecordPlayerStartActions(steamId);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerUpgrade), "ApplyUpgrade")]
	internal static class RepairRemoteStartingUpgradeActionsPatch
	{
		private static void Postfix(PlayerUpgrade __instance, string steamId, int level)
		{
			if ((Object)(object)SLRUpgradePack.Instance != (Object)null)
			{
				SLRUpgradePack.Instance.RepairRemotePlayerStartAction(__instance, steamId, level);
			}
		}
	}
	[HarmonyPatch(typeof(LevelGenerator), "Start")]
	internal static class LevelGeneratorStartingUpgradeLevelsPatch
	{
		[HarmonyPriority(800)]
		private static void Prefix()
		{
			if ((Object)(object)SLRUpgradePack.Instance != (Object)null)
			{
				SLRUpgradePack.Instance.InitializeStartingLevelsForActivePlayers();
			}
		}
	}
}
namespace SLRUpgradePack.UpgradeManagers
{
	public class ArmorUpgrade : UpgradeBase<float>
	{
		public ArmorUpgrade(bool enabled, float upgradeAmount, bool exponential, float exponentialAmount, ConfigFile config, AssetBundle assetBundle, float priceMultiplier)
			: base("Armor", "assets/repo/mods/resources/items/items/item upgrade armor lib.asset", enabled, upgradeAmount, exponential, exponentialAmount, config, assetBundle, priceMultiplier, configureAmount: true, canBeExponential: true, (int?)null, (string?)null, (string?)null, (string?)null)
		{
		}

		public override float Calculate(float value, PlayerAvatar? player, int level)
		{
			return UpgradeBase<float>.DefaultCalculateFloatReduce(this, "Armor", value, player, level);
		}
	}
	[HarmonyPatch(typeof(PlayerHealth), "Hurt")]
	public class PlayerHealthArmorPatch
	{
		private static void Prefix(PlayerHealth __instance, ref int damage, PlayerAvatar ___playerAvatar)
		{
			ArmorUpgrade armorUpgradeInstance = SLRUpgradePack.ArmorUpgradeInstance;
			if (armorUpgradeInstance.UpgradeEnabled.Value)
			{
				SLRUpgradePack.Logger.LogDebug((object)$"Original damage amount: {damage}");
				PlayerUpgrade? upgradeRegister = armorUpgradeInstance.UpgradeRegister;
				int num = ((upgradeRegister != null) ? upgradeRegister.GetLevel(___playerAvatar) : 0);
				damage = (int)Math.Ceiling(armorUpgradeInstance.Calculate(damage, ___playerAvatar, num));
				SLRUpgradePack.Logger.LogDebug((object)$"After calculation with level {num}: {damage}");
			}
		}
	}
	public class ExtraLifeUpgrade : UpgradeBase<float>
	{
		private readonly Dictionary<string, Coroutine?> _reviveCoroutines = new Dictionary<string, Coroutine>();

		private static readonly FieldRef<PlayerHealth, int>? MaxHealthRef = AccessTools.FieldRefAccess<PlayerHealth, int>("maxHealth");

		private readonly FieldRef<PlayerHealth, int> _healthRef = AccessTools.FieldRefAccess<PlayerHealth, int>("health");

		private static readonly FieldRef<PlayerHealth, PlayerAvatar> _playerAvatarRef = AccessTools.FieldRefAccess<PlayerHealth, PlayerAvatar>("playerAvatar");

		private static readonly FieldRef<PlayerAvatar, bool> _deadSetRef = AccessTools.FieldRefAccess<PlayerAvatar, bool>("deadSet");

		private readonly FieldRef<PlayerDeathHead, bool> _inExtractionPointRef = AccessTools.FieldRefAccess<PlayerDeathHead, bool>("inExtractionPoint");

		private readonly FieldRef<PlayerDeathHead, bool> _deathHeadTriggeredRef = AccessTools.FieldRefAccess<PlayerDeathHead, bool>("triggered");

		private readonly FieldRef<PlayerDeathHead, RoomVolumeCheck> _deathHeadRoomVolumeCheckRef = AccessTools.FieldRefAccess<PlayerDeathHead, RoomVolumeCheck>("roomVolumeCheck");

		private readonly FieldRef<PlayerAvatar, RoomVolumeCheck> _playerRoomVolumeCheckRef = AccessTools.FieldRefAccess<PlayerAvatar, RoomVolumeCheck>("RoomVolumeCheck");

		private readonly FieldRef<RoomVolumeCheck, bool> _roomVolumeInExtractionPointRef = AccessTools.FieldRefAccess<RoomVolumeCheck, bool>("inExtractionPoint");

		private readonly FieldRef<RoundDirector, ExtractionPoint> _currentExtractionPointRef = AccessTools.FieldRefAccess<RoundDirector, ExtractionPoint>("extractionPointCurrent");

		private readonly FieldRef<ExtractionPoint, State> _extractionPointStateRef = AccessTools.FieldRefAccess<ExtractionPoint, State>("currentState");

		private readonly FieldRef<PlayerDeathHead, PhysGrabObject> _physGrabObjectRef = AccessTools.FieldRefAccess<PlayerDeathHead, PhysGrabObject>("physGrabObject");

		private static readonly FieldRef<PlayerAvatar, PlayerDeathHead> _playerDeathHeadRef = AccessTools.FieldRefAccess<PlayerAvatar, PlayerDeathHead>("playerDeathHead");

		private static readonly FieldRef<RoundDirector, bool> _extractionPointsFetchedRef = AccessTools.FieldRefAccess<RoundDirector, bool>("extractionPointsFetched");

		private static readonly FieldRef<PlayerAvatar, PlayerTumble> _playerTumbleRef = AccessTools.FieldRefAccess<PlayerAvatar, PlayerTumble>("tumble");

		private static readonly FieldRef<PlayerTumble, PhysGrabObject> _tumblePhysGrabObjectRef = AccessTools.FieldRefAccess<PlayerTumble, PhysGrabObject>("physGrabObject");

		private static readonly FieldRef<PlayerTumble, bool> _isTumblingRef = AccessTools.FieldRefAccess<PlayerTumble, bool>("isTumbling");

		private static readonly Vector3 ExtraLifeRespawnPosition = new Vector3(0f, 0.5f, 0f);

		public ConfigEntry<int> RevivePercent { get; protected set; }

		public ExtraLifeUpgrade(bool enabled, float upgradeAmount, bool exponential, float exponentialAmount, ConfigFile config, AssetBundle assetBundle, int revivePercent, float priceMultiplier)
			: base("Extra Life", "assets/repo/mods/resources/items/items/item upgrade extra life lib.asset", enabled, upgradeAmount, exponential, exponentialAmount, config, assetBundle, priceMultiplier, configureAmount: false, canBeExponential: true, (int?)null, (string?)null, (string?)null, (string?)null)
		{
			RevivePercent = config.Bind<int>("Extra Life Upgrade", "revivePercent", revivePercent, "Percentage of health to recover when revived");
		}

		public override float Calculate(float value, PlayerAvatar? player, int level)
		{
			return UpgradeBase<float>.DefaultCalculateFloatIncrease(this, "ExtraLife", value, player, level);
		}

		internal override void InitUpgrade(PlayerAvatar player, int level)
		{
			base.InitUpgrade(player, level);
			if (SemiFunc.IsMasterClientOrSingleplayer())
			{
				SLRUpgradePack.Instance.Actions["Extra Life"] = ExtraLifeUpdateAction;
			}
		}

		private void ExtraLifeUpdateAction()
		{
			if (!base.UpgradeEnabled.Value || base.UpgradeRegister == null || !Object.op_Implicit((Object)(object)RoundDirector.instance) || !_extractionPointsFetchedRef.Invoke(RoundDirector.instance))
			{
				return;
			}
			foreach (var (player, level) in GetActivePlayerLevels())
			{
				TryScheduleRevive(player, level);
			}
		}

		internal void OnPlayerDeath(PlayerAvatar player)
		{
			OnPlayerDeathObserved(player, "PlayerDeathRPC");
		}

		internal void OnPlayerHurt(PlayerHealth health)
		{
			if (Object.op_Implicit((Object)(object)health))
			{
				PlayerAvatar val = _playerAvatarRef.Invoke(health);
				if (Object.op_Implicit((Object)(object)val) && _deadSetRef.Invoke(val) && _healthRef.Invoke(health) == 0)
				{
					OnPlayerDeathObserved(val, "PlayerHealth.Hurt");
				}
			}
		}

		private void OnPlayerDeathObserved(PlayerAvatar player, string source)
		{
			if (SemiFunc.IsMasterClientOrSingleplayer() && Object.op_Implicit((Object)(object)player) && Object.op_Implicit((Object)(object)player.playerHealth) && base.UpgradeEnabled.Value && base.UpgradeRegister != null)
			{
				int level = base.UpgradeRegister.GetLevel(player);
				SLRUpgradePack.Logger.LogInfo((object)$"Extra Life observed {source} for {SemiFunc.PlayerGetName(player)}: level={level}, health={_healthRef.Invoke(player.playerHealth)}, dead={_deadSetRef.Invoke(player)}.");
				TryScheduleRevive(player, level);
			}
		}

		private void TryScheduleRevive(PlayerAvatar player, int level)
		{
			if (level <= 0 || !Object.op_Implicit((Object)(object)player) || !Object.op_Implicit((Object)(object)player.playerHealth) || !Object.op_Implicit((Object)(object)RoundDirector.instance) || !_extractionPointsFetchedRef.Invoke(RoundDirector.instance) || !_deadSetRef.Invoke(player) || _healthRef.Invoke(player.playerHealth) != 0)
			{
				return;
			}
			PlayerDeathHead val = _playerDeathHeadRef.Invoke(player);
			if (Object.op_Implicit((Object)(object)val) && !IsExtractionReviveBlocked(player, val))
			{
				string key = SemiFunc.PlayerGetSteamID(player);
				if (!_reviveCoroutines.TryGetValue(key, out Coroutine value) || value == null)
				{
					_reviveCoroutines[key] = ((MonoBehaviour)SLRUpgradePack.Instance).StartCoroutine(BeginReviving(player));
				}
			}
		}

		private IEnumerator BeginReviving(PlayerAvatar player)
		{
			string playerID = SemiFunc.PlayerGetSteamID(player);
			try
			{
				yield return (object)new WaitForEndOfFrame();
				yield return (object)new WaitForSeconds(0.2f);
				if (!Object.op_Implicit((Object)(object)player) || !Object.op_Implicit((Object)(object)player.playerHealth) || !base.UpgradeEnabled.Value || base.UpgradeRegister == null || base.UpgradeRegister.GetLevel(player) == 0 || !_deadSetRef.Invoke(player) || _healthRef.Invoke(player.playerHealth) != 0)
				{
					yield break;
				}
				PlayerDeathHead val = _playerDeathHeadRef.Invoke(player);
				if (!Object.op_Implicit((Object)(object)val))
				{
					yield break;
				}
				SLRUpgradePack.Logger.LogInfo((object)("Preparing to revive " + SemiFunc.PlayerGetName(player)));
				if (IsExtractionReviveBlocked(player, val))
				{
					SLRUpgradePack.Logger.LogInfo((object)("Deferring Extra Life for " + SemiFunc.PlayerGetName(player) + " because the extraction point can revive this player"));
				}
				else if (ReviveLogic(player))
				{
					while (Object.op_Implicit((Object)(object)player) && Object.op_Implicit((Object)(object)player.playerHealth) && _deadSetRef.Invoke(player) && _healthRef.Invoke(player.playerHealth) == 0)
					{
						yield return null;
					}
				}
			}
			finally
			{
				_reviveCoroutines.Remove(playerID);
			}
		}

		private bool IsExtractionReviveBlocked(PlayerAvatar player, PlayerDeathHead playerHead)
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Invalid comparison between Unknown and I4
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Invalid comparison between Unknown and I4
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Invalid comparison between Unknown and I4
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Invalid comparison between Unknown and I4
			if (!Object.op_Implicit((Object)(object)playerHead))
			{
				return false;
			}
			RoomVolumeCheck val = (Object.op_Implicit((Object)(object)player) ? _playerRoomVolumeCheckRef.Invoke(player) : null);
			bool flag = false;
			if (Object.op_Implicit((Object)(object)val))
			{
				val.CheckSet();
				flag = _roomVolumeInExtractionPointRef.Invoke(val);
			}
			if (_deathHeadTriggeredRef.Invoke(playerHead))
			{
				RoomVolumeCheck val2 = _deathHeadRoomVolumeCheckRef.Invoke(playerHead);
				if (Object.op_Implicit((Object)(object)val2))
				{
					val2.CheckSet();
					flag |= _roomVolumeInExtractionPointRef.Invoke(val2);
				}
				else
				{
					flag |= _inExtractionPointRef.Invoke(playerHead);
				}
			}
			if (!flag || !Object.op_Implicit((Object)(object)RoundDirector.instance))
			{
				return false;
			}
			ExtractionPoint val3 = _currentExtractionPointRef.Invoke(RoundDirector.instance);
			if (!Object.op_Implicit((Object)(object)val3))
			{
				return false;
			}
			State val4 = _extractionPointStateRef.Invoke(val3);
			if ((int)val4 != 3 && (int)val4 != 4 && (int)val4 != 6)
			{
				return (int)val4 == 7;
			}
			return true;
		}

		private bool ReviveLogic(PlayerAvatar player)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			ExtraLifeUpgrade extraLifeUpgradeInstance = SLRUpgradePack.ExtraLifeUpgradeInstance;
			if (extraLifeUpgradeInstance?.UpgradeRegister == null || !Object.op_Implicit((Object)(object)player) || !Object.op_Implicit((Object)(object)player.playerHealth))
			{
				return false;
			}
			PlayerDeathHead val = _playerDeathHeadRef.Invoke(player);
			PhysGrabObject val2 = (Object.op_Implicit((Object)(object)val) ? _physGrabObjectRef.Invoke(val) : null);
			if (Object.op_Implicit((Object)(object)val2))
			{
				val2.centerPoint = ExtraLifeRespawnPosition + Vector3.up * 0.25f;
			}
			PlayerTumble val3 = _playerTumbleRef.Invoke(player);
			if (Object.op_Implicit((Object)(object)val3) && _isTumblingRef.Invoke(val3))
			{
				val3.TumbleSet(false, false, false);
			}
			try
			{
				player.Revive(false);
			}
			catch (Exception arg)
			{
				SLRUpgradePack.Logger.LogError((object)$"Extra Life could not revive {SemiFunc.PlayerGetName(player)}; the life was not consumed. {arg}");
				return false;
			}
			player.Spawn(ExtraLifeRespawnPosition, Quaternion.identity, false);
			PhysGrabObject val4 = (Object.op_Implicit((Object)(object)val3) ? _tumblePhysGrabObjectRef.Invoke(val3) : null);
			if (Object.op_Implicit((Object)(object)val4))
			{
				val4.Teleport(ExtraLifeRespawnPosition, Quaternion.identity);
			}
			if (!SemiFunc.IsMultiplayer() && (_deadSetRef.Invoke(player) || _healthRef.Invoke(player.playerHealth) <= 0))
			{
				SLRUpgradePack.Logger.LogWarning((object)("Extra Life revive did not complete for " + SemiFunc.PlayerGetName(player) + "; the life was not consumed."));
				return false;
			}
			FieldRef<PlayerHealth, int>? maxHealthRef = MaxHealthRef;
			int num = ((maxHealthRef != null) ? maxHealthRef.Invoke(player.playerHealth) : 0);
			player.playerHealth.HealOther(Mathf.FloorToInt((float)num * ((float)extraLifeUpgradeInstance.RevivePercent.Value / 100f)), true);
			string text = SemiFunc.PlayerGetSteamID(player);
			int level = extraLifeUpgradeInstance.UpgradeRegister.GetLevel(player);
			int level2 = extraLifeUpgradeInstance.UpgradeRegister.GetLevel(text);
			int num2 = Math.Max(0, level - 1);
			extraLifeUpgradeInstance.UpgradeRegister.SetLevel(player, num2);
			int level3 = extraLifeUpgradeInstance.UpgradeRegister.GetLevel(player);
			int level4 = extraLifeUpgradeInstance.UpgradeRegister.GetLevel(text);
			if (level3 != num2 || level4 != num2)
			{
				SLRUpgradePack.Logger.LogError((object)$"Extra Life level deduction mismatch for {SemiFunc.PlayerGetName(player)} ({text}): before={level}, steamIdBefore={level2}, target={num2}, after={level3}, steamIdAfter={level4}.");
			}
			Vector3 position = ((Component)player).transform.position;
			Vector3 val5 = (Object.op_Implicit((Object)(object)val4) ? ((Component)val4).transform.position : position);
			SLRUpgradePack.Logger.LogInfo((object)$"Extra Life used for {SemiFunc.PlayerGetName(player)}: level {level} -> {level3}; respawn requested at {ExtraLifeRespawnPosition}, player={position}, tumble={val5}.");
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerAvatar), "PlayerDeathRPC")]
	internal static class ExtraLifePlayerDeathPatch
	{
		private static void Postfix(PlayerAvatar __instance)
		{
			SLRUpgradePack.ExtraLifeUpgradeInstance?.OnPlayerDeath(__instance);
		}
	}
	[HarmonyPatch(typeof(PlayerHealth), "Hurt")]
	internal static class ExtraLifePlayerHurtPatch
	{
		private static void Postfix(PlayerHealth __instance)
		{
			SLRUpgradePack.ExtraLifeUpgradeInstance?.OnPlayerHurt(__instance);
		}
	}
	[HarmonyPatch(typeof(PlayerAvatar), "ReviveRPC")]
	internal static class ReviveSpectateCameraNullGuardPatch
	{
		private static readonly FieldRef<PlayerAvatar, bool> DeadSetRef = AccessTools.FieldRefAccess<PlayerAvatar, bool>("deadSet");

		private static readonly FieldRef<PlayerAvatar, bool>? IsLocalRef = AccessTools.FieldRefAccess<PlayerAvatar, bool>("isLocal");

		[HarmonyPostfix]
		private static void Postfix(PlayerAvatar __instance)
		{
			if (!Object.op_Implicit((Object)(object)__instance))
			{
				return;
			}
			FieldRef<PlayerAvatar, bool>? isLocalRef = IsLocalRef;
			if (isLocalRef != null && isLocalRef.Invoke(__instance))
			{
				SLRUpgradePack instance = SLRUpgradePack.Instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(RestoreLocalAimAfterRevive(__instance));
				}
			}
		}

		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo safeStopSpectate = AccessTools.Method(typeof(ReviveSpectateCameraNullGuardPatch), "StopSpectateIfAvailable", (Type[])null, (Type[])null);
			bool patched = false;
			foreach (CodeInstruction instruction in instructions)
			{
				if (!patched && safeStopSpectate != null && instruction.opcode == OpCodes.Callvirt && instruction.operand is MethodInfo methodInfo && methodInfo.DeclaringType == typeof(SpectateCamera) && methodInfo.Name == "StopSpectate")
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = safeStopSpectate;
					patched = true;
				}
				yield return instruction;
			}
			if (!patched)
			{
				SLRUpgradePack.Logger.LogError((object)"Could not install the null-safe SpectateCamera guard in PlayerAvatar.ReviveRPC; Extra Life revives may fail.");
			}
		}

		private static void StopSpectateIfAvailable(SpectateCamera camera)
		{
			if (Object.op_Implicit((Object)(object)camera))
			{
				camera.StopSpectate();
			}
		}

		private static IEnumerator RestoreLocalAimAfterRevive(PlayerAvatar player)
		{
			yield return (object)new WaitForSecondsRealtime(0.4f);
			if (!Object.op_Implicit((Object)(object)player))
			{
				yield break;
			}
			FieldRef<PlayerAvatar, bool>? isLocalRef = IsLocalRef;
			if (isLocalRef != null && isLocalRef.Invoke(player) && !DeadSetRef.Invoke(player) && Object.op_Implicit((Object)(object)GameDirector.instance) && (int)GameDirector.instance.currentState == 2)
			{
				Aim instance = Aim.instance;
				if (Object.op_Implicit((Object)(object)instance))
				{
					instance.SetState((State)0);
				}
			}
		}
	}
	public class HeartOfGoldUpgrade : UpgradeBase<float>
	{
		internal const byte ViewRegistrationMessageType = 0;

		internal const byte RegistrationAckMessageType = 1;

		public static NetworkedEvent HeartOfGoldEvent = new NetworkedEvent("Heart Of Gold", (Action<EventData>)HeartOfGoldAction);

		public ConfigEntry<float> BaseHeartValue { get; protected set; }

		internal Dictionary<string, GoldenHeart> GoldenHearts { get; set; } = new Dictionary<string, GoldenHeart>();

		private static void HeartOfGoldAction(EventData e)
		{
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Expected O, but got Unknown
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			NetworkMessage networkMessage = NetworkMessage.FromByteArray((byte[])e.CustomData);
			HeartOfGoldUpgrade heartOfGoldUpgradeInstance = SLRUpgradePack.HeartOfGoldUpgradeInstance;
			if (networkMessage.MessageType == 1)
			{
				if (!string.IsNullOrEmpty(networkMessage.PlayerId) && networkMessage.PhotonId.HasValue && heartOfGoldUpgradeInstance.GoldenHearts.TryGetValue(networkMessage.PlayerId, out GoldenHeart value) && Object.op_Implicit((Object)(object)value))
				{
					value.RecordRegistrationAck(networkMessage.PhotonId.Value, e.Sender);
				}
			}
			else
			{
				if (networkMessage.MessageType != 0 || string.IsNullOrEmpty(networkMessage.PlayerId) || !networkMessage.PhotonId.HasValue)
				{
					return;
				}
				PlayerAvatar val = SemiFunc.PlayerAvatarGetFromSteamID(networkMessage.PlayerId);
				if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val.photonView) || val.photonView.OwnerActorNr != e.Sender)
				{
					SLRUpgradePack.Logger.LogWarning((object)$"Ignoring Heart of Gold view registration for '{networkMessage.PlayerId}' from non-owner actor {e.Sender}.");
					return;
				}
				PlayerUpgrade upgradeRegister = heartOfGoldUpgradeInstance.UpgradeRegister;
				if (upgradeRegister != null)
				{
					if (!heartOfGoldUpgradeInstance.GoldenHearts.TryGetValue(networkMessage.PlayerId, out GoldenHeart value2) || !Object.op_Implicit((Object)(object)value2))
					{
						heartOfGoldUpgradeInstance.InitUpgrade(val, upgradeRegister.GetLevel(val));
						value2 = heartOfGoldUpgradeInstance.GoldenHearts[networkMessage.PlayerId];
					}
					if (value2.SetViewId(networkMessage.PhotonId.Value))
					{
						NetworkMessage msg = new NetworkMessage
						{
							PlayerId = networkMessage.PlayerId,
							PhotonId = networkMessage.PhotonId,
							MessageType = 1
						};
						NetworkedEvent heartOfGoldEvent = HeartOfGoldEvent;
						byte[] array = NetworkMessage.ToByteArray(msg);
						RaiseEventOptions val2 = new RaiseEventOptions();
						val2.TargetActors = new int[1] { e.Sender };
						heartOfGoldEvent.RaiseEvent((object)array, val2, SendOptions.SendReliable);
					}
				}
			}
		}

		public HeartOfGoldUpgrade(bool enabled, float upgradeAmount, bool exponential, float exponentialAmount, ConfigFile config, AssetBundle assetBundle, float baseValue, float priceMultiplier)
			: base("Heart Of Gold", "assets/repo/mods/resources/items/items/item upgrade heart of gold lib.asset", enabled, upgradeAmount, exponential, exponentialAmount, config, assetBundle, priceMultiplier, configureAmount: true, canBeExponential: true, (int?)null, (string?)null, (string?)null, (string?)null)
		{
			BaseHeartValue = config.Bind<float>("Heart Of Gold Upgrade", "Base Value", baseValue, "Base value to scale by player health");
		}

		public override float Calculate(float value, PlayerAvatar? player, int level)
		{
			return UpgradeBase<float>.DefaultCalculateFloatIncrease(this, "HeartOfGold", value, player, level);
		}

		internal override void InitUpgrade(PlayerAvatar player, int level)
		{
			base.InitUpgrade(player, level);
			EnsureGoldenHeart(player, level);
		}

		internal override void UseUpgrade(PlayerAvatar player, int level)
		{
			base.UseUpgrade(player, level);
			EnsureGoldenHeart(player, level);
		}

		private void EnsureGoldenHeart(PlayerAvatar player, int level)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)player))
			{
				string key = SemiFunc.PlayerGetSteamID(player);
				if (GoldenHearts.TryGetValue(key, out GoldenHeart value) && Object.op_Implicit((Object)(object)value))
				{
					value.player = player;
					return;
				}
				value = new GameObject("Golden Heart: " + SemiFunc.PlayerGetName(player)).AddComponent<GoldenHeart>();
				value.player = player;
				GoldenHearts[key] = value;
				SLRUpgradePack.Logger.LogInfo((object)$"Initialized Heart of Gold tracker for {SemiFunc.PlayerGetName(player)} at level {level}");
			}
		}
	}
	public class GoldenHeart : MonoBehaviour
	{
		private const float RegistrationRetryInterval = 1f;

		private bool createRpcPending;

		private bool createRequested;

		private bool valueSyncPending = true;

		private bool hasQueuedMasterBaseValue;

		private float queuedMasterBaseValue;

		private bool hasQueuedFinalValue;

		private float queuedFinalBaseValue;

		private float queuedFinalValue;

		private float nextRegistrationRetryTime;

		private bool missingRpcViewWarningLogged;

		private bool viewAllocationFailureLogged;

		private bool registrationReadyLogged;

		private readonly HashSet<int> registeredActorNumbers = new HashSet<int>();

		private readonly HashSet<int> knownRemoteActorNumbers = new HashSet<int>();

		private PhotonView photonView;

		private readonly FieldRef<PlayerHealth, int> _healthRef = AccessTools.FieldRefAccess<PlayerHealth, int>("health");

		private readonly FieldRef<ValuableObject, PhysAttribute> _physAttributePresetRef = AccessTools.FieldRefAccess<ValuableObject, PhysAttribute>("physAttributePreset");

		private readonly FieldRef<ValuableObject, bool> _discoveredRef = AccessTools.FieldRefAccess<ValuableObject, bool>("discovered");

		private readonly FieldRef<ValuableObject, float> _dollarValueCurrentRef = AccessTools.FieldRefAccess<ValuableObject, float>("dollarValueCurrent");

		internal PlayerAvatar player { get; set; }

		internal bool Pause { get; set; }

		internal float NextExtractionZoneRefreshTime { get; set; }

		internal int lastLevel { get; set; } = -1;

		internal int lastHealth { get; set; } = -1;

		internal ValuableObject? ValuableComponent { get; private set; }

		private void Awake()
		{
			if (!((Component)this).TryGetComponent<PhotonView>(ref photonView))
			{
				photonView = ((Component)this).gameObject.AddComponent<PhotonView>();
			}
		}

		private bool CanSendPhotonRpc(string methodName)
		{
			if (Object.op_Implicit((Object)(object)photonView) && photonView.ViewID != 0)
			{
				return true;
			}
			if (!missingRpcViewWarningLogged)
			{
				missingRpcViewWarningLogged = true;
				SLRUpgradePack.Logger.LogWarning((object)("Skipping Heart of Gold RPC " + methodName + " for " + SemiFunc.PlayerGetName(player) + " because its PhotonView has no registered ID."));
			}
			return false;
		}

		public void DestroyOnlyMe()
		{
			if (Object.op_Implicit((Object)(object)ValuableComponent) || createRequested)
			{
				if (SemiFunc.IsMultiplayer() && CanSendPhotonRpc("DestroyOnlyMeRPC"))
				{
					photonView.RPC("DestroyOnlyMeRPC", (RpcTarget)0, Array.Empty<object>());
				}
				else
				{
					DestroyOnlyMeRPC();
				}
			}
		}

		[PunRPC]
		private void DestroyOnlyMeRPC()
		{
			createRequested = false;
			createRpcPending = false;
			hasQueuedMasterBaseValue = false;
			hasQueuedFinalValue = false;
			ValuableObject valuableComponent = ValuableComponent;
			if (!((Object)(object)valuableComponent == (Object)null) && Object.op_Implicit((Object)(object)valuableComponent))
			{
				SLRUpgradePack.Logger.LogInfo((object)("Components in GoldenHeart: " + string.Join(',', from v in ((Component)this).GetComponents<Object>()
					select ((object)v).ToString())));
				PhysGrabObject component = ((Component)valuableComponent).GetComponent<PhysGrabObject>();
				if (Object.op_Implicit((Object)(object)RoundDirector.instance) && Object.op_Implicit((Object)(object)component))
				{
					RoundDirector.instance.PhysGrabObjectRemove(component);
				}
				Object.Destroy((Object)(object)valuableComponent);
				ValuableComponent = null;
			}
		}

		public void CreateOnlyMe()
		{
			if (!Object.op_Implicit((Object)(object)ValuableComponent) && !createRpcPending && !createRequested && !Pause && (!SemiFunc.IsMultiplayer() || CanSendPhotonRpc("CreateOnlyMeRPC")))
			{
				createRpcPending = true;
				if (SemiFunc.IsMultiplayer())
				{
					photonView.RPC("CreateOnlyMeRPC", (RpcTarget)0, Array.Empty<object>());
				}
				else
				{
					CreateOnlyMeRPC();
				}
			}
		}

		[PunRPC]
		private void CreateOnlyMeRPC()
		{
			createRpcPending = false;
			if (Object.op_Implicit((Object)(object)ValuableComponent))
			{
				createRequested = false;
				return;
			}
			createRequested = true;
			TryCreateValuableComponent();
		}

		private void TryCreateValuableComponent()
		{
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0338: Unknown result type (might be due to invalid IL or missing references)
			//IL_033f: Expected O, but got Unknown
			//IL_0353: Unknown result type (might be due to invalid IL or missing references)
			//IL_0358: Unknown result type (might be due to invalid IL or missing references)
			//IL_036c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0376: Unknown result type (might be due to invalid IL or missing references)
			//IL_037b: Unknown result type (might be due to invalid IL or missing references)
			if (!createRequested || Pause || !Object.op_Implicit((Object)(object)player) || !Object.op_Implicit((Object)(object)player.healthGrab) || !Object.op_Implicit((Object)(object)player.playerHealth) || Object.op_Implicit((Object)(object)ValuableComponent))
			{
				return;
			}
			HeartOfGoldUpgrade heartOfGoldUpgradeInstance = SLRUpgradePack.HeartOfGoldUpgradeInstance;
			PlayerUpgrade upgradeRegister = heartOfGoldUpgradeInstance.UpgradeRegister;
			if (upgradeRegister == null)
			{
				return;
			}
			PhotonView component = ((Component)player.healthGrab).GetComponent<PhotonView>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				SLRUpgradePack.Logger.LogError((object)("Player health-grab object for " + SemiFunc.PlayerGetName(player) + " has no PhotonView; cannot add Heart of Gold physics components."));
			}
			else if (!SemiFunc.IsMultiplayer() || component.ViewID != 0)
			{
				SLRUpgradePack.Logger.LogInfo((object)$"Adding valuable component to player {SemiFunc.PlayerGetName(player)} using PhotonView {component.ViewID}");
				ValuableComponent = ((Component)player.healthGrab).gameObject.AddComponent<ValuableObject>();
				ValuableObjectValuePatch.MarkExcludedFromExtractionGoal(ValuableComponent);
				SLRUpgradePack.Logger.LogInfo((object)("Valuable component " + SemiFunc.PlayerGetName(player) + " instantiated at " + JsonConvert.SerializeObject((object)((Component)ValuableComponent).transform)));
				ValuableComponent.valuePreset = ScriptableObject.CreateInstance<Value>();
				ValuableComponent.valuePreset.valueMin = (ValuableComponent.valuePreset.valueMax = heartOfGoldUpgradeInstance.Calculate((float)_healthRef.Invoke(player.playerHealth) * heartOfGoldUpgradeInstance.BaseHeartValue.Value, player, upgradeRegister.GetLevel(player)));
				ValuableComponent.durabilityPreset = ScriptableObject.CreateInstance<Durability>();
				ValuableComponent.durabilityPreset.durability = 999f;
				ValuableComponent.durabilityPreset.fragility = 0f;
				ValuableComponent.physAttributePreset = ScriptableObject.CreateInstance<PhysAttribute>();
				((Component)ValuableComponent).transform.localScale = Vector3.zero;
				((Component)ValuableComponent).transform.SetParent(((Component)player).transform, false);
				((Component)ValuableComponent).gameObject.AddComponent<Rigidbody>();
				PhotonTransformView item = ((Component)ValuableComponent).gameObject.AddComponent<PhotonTransformView>();
				PhysGrabObjectImpactDetector val = ((Component)ValuableComponent).gameObject.AddComponent<PhysGrabObjectImpactDetector>();
				PhysGrabObject val2 = ((Component)ValuableComponent).gameObject.AddComponent<PhysGrabObject>();
				if (!component.ObservedComponents.Contains((Component)(object)val2))
				{
					component.ObservedComponents.Add((Component)(object)val2);
				}
				if (!component.ObservedComponents.Contains((Component)(object)val))
				{
					component.ObservedComponents.Add((Component)(object)val);
				}
				if (!component.ObservedComponents.Contains((Component)(object)item))
				{
					component.ObservedComponents.Add((Component)(object)item);
				}
				((Behaviour)val).enabled = false;
				((Behaviour)val2).enabled = false;
				((Component)val2).transform.localScale = Vector3.zero;
				((Component)val2).transform.SetParent(((Component)ValuableComponent).transform, false);
				((Component)val).transform.localScale = Vector3.zero;
				((Component)val).transform.SetParent(((Component)ValuableComponent).transform, false);
				((Component)ValuableComponent).gameObject.AddComponent<RoomVolumeCheck>().CurrentRooms = new List<RoomVolume>();
				ValuableObject? valuableComponent = ValuableComponent;
				Gradient val3 = new Gradient();
				val3.alphaKeys = (GradientAlphaKey[])(object)new GradientAlphaKey[1]
				{
					new GradientAlphaKey(1f, 0f)
				};
				val3.colorKeys = (GradientColorKey[])(object)new GradientColorKey[1]
				{
					new GradientColorKey(Color.yellow, 0f)
				};
				valuableComponent.particleColors = val3;
				_physAttributePresetRef.Invoke(ValuableComponent) = ScriptableObject.CreateInstance<PhysAttribute>();
				int num = (lastLevel = -1);
				lastHealth = num;
				createRequested = false;
				if (hasQueuedMasterBaseValue)
				{
					float baseValue = queuedMasterBaseValue;
					hasQueuedMasterBaseValue = false;
					ApplyHeartValue(baseValue);
				}
				else if (hasQueuedFinalValue)
				{
					float baseValue2 = queuedFinalBaseValue;
					float finalValue = queuedFinalValue;
					hasQueuedFinalValue = false;
					ApplySyncedHeartValue(baseValue2, finalValue);
				}
			}
		}

		private void Update()
		{
			if (!Object.op_Implicit((Object)(object)player))
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			if (createRequested)
			{
				TryCreateValuableComponent();
			}
			if ((Object)(object)SemiFunc.PlayerAvatarLocal() != (Object)(object)player || !Object.op_Implicit((Object)(object)player.playerHealth))
			{
				return;
			}
			HeartOfGoldUpgrade heartOfGoldUpgradeInstance = SLRUpgradePack.HeartOfGoldUpgradeInstance;
			PlayerUpgrade upgradeRegister = heartOfGoldUpgradeInstance.UpgradeRegister;
			if (!heartOfGoldUpgradeInstance.UpgradeEnabled.Value || upgradeRegister == null || Pause)
			{
				return;
			}
			int level = upgradeRegister.GetLevel(player);
			if (level == 0 || (SemiFunc.IsMultiplayer() && !EnsureRemoteViewsRegistered()))
			{
				return;
			}
			if (!Object.op_Implicit((Object)(object)ValuableComponent))
			{
				CreateOnlyMe();
			}
			if (!Object.op_Implicit((Object)(object)ValuableComponent))
			{
				return;
			}
			int num = _healthRef.Invoke(player.playerHealth);
			if (num == 0)
			{
				return;
			}
			if (lastLevel != level || lastHealth != num)
			{
				lastLevel = level;
				lastHealth = num;
				valueSyncPending = true;
			}
			float num2 = heartOfGoldUpgradeInstance.Calculate((float)num * heartOfGoldUpgradeInstance.BaseHeartValue.Value, player, level);
			if (valueSyncPending)
			{
				if (!SemiFunc.IsMultiplayer())
				{
					ApplyHeartValue(num2);
				}
				else if (CanSendPhotonRpc("UpdateOnlyMeRPC"))
				{
					photonView.RPC("UpdateOnlyMeRPC", (RpcTarget)2, new object[1] { num2 });
				}
				valueSyncPending = false;
			}
		}

		private bool EnsureRemoteViewsRegistered()
		{
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			if (!PhotonNetwork.InRoom)
			{
				return false;
			}
			if (photonView.ViewID == 0)
			{
				if (!PhotonNetwork.AllocateViewID(photonView) || photonView.ViewID == 0)
				{
					if (!viewAllocationFailureLogged)
					{
						viewAllocationFailureLogged = true;
						SLRUpgradePack.Logger.LogWarning((object)("Heart of Gold could not allocate a PhotonView ID for " + SemiFunc.PlayerGetName(player) + "; delaying its RPCs."));
					}
					return false;
				}
				registeredActorNumbers.Clear();
				knownRemoteActorNumbers.Clear();
				registrationReadyLogged = false;
			}
			HashSet<int> hashSet = PhotonNetwork.PlayerListOthers.Select((Player remotePlayer) => remotePlayer.ActorNumber).ToHashSet();
			if (!knownRemoteActorNumbers.SetEquals(hashSet))
			{
				knownRemoteActorNumbers.Clear();
				knownRemoteActorNumbers.UnionWith(hashSet);
				registeredActorNumbers.IntersectWith(hashSet);
				valueSyncPending = true;
				registrationReadyLogged = false;
			}
			if (hashSet.All(registeredActorNumbers.Contains))
			{
				if (!registrationReadyLogged)
				{
					registrationReadyLogged = true;
					SLRUpgradePack.Logger.LogInfo((object)$"Heart of Gold PhotonView {photonView.ViewID} registered for {SemiFunc.PlayerGetName(player)} on {hashSet.Count} remote peer(s).");
				}
				return true;
			}
			if (Time.unscaledTime < nextRegistrationRetryTime)
			{
				return false;
			}
			NetworkMessage msg = new NetworkMessage
			{
				PlayerId = SemiFunc.PlayerGetSteamID(player),
				PhotonId = photonView.ViewID,
				MessageType = 0
			};
			HeartOfGoldUpgrade.HeartOfGoldEvent.RaiseEvent((object)NetworkMessage.ToByteArray(msg), NetworkingEvents.RaiseOthers, SendOptions.SendReliable);
			nextRegistrationRetryTime = Time.unscaledTime + 1f;
			return false;
		}

		internal void RecordRegistrationAck(int photonId, int actorNumber)
		{
			if (photonView.ViewID == photonId && actorNumber > 0)
			{
				registeredActorNumbers.Add(actorNumber);
			}
		}

		[PunRPC]
		private void UpdateOnlyMeRPC(float baseValue)
		{
			if (SemiFunc.IsMasterClient())
			{
				ApplyHeartValue(baseValue);
			}
		}

		private void ApplyHeartValue(float baseValue)
		{
			if (!Object.op_Implicit((Object)(object)player) || !Object.op_Implicit((Object)(object)player.playerHealth))
			{
				return;
			}
			ValuableObject valuableComponent = ValuableComponent;
			if ((Object)(object)valuableComponent == (Object)null || !Object.op_Implicit((Object)(object)valuableComponent))
			{
				queuedMasterBaseValue = baseValue;
				hasQueuedMasterBaseValue = true;
				createRequested = true;
				TryCreateValuableComponent();
				return;
			}
			if (!_discoveredRef.Invoke(valuableComponent))
			{
				valuableComponent.Discover((State)0);
			}
			valuableComponent.valuePreset.valueMin = baseValue;
			valuableComponent.valuePreset.valueMax = baseValue;
			_dollarValueCurrentRef.Invoke(valuableComponent) = baseValue;
			ValuableObjectValuePatch.Action(valuableComponent);
			float num = _dollarValueCurrentRef.Invoke(valuableComponent);
			valuableComponent.valuePreset.valueMin = baseValue;
			valuableComponent.valuePreset.valueMax = baseValue;
			PlayerUpgrade? upgradeRegister = SLRUpgradePack.HeartOfGoldUpgradeInstance.UpgradeRegister;
			int num2 = ((upgradeRegister != null) ? upgradeRegister.GetLevel(player) : 0);
			SLRUpgradePack.Logger.LogInfo((object)$"Heart of Gold value updated for {SemiFunc.PlayerGetName(player)}: base={baseValue}, final={num}, health={_healthRef.Invoke(player.playerHealth)}, level={num2}");
			if (!SemiFunc.IsMultiplayer())
			{
				HeartOfGoldValueSetRPC(baseValue, num);
			}
			else if (CanSendPhotonRpc("HeartOfGoldValueSetRPC"))
			{
				photonView.RPC("HeartOfGoldValueSetRPC", (RpcTarget)0, new object[2] { baseValue, num });
			}
		}

		[PunRPC]
		private void HeartOfGoldValueSetRPC(float baseValue, float finalValue)
		{
			ValuableObject valuableComponent = ValuableComponent;
			if ((Object)(object)valuableComponent == (Object)null || !Object.op_Implicit((Object)(object)valuableComponent))
			{
				queuedFinalBaseValue = baseValue;
				queuedFinalValue = finalValue;
				hasQueuedFinalValue = true;
				createRequested = true;
				TryCreateValuableComponent();
			}
			else
			{
				ApplySyncedHeartValue(baseValue, finalValue);
			}
		}

		private void ApplySyncedHeartValue(float baseValue, float finalValue)
		{
			ValuableObject valuableComponent = ValuableComponent;
			if (!((Object)(object)valuableComponent == (Object)null) && Object.op_Implicit((Object)(object)valuableComponent))
			{
				if (!_discoveredRef.Invoke(valuableComponent))
				{
					valuableComponent.Discover((State)0);
				}
				valuableComponent.valuePreset.valueMin = baseValue;
				valuableComponent.valuePreset.valueMax = baseValue;
				_dollarValueCurrentRef.Invoke(valuableComponent) = finalValue;
			}
		}

		public void PauseLogic(bool pause)
		{
			if (!SemiFunc.IsMultiplayer())
			{
				PauseLogicRPC(pause);
			}
			else if (CanSendPhotonRpc("PauseLogicRPC"))
			{
				photonView.RPC("PauseLogicRPC", (RpcTarget)0, new object[1] { pause });
			}
			else
			{
				PauseLogicRPC(pause);
			}
		}

		[PunRPC]
		private void PauseLogicRPC(bool pause)
		{
			Pause = pause;
		}

		internal bool SetViewId(int id)
		{
			if (id <= 0 || !Object.op_Implicit((Object)(object)photonView))
			{
				return false;
			}
			PhotonView val = PhotonView.Find(id);
			if (Object.op_Implicit((Object)(object)val) && (Object)(object)val != (Object)(object)photonView)
			{
				SLRUpgradePack.Logger.LogWarning((object)$"Could not register Heart of Gold view {id} for {SemiFunc.PlayerGetName(player)}; that ID is already assigned to {((Object)((Component)val).gameObject).name}.");
				return false;
			}
			if (photonView.ViewID != id)
			{
				photonView.ViewID = id;
				if (Object.op_Implicit((Object)(object)player) && Object.op_Implicit((Object)(object)player.photonView) && player.photonView.Owner != null)
				{
					photonView.TransferOwnership(player.photonView.Owner);
				}
			}
			return photonView.ViewID == id;
		}
	}
	[HarmonyPatch(typeof(ExtractionPoint))]
	public class ExtractionPointDestroyPatch
	{
		private static readonly FieldRef<RoundDirector, int> TotalHaulRef = AccessTools.FieldRefAccess<RoundDirector, int>("totalHaul");

		private static readonly FieldRef<RoundDirector, int> CurrentHaulRef = AccessTools.FieldRefAccess<RoundDirector, int>("currentHaul");

		private static readonly FieldRef<ValuableObject, float> DollarValueCurrentRef = AccessTools.FieldRefAccess<ValuableObject, float>("dollarValueCurrent");

		private static readonly FieldRef<ProgressionManager, float> HaulingPointsRef = AccessTools.FieldRefAccess<ProgressionManager, float>("roundPointsHauling");

		private static readonly FieldRef<PlayerAvatar, PlayerDeathHead> PlayerDeathHeadRef = AccessTools.FieldRefAccess<PlayerAvatar, PlayerDeathHead>("playerDeathHead");

		private static readonly FieldRef<PlayerAvatar, RoomVolumeCheck> PlayerAvatarRoomVolumeCheckRef = AccessTools.FieldRefAccess<PlayerAvatar, RoomVolumeCheck>("RoomVolumeCheck");

		private static readonly FieldRef<PlayerDeathHead, RoomVolumeCheck> PlayerDeathHeadRoomVolumeCheckRef = AccessTools.FieldRefAccess<PlayerDeathHead, RoomVolumeCheck>("roomVolumeCheck");

		private static readonly FieldRef<PlayerDeathHead, bool> PlayerDeathHeadTriggeredRef = AccessTools.FieldRefAccess<PlayerDeathHead, bool>("triggered");

		private static readonly FieldRef<RoomVolumeCheck, bool> RoomVolumeInExtractionPointRef = AccessTools.FieldRefAccess<RoomVolumeCheck, bool>("inExtractionPoint");

		private static readonly MethodInfo ExtractCosmeticMethod = AccessTools.Method(typeof(ExtractionPoint), "ExtractCosmeticWorldObject", new Type[1] { typeof(bool) }, (Type[])null);

		private static readonly Dictionary<int, bool> LastReportedExtractionPresence = new Dictionary<int, bool>();

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

		private static float NextRoundHaulTraceTime;

		internal static bool TryGetGoldenHeart(HeartOfGoldUpgrade upgrade, ValuableObject valuableObject, out GoldenHeart goldenHeart)
		{
			foreach (GoldenHeart value in upgrade.GoldenHearts.Values)
			{
				if (Object.op_Implicit((Object)(object)value) && (Object)(object)value.ValuableComponent == (Object)(object)valuableObject)
				{
					goldenHeart = value;
					return true;
				}
			}
			goldenHeart = null;
			return false;
		}

		internal static bool IsGoldenHeartValuable(ValuableObject valuableObject)
		{
			HeartOfGoldUpgrade heartOfGoldUpgradeInstance = SLRUpgradePack.HeartOfGoldUpgradeInstance;
			GoldenHeart goldenHeart;
			if (heartOfGoldUpgradeInstance != null && Object.op_Implicit((Object)(object)valuableObject))
			{
				return TryGetGoldenHeart(heartOfGoldUpgradeInstance, valuableObject, out goldenHeart);
			}
			return false;
		}

		private static void AddGoldenHeartHaulValue(ExtractionPoint extractionPoint, ValuableObject valuableObject)
		{
			float num = DollarValueCurrentRef.Invoke(valuableObject);
			TotalHaulRef.Invoke(RoundDirector.instance) += (int)num;
			float localPlayerHaulScore = valuableObject.GetLocalPlayerHaulScore(((Component)extractionPoint).gameObject);
			if (localPlayerHaulScore > 0f)
			{
				HaulingPointsRef.Invoke(ProgressionManager.instance) += num / 10f * localPlayerHaulScore;
			}
		}

		internal static void AddPlayerHeartValueToCurrentHaul(RoundDirector roundDirector)
		{
			HeartOfGoldUpgrade heartOfGoldUpgradeInstance = SLRUpgradePack.HeartOfGoldUpgradeInstance;
			if (heartOfGoldUpgradeInstance == null || !Object.op_Implicit((Object)(object)roundDirector) || !heartOfGoldUpgradeInstance.UpgradeEnabled.Value || !SemiFunc.IsMasterClientOrSingleplayer())
			{
				return;
			}
			if (heartOfGoldUpgradeInstance.GoldenHearts.Values.Any((GoldenHeart heart) => Object.op_Implicit((Object)(object)heart) && Object.op_Implicit((Object)(object)heart.ValuableComponent)) && Time.unscaledTime >= NextRoundHaulTraceTime)
			{
				SLRUpgradePack.Logger.LogInfo((object)$"Heart of Gold round haul check: currentHaul={CurrentHaulRef.Invoke(roundDirector)}, listedHearts={heartOfGoldUpgradeInstance.GoldenHearts.Values.Count((GoldenHeart heart) => Object.op_Implicit((Object)(object)heart) && Object.op_Implicit((Object)(object)heart.ValuableComponent) && roundDirector.dollarHaulList.Contains(((Component)heart.ValuableComponent).gameObject))}");
				NextRoundHaulTraceTime = Time.unscaledTime + 2f;
			}
			int num = 0;
			foreach (GoldenHeart value in heartOfGoldUpgradeInstance.GoldenHearts.Values)
			{
				if (!IsPlayerHeartInExtraction(value))
				{
					continue;
				}
				ValuableObject valuableComponent = value.ValuableComponent;
				if (Object.op_Implicit((Object)(object)valuableComponent))
				{
					int num2 = (int)DollarValueCurrentRef.Invoke(valuableComponent);
					num += num2;
					if (LastReportedHaulApplications.Add(((Object)value).GetInstanceID()))
					{
						SLRUpgradePack.Logger.LogInfo((object)$"Added Heart of Gold value to live haul for {SemiFunc.PlayerGetName(value.player)}: {num2}");
					}
				}
			}
			if (num > 0)
			{
				CurrentHaulRef.Invoke(roundDirector) += num;
			}
		}

		internal static bool IsPlayerHeartInExtraction(GoldenHeart goldenHeart, bool refreshZone = false)
		{
			if (!Object.op_Implicit((Object)(object)goldenHeart) || goldenHeart.Pause || !Object.op_Implicit((Object)(object)goldenHeart.player) || !Object.op_Implicit((Object)(object)goldenHeart.ValuableComponent))
			{
				return false;
			}
			PlayerDeathHead val = PlayerDeathHeadRef.Invoke(goldenHeart.player);
			RoomVolumeCheck val2 = PlayerAvatarRoomVolumeCheckRef.Invoke(goldenHeart.player);
			RoomVolumeCheck val3 = (Object.op_Implicit((Object)(object)val) ? PlayerDeathHeadRoomVolumeCheckRef.Invoke(val) : null);
			if (!Object.op_Implicit((Object)(object)val2) && !Object.op_Implicit((Object)(object)val3))
			{
				return false;
			}
			if (refreshZone || Time.time >= goldenHeart.NextExtractionZoneRefreshTime)
			{
				if (Object.op_Implicit((Object)(object)val2))
				{
					val2.CheckSet();
				}
				if (Object.op_Implicit((Object)(object)val3))
				{
					val3.CheckSet();
				}
				goldenHeart.NextExtractionZoneRefreshTime = Time.time + 0.1f;
			}
			bool flag = Object.op_Implicit((Object)(object)val2) && RoomVolumeInExtractionPointRef.Invoke(val2);
			bool flag2 = Object.op_Implicit((Object)(object)val) && PlayerDeathHeadTriggeredRef.Invoke(val) && Object.op_Implicit((Object)(object)val3) && RoomVolumeInExtractionPointRef.Invoke(val3);
			bool flag3 = flag || flag2;
			int instanceID = ((Object)goldenHeart).GetInstanceID();
			if (!LastReportedExtractionPresence.TryGetValue(instanceID, out var value) || value != flag3)
			{
				LastReportedExtractionPresence[instanceID] = flag3;
				SLRUpgradePack.Logger.LogInfo((object)$"Heart of Gold zone check for {SemiFunc.PlayerGetName(goldenHeart.player)}: inExtraction={flag3}, avatar={flag}, deathHead={flag2}, value={DollarValueCurrentRef.Invoke(goldenHeart.ValuableComponent)}");
			}
			if (!flag3)
			{
				LastReportedHaulApplications.Remove(instanceID);
			}
			return flag3;
		}

		private static void ExtractGoldenHeart(ExtractionPoint extractionPoint, GoldenHeart goldenHeart)
		{
			ValuableObject valuableComponent = goldenHeart.ValuableComponent;
			if (Object.op_Implicit((Object)(object)valuableComponent))
			{
				AddGoldenHeartHaulValue(extractionPoint, valuableComponent);
				RoundDirector.instance.dollarHaulList.Remove(((Component)valuableComponent).gameObject);
				SLRUpgradePack.Logger.LogInfo((object)("Player " + SemiFunc.PlayerGetName(goldenHeart.player) + " in extraction zone counts as valuable"));
				goldenHeart.Pause = true;
				goldenHeart.PauseLogic(pause: true);
				goldenHeart.DestroyOnlyMe();
			}
		}

		[HarmonyPatch("DestroyAllPhysObjectsInHaulList")]
		[HarmonyPrefix]
		private static bool DestroyAllPrefix(ExtractionPoint __instance)
		{
			HeartOfGoldUpgrade heartOfGoldUpgradeInstance = SLRUpgradePack.HeartOfGoldUpgradeInstance;
			if (!SemiFunc.IsMasterClientOrSingleplayer() || !heartOfGoldUpgradeInstance.UpgradeEnabled.Value)
			{
				return true;
			}
			PhysGrabObject val = default(PhysGrabObject);
			ValuableObject val2 = default(ValuableObject);
			foreach (GameObject item in new List<GameObject>(RoundDirector.instance.dollarHaulList))
			{
				if (Object.op_Implicit((Object)(object)item) && item.TryGetComponent<PhysGrabObject>(ref val) && Object.op_Implicit((Object)(object)val) && item.TryGetComponent<ValuableObject>(ref val2) && Object.op_Implicit((Object)(object)val2) && TryGetGoldenHeart(heartOfGoldUpgradeInstance, val2, out GoldenHeart goldenHeart))
				{
					ExtractGoldenHeart(__instance, goldenHeart);
				}
			}
			foreach (GoldenHeart item2 in new List<GoldenHeart>(heartOfGoldUpgradeInstance.GoldenHearts.Values))
			{
				if (IsPlayerHeartInExtraction(item2, refreshZone: true))
				{
					ExtractGoldenHeart(__instance, item2);
				}
			}
			return true;
		}

		[HarmonyPatch("DestroyTheFirstPhysObjectsInHaulList")]
		[HarmonyPrefix]
		private static bool DestroyFirstPrefix(ExtractionPoint __instance)
		{
			HeartOfGoldUpgrade heartOfGoldUpgradeInstance = SLRUpgradePack.HeartOfGoldUpgradeInstance;
			if (!SemiFunc.IsMasterClientOrSingleplayer() || !heartOfGoldUpgradeInstance.UpgradeEnabled.Value)
			{
				return true;
			}
			if ((bool)ExtractCosmeticMethod.Invoke(__instance, new object[1] { false }))
			{
				return false;
			}
			List<GameObject> dollarHaulList = RoundDirector.instance.dollarHaulList;
			PhysGrabObject val = default(PhysGrabObject);
			ValuableObject val2 = default(ValuableObject);
			if (dollarHaulList.Count == 0 || !Object.op_Implicit((Object)(object)dollarHaulList[0]) || !dollarHaulList[0].TryGetComponent<PhysGrabObject>(ref val) || !Object.op_Implicit((Object)(object)val) || !dollarHaulList[0].TryGetComponent<ValuableObject>(ref val2) || !Object.op_Implicit((Object)(object)val2) || !TryGetGoldenHeart(heartOfGoldUpgradeInstance, val2, out GoldenHeart goldenHeart))
			{
				return true;
			}
			ExtractGoldenHeart(__instance, goldenHeart);
			return false;
		}
	}
	[HarmonyPatch(typeof(RoundDirector), "Update")]
	public class RoundDirectorUpdatePatch
	{
		private static void Prefix(RoundDirector __instance)
		{
			ValuableObject val = default(ValuableObject);
			__instance.dollarHaulList.RemoveAll((GameObject go) => (Object)(object)go == (Object)null || !go.TryGetComponent<ValuableObject>(ref val) || !Object.op_Implicit((Object)(object)val));
		}
	}
	[HarmonyPatch(typeof(RoundDirector), "HaulCheck")]
	public class RoundDirectorHaulCheckPatch
	{
		private static void Prefix(RoundDirector __instance)
		{
			if (SemiFunc.IsMasterClientOrSingleplayer())
			{
				ValuableObject val = default(ValuableObject);
				__instance.dollarHaulList.RemoveAll((GameObject gameObject) => Object.op_Implicit((Object)(object)gameObject) && gameObject.TryGetComponent<ValuableObject>(ref val) && Object.op_Implicit((Object)(object)val) && ExtractionPointDestroyPatch.IsGoldenHeartValuable(val));
			}
		}

		private static void Postfix(RoundDirector __instance)
		{
			ExtractionPointDestroyPatch.AddPlayerHeartValueToCurrentHaul(__instance);
		}
	}
	public class InventorySlotUpgrade : UpgradeBase<int>
	{
		internal static readonly Dictionary<string, Dictionary<int, int>> serverMonitoredInventoryItems = new Dictionary<string, Dictionary<int, int>>();

		private Coroutine? _deferredInventoryRefresh;

		public ConfigEntry<KeyboardShortcut> ItemSlot4 { get; }

		public ConfigEntry<KeyboardShortcut> ItemSlot5 { get; }

		public ConfigEntry<KeyboardShortcut> ItemSlot6 { get; }

		public ConfigEntry<KeyboardShortcut> ItemSlot7 { get; }

		public ConfigEntry<KeyboardShortcut> ItemSlot8 { get; }

		public ConfigEntry<KeyboardShortcut> ItemSlot9 { get; }

		internal string? BoundPlayer { get; set; }

		public Inventory? InventoryRef { get; set; }

		public InventoryUI? UIRef { get; set; }

		public InventorySlotUpgrade(bool enabled, int upgradeAmount, ConfigFile config, AssetBundle assetBundle, float priceMultiplier)
			: base("Inventory Slot", "assets/repo/mods/resources/items/items/item upgrade inventory slot lib.asset", enabled, upgradeAmount, exponential: false, 0, config, assetBundle, priceMultiplier, configureAmount: false, canBeExponential: false, (int?)6, (string?)null, (string?)null, (string?)null)
		{
			//IL_0037: 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_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			ItemSlot4 = config.Bind<KeyboardShortcut>("Inventory Slot Upgrade", "Item Slot 4", new KeyboardShortcut((KeyCode)122, Array.Empty<KeyCode>()), "Key to select inventory slot 4.");
			ItemSlot5 = config.Bind<KeyboardShortcut>("Inventory Slot Upgrade", "Item Slot 5", new KeyboardShortcut((KeyCode)120, Array.Empty<KeyCode>()), "Key to select inventory slot 5.");
			ItemSlot6 = config.Bind<KeyboardShortcut>("Inventory Slot Upgrade", "Item Slot 6", new KeyboardShortcut((KeyCode)99, Array.Empty<KeyCode>()), "Key to select inventory slot 6.");
			ItemSlot7 = config.Bind<KeyboardShortcut>("Inventory Slot Upgrade", "Item Slot 7", new KeyboardShortcut((KeyCode)110, Array.Empty<KeyCode>()), "Key to select inventory slot 7.");
			ItemSlot8 = config.Bind<KeyboardShortcut>("Inventory Slot Upgrade", "Item Slot 8", new KeyboardShortcut((KeyCode)109, Array.Empty<KeyCode>()), "Key to select inventory slot 8.");
			ItemSlot9 = config.Bind<KeyboardShortcut>("Inventory Slot Upgrade", "Item Slot 9", new KeyboardShortcut((KeyCode)44, Array.Empty<KeyCode>()), "Key to select inventory slot 9.");
		}

		internal ConfigEntry<KeyboardShortcut>? GetSlotBinding(int index)
		{
			return (ConfigEntry<KeyboardShortcut>?)(index switch
			{
				3 => ItemSlot4, 
				4 => ItemSlot5, 
				5 => ItemSlot6, 
				6 => ItemSlot7, 
				7 => ItemSlot8, 
				8 => ItemSlot9, 
				_ => null, 
			});
		}

		public override int Calculate(int value, PlayerAvatar? player, int level)
		{
			return value + level;
		}

		internal override void InitUpgrade(PlayerAvatar player, int level)
		{
			base.InitUpgrade(player, level);
			if ((Object)(object)player == (Object)(object)SemiFunc.PlayerAvatarLocal())
			{
				BoundPlayer = SemiFunc.PlayerGetSteamID(player);
				RefreshLocalInventory();
			}
		}

		internal override void UseUpgrade(PlayerAvatar player, int level)
		{
			base.UseUpgrade(player, level);
			if ((Object)(object)player == (Object)(object)SemiFunc.PlayerAvatarLocal())
			{
				BoundPlayer = SemiFunc.PlayerGetSteamID(player);
				RefreshLocalInventory();
				ScheduleLocalInventoryRefresh();
			}
		}

		private void RefreshLocalInventory()
		{
			if (Object.op_Implicit((Object)(object)InventoryRef))
			{
				InventoryStartPatch.Postfix(InventoryRef);
			}
			if (Object.op_Implicit((Object)(object)UIRef))
			{
				InventoryUIStartPatch.Postfix(UIRef);
			}
		}

		private void ScheduleLocalInventoryRefresh()
		{
			if (_deferredInventoryRefresh != null)
			{
				((MonoBehaviour)SLRUpgradePack.Instance).StopCoroutine(_deferredInventoryRefresh);
			}
			_deferredInventoryRefresh = ((MonoBehaviour)SLRUpgradePack.Instance).StartCoroutine(RefreshLocalInventoryNextFrame());
		}

		private IEnumerator RefreshLocalInventoryNextFrame()
		{
			yield return null;
			_deferredInventoryRefresh = null;
			RefreshLocalInventory();
		}
	}
	[HarmonyPatch(typeof(InventoryUI), "Start")]
	public class InventoryUIStartPatch
	{
		private static readonly FieldRef<InventoryUI, List<GameObject>> allChildren = AccessTools.FieldRefAccess<InventoryUI, List<GameObject>>("allChildren");

		private static readonly FieldRef<SemiUI, Vector3> initialPosition = AccessTools.FieldRefAccess<SemiUI, Vector3>("initialPosition");

		private static readonly FieldRef<SemiUI, Vector2> hidePositionCurrent = AccessTools.FieldRefAccess<SemiUI, Vector2>("hidePositionCurrent");

		private static readonly FieldRef<InventorySpot, ItemEquippable> currentItem = AccessTools.FieldRefAccess<InventorySpot, ItemEquippable>("<CurrentItem>k__BackingField");

		private static readonly FieldRef<BatteryVisualLogic, ItemBattery> previousItemBattery = AccessTools.FieldRefAccess<BatteryVisualLogic, ItemBattery>("itemBatteryPrev");

		private static readonly FieldRef<BatteryVisualLogic, List<GameObject>> batteryBars = AccessTools.FieldRefAccess<BatteryVisualLogic, List<GameObject>>("bars");

		private static readonly FieldRef<InventorySpot, BatteryVisualLogic> inventorySpotBatteryVisual = AccessTools.FieldRefAccess<InventorySpot, BatteryVisualLogic>("batteryVisualLogic");

		private static readonly FieldRef<BatteryVisualLogic, Vector3> batteryTargetPosition = AccessTools.FieldRefAccess<BatteryVisualLogic, Vector3>("targetPosition");

		private static readonly FieldRef<BatteryVisualLogic, Vector3> batteryTargetPositionOriginal = AccessTools.FieldRefAccess<BatteryVisualLogic, Vector3>("targetPositionOriginal");

		private static readonly FieldRef<BatteryVisualLogic, float> batteryTargetScale = AccessTools.FieldRefAccess<BatteryVisualLogic, float>("targetScale");

		private static readonly FieldRef<BatteryVisualLogic, float> batteryTargetScaleOriginal = AccessTools.FieldRefAccess<BatteryVisualLogic, float>("targetScaleOriginal");

		private static readonly FieldRef<BatteryVisualLogic, float> batteryTargetRotation = AccessTools.FieldRefAccess<BatteryVisualLogic, float>("targetRotation");

		private static readonly FieldRef<BatteryVisualLogic, float> batteryTargetRotationOriginal = AccessTools.FieldRefAccess<BatteryVisualLogic, float>("targetRotationOriginal");

		private static readonly FieldRef<BatteryVisualLogic, bool> batteryDoOutro = AccessTools.FieldRefAccess<BatteryVisualLogic, bool>("doOutro");

		private static readonly FieldRef<BatteryVisualLogic, SpringFloat> batterySpringScale = AccessTools.FieldRefAccess<BatteryVisualLogic, SpringFloat>("springScale");

		private static readonly FieldRef<BatteryVisualLogic, SpringFloat> batterySpringRotation = AccessTools.FieldRefAccess<BatteryVisualLogic, SpringFloat>("springRotation");

		private static readonly FieldRef<BatteryVisualLogic, SpringVector3> batterySpringPosition = AccessTools.FieldRefAccess<BatteryVisualLogic, SpringVector3>("springPosition");

		private static readonly FieldRef<SpringFloat, float> springFloatDamping = AccessTools.FieldRefAccess<SpringFloat, float>("damping");

		private static readonly FieldRef<SpringFloat, float> springFloatSpeed = AccessTools.FieldRefAccess<SpringFloat, float>("speed");

		private static readonly FieldRef<SpringFloat, float> springFloatLastPosition = AccessTools.FieldRefAccess<SpringFloat, float>("lastPosition");

		private static readonly FieldRef<SpringVector3, float> springVectorDamping = AccessTools.FieldRefAccess<SpringVector3, float>("damping");

		private static readonly FieldRef<SpringVector3, float> springVectorSpeed = AccessTools.FieldRefAccess<SpringVector3, float>("speed");

		private static readonly FieldRef<SpringVector3, Vector3> springVectorLastPosition = AccessTools.FieldRefAccess<SpringVector3, Vector3>("lastPosition");

		private static readonly FieldRef<InventoryBattery, Vector3> originalBatteryScale = AccessTools.FieldRefAccess<InventoryBattery, Vector3>("originalLocalScale");

		private static readonly Dictionary<int, (int frame, int batteryId)> batteryVisualRefreshes = new Dictionary<int, (int, int)>();

		private static readonly Dictionary<int, TextMeshProUGUI> slotNumberLabels = new Dictionary<int, TextMeshProUGUI>();

		private static readonly Dictionary<int, (Vector3 position, float scale, float rotation)> clonedBatteryVisualsPendingStart = new Dictionary<int, (Vector3, float, float)>();

		private static int batteryVisualRefreshFrame = -1;

		internal static void Postfix(InventoryUI __instance)
		{
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0297: Unknown result type (might be due to invalid IL or missing references)
			//IL_029c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0432: Unknown result type (might be due to invalid IL or missing references)
			//IL_0434: Unknown result type (might be due to invalid IL or missing references)
			//IL_0436: Unknown result type (might be due to invalid IL or missing references)
			//IL_0438: Unknown result type (might be due to invalid IL or missing references)
			//IL_043a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0668: Unknown result type (might be due to invalid IL or missing references)
			//IL_066f: Expected O, but got Unknown
			//IL_0535: Unknown result type (might be due to invalid IL or missing references)
			//IL_0537: Unknown result type (might be due to invalid IL or missing references)
			//IL_054a: Unknown result type (might be due to invalid IL or missing references)
			//IL_054f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0551: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a3: Unknown result type (might be due to invalid IL or missing references)
			InventorySlotUpgrade inventorySlotUpgradeInstance = SLRUpgradePack.InventorySlotUpgradeInstance;
			inventorySlotUpgradeInstance.UIRef = __instance;
			PlayerUpgrade upgradeRegister = inventorySlotUpgradeInstance.UpgradeRegister;
			string boundPlayer = inventorySlotUpgradeInstance.BoundPlayer;
			if (!inventorySlotUpgradeInstance.UpgradeEnabled.Value || boundPlayer == null || upgradeRegister == null)
			{
				return;
			}
			int num = inventorySlotUpgradeInstance.Calculate(3, SemiFunc.PlayerAvatarLocal(), upgradeRegister.GetLevel(boundPlayer));
			if (num <= 3)
			{
				return;
			}
			SLRUpgradePack.Logger.LogInfo((object)$"Redrawing for {num} slots");
			float num2 = (float)(-(num * 40)) / 2f + 20f;
			Dictionary<int, InventorySpot> dictionary = (from spot in ((Component)__instance).GetComponentsInChildren<InventorySpot>(true)
				where Object.op_Implicit((Object)(object)spot)
				group spot by spot.inventorySpotIndex).ToDictionary((IGrouping<int, InventorySpot> group) => group.Key, (IGrouping<int, InventorySpot> group) => group.First());
			if (!dictionary.TryGetValue(0, out var templateSpot) || !Object.op_Implicit((Object)(object)templateSpot))
			{
				SLRUpgradePack.Logger.LogWarning((object)"Could not resize inventory UI: no base InventorySpot template was found.");
				return;
			}
			BatteryVisualLogic componentInChildren = ((Component)templateSpot).GetComponentInChildren<BatteryVisualLogic>(true);
			SemiUI component = ((Component)templateSpot).GetComponent<SemiUI>();
			Vector2 val = (Object.op_Implicit((Object)(object)component) ? component.showPosition : Vector2.op_Implicit(((Component)templateSpot).transform.localPosition));
			Vector2 val2 = (Object.op_Implicit((Object)(object)component) ? (component.hidePosition - val) : Vector2.zero);
			Vector2 templateHideCurrentOffset = (Object.op_Implicit((Object)(object)component) ? (hidePositionCurrent.Invoke(component) - val) : val2);
			Vector3 templateInitialOffset = (Object.op_Implicit((Object)(object)component) ? (initialPosition.Invoke(component) - Vector2.op_Implicit(val)) : Vector3.zero);
			InventoryBattery val3 = ((IEnumerable<InventoryBattery>)((Component)__instance).GetComponentsInChildren<InventoryBattery>(true)).FirstOrDefault((Func<InventoryBattery, bool>)((InventoryBattery battery) => Object.op_Implicit((Object)(object)battery) && battery.inventorySpot == templateSpot.inventorySpotIndex && !Object.op_Implicit((Object)(object)((Component)battery).GetComponentInParent<InventorySpot>())));
			Vector3 localScale = (Object.op_Implicit((Object)(object)val3) ? GetBatteryDisplayScale(val3) : Vector3.zero);
			Vector3 val4 = (Object.op_Implicit((Object)(object)val3) ? ((Component)templateSpot).transform.InverseTransformPoint(((Component)val3).transform.position) : Vector3.zero);
			Quaternion val5 = (Object.op_Implicit((Object)(object)val3) ? (Quaternion.Inverse(((Component)templateSpot).transform.rotation) * ((Component)val3).transform.rotation) : Quaternion.identity);
			Vector2 position = default(Vector2);
			int key;
			for (int num3 = 0; num3 < num; num3++)
			{
				((Vector2)(ref position))..ctor(num2 + (float)num3 * 40f, -175.3f);
				if (dictionary.TryGetValue(num3, out var value) && Object.op_Implicit((Object)(object)value))
				{
					SetSpotPosition(value, position, val, val2, templateHideCurrentOffset, templateInitialOffset, startHasRun: true);
					continue;
				}
				Transform val6 = Object.Instantiate<Transform>(((Component)templateSpot).transform, ((Component)templateSpot).transform.parent, false);
				((Object)((Component)val6).gameObject).name = $"Inventory Spot {num3 + 1}";
				BatteryVisualLogic componentInChildren2 = ((Component)val6).GetComponentInChildren<BatteryVisualLogic>(true);
				if (Object.op_Implicit((Object)(object)componentInChildren2))
				{
					((Component)componentInChildren2).gameObject.SetActive(true);
				}
				InventorySpot component2 = ((Component)val6).GetComponent<InventorySpot>();
				if (!Object.op_Implicit((Object)(object)component2))
				{
					Object.Destroy((Object)(object)((Component)val6).gameObject);
					SLRUpgradePack.Logger.LogWarning((object)$"Could not create inventory slot {num3 + 1}: cloned template has no InventorySpot.");
					continue;
				}
				component2.inventorySpotIndex = num3;
				currentItem.Invoke(component2) = null;
				if (Object.op_Implicit((Object)(object)componentInChildren2))
				{
					inventorySpotBatteryVisual.Invoke(component2) = componentInChildren2;
					componentInChildren2.itemBattery = null;
					previousItemBattery.Invoke(componentInChildren2) = null;
					RebindBatteryBars(componentInChildren2);
					if (Object.op_Implicit((Object)(object)componentInChildren))
					{
						ResetClonedBatteryVisual(componentInChildren2, componentInChildren);
					}
				}
				InventoryBattery[] componentsInChildren = ((Component)component2).GetComponentsInChildren<InventoryBattery>(true);
				for (key = 0; key < componentsInChildren.Length; key++)
				{
					componentsInChildren[key].inventorySpot = num3;
				}
				RestoreClonedBatteryScales(templateSpot, val6);
				InventorySpotUpdatePatch.RefreshSlotBindingLabel(component2);
				SetSpotPosition(component2, position, val, val2, templateHideCurrentOffset, templateInitialOffset, startHasRun: false);
				dictionary[num3] = component2;
			}
			if (Object.op_Implicit((Object)(object)val3))
			{
				HashSet<int> hashSet = new HashSet<int>();
				InventoryBattery[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<InventoryBattery>(true);
				for (key = 0; key < componentsInChildren.Length; key++)
				{
					InventoryBattery val7 = componentsInChildren[key];
					InventorySpot componentInParent = ((Component)val7).GetComponentInParent<InventorySpot>();
					if (Object.op_Implicit((Object)(object)componentInParent))
					{
						val7.inventorySpot = componentInParent.inventorySpotIndex;
					}
					hashSet.Add(val7.inventorySpot);
				}
				for (int num4 = 3; num4 < num; num4++)
				{
					if (!hashSet.Contains(num4) && dictionary.TryGetValue(num4, out var value2) && Object.op_Implicit((Object)(object)value2))
					{
						Transform val8 = Object.Instantiate<Transform>(((Component)val3).transform, ((Component)val3).transform.parent, false);
						((Object)((Component)val8).gameObject).name = $"Inventory Battery {num4 + 1}";
						val8.position = ((Component)value2).transform.TransformPoint(val4);
						val8.rotation = ((Component)value2).transform.rotation * val5;
						InventoryBattery component3 = ((Component)val8).GetComponent<InventoryBattery>();
						if (!Object.op_Implicit((Object)(object)component3))
						{
							Object.Destroy((Object)(object)((Component)val8).gameObject);
							SLRUpgradePack.Logger.LogWarning((object)$"Could not create battery indicator for inventory slot {num4 + 1}: cloned template has no InventoryBattery.");
						}
						else
						{
							component3.inventorySpot = num4;
							val8.localScale = localScale;
							hashSet.Add(num4);
						}
					}
				}
			}
			foreach (KeyValuePair<int, InventorySpot> item in dictionary)
			{
				item.Deconstruct(out key, out var value3);
				int num5 = key;
				InventorySpot val9 = value3;
				if (Object.op_Implicit((Object)(object)val9))
				{
					InventoryBattery[] componentsInChildren = ((Component)val9).GetComponentsInChildren<InventoryBattery>(true);
					for (key = 0; key < componentsInChildren.Length; key++)
					{
						componentsInChildren[key].inventorySpot = num5;
					}
					InventoryStartPatch.RegisterSpot(val9, num5);
				}
			}
			List<GameObject> list = allChildren.Invoke(__instance);
			list.Clear();
			foreach (Transform item2 in ((Component)__instance).transform)
			{
				Transform val10 = item2;
				list.Add(((Component)val10).gameObject);
			}
			Canvas.ForceUpdateCanvases();
		}

		private static void SetSpotPosition(InventorySpot spot, Vector2 position, Vector2 templateShowPosition, Vector2 templateHideOffset, Vector2 templateHideCurrentOffset, Vector3 templateInitialOffset, bool startHasRun)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			_ = position - templateShowPosition;
			Vector3 localPosition = Vector2.op_Implicit(position);
			localPosition.z = ((Component)spot).transform.localPosition.z;
			((Component)spot).transform.localPosition = localPosition;
			SemiUI component = ((Component)spot).GetComponent<SemiUI>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.showPosition = position;
				component.hidePosition = (startHasRun ? (position + templateHideOffset) : templateHideOffset);
				hidePositionCurrent.Invoke(component) = position + templateHideCurrentOffset;
				initialPosition.Invoke(component) = Vector2.op_Implicit(position) + templateInitialOffset;
			}
		}

		private static Vector3 GetBatteryDisplayScale(InventoryBattery battery)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = originalBatteryScale.Invoke(battery);
			if (!(val == Vector3.zero))
			{
				return val;
			}
			return ((Component)battery).transform.localScale;
		}

		private static void RebindBatteryBars(BatteryVisualLogic batteryVisual)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			if (!Object.op_Implicit((Object)(object)batteryVisual.batteryBarContainer))
			{
				SLRUpgradePack.Logger.LogWarning((object)"Could not rebind cloned battery bars: the bar container reference is missing.");
				batteryBars.Invoke(batteryVisual) = new List<GameObject>();
				return;
			}
			List<GameObject> list = new List<GameObject>(batteryVisual.batteryBarContainer.childCount);
			foreach (Transform item in batteryVisual.batteryBarContainer)
			{
				Transform val = item;
				list.Add(((Component)val).gameObject);
			}
			batteryBars.Invoke(batteryVisual) = list;
		}

		internal static BatteryVisualLogic? BindBatteryVisual(InventorySpot spot, bool activateForVanillaStart)
		{
			if (!Object.op_Implicit((Object)(object)spot))
			{
				return null;
			}
			BatteryVisualLogic val = inventorySpotBatteryVisual.Invoke(spot);
			if (Object.op_Implicit((Object)(object)val) && (Object)(object)((Component)val).transform != (Object)(object)((Component)spot).transform && !((Component)val).transform.IsChildOf(((Component)spot).transform))
			{
				val = null;
			}
			if (!Object.op_Implicit((Object)(object)val))
			{
				val = ((Component)spot).GetComponentInChildren<BatteryVisualLogic>(true);
			}
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			inventorySpotBatteryVisual.Invoke(spot) = val;
			if (activateForVanillaStart && !((Component)val).gameObject.activeSelf)
			{
				((Component)val).gameObject.SetActive(true);
			}
			return val;
		}

		private static void ResetClonedBatteryVisual(BatteryVisualLogic visual, BatteryVisualLogic template)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = batteryTargetPositionOriginal.Invoke(template);
			if (float.IsNaN(val.x) || float.IsInfinity(val.x) || float.IsNaN(val.y) || float.IsInfinity(val.y) || float.IsNaN(val.z) || float.IsInfinity(val.z))
			{
				val = ((Component)visual).transform.localPosition;
			}
			float num = batteryTargetScaleOriginal.Invoke(template);
			if (!IsUsableScale(num))
			{
				num = batteryTargetScale.Invoke(template);
			}
			if (!IsUsableScale(num))
			{
				num = Mathf.Max(((Component)visual).transform.localScale.x, ((Component)visual).transform.localScale.y);
			}
			if (!IsUsableScale(num))
			{
				num = 0.5f;
			}
			float num2 = batteryTargetRotationOriginal.Invoke(template);
			if (float.IsNaN(num2) || float.IsInfinity(num2))
			{
				num2 = 0f;
			}
			ApplyClonedBatteryVisualState(visual, val, num, num2);
			clonedBatteryVisualsPendingStart[((Object)visual).GetInstanceID()] = (val, num, num2);
		}

		private static void ApplyClonedBatteryVisualState(BatteryVisualLogic visual, Vector3 targetPosition, float targetScale, float targetRotation)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing referenc