Decompiled source of WeaponUpgradeStation v0.2.32

plugins/WeaponUpgradeStation.dll

Decompiled 28 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Linq;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using WeaponUpgradeStation.Integration;
using WeaponUpgradeStation.Upgrades;

[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("WeaponUpgradeStation")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.32.0")]
[assembly: AssemblyInformationalVersion("0.2.32")]
[assembly: AssemblyProduct("WeaponUpgradeStation")]
[assembly: AssemblyTitle("WeaponUpgradeStation")]
[assembly: AssemblyVersion("0.2.32.0")]
[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 WeaponUpgradeStation
{
	[BepInPlugin("com.example.weaponupgradestation", "Weapon Upgrade Station", "0.2.32")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.example.weaponupgradestation";

		public const string PluginName = "Weapon Upgrade Station";

		public const string PluginVersion = "0.2.32";

		internal static Plugin Instance { get; private set; }

		internal static Harmony HarmonyInstance { get; private set; }

		internal static UpgradeSettings Settings { get; private set; }

		internal static UpgradeEngine Engine { get; private set; }

		private void Awake()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			Instance = this;
			Settings = new UpgradeSettings(((BaseUnityPlugin)this).Config);
			Engine = new UpgradeEngine(Settings);
			HarmonyInstance = new Harmony("com.example.weaponupgradestation");
			HarmonyInstance.PatchAll();
			ConfigEntry<bool> logEnemyRolls = ((BaseUnityPlugin)this).Config.Bind<bool>("Enemy Drops", "LogRolls", false, "Log each confirmed enemy drop roll. Diagnostic only.");
			EnemyDropPatch.Install(HarmonyInstance, Engine, ((BaseUnityPlugin)this).Logger, () => logEnemyRolls.Value);
			ConfigEntry<bool> testSlot = ((BaseUnityPlugin)this).Config.Bind<bool>("Station", "SpawnTestSlotMaterial", false, "Place two red damage materials and two white slot materials beside the station for single-player testing.");
			ConfigEntry<bool> testSword = ((BaseUnityPlugin)this).Config.Bind<bool>("Station", "SpawnTestSword", false, "Grant a sword to the single-player run for testing if the team does not already own one.");
			ConfigEntry<bool> testHandgun = ((BaseUnityPlugin)this).Config.Bind<bool>("Station", "SpawnTestHandgun", false, "Grant a handgun to the single-player run for testing if the team does not already own one.");
			ConfigEntry<bool> testBatteryMaterials = ((BaseUnityPlugin)this).Config.Bind<bool>("Station", "TestBatteryMaterials", false, "Use battery materials instead of damage materials in the test supplies.");
			ConfigEntry<bool> testElementMaterials = ((BaseUnityPlugin)this).Config.Bind<bool>("Station", "TestElementMaterials", false, "Use electric and fire materials in the test supplies. Takes precedence over battery materials.");
			TruckUpgradeStation.Install(HarmonyInstance, ((BaseUnityPlugin)this).Logger, () => testSlot.Value, () => testBatteryMaterials.Value, () => testElementMaterials.Value);
			TestWeaponOwnership.Install(HarmonyInstance, ((BaseUnityPlugin)this).Logger, () => testHandgun.Value, () => testSword.Value);
			ConfigEntry<bool> logDamage = ((BaseUnityPlugin)this).Config.Bind<bool>("Effect.Damage", "LogHits", false, "Log enemy hit damage before resistance when an attack bonus is applied.");
			WeaponDamagePatch.Install(HarmonyInstance, ((BaseUnityPlugin)this).Logger, () => logDamage.Value);
			ConfigEntry<bool> logElements = ((BaseUnityPlugin)this).Config.Bind<bool>("Weapon Effects", "LogElements", false, "Log applied stuns and damage from each burn tick.");
			WeaponElementEffects.Initialize(((BaseUnityPlugin)this).Logger, () => logElements.Value);
			ConfigEntry<bool> logBattery = ((BaseUnityPlugin)this).Config.Bind<bool>("Effect.BatteryConsumptionImmunity", "LogRolls", false, "Log weapon battery consumption rolls and their results.");
			WeaponBatteryPatch.Install(HarmonyInstance, ((BaseUnityPlugin)this).Logger, () => logBattery.Value);
			RunUpgradeInventory.Install(HarmonyInstance, ((BaseUnityPlugin)this).Logger);
			SlotMaterialShopDisplay.Install(HarmonyInstance, ((BaseUnityPlugin)this).Logger);
			ConfigEntry<bool> showWeaponUpgrades = ((BaseUnityPlugin)this).Config.Bind<bool>("Weapon Display", "ShowUpgrades", true, "Show the slots and levels on an upgraded weapon when aimed at or held.");
			((Component)this).gameObject.AddComponent<WeaponUpgradeDisplay>().Initialize(((BaseUnityPlugin)this).Logger, () => showWeaponUpgrades.Value);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Weapon Upgrade Station 0.2.32 loaded. Core upgrade rules are initialized.");
			((BaseUnityPlugin)this).Logger.LogWarning((object)"Prototype build: materials and weapon upgrades carry across single-player scenes and saved checkpoints. Multiplayer sync is pending.");
		}

		private void OnDestroy()
		{
			EnemyDropPatch.Clear();
			Harmony harmonyInstance = HarmonyInstance;
			if (harmonyInstance != null)
			{
				harmonyInstance.UnpatchSelf();
			}
		}
	}
}
namespace WeaponUpgradeStation.Upgrades
{
	internal sealed class UpgradeDefinition
	{
		public static readonly UpgradeType[] Types = (UpgradeType[])Enum.GetValues(typeof(UpgradeType));

		public bool Enabled { get; set; } = true;

		public int MaximumLevel { get; set; }

		public double AmountPerLevel { get; set; }

		public double MaximumAmount { get; set; }
	}
	internal sealed class UpgradeEngine
	{
		private readonly UpgradeSettings _settings;

		public UpgradeEngine(UpgradeSettings settings)
		{
			_settings = settings;
		}

		public UpgradeType? RollDrop(int enemyLevel, Random random)
		{
			double dropChance = _settings.GetDropChance(enemyLevel);
			if (dropChance <= 0.0 || random.NextDouble() >= dropChance)
			{
				return null;
			}
			List<(UpgradeType, double)> list = new List<(UpgradeType, double)>();
			double num = 0.0;
			UpgradeType[] types = UpgradeDefinition.Types;
			foreach (UpgradeType upgradeType in types)
			{
				double dropWeight = _settings.GetDropWeight(upgradeType);
				if (!(dropWeight <= 0.0))
				{
					num += dropWeight;
					list.Add((upgradeType, dropWeight));
				}
			}
			if (list.Count == 0)
			{
				return null;
			}
			double num2 = random.NextDouble() * num;
			foreach (var item in list)
			{
				num2 -= item.Item2;
				if (num2 < 0.0)
				{
					return item.Item1;
				}
			}
			return list[list.Count - 1].Item1;
		}

		public UpgradeResult TryApply(WeaponUpgradeState state, UpgradeType type, bool compatible, bool hasUpgradeMaterial, bool hasSlotMaterial, int? slotIndex)
		{
			UpgradeDefinition effect = _settings.GetEffect(type);
			if (!effect.Enabled)
			{
				return UpgradeResult.Disabled;
			}
			if (!compatible)
			{
				return UpgradeResult.IncompatibleWeapon;
			}
			if (!hasUpgradeMaterial || !hasSlotMaterial)
			{
				return UpgradeResult.MissingMaterial;
			}
			if (slotIndex.HasValue)
			{
				int valueOrDefault = slotIndex.GetValueOrDefault();
				if (valueOrDefault < 0 || valueOrDefault >= state.SlotCount || state.GetSlot(valueOrDefault).Type != type)
				{
					return UpgradeResult.InvalidSlot;
				}
				int level = state.GetSlot(valueOrDefault).Level;
				if (level == int.MaxValue || (effect.MaximumLevel > 0 && level >= effect.MaximumLevel))
				{
					return UpgradeResult.MaximumReached;
				}
				state.LevelUp(valueOrDefault);
			}
			else
			{
				int maximumSlots = _settings.MaximumSlots;
				if (maximumSlots > 0 && state.SlotCount >= maximumSlots)
				{
					return UpgradeResult.MaximumReached;
				}
				state.AddSlot(type);
			}
			return UpgradeResult.Success;
		}

		public double GetAmount(WeaponUpgradeState state, UpgradeType type, double multiplier = 1.0)
		{
			UpgradeDefinition effect = _settings.GetEffect(type);
			if (!effect.Enabled)
			{
				return 0.0;
			}
			double num = 0.0;
			for (int i = 0; i < state.SlotCount; i++)
			{
				UpgradeSlot slot = state.GetSlot(i);
				if (slot.Type == type)
				{
					num += (double)slot.Level * effect.AmountPerLevel * multiplier;
				}
			}
			if (effect.MaximumAmount >= 0.0)
			{
				num = Math.Min(effect.MaximumAmount, num);
			}
			if (type == UpgradeType.BatteryConsumptionImmunity)
			{
				num = Math.Min(1.0, num);
			}
			return num;
		}
	}
	internal sealed class UpgradeSettings
	{
		private sealed class EffectConfig
		{
			private readonly ConfigEntry<bool> _enabled;

			private readonly ConfigEntry<float> _dropWeight;

			private readonly ConfigEntry<int> _maximumLevel;

			private readonly ConfigEntry<float> _amountPerLevel;

			private readonly ConfigEntry<float> _maximumAmount;

			public double DropWeight
			{
				get
				{
					if (!_enabled.Value)
					{
						return 0.0;
					}
					return _dropWeight.Value;
				}
			}

			public unsafe EffectConfig(ConfigFile config, UpgradeType type)
			{
				//IL_0081: Unknown result type (might be due to invalid IL or missing references)
				//IL_008b: Expected O, but got Unknown
				//IL_0108: Unknown result type (might be due to invalid IL or missing references)
				//IL_0112: Expected O, but got Unknown
				//IL_0268: Unknown result type (might be due to invalid IL or missing references)
				//IL_0272: Expected O, but got Unknown
				//IL_029f: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a9: Expected O, but got Unknown
				string text = $"Effect.{type}";
				_enabled = config.Bind<bool>(text, "Enabled", true, "Enable drops and applied effects.");
				ConfigEntry<float> val = config.Bind<float>(text, "DropWeight", float.NaN, "Previous shared drop weight.");
				_dropWeight = config.Bind<float>("Drop Weights", type.ToString(), 1f, new ConfigDescription("Relative drop weight shared by all enemy levels. 0 excludes this material. Rounded to two decimal places.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), new object[1] { "REPOConfigStep=0.01" }));
				if (_dropWeight.Value == 1f && !float.IsNaN(val.Value))
				{
					_dropWeight.Value = val.Value;
				}
				config.Remove(((ConfigEntryBase)val).Definition);
				NormalizeWeight();
				_dropWeight.SettingChanged += delegate
				{
					NormalizeWeight();
				};
				_maximumLevel = config.Bind<int>(text, "MaximumLevel", 0, new ConfigDescription("Maximum level per slot. 0 = unlimited.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, int.MaxValue), Array.Empty<object>()));
				string text2 = type switch
				{
					UpgradeType.Damage => "flat damage points for ranged weapons (melee gets twice this amount)", 
					UpgradeType.BatteryCapacity => "battery bars for ranged weapons (melee gets twice this amount)", 
					UpgradeType.Electric => "seconds of stun for ranged weapons (melee gets twice this amount)", 
					UpgradeType.Fire => "damage per second", 
					_ => "probability for ranged weapons (0.10 = 10 percent, melee gets twice this amount)", 
				};
				object obj = type switch
				{
					UpgradeType.Damage => ("FlatDamagePerLevel", 10f, "1"), 
					UpgradeType.BatteryCapacity => ("BarsPerLevel", 1f, "1"), 
					UpgradeType.BatteryConsumptionImmunity => ("SkipChancePerLevel", 0.05f, "0.01"), 
					UpgradeType.Electric => ("StunSecondsPerLevel", 0.5f, "0.01"), 
					UpgradeType.Fire => ("DamagePerSecondPerLevel", 5f, "1"), 
					_ => ("AmountPerLevel", 0f, "0.01"), 
				};
				string item = ((ValueTuple<string, float, string>*)(&obj))->Item1;
				float item2 = ((ValueTuple<string, float, string>*)(&obj))->Item2;
				string item3 = ((ValueTuple<string, float, string>*)(&obj))->Item3;
				AcceptableValueRange<float> val2 = ((type == UpgradeType.BatteryConsumptionImmunity) ? new AcceptableValueRange<float>(0f, 1f) : null);
				_amountPerLevel = config.Bind<float>(text, item, item2, new ConfigDescription("Amount per level in " + text2 + ".", (AcceptableValueBase)(object)val2, new object[1] { "REPOConfigStep=" + item3 }));
				_maximumAmount = config.Bind<float>(text, "MaximumAmount", -1f, new ConfigDescription("Cap on the combined effect. A negative value removes the cap.", (AcceptableValueBase)null, new object[1] { "REPOConfigStep=" + item3 }));
			}

			private void NormalizeWeight()
			{
				float num = (float)Math.Round((decimal)Math.Min(5.0, NonNegative(_dropWeight.Value)), 2, MidpointRounding.AwayFromZero);
				if (!_dropWeight.Value.Equals(num))
				{
					_dropWeight.Value = num;
				}
			}

			public UpgradeDefinition Read()
			{
				return new UpgradeDefinition
				{
					Enabled = _enabled.Value,
					MaximumLevel = _maximumLevel.Value,
					AmountPerLevel = Math.Min(1E+100, NonNegative(_amountPerLevel.Value)),
					MaximumAmount = ((_maximumAmount.Value < 0f) ? (-1.0) : NonNegative(_maximumAmount.Value))
				};
			}
		}

		private readonly ConfigEntry<int> _maximumSlots;

		private readonly ConfigEntry<float>[] _enemyDropChances;

		private readonly Dictionary<UpgradeType, EffectConfig> _effects = new Dictionary<UpgradeType, EffectConfig>();

		private readonly ConfigEntry<float> _fireDuration;

		private readonly ConfigEntry<float> _maximumFireDuration;

		private readonly ConfigEntry<float> _electricReapplyDelay;

		public ConfigEntry<int> SlotPrice { get; }

		public int SlotPriceThousands => (int)(((long)SlotPrice.Value + 999L) / 1000);

		public double FireDuration
		{
			get
			{
				double num = NonNegative(_fireDuration.Value);
				double num2 = _maximumFireDuration.Value;
				if (!(num2 < 0.0))
				{
					return Math.Min(num, NonNegative(num2));
				}
				return num;
			}
		}

		public double ElectricReapplyDelay => NonNegative(_electricReapplyDelay.Value);

		public int MaximumSlots => _maximumSlots.Value;

		public UpgradeSettings(ConfigFile config)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Expected O, but got Unknown
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Expected O, but got Unknown
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Expected O, but got Unknown
			SlotPrice = config.Bind<int>("Shop", "SlotPrice", 50000, new ConfigDescription("Price of one slot material in dollars, rounded up to the game's 1,000-dollar currency unit.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, int.MaxValue), Array.Empty<object>()));
			_maximumSlots = config.Bind<int>("Station", "MaximumSlots", 5, new ConfigDescription("Maximum slots per weapon. 0 = unlimited.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, int.MaxValue), Array.Empty<object>()));
			float[] array = new float[3] { 0.01f, 0.05f, 0.1f };
			_enemyDropChances = new ConfigEntry<float>[array.Length];
			for (int i = 0; i < array.Length; i++)
			{
				_enemyDropChances[i] = config.Bind<float>("Enemy Drops", $"Level{i + 1}Chance", array[i], new ConfigDescription("Drop probability from 0 to 1 for this enemy level. Level 0 never drops.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[1] { "REPOConfigStep=0.01" }));
			}
			_fireDuration = config.Bind<float>("Effect.Fire", "BurnDurationSeconds", 5f, new ConfigDescription("Burn duration in seconds. One damage tick per full second.", (AcceptableValueBase)null, new object[1] { "REPOConfigStep=1" }));
			_maximumFireDuration = config.Bind<float>("Effect.Fire", "MaximumDurationSeconds", -1f, new ConfigDescription("A negative value removes the fire duration cap.", (AcceptableValueBase)null, new object[1] { "REPOConfigStep=1" }));
			_electricReapplyDelay = config.Bind<float>("Effect.Electric", "ReapplyDelaySeconds", 0f, new ConfigDescription("Minimum time between stuns applied to the same enemy.", (AcceptableValueBase)null, new object[1] { "REPOConfigStep=0.01" }));
			bool saveOnConfigSet = config.SaveOnConfigSet;
			config.SaveOnConfigSet = false;
			try
			{
				UpgradeType[] types = UpgradeDefinition.Types;
				foreach (UpgradeType upgradeType in types)
				{
					_effects.Add(upgradeType, new EffectConfig(config, upgradeType));
				}
			}
			finally
			{
				config.SaveOnConfigSet = saveOnConfigSet;
			}
			if (saveOnConfigSet)
			{
				config.Save();
			}
		}

		public double GetDropChance(int enemyLevel)
		{
			if (enemyLevel < 1 || enemyLevel > 3)
			{
				return 0.0;
			}
			return Math.Min(1.0, NonNegative(_enemyDropChances[enemyLevel - 1].Value));
		}

		public UpgradeDefinition GetEffect(UpgradeType type)
		{
			return _effects[type].Read();
		}

		public double GetDropWeight(UpgradeType type)
		{
			return _effects[type].DropWeight;
		}

		private static double NonNegative(double value)
		{
			if (!double.IsNaN(value) && !double.IsInfinity(value))
			{
				return Math.Max(0.0, value);
			}
			return 0.0;
		}
	}
	public enum UpgradeType
	{
		Damage,
		BatteryCapacity,
		BatteryConsumptionImmunity,
		Electric,
		Fire
	}
	public enum UpgradeResult
	{
		Success,
		Disabled,
		IncompatibleWeapon,
		MissingMaterial,
		InvalidSlot,
		MaximumReached
	}
	[Serializable]
	public sealed class WeaponUpgradeState
	{
		private readonly List<UpgradeSlot> _slots = new List<UpgradeSlot>();

		public int SlotCount => _slots.Count;

		public UpgradeSlot GetSlot(int index)
		{
			return _slots[index];
		}

		internal void AddSlot(UpgradeType type, int level = 1)
		{
			_slots.Add(new UpgradeSlot(type, level));
		}

		internal void LevelUp(int index)
		{
			UpgradeSlot upgradeSlot = _slots[index];
			_slots[index] = new UpgradeSlot(upgradeSlot.Type, upgradeSlot.Level + 1);
		}
	}
	[Serializable]
	public readonly struct UpgradeSlot
	{
		public UpgradeType Type { get; }

		public int Level { get; }

		internal UpgradeSlot(UpgradeType type, int level)
		{
			Type = type;
			Level = level;
		}
	}
}
namespace WeaponUpgradeStation.Integration
{
	internal sealed class EnemyDropPatch
	{
		private static EnemyDropPatch? _active;

		private readonly FieldInfo _dead;

		private readonly FieldInfo _deadImpulse;

		private readonly FieldInfo _enemy;

		private readonly FieldInfo _parent;

		private readonly FieldInfo _difficulty;

		private readonly Func<bool> _isAuthority;

		private readonly UpgradeEngine _engine;

		private readonly ManualLogSource _log;

		private readonly Func<bool> _logRolls;

		private readonly Random _random = new Random();

		private readonly Func<bool>? _isMultiplayer;

		private EnemyDropPatch(FieldInfo dead, FieldInfo deadImpulse, FieldInfo enemy, FieldInfo parent, FieldInfo difficulty, Func<bool> isAuthority, UpgradeEngine engine, ManualLogSource log, Func<bool> logRolls, Func<bool>? isMultiplayer)
		{
			_dead = dead;
			_deadImpulse = deadImpulse;
			_enemy = enemy;
			_parent = parent;
			_difficulty = difficulty;
			_isAuthority = isAuthority;
			_engine = engine;
			_log = log;
			_logRolls = logRolls;
			_isMultiplayer = isMultiplayer;
		}

		internal static void Install(Harmony harmony, UpgradeEngine engine, ManualLogSource log, Func<bool> logRolls)
		{
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Expected O, but got Unknown
			//IL_026c: Expected O, but got Unknown
			try
			{
				Type type = AccessTools.TypeByName("EnemyHealth");
				Type type2 = AccessTools.TypeByName("Enemy");
				Type type3 = AccessTools.TypeByName("EnemyParent");
				Type type4 = AccessTools.TypeByName("Photon.Pun.PhotonMessageInfo");
				Type type5 = AccessTools.TypeByName("SemiFunc");
				MethodInfo methodInfo = ((type4 == null) ? null : AccessTools.Method(type, "DeathImpulseRPC", new Type[1] { type4 }, (Type[])null));
				MethodInfo methodInfo2 = AccessTools.Method(type5, "IsMasterClientOrSingleplayer", Type.EmptyTypes, (Type[])null);
				MethodInfo methodInfo3 = AccessTools.Method(type5, "IsMultiplayer", Type.EmptyTypes, (Type[])null);
				FieldInfo fieldInfo = AccessTools.Field(type, "dead");
				FieldInfo fieldInfo2 = AccessTools.Field(type, "deadImpulse");
				FieldInfo fieldInfo3 = AccessTools.Field(type, "enemy");
				FieldInfo fieldInfo4 = AccessTools.Field(type2, "EnemyParent");
				FieldInfo fieldInfo5 = AccessTools.Field(type3, "difficulty");
				if (methodInfo == null || methodInfo.ReturnType != typeof(void) || methodInfo2 == null || !methodInfo2.IsStatic || methodInfo2.ReturnType != typeof(bool) || fieldInfo?.FieldType != typeof(bool) || fieldInfo2?.FieldType != typeof(bool) || fieldInfo3 == null || fieldInfo3.FieldType != type2 || fieldInfo4 == null || fieldInfo4.FieldType != type3 || fieldInfo5 == null || !fieldInfo5.FieldType.IsEnum)
				{
					log.LogWarning((object)"Enemy drop hook unavailable: game assembly signatures differ.");
					return;
				}
				Func<bool> func = (((object)methodInfo3 != null && methodInfo3.IsStatic && methodInfo3.ReturnType == typeof(bool)) ? ((Func<bool>)methodInfo3.CreateDelegate(typeof(Func<bool>))) : null);
				if (func == null)
				{
					log.LogWarning((object)"Upgrade material spawning unavailable: game mode signature differs.");
				}
				_active = new EnemyDropPatch(fieldInfo, fieldInfo2, fieldInfo3, fieldInfo4, fieldInfo5, (Func<bool>)methodInfo2.CreateDelegate(typeof(Func<bool>)), engine, log, logRolls, func);
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(EnemyDropPatch), "BeforeDeath", (Type[])null), new HarmonyMethod(typeof(EnemyDropPatch), "AfterDeath", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				log.LogInfo((object)"Enemy drop roll hook installed.");
			}
			catch (Exception ex)
			{
				_active = null;
				log.LogWarning((object)("Enemy drop hook unavailable: " + ex.Message));
			}
		}

		internal static void Clear()
		{
			_active = null;
		}

		private static void BeforeDeath(object __instance, out (int Level, Vector3? Position) __state)
		{
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			__state = default((int, Vector3?));
			EnemyDropPatch active = _active;
			if (active == null || !active._isAuthority())
			{
				return;
			}
			object value = active._dead.GetValue(__instance);
			if (!(value is bool) || !(bool)value)
			{
				value = active._deadImpulse.GetValue(__instance);
				if (value is bool && (bool)value)
				{
					object value2 = active._enemy.GetValue(__instance);
					object obj = ((value2 == null) ? null : active._parent.GetValue(value2));
					int num = ((obj != null) ? (active._difficulty.GetValue(obj)?.ToString() switch
					{
						"Difficulty1" => 1, 
						"Difficulty2" => 2, 
						"Difficulty3" => 3, 
						_ => 0, 
					}) : 0);
					int item = num;
					Component val = (Component)((__instance is Component) ? __instance : null);
					__state = (Level: item, Position: (val != null && (Object)(object)val != (Object)null) ? new Vector3?(val.transform.position) : ((Vector3?)null));
				}
			}
		}

		private static void AfterDeath(object __instance, (int Level, Vector3? Position) __state)
		{
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			EnemyDropPatch active = _active;
			if (active == null || !__state.Position.HasValue)
			{
				return;
			}
			object value = active._dead.GetValue(__instance);
			if (!(value is bool) || !(bool)value)
			{
				return;
			}
			int item = __state.Level;
			UpgradeType? upgradeType = active._engine.RollDrop(item, active._random);
			if (active._logRolls())
			{
				string arg = upgradeType?.ToString() ?? "none";
				active._log.LogInfo((object)$"Enemy drop roll: enemy level {item}, material {arg}.");
			}
			if (!upgradeType.HasValue)
			{
				return;
			}
			UpgradeType valueOrDefault = upgradeType.GetValueOrDefault();
			try
			{
				Func<bool>? isMultiplayer = active._isMultiplayer;
				if (isMultiplayer != null && !isMultiplayer())
				{
					UpgradeMaterialDrop.Spawn(valueOrDefault, __state.Position.Value);
					active._log.LogInfo((object)$"Upgrade material spawned: {valueOrDefault}.");
				}
			}
			catch (Exception ex)
			{
				active._log.LogWarning((object)("Upgrade material spawn failed: " + ex.Message));
			}
		}
	}
	public interface IWeaponUpgradeAdapter
	{
		bool CanApply(object weapon, UpgradeType type);

		void ApplySuccessfulUpgrade(object weapon, UpgradeType type, double amount);
	}
	internal static class RunUpgradeInventory
	{
		private const string RackName = "Weapon Upgrade Slot Stock";

		private static readonly Dictionary<UpgradeType, int> Materials = new Dictionary<UpgradeType, int>();

		private static readonly Dictionary<string, WeaponUpgradeState> Weapons = new Dictionary<string, WeaponUpgradeState>(StringComparer.Ordinal);

		private static readonly List<SlotMaterial> ShopStock = new List<SlotMaterial>(5);

		private static GameObject? _rack;

		private static int _slots;

		private static Type _attributes = null;

		private static Type _roomVolume = null;

		private static Type _itemVolume = null;

		private static FieldInfo _id = null;

		private static FieldInfo _checkoutRoom = null;

		private static FieldInfo _isShop = null;

		private static FieldInfo _isExtractionRoom = null;

		private static FieldInfo _secretShopVolume = null;

		private static FieldInfo _shopCost = null;

		private static MethodInfo _updateCost = null;

		private static Func<bool> _multiplayer = null;

		private static Func<bool> _inShop = null;

		private static Func<int> _currency = null;

		private static Func<int, int> _setCurrency = null;

		private static ManualLogSource _log = null;

		private static bool _ready;

		private static FieldInfo _saveName = null;

		private static MethodInfo _saveLevel = null;

		internal static void Install(Harmony harmony, ManualLogSource log)
		{
			try
			{
				Type type = AccessTools.TypeByName("ExtractionPoint");
				Type type2 = AccessTools.TypeByName("ShopManager");
				Type type3 = AccessTools.TypeByName("SemiFunc");
				Type type4 = AccessTools.TypeByName("PunManager");
				_attributes = AccessTools.TypeByName("ItemAttributes");
				_roomVolume = AccessTools.TypeByName("RoomVolume");
				_id = Field(_attributes, "instanceName", typeof(string));
				_checkoutRoom = Field(type, "roomVolume", typeof(GameObject));
				_isShop = Field(type, "isShop", typeof(bool));
				_isExtractionRoom = Field(_roomVolume, "Extraction", typeof(bool));
				_itemVolume = AccessTools.TypeByName("ItemVolume");
				_secretShopVolume = AccessTools.Field(_itemVolume, "itemSecretShopType");
				if (_secretShopVolume == null || !_secretShopVolume.FieldType.IsEnum)
				{
					throw new InvalidOperationException("Unexpected shop volume type.");
				}
				_shopCost = Field(type2, "totalCost", typeof(int));
				_updateCost = Method(type3, "ShopUpdateCost", typeof(void));
				_multiplayer = (Func<bool>)Method(type3, "IsMultiplayer", typeof(bool)).CreateDelegate(typeof(Func<bool>));
				_inShop = (Func<bool>)Method(type3, "RunIsShop", typeof(bool)).CreateDelegate(typeof(Func<bool>));
				_currency = (Func<int>)Method(type3, "StatGetRunCurrency", typeof(int)).CreateDelegate(typeof(Func<int>));
				_setCurrency = (Func<int, int>)Method(type3, "StatSetRunCurrency", typeof(int), typeof(int)).CreateDelegate(typeof(Func<int, int>));
				_log = log;
				harmony.Patch((MethodBase)Method(type, "DestroyAllPhysObjectsInHaulList", typeof(void)), Hook("ExtractMaterials"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)Method(type, "DestroyAllPhysObjectsInShoppingList", typeof(void)), (HarmonyMethod)null, Hook("BuyCubes"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)Method(type, "ShopHasItems", typeof(bool)), (HarmonyMethod)null, Hook("IncludeCubes"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)Method(type2, "ShopCheck", typeof(void)), (HarmonyMethod)null, Hook("IncludeCost"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)Method(type, "ShopSetup", typeof(void)), (HarmonyMethod)null, Hook("QueueShopStock"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)Method(type4, "UpdateShoppingListRPC", typeof(void), typeof(int), typeof(string[]), typeof(int[]), AccessTools.TypeByName("Photon.Pun.PhotonMessageInfo")), Hook("IncludeReceipt"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)Method(type4, "SetItemNameLOGIC", typeof(void), typeof(string), typeof(int), _attributes), (HarmonyMethod)null, Hook("RestoreWeapon"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)Method(AccessTools.TypeByName("RunManager"), "ResetProgress", typeof(void)), (HarmonyMethod)null, Hook("Clear"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_ready = true;
				log.LogInfo((object)"Run upgrade inventory hooks installed.");
				InstallSaveHooks(harmony);
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("Run upgrade inventory hooks unavailable: " + ex.Message));
			}
		}

		internal static void RememberWeapon(Rigidbody weapon, WeaponSlots slots)
		{
			if (_ready)
			{
				Component componentInChildren = ((Component)weapon).GetComponentInChildren(_attributes, true);
				if ((Object)(object)componentInChildren != (Object)null && _id.GetValue(componentInChildren) is string { Length: >0 } text)
				{
					RecordWeapon(text, slots.State);
				}
				else
				{
					_log.LogInfo((object)("Run upgrade inventory awaiting a native item ID for " + ((Object)weapon).name + "."));
				}
			}
		}

		private static void RecordWeapon(string id, WeaponUpgradeState state)
		{
			Weapons[id] = state;
			_log.LogInfo((object)$"Run upgrade inventory recorded weapon {id}, {state.SlotCount} slots.");
		}

		private static void RestoreWeapon(string __0, Component __2)
		{
			if (!_ready || _multiplayer() || (Object)(object)__2 == (Object)null || string.IsNullOrEmpty(__0))
			{
				return;
			}
			Rigidbody componentInParent = __2.GetComponentInParent<Rigidbody>();
			if ((Object)(object)componentInParent == (Object)null)
			{
				return;
			}
			WeaponSlots component = ((Component)componentInParent).GetComponent<WeaponSlots>();
			WeaponUpgradeState value;
			if ((Object)(object)component != (Object)null && component.State.SlotCount > 0)
			{
				if (!Weapons.ContainsKey(__0))
				{
					RecordWeapon(__0, component.State);
				}
			}
			else if (Weapons.TryGetValue(__0, out value))
			{
				(component ?? ((Component)componentInParent).gameObject.AddComponent<WeaponSlots>()).State = value;
				WeaponBatteryPatch.ApplyCapacity(componentInParent, value, preserveChargePercent: true);
				_log.LogInfo((object)$"Run upgrade inventory restored weapon {__0}, {value.SlotCount} slots.");
			}
		}

		private static void ExtractMaterials(Component __instance)
		{
			try
			{
				StoreExtractedMaterials(__instance);
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Run upgrade inventory could not collect materials: " + ex.Message));
			}
		}

		private static void StoreExtractedMaterials(Component __instance)
		{
			if (!_ready || _multiplayer())
			{
				return;
			}
			object value = _isShop.GetValue(__instance);
			if (value is bool && (bool)value)
			{
				return;
			}
			Component room = GetRoom(__instance);
			if ((Object)(object)room == (Object)null)
			{
				return;
			}
			UpgradeMaterialDrop[] array = Object.FindObjectsByType<UpgradeMaterialDrop>((FindObjectsSortMode)0);
			foreach (UpgradeMaterialDrop upgradeMaterialDrop in array)
			{
				if (IsInExtraction((Component)(object)upgradeMaterialDrop, room))
				{
					Materials.TryGetValue(upgradeMaterialDrop.Type, out var value2);
					if (!upgradeMaterialDrop.Banked)
					{
						value2 = (Materials[upgradeMaterialDrop.Type] = value2 + 1);
					}
					Remove((Component)(object)upgradeMaterialDrop);
					_log.LogInfo((object)$"Run upgrade inventory extracted {upgradeMaterialDrop.Type}. Stored: {value2}.");
				}
			}
		}

		internal static void PlaceStock(Vector3 origin, Vector3 right, Vector3 forward)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: 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_0016: 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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			if (!_ready)
			{
				return;
			}
			int num = 0;
			for (int i = 0; i < _slots; i++)
			{
				UpgradeMaterialDrop.SpawnSlotMaterial(StockPosition(origin, right, forward, num++)).Banked = true;
			}
			foreach (KeyValuePair<UpgradeType, int> material in Materials)
			{
				for (int j = 0; j < material.Value; j++)
				{
					UpgradeMaterialDrop.SpawnMaterial(material.Key, StockPosition(origin, right, forward, num++)).GetComponent<UpgradeMaterialDrop>().Banked = true;
				}
			}
			if (num > 0)
			{
				_log.LogInfo((object)$"Run upgrade inventory returned {num} stored materials to the truck ({_slots} slot cubes).");
			}
		}

		private static Vector3 StockPosition(Vector3 origin, Vector3 right, Vector3 forward, int index)
		{
			//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_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			return origin + right * ((float)(index % 5 - 2) * 0.3f) + forward * ((float)(index / 5 % 3 - 1) * 0.3f) + Vector3.up * (0.25f + (float)(index / 15) * 0.28f);
		}

		internal static void Consume(UpgradeMaterialDrop material, SlotMaterial slot)
		{
			ConsumeMaterial(material);
			if (slot.Banked && _slots > 0)
			{
				_slots--;
			}
		}

		internal static void RecordExchange(UpgradeMaterialDrop first, UpgradeMaterialDrop second, SlotMaterial result)
		{
			ConsumeMaterial(first);
			ConsumeMaterial(second);
			_slots++;
			result.Banked = true;
		}

		private static void ConsumeMaterial(UpgradeMaterialDrop material)
		{
			if (material.Banked && Materials.TryGetValue(material.Type, out var value) && value > 0)
			{
				Materials[material.Type] = value - 1;
			}
		}

		private static void QueueShopStock(MonoBehaviour __instance)
		{
			if (_ready && !_multiplayer())
			{
				object value = _isShop.GetValue(__instance);
				if (value is bool && (bool)value)
				{
					__instance.StartCoroutine(PlaceShopStock((Component)(object)__instance));
				}
			}
		}

		private static IEnumerator PlaceShopStock(Component checkout)
		{
			yield return (object)new WaitForSeconds(1f);
			if ((Object)(object)checkout == (Object)null || !_inShop() || (Object)(object)_rack != (Object)null)
			{
				yield break;
			}
			try
			{
				BuildShopStock(checkout);
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Run upgrade inventory could not place shop stock: " + ex.Message));
			}
		}

		private static void BuildShopStock(Component checkout)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: 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_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: 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_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: 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_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: 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_0295: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0309: Unknown result type (might be due to invalid IL or missing references)
			Component val = null;
			Object[] array = Object.FindObjectsByType(_itemVolume, (FindObjectsSortMode)0);
			foreach (Object obj in array)
			{
				Component val2 = (Component)(object)((obj is Component) ? obj : null);
				if (val2 != null && !((Object)(object)val2 == (Object)null) && !(val2.gameObject.scene != checkout.gameObject.scene) && Convert.ToInt32(_secretShopVolume.GetValue(val2)) == 0)
				{
					Vector3 val3 = val2.transform.position - checkout.transform.position;
					if (((Vector3)(ref val3)).sqrMagnitude <= 144f && val3.y <= 1.6f && ((Object)(object)val == (Object)null || val2.transform.position.y > val.transform.position.y))
					{
						val = val2;
					}
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				_log.LogInfo((object)"Run upgrade inventory found no nearby storefront shelf volume. Using an extra rack beside checkout.");
			}
			Transform val4 = (((Object)(object)val != (Object)null) ? val.transform : checkout.transform);
			Vector3 val5 = Vector3.ProjectOnPlane(val4.right, Vector3.up);
			Vector3 val6 = ((Vector3)(ref val5)).normalized;
			if (val6 == Vector3.zero)
			{
				val6 = Vector3.right;
			}
			Vector3 val7 = (((Object)(object)val != (Object)null) ? (val4.position + Vector3.up * 0.55f) : (val4.position + val6 * 2.1f + Vector3.up * 0.7f));
			if (Physics.CheckBox(val7, new Vector3(0.04f, 0.04f, 0.04f), Quaternion.identity, LayerMask.GetMask(new string[1] { "Default" }), (QueryTriggerInteraction)1))
			{
				val7 += Vector3.up * 0.2f;
			}
			if (!((Object)(object)_rack != (Object)null))
			{
				GameObject val8 = GameObject.CreatePrimitive((PrimitiveType)3);
				((Object)val8).name = "Weapon Upgrade Slot Stock";
				val8.transform.SetPositionAndRotation(val7, Quaternion.LookRotation(Vector3.Cross(val6, Vector3.up)));
				val8.transform.localScale = new Vector3(1.55f, 0.07f, 0.45f);
				val8.transform.SetParent(checkout.transform, true);
				_rack = val8;
				AddPriceLabel(val8);
				ShopStock.Clear();
				for (int j = 0; j < 5; j++)
				{
					SlotMaterial slotMaterial = UpgradeMaterialDrop.SpawnSlotMaterial(val8.transform.position + val6 * ((float)(j - 2) * 0.28f) + Vector3.up * 0.16f);
					slotMaterial.PriceThousands = Plugin.Settings.SlotPriceThousands;
					slotMaterial.ForSale = true;
					ShopStock.Add(slotMaterial);
				}
				((MonoBehaviour)val8.AddComponent<ShopSlotDisplay>()).StartCoroutine(RefreshCheckout());
				_log.LogInfo((object)$"Run upgrade inventory placed five slot cubes in shop at {(long)Plugin.Settings.SlotPriceThousands * 1000L:N0} dollars each, position {val7}.");
			}
		}

		private static IEnumerator RefreshCheckout()
		{
			int previous = 0;
			WaitForSeconds interval = new WaitForSeconds(0.2f);
			while (_inShop())
			{
				int count = ShopCubes(null).Count;
				if (count != previous)
				{
					previous = count;
					_updateCost.Invoke(null, null);
				}
				yield return interval;
			}
		}

		private static void AddPriceLabel(GameObject rack)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Slot material price");
			val.transform.SetParent(rack.transform, true);
			val.transform.SetPositionAndRotation(rack.transform.position + Vector3.up * 0.34f, rack.transform.rotation);
			TextMesh obj = val.AddComponent<TextMesh>();
			obj.anchor = (TextAnchor)4;
			obj.characterSize = 0.025f;
			obj.fontSize = 36;
			obj.text = $"SLOT MATERIAL\n{(long)Plugin.Settings.SlotPriceThousands * 1000L:N0} DOLLARS EACH";
			obj.color = Color.white;
		}

		private static void IncludeCubes(Component __instance, ref bool __result)
		{
			if (_ready && !__result && !_multiplayer())
			{
				object value = _isShop.GetValue(__instance);
				if (value is bool && (bool)value)
				{
					__result = ShopCubes(GetRoom(__instance)).Count > 0;
				}
			}
		}

		private static void IncludeCost(Component __instance)
		{
			if (_ready && !_multiplayer() && _inShop())
			{
				long val = (int)_shopCost.GetValue(__instance) + GetSlotCost(ShopCubes(null));
				_shopCost.SetValue(__instance, (int)Math.Min(2147483647L, val));
			}
		}

		private static void IncludeReceipt(ref int __0, ref string[] __1, ref int[] __2)
		{
			if (_ready && !_multiplayer() && _inShop())
			{
				List<SlotMaterial> list = ShopCubes(null);
				int count = list.Count;
				if (count != 0)
				{
					int num = (int)Math.Min(2147483647L, GetSlotCost(list));
					__0 = (int)Math.Min(2147483647L, (long)__0 + (long)num);
					Array.Resize(ref __1, __1.Length + 1);
					Array.Resize(ref __2, __2.Length + 1);
					__1[__1.Length - 1] = $"Slot material x{count}";
					__2[__2.Length - 1] = num;
				}
			}
		}

		private static void BuyCubes(Component __instance)
		{
			if (!_ready || _multiplayer())
			{
				return;
			}
			object value = _isShop.GetValue(__instance);
			if (!(value is bool) || !(bool)value)
			{
				return;
			}
			List<SlotMaterial> list = ShopCubes(GetRoom(__instance));
			long slotCost = GetSlotCost(list);
			int num = _currency();
			if (list.Count == 0 || slotCost > num)
			{
				return;
			}
			if (slotCost > 0)
			{
				_setCurrency(num - (int)slotCost);
			}
			_slots += list.Count;
			foreach (SlotMaterial item in list)
			{
				Remove((Component)(object)item);
			}
			RefreshShopCost();
			_log.LogInfo((object)$"Run upgrade inventory purchased {list.Count} slot cubes for {slotCost * 1000:N0} dollars. Stored: {_slots}. Funds: {num}K -> {_currency()}K.");
		}

		internal static void RefreshShopCost()
		{
			if (_ready)
			{
				_updateCost.Invoke(null, null);
			}
		}

		private static long GetSlotCost(List<SlotMaterial> cubes)
		{
			long num = 0L;
			foreach (SlotMaterial cube in cubes)
			{
				num += cube.PriceThousands;
			}
			return num;
		}

		private static List<SlotMaterial> ShopCubes(Component? room)
		{
			List<SlotMaterial> list = new List<SlotMaterial>();
			foreach (SlotMaterial item in ShopStock)
			{
				if ((Object)(object)item != (Object)null && ((Component)item).gameObject.activeInHierarchy && item.ForSale && IsInExtraction((Component)(object)item, room))
				{
					list.Add(item);
				}
			}
			return list;
		}

		private static Component? GetRoom(Component extraction)
		{
			object? value = _checkoutRoom.GetValue(extraction);
			object? obj = ((value is GameObject) ? value : null);
			object obj2 = ((obj != null) ? ((GameObject)obj).GetComponentInChildren(_roomVolume, true) : null);
			if (obj2 == null)
			{
				object? value2 = _checkoutRoom.GetValue(extraction);
				object? obj3 = ((value2 is GameObject) ? value2 : null);
				if (obj3 == null)
				{
					return null;
				}
				obj2 = ((GameObject)obj3).GetComponentInParent(_roomVolume);
			}
			return (Component?)obj2;
		}

		private static bool IsInExtraction(Component item, Component? room)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			int mask = LayerMask.GetMask(new string[1] { "RoomVolume" });
			Collider[] array = Physics.OverlapSphere(item.transform.position, 0.05f, mask, (QueryTriggerInteraction)2);
			for (int i = 0; i < array.Length; i++)
			{
				Component componentInParent = ((Component)array[i]).GetComponentInParent(_roomVolume);
				if ((Object)(object)componentInParent != (Object)null)
				{
					object value = _isExtractionRoom.GetValue(componentInParent);
					if (value is bool && (bool)value && ((Object)(object)room == (Object)null || (Object)(object)componentInParent == (Object)(object)room))
					{
						return true;
					}
				}
			}
			return false;
		}

		private static void Remove(Component item)
		{
			item.gameObject.SetActive(false);
			Object.Destroy((Object)(object)item.gameObject);
		}

		private static void Clear()
		{
			Materials.Clear();
			Weapons.Clear();
			ShopStock.Clear();
			_slots = 0;
		}

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

		private static FieldInfo Field(Type type, string name, Type fieldType)
		{
			FieldInfo fieldInfo = AccessTools.Field(type, name);
			if (!(fieldInfo != null) || !(fieldInfo.FieldType == fieldType))
			{
				throw new InvalidOperationException("Unexpected run inventory field: " + name + ".");
			}
			return fieldInfo;
		}

		private static MethodInfo Method(Type type, string name, Type returnType, params Type[] parameters)
		{
			MethodInfo methodInfo = AccessTools.Method(type, name, parameters, (Type[])null);
			if (!(methodInfo != null) || !(methodInfo.ReturnType == returnType))
			{
				throw new InvalidOperationException("Unexpected run inventory method: " + name + ".");
			}
			return methodInfo;
		}

		private static void InstallSaveHooks(Harmony harmony)
		{
			try
			{
				Type type = AccessTools.TypeByName("StatsManager");
				_saveName = Field(type, "saveFileCurrent", typeof(string));
				_saveLevel = Method(type, "GetRunStatSaveLevel", typeof(int));
				harmony.Patch((MethodBase)Method(type, "SaveGame", typeof(void), typeof(string)), (HarmonyMethod)null, Hook("SaveInventory"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)Method(type, "LoadGame", typeof(void), typeof(string), typeof(List<string>)), (HarmonyMethod)null, Hook("LoadInventory"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)Method(type, "SaveFileCreate", typeof(void), typeof(string), typeof(bool)), (HarmonyMethod)null, Hook("StartNewSave"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_log.LogInfo((object)"Run upgrade inventory save hooks installed.");
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Run upgrade inventory save hooks unavailable: " + ex.Message));
			}
		}

		private static void StartNewSave()
		{
			if (!_multiplayer())
			{
				Clear();
			}
		}

		private static void SaveInventory(object __instance, string __0)
		{
			if (string.IsNullOrEmpty(__0) || _multiplayer())
			{
				return;
			}
			try
			{
				int num = (int)_saveLevel.Invoke(__instance, null);
				string text = InventoryPath(__0);
				Directory.CreateDirectory(Path.GetDirectoryName(text));
				XElement xElement = new XElement("upgradeInventory", new XAttribute("version", 1), new XAttribute("saveLevel", num), new XAttribute("slotCubes", _slots));
				foreach (KeyValuePair<UpgradeType, int> material in Materials)
				{
					if (material.Value > 0)
					{
						xElement.Add(new XElement("material", new XAttribute("type", material.Key), new XAttribute("count", material.Value)));
					}
				}
				foreach (KeyValuePair<string, WeaponUpgradeState> weapon in Weapons)
				{
					XElement xElement2 = new XElement("weapon", new XAttribute("id", weapon.Key));
					for (int i = 0; i < weapon.Value.SlotCount; i++)
					{
						UpgradeSlot slot = weapon.Value.GetSlot(i);
						xElement2.Add(new XElement("slot", new XAttribute("type", slot.Type), new XAttribute("level", slot.Level)));
					}
					xElement.Add(xElement2);
				}
				string text2 = text + ".tmp";
				xElement.Save(text2);
				if (File.Exists(text))
				{
					File.Replace(text2, text, null);
				}
				else
				{
					File.Move(text2, text);
				}
				_log.LogInfo((object)$"Run upgrade inventory saved at checkpoint {num}: {CountMaterials()} spheres, {_slots} slot cubes, {Weapons.Count} weapons.");
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Run upgrade inventory save failed: " + ex.Message));
			}
		}

		private static void LoadInventory(object __instance, string __0)
		{
			if (string.IsNullOrEmpty(__0) || _multiplayer() || !string.Equals(_saveName.GetValue(__instance) as string, __0, StringComparison.Ordinal))
			{
				return;
			}
			Clear();
			try
			{
				int num = (int)_saveLevel.Invoke(__instance, null);
				string text = InventoryPath(__0);
				if (!File.Exists(text))
				{
					return;
				}
				XElement xElement = XElement.Load(text);
				if ((int?)xElement.Attribute("version") != 1 || (int?)xElement.Attribute("saveLevel") != num)
				{
					_log.LogWarning((object)"Run upgrade inventory does not match this save checkpoint.");
					return;
				}
				int valueOrDefault = ((int?)xElement.Attribute("slotCubes")).GetValueOrDefault();
				Dictionary<UpgradeType, int> dictionary = new Dictionary<UpgradeType, int>();
				Dictionary<string, WeaponUpgradeState> dictionary2 = new Dictionary<string, WeaponUpgradeState>(StringComparer.Ordinal);
				foreach (XElement item in xElement.Elements("material"))
				{
					int valueOrDefault2 = ((int?)item.Attribute("count")).GetValueOrDefault();
					if (valueOrDefault2 > 0 && TryReadType(item, out var type))
					{
						dictionary[type] = valueOrDefault2;
					}
				}
				foreach (XElement item2 in xElement.Elements("weapon"))
				{
					string text2 = (string?)item2.Attribute("id");
					if (string.IsNullOrEmpty(text2))
					{
						continue;
					}
					WeaponUpgradeState weaponUpgradeState = new WeaponUpgradeState();
					foreach (XElement item3 in item2.Elements("slot"))
					{
						int valueOrDefault3 = ((int?)item3.Attribute("level")).GetValueOrDefault();
						if (valueOrDefault3 > 0 && TryReadType(item3, out var type2))
						{
							weaponUpgradeState.AddSlot(type2, valueOrDefault3);
						}
					}
					if (weaponUpgradeState.SlotCount > 0)
					{
						dictionary2[text2] = weaponUpgradeState;
					}
				}
				_slots = Math.Max(0, valueOrDefault);
				foreach (KeyValuePair<UpgradeType, int> item4 in dictionary)
				{
					Materials.Add(item4.Key, item4.Value);
				}
				foreach (KeyValuePair<string, WeaponUpgradeState> item5 in dictionary2)
				{
					Weapons.Add(item5.Key, item5.Value);
				}
				_log.LogInfo((object)$"Run upgrade inventory loaded at checkpoint {num}: {CountMaterials()} spheres, {_slots} slot cubes, {Weapons.Count} weapons.");
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Run upgrade inventory load failed: " + ex.Message));
			}
		}

		private static bool TryReadType(XElement element, out UpgradeType type)
		{
			if (Enum.TryParse<UpgradeType>((string?)element.Attribute("type"), out type))
			{
				return Enum.IsDefined(typeof(UpgradeType), type);
			}
			return false;
		}

		private static long CountMaterials()
		{
			long num = 0L;
			foreach (int value in Materials.Values)
			{
				num += value;
			}
			return num;
		}

		private static string InventoryPath(string saveName)
		{
			using SHA256 sHA = SHA256.Create();
			string text = BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(saveName))).Replace("-", "");
			return Path.Combine(Paths.ConfigPath, "WeaponUpgradeStation", text + ".xml");
		}
	}
	internal sealed class ShopSlotDisplay : MonoBehaviour
	{
	}
	internal sealed class SlotMaterial : MonoBehaviour
	{
		internal bool Banked { get; set; }

		internal bool ForSale { get; set; }

		internal int PriceThousands { get; set; }
	}
	internal static class SlotMaterialShopDisplay
	{
		private static FieldInfo _valueUi;

		private static FieldInfo _local;

		private static FieldInfo _grabbed;

		private static FieldInfo _held;

		private static FieldInfo _aimed;

		private static FieldInfo _discountTarget;

		private static FieldInfo _discountRange;

		private static FieldInfo _discountMinimum;

		private static FieldInfo _center;

		private static MethodInfo _show;

		private static MethodInfo _targetValid;

		private static MethodInfo _discountFeedback;

		private static Func<bool> _inShop;

		private static Func<bool> _multiplayer;

		private static ManualLogSource _log;

		private static bool _ready;

		internal static void Install(Harmony harmony, ManualLogSource log)
		{
			try
			{
				Type type = AccessTools.TypeByName("PhysGrabber");
				Type type2 = AccessTools.TypeByName("PhysGrabObject");
				Type type3 = AccessTools.TypeByName("ShopKeeper");
				Type type4 = AccessTools.TypeByName("WorldSpaceUIValue");
				Type type5 = AccessTools.TypeByName("SemiFunc");
				_valueUi = Field(type4, "instance", type4);
				_local = Field(type, "isLocal", typeof(bool));
				_grabbed = Field(type, "grabbed", typeof(bool));
				_held = Field(type, "grabbedPhysGrabObject", type2);
				_aimed = Field(type, "currentlyLookingAtPhysGrabObject", type2);
				_discountTarget = Field(type3, "itemReactObject", type2);
				_discountRange = Field(type3, "itemLikeDiscountRange", typeof(Vector2));
				_discountMinimum = Field(type3, "itemLikeDiscountMinimumValue", typeof(int));
				_center = Field(type2, "centerPoint", typeof(Vector3));
				_show = Method(type4, "Show", typeof(void), type2, typeof(int), typeof(bool), typeof(Vector3));
				_targetValid = Method(type3, "ItemTargetValid", typeof(bool));
				_discountFeedback = Method(type3, "ItemDiscountLogic", typeof(void), type2, typeof(Vector3), typeof(int));
				_inShop = (Func<bool>)Method(type5, "RunIsShop", typeof(bool)).CreateDelegate(typeof(Func<bool>));
				_multiplayer = (Func<bool>)Method(type5, "IsMultiplayer", typeof(bool)).CreateDelegate(typeof(Func<bool>));
				_log = log;
				harmony.Patch((MethodBase)Method(type, "ShowValue", typeof(void)), (HarmonyMethod)null, Hook("ShowSlotPrice"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)Method(type3, "ItemDiscountTargetValid", typeof(bool), type2), (HarmonyMethod)null, Hook("AllowDiscount"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)Method(type3, "ItemDiscountApply", typeof(void)), Hook("ApplyDiscount"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_ready = true;
				log.LogInfo((object)"Slot material price and shopkeeper hooks installed.");
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("Slot material price and shopkeeper hooks unavailable: " + ex.Message));
			}
		}

		private static void ShowSlotPrice(Component __instance)
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			if (!_ready)
			{
				return;
			}
			object value = _local.GetValue(__instance);
			if (!(value is bool) || !(bool)value || Cursor.visible || !_inShop())
			{
				return;
			}
			value = _grabbed.GetValue(__instance);
			object? value2 = ((value is bool && (bool)value) ? _held : _aimed).GetValue(__instance);
			Component val = (Component)((value2 is Component) ? value2 : null);
			SlotMaterial saleCube = GetSaleCube(val);
			if ((Object)(object)saleCube != (Object)null)
			{
				object? value3 = _valueUi.GetValue(null);
				Component val2 = (Component)((value3 is Component) ? value3 : null);
				if (val2 != null && (Object)(object)val2 != (Object)null)
				{
					_show.Invoke(val2, new object[4]
					{
						val,
						saleCube.PriceThousands,
						true,
						Vector3.zero
					});
				}
			}
		}

		private static void AllowDiscount(Component __0, ref bool __result)
		{
			if (_ready && !__result)
			{
				SlotMaterial saleCube = GetSaleCube(__0);
				if (saleCube != null && saleCube.PriceThousands > 0 && !_multiplayer())
				{
					__result = true;
				}
			}
		}

		private static bool ApplyDiscount(Component __instance)
		{
			//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_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: 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)
			if (_ready)
			{
				object? value = _discountTarget.GetValue(__instance);
				SlotMaterial saleCube = GetSaleCube((Component?)((value is Component) ? value : null));
				if (saleCube != null)
				{
					try
					{
						if (_multiplayer())
						{
							goto IL_0058;
						}
						object obj = _targetValid.Invoke(__instance, null);
						if (!(obj is bool) || !(bool)obj || saleCube.PriceThousands <= 0)
						{
							goto IL_0058;
						}
						Vector2 val = (Vector2)_discountRange.GetValue(__instance);
						float num = Random.Range(Mathf.Clamp01(Mathf.Min(val.x, val.y)), Mathf.Clamp01(Mathf.Max(val.x, val.y)));
						int num2 = Mathf.CeilToInt((float)Mathf.Max(0, (int)_discountMinimum.GetValue(__instance)) / 1000f);
						int num3 = Mathf.Max(Mathf.CeilToInt((float)saleCube.PriceThousands * num), num2);
						int num4 = Mathf.Max(0, saleCube.PriceThousands - num3);
						int num5 = saleCube.PriceThousands - num4;
						if (num5 <= 0)
						{
							return false;
						}
						saleCube.PriceThousands = num4;
						Component componentInParent = ((Component)saleCube).GetComponentInParent(_discountTarget.FieldType);
						_discountFeedback.Invoke(__instance, new object[3]
						{
							componentInParent,
							_center.GetValue(componentInParent),
							num5
						});
						RunUpgradeInventory.RefreshShopCost();
						_log.LogInfo((object)$"Shopkeeper discounted slot material by {num5}K to {num4}K.");
						goto end_IL_0023;
						IL_0058:
						return false;
						end_IL_0023:;
					}
					catch (Exception ex)
					{
						_log.LogWarning((object)("Shopkeeper could not finish the slot material discount: " + ex.Message));
					}
					return false;
				}
			}
			return true;
		}

		private static SlotMaterial? GetSaleCube(Component? target)
		{
			if ((Object)(object)target == (Object)null)
			{
				return null;
			}
			SlotMaterial component = target.GetComponent<SlotMaterial>();
			if (!((Object)(object)component != (Object)null) || !component.ForSale)
			{
				return null;
			}
			return component;
		}

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

		private static FieldInfo Field(Type type, string name, Type fieldType)
		{
			FieldInfo fieldInfo = AccessTools.Field(type, name);
			if (!(fieldInfo != null) || !(fieldInfo.FieldType == fieldType))
			{
				throw new InvalidOperationException("Unexpected shop display field: " + name + ".");
			}
			return fieldInfo;
		}

		private static MethodInfo Method(Type type, string name, Type returnType, params Type[] parameters)
		{
			MethodInfo methodInfo = AccessTools.Method(type, name, parameters, (Type[])null);
			if (!(methodInfo != null) || !(methodInfo.ReturnType == returnType))
			{
				throw new InvalidOperationException("Unexpected shop display method: " + name + ".");
			}
			return methodInfo;
		}
	}
	internal static class TestWeaponOwnership
	{
		private static Func<bool> _grantHandgun;

		private static Func<bool> _grantSword;

		private static Func<bool> _isMission;

		private static Func<bool> _isMultiplayer;

		private static FieldInfo _statsInstance;

		private static FieldInfo _items;

		private static FieldInfo _ownedItems;

		private static FieldInfo _physicalItem;

		private static MethodInfo _grantItem;

		private static ManualLogSource _log;

		internal static void Install(Harmony harmony, ManualLogSource log, Func<bool> grantHandgun, Func<bool> grantSword)
		{
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Expected O, but got Unknown
			try
			{
				Type type = AccessTools.TypeByName("StatsManager");
				Type type2 = AccessTools.TypeByName("Item");
				Type type3 = AccessTools.TypeByName("SemiFunc");
				Type type4 = AccessTools.TypeByName("ItemManager");
				Type type5 = AccessTools.Inner(AccessTools.TypeByName("PunManager"), "ItemSpawn");
				_statsInstance = AccessTools.Field(type, "instance");
				_items = AccessTools.Field(type, "itemDictionary");
				_ownedItems = AccessTools.Field(type, "itemsPurchased");
				_physicalItem = AccessTools.Field(type2, "physicalItem");
				_grantItem = AccessTools.Method(type, "ItemPurchase", new Type[1] { typeof(string) }, (Type[])null);
				MethodInfo methodInfo = AccessTools.Method(type4, "ItemsInitialize", new Type[1] { typeof(List<>).MakeGenericType(type5) }, (Type[])null);
				if (_statsInstance?.FieldType != type || _items == null || _ownedItems?.FieldType != typeof(Dictionary<string, int>) || _physicalItem?.FieldType != typeof(bool) || _grantItem?.ReturnType != typeof(void) || methodInfo?.ReturnType != typeof(void))
				{
					throw new InvalidOperationException("Test weapon ownership signatures differ.");
				}
				_isMission = (Func<bool>)AccessTools.Method(type3, "RunIsLevel", Type.EmptyTypes, (Type[])null).CreateDelegate(typeof(Func<bool>));
				_isMultiplayer = (Func<bool>)AccessTools.Method(type3, "IsMultiplayer", Type.EmptyTypes, (Type[])null).CreateDelegate(typeof(Func<bool>));
				_grantHandgun = grantHandgun;
				_grantSword = grantSword;
				_log = log;
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(TestWeaponOwnership), "BeforeItemSetup", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("Test weapon ownership hook unavailable: " + ex.Message));
			}
		}

		private static void BeforeItemSetup()
		{
			try
			{
				if (!_isMission() || _isMultiplayer() || (!_grantHandgun() && !_grantSword()))
				{
					return;
				}
				object value = _statsInstance.GetValue(null);
				if (value != null && _ownedItems.GetValue(value) is Dictionary<string, int> owned && _items.GetValue(value) is IDictionary catalog)
				{
					if (_grantHandgun())
					{
						GrantIfMissing(value, owned, catalog, "Item Gun Handgun");
					}
					if (_grantSword())
					{
						GrantIfMissing(value, owned, catalog, "Item Melee Sword");
					}
				}
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Test weapon ownership setup failed: " + ex.Message));
			}
		}

		private static void GrantIfMissing(object stats, Dictionary<string, int> owned, IDictionary catalog, string name)
		{
			if (owned.TryGetValue(name, out var value) && value > 0)
			{
				return;
			}
			object? obj = catalog[name];
			Object val = (Object)((obj is Object) ? obj : null);
			if (val != null && !(val == (Object)null))
			{
				object value2 = _physicalItem.GetValue(val);
				if (value2 is bool && (bool)value2)
				{
					_grantItem.Invoke(stats, new object[1] { name });
					_log.LogInfo((object)("Granted one owned test weapon: " + name + "."));
					return;
				}
			}
			_log.LogWarning((object)("Test weapon ownership unavailable: " + name + " is missing from the item catalog."));
		}
	}
	internal sealed class TruckUpgradeStation : MonoBehaviour
	{
		private const string StationName = "Weapon Upgrade Station";

		private static Func<bool>? _runIsLevel;

		private static Func<bool>? _isMultiplayer;

		private static Type? _roomVolume;

		private static FieldInfo? _truckFlag;

		private static FieldInfo? _chargerInstance;

		private static FieldInfo? _chargeBar;

		private static FieldInfo? _chargerCylinder;

		private static ManualLogSource? _log;

		private static Func<bool>? _spawnTestSlot;

		private static Func<bool>? _testBatteryMaterials;

		private static Func<bool>? _testElementMaterials;

		private static Type? _gun;

		private static Type? _melee;

		private static Type? _battery;

		private static Type? _grabbable;

		private static FieldInfo? _grabbedLocal;

		private readonly HashSet<UpgradeMaterialDrop> _materials = new HashSet<UpgradeMaterialDrop>();

		private readonly HashSet<Rigidbody> _weapons = new HashSet<Rigidbody>();

		private readonly HashSet<UpgradeMaterialDrop> _inputMaterials = new HashSet<UpgradeMaterialDrop>();

		private BoxCollider _intake;

		private Rigidbody? _pendingWeapon;

		private UpgradeMaterialDrop? _pendingMaterial;

		private SlotMaterial? _pendingSlot;

		private UpgradeMaterialDrop? _pendingExchange;

		private float _readySince;

		private bool _attempted;

		internal static void Install(Harmony harmony, ManualLogSource log, Func<bool> spawnTestSlot, Func<bool> testBatteryMaterials, Func<bool> testElementMaterials)
		{
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.DeclaredMethod(AccessTools.TypeByName("TruckSafetySpawnPoint"), "Awake", Type.EmptyTypes, (Type[])null);
				Type type = AccessTools.TypeByName("SemiFunc");
				_runIsLevel = (Func<bool>)AccessTools.Method(type, "RunIsLevel", Type.EmptyTypes, (Type[])null).CreateDelegate(typeof(Func<bool>));
				_isMultiplayer = (Func<bool>)AccessTools.Method(type, "IsMultiplayer", Type.EmptyTypes, (Type[])null).CreateDelegate(typeof(Func<bool>));
				_roomVolume = AccessTools.TypeByName("RoomVolume");
				_truckFlag = AccessTools.Field(_roomVolume, "Truck");
				Type type2 = AccessTools.TypeByName("ChargingStation");
				_chargerInstance = AccessTools.Field(type2, "instance");
				_chargeBar = AccessTools.Field(type2, "chargeBar");
				_chargerCylinder = AccessTools.Field(type2, "crystalCylinder");
				if (!(methodInfo == null) && !methodInfo.IsStatic && !(methodInfo.ReturnType != typeof(void)) && !(_roomVolume == null) && typeof(Component).IsAssignableFrom(_roomVolume) && !(_truckFlag?.FieldType != typeof(bool)))
				{
					FieldInfo? chargerInstance = _chargerInstance;
					if ((object)chargerInstance != null && chargerInstance.IsStatic && !(_chargerInstance.FieldType != type2) && !(_chargeBar?.FieldType != typeof(Transform)) && !(_chargerCylinder?.FieldType != typeof(Transform)))
					{
						_log = log;
						_spawnTestSlot = spawnTestSlot;
						_testBatteryMaterials = testBatteryMaterials;
						_testElementMaterials = testElementMaterials;
						_gun = AccessTools.TypeByName("ItemGun");
						_melee = AccessTools.TypeByName("ItemMelee");
						_battery = AccessTools.TypeByName("ItemBattery");
						_grabbable = AccessTools.TypeByName("PhysGrabObject");
						_grabbedLocal = AccessTools.Field(_grabbable, "grabbedLocal");
						harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(TruckUpgradeStation), "AfterTruckAwake", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						return;
					}
				}
				throw new InvalidOperationException("Truck placement signatures differ.");
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("Truck station hook unavailable: " + ex.Message));
			}
		}

		private static void AfterTruckAwake(MonoBehaviour __instance)
		{
			__instance.StartCoroutine(PlaceAfterTruckAwake(((Component)__instance).transform));
		}

		private static IEnumerator PlaceAfterTruckAwake(Transform anchor)
		{
			yield return null;
			if ((Object)(object)anchor == (Object)null)
			{
				yield break;
			}
			try
			{
				if (_runIsLevel?.Invoke() ?? false)
				{
					Func<bool>? isMultiplayer = _isMultiplayer;
					if (isMultiplayer != null && !isMultiplayer())
					{
						Place(anchor);
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log = _log;
				if (log != null)
				{
					log.LogWarning((object)("Truck upgrade station placement failed: " + ex.Message));
				}
			}
		}

		private static void Place(Transform anchor)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			//IL_032d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: 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_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0292: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: 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_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: 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_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: 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_022d: 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_0239: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)anchor.Find("Weapon Upgrade Station") != (Object)null)
			{
				return;
			}
			int mask = LayerMask.GetMask(new string[1] { "RoomVolume" });
			if (!TryGetChargerPlacement(out var position, out var rotation))
			{
				ManualLogSource? log = _log;
				if (log != null)
				{
					log.LogWarning((object)"Truck upgrade station placement skipped: charging station markers unavailable.");
				}
				return;
			}
			RaycastHit val = default(RaycastHit);
			if (!Physics.Raycast(new Vector3(position.x, anchor.position.y + 0.25f, position.z), Vector3.down, ref val, 3f, LayerMask.GetMask(new string[1] { "Default" }), (QueryTriggerInteraction)1))
			{
				ManualLogSource? log2 = _log;
				if (log2 != null)
				{
					log2.LogWarning((object)"Truck upgrade station placement skipped: no floor beside the charger.");
				}
				return;
			}
			position.y = ((RaycastHit)(ref val)).point.y + 0.04f;
			if (!InsideTruck(position, mask))
			{
				ManualLogSource? log3 = _log;
				if (log3 != null)
				{
					log3.LogWarning((object)"Truck upgrade station placement skipped: no truck room at the tray position.");
				}
				return;
			}
			GameObject val2 = new GameObject("Weapon Upgrade Station");
			val2.transform.SetParent(anchor, false);
			val2.transform.SetPositionAndRotation(position, rotation);
			val2.AddComponent<TruckUpgradeStation>().BuildBasin();
			ManualLogSource? log4 = _log;
			if (log4 != null)
			{
				log4.LogInfo((object)"Upgrade station placed in truck, left of the charging station.");
			}
			Vector3 val3 = val2.transform.forward;
			if (Vector3.Dot(anchor.position - position, val3) < 0f)
			{
				val3 = -val3;
			}
			bool flag = _testElementMaterials?.Invoke() ?? false;
			bool flag2 = _testBatteryMaterials?.Invoke() ?? false;
			Func<bool>? spawnTestSlot = _spawnTestSlot;
			if (spawnTestSlot != null && spawnTestSlot())
			{
				Vector3 val4 = position + val3 * 0.6f;
				Vector3 val5 = val2.transform.right * 0.32f;
				Vector3 val6 = Vector3.up * 0.24f;
				if (flag || flag2)
				{
					UpgradeType upgradeType = ((!flag) ? UpgradeType.BatteryCapacity : UpgradeType.Electric);
					UpgradeType upgradeType2 = (flag ? UpgradeType.Fire : UpgradeType.BatteryConsumptionImmunity);
					for (int i = 0; i < 4; i++)
					{
						Vector3 val7 = val4 + val5 * ((float)i - 1.5f) + val6;
						UpgradeMaterialDrop.SpawnMaterial((i < 2) ? upgradeType : upgradeType2, val7);
						UpgradeMaterialDrop.SpawnSlotMaterial(val7 + val3 * 0.3f);
					}
					ManualLogSource? log5 = _log;
					if (log5 != null)
					{
						log5.LogInfo((object)$"Truck upgrade station spawned two {upgradeType}, two {upgradeType2} and four slot materials for testing.");
					}
				}
				else
				{
					UpgradeMaterialDrop.SpawnSlotMaterial(val4 - val5 * 1.5f + val6);
					UpgradeMaterialDrop.SpawnSlotMaterial(val4 - val5 * 0.5f + val6);
					UpgradeMaterialDrop.SpawnMaterial(UpgradeType.Damage, val4 + val5 * 0.5f + val6);
					UpgradeMaterialDrop.SpawnMaterial(UpgradeType.Damage, val4 + val5 * 1.5f + val6);
					ManualLogSource? log6 = _log;
					if (log6 != null)
					{
						log6.LogInfo((object)"Truck upgrade station spawned two red damage materials and two white slot materials for testing.");
					}
				}
			}
			RunUpgradeInventory.PlaceStock(anchor.position, val2.transform.right, val3);
		}

		private static bool TryGetChargerPlacement(out Vector3 position, out Quaternion rotation)
		{
			//IL_0001: 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_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			position = default(Vector3);
			rotation = Quaternion.identity;
			object? obj = _chargerInstance?.GetValue(null);
			Component val = (Component)((obj is Component) ? obj : null);
			if (!((Object)(object)val == (Object)null))
			{
				object? obj2 = _chargeBar?.GetValue(val);
				Transform val2 = (Transform)((obj2 is Transform) ? obj2 : null);
				if (val2 != null && !((Object)(object)val2 == (Object)null))
				{
					object? obj3 = _chargerCylinder?.GetValue(val);
					Transform val3 = (Transform)((obj3 is Transform) ? obj3 : null);
					if (val3 != null && !((Object)(object)val3 == (Object)null))
					{
						Vector3 val4 = Vector3.ProjectOnPlane(val3.position - val2.position, Vector3.up);
						if (((Vector3)(ref val4)).sqrMagnitude < 0.0025f)
						{
							return false;
						}
						((Vector3)(ref val4)).Normalize();
						position = val3.position + val4 * 1.65f;
						rotation = Quaternion.LookRotation(Vector3.Cross(Vector3.up, val4));
						return true;
					}
				}
			}
			return false;
		}

		private void BuildBasin()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: 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_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			Color color = default(Color);
			((Color)(ref color))..ctor(0.08f, 0.33f, 0.48f);
			Color color2 = default(Color);
			((Color)(ref color2))..ctor(0.15f, 0.55f, 0.8f);
			AddBasinPart("Base", Vector3.zero, new Vector3(1.55f, 0.08f, 0.68f), color);
			Vector3 size = default(Vector3);
			((Vector3)(ref size))..ctor(0.07f, 0.22f, 0.68f);
			AddBasinPart("Left Rim", new Vector3(-0.73999995f, 0.15f, 0f), size, color2);
			AddBasinPart("Right Rim", new Vector3(0.73999995f, 0.15f, 0f), size, color2);
			Vector3 size2 = default(Vector3);
			((Vector3)(ref size2))..ctor(1.41f, 0.22f, 0.07f);
			AddBasinPart("Front Rim", new Vector3(0f, 0.15f, 0.305f), size2, color2);
			AddBasinPart("Back Rim", new Vector3(0f, 0.15f, -0.305f), size2, color2);
			_intake = ((Component)this).gameObject.AddComponent<BoxCollider>();
			((Collider)_intake).isTrigger = true;
			_intake.center = new Vector3(0f, 0.15f, 0f);
			_intake.size = new Vector3(1.41f, 0.22f, 0.54f);
		}

		private IEnumerator Start()
		{
			if (_gun == null || _melee == null || _battery == null || _grabbable == null || _grabbedLocal?.FieldType != typeof(bool))
			{
				ManualLogSource? log = _log;
				if (log != null)
				{
					log.LogWarning((object)"Truck upgrade slot creation unavailable: weapon signatures differ.");
				}
				yield break;
			}
			WaitForSeconds interval = new WaitForSeconds(0.2f);
			while (true)
			{
				yield return interval;
				CheckSlotInputs();
			}
		}

		private void CheckSlotInputs()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			_weapons.Clear();
			_inputMaterials.Clear();
			UpgradeMaterialDrop upgradeMaterialDrop = null;
			UpgradeMaterialDrop upgradeMaterialDrop2 = null;
			SlotMaterial slotMaterial = null;
			int num = 0;
			int num2 = 0;
			Vector3 val = Vector3.Scale(_intake.size * 0.5f, ((Component)this).transform.lossyScale);
			Collider[] array = Physics.OverlapBox(((Component)this).transform.TransformPoint(_intake.center), val, ((Component)this).transform.rotation, LayerMask.GetMask(new string[1] { "PhysGrabObject" }), (QueryTriggerInteraction)1);
			UpgradeMaterialDrop upgradeMaterialDrop3 = default(UpgradeMaterialDrop);
			SlotMaterial slotMaterial2 = default(SlotMaterial);
			for (int i = 0; i < array.Length; i++)
			{
				Rigidbody attachedRigidbody = array[i].attachedRigidbody;
				if ((Object)(object)attachedRigidbody == (Object)null)
				{
					continue;
				}
				if (((Component)attachedRigidbody).TryGetComponent<UpgradeMaterialDrop>(ref upgradeMaterialDrop3))
				{
					if (_inputMaterials.Add(upgradeMaterialDrop3))
					{
						switch (num)
						{
						case 0:
							upgradeMaterialDrop = upgradeMaterialDrop3;
							break;
						case 1:
							upgradeMaterialDrop2 = upgradeMaterialDrop3;
							break;
						}
						num++;
					}
				}
				else if (((Component)attachedRigidbody).TryGetComponent<SlotMaterial>(ref slotMaterial2) && !slotMaterial2.ForSale)
				{
					slotMaterial = slotMaterial2;
					num2++;
				}
				else if ((Object)(object)((Component)attachedRigidbody).GetComponentInChildren(_gun) != (Object)null || (Object)(object)((Component)attachedRigidbody).GetComponentInChildren(_melee) != (Object)null)
				{
					_weapons.Add(attachedRigidbody);
				}
			}
			if (_weapons.Count == 0 && num2 == 0 && num == 2 && (Object)(object)upgradeMaterialDrop != (Object)null && (Object)(object)upgradeMaterialDrop2 != (Object)null && upgradeMaterialDrop.Type == upgradeMaterialDrop2.Type)
			{
				_pendingWeapon = null;
				CheckExchange(upgradeMaterialDrop, upgradeMaterialDrop2);
				return;
			}
			_pendingExchange = null;
			if (_weapons.Count != 1 || num != 1 || num2 != 1 || (Object)(object)upgradeMaterialDrop == (Object)null || (Object)(object)slotMaterial == (Object)null)
			{
				_pendingWeapon = null;
				return;
			}
			using HashSet<Rigidbody>.Enumerator enumerator = _weapons.GetEnumerator();
			enumerator.MoveNext();
			Rigidbody current = enumerator.Current;
			if ((Object)(object)_pendingWeapon != (Object)(object)current || (Object)(object)_pendingMaterial != (Object)(object)upgradeMaterialDrop || (Object)(object)_pendingSlot != (Object)(object)slotMaterial)
			{
				_pendingWeapon = current;
				_pendingMaterial = upgradeMaterialDrop;
				_pendingSlot = slotMaterial;
				_readySince = Time.time;
				_attempted = false;
			}
			if (!IsSettled(current) || !IsSettled(((Component)upgradeMaterialDrop).GetComponent<Rigidbody>()) || !IsSettled(((Component)slotMaterial).GetComponent<Rigidbody>()))
			{
				_readySince = Time.time;
			}
			else
			{
				if (_attempted || Time.time - _readySince < 0.75f)
				{
					return;
				}
				_attempted = true;
				WeaponSlots weaponSlots = ((Component)current).GetComponent<WeaponSlots>() ?? ((Component)current).gameObject.AddComponent<WeaponSlots>();
				bool compatible = (upgradeMaterialDrop.Type != UpgradeType.BatteryCapacity && upgradeMaterialDrop.Type != UpgradeType.BatteryConsumptionImmunity) || (Object)(object)((Component)current).GetComponentInChildren(_battery) != (Object)null;
				int? num3 = FindMatchingSlot(weaponSlots.State, upgradeMaterialDrop.Type);
				UpgradeResult upgradeResult = Plugin.Engine.TryApply(weaponSlots.State, upgradeMaterialDrop.Type, compatible, hasUpgradeMaterial: true, hasSlotMaterial: true, num3);
				if (upgradeResult != UpgradeResult.Success)
				{
					ManualLogSource? log = _log;
					if (log != null)
					{
						log.LogInfo((object)$"Truck upgrade station rejected upgrade: {upgradeResult}.");
					}
					return;
				}
				_materials.Remove(upgradeMaterialDrop);
				RunUpgradeInventory.Consume(upgradeMaterialDrop, slotMaterial);
				((Component)upgradeMaterialDrop).gameObject.SetActive(false);
				((Component)slotMaterial).gameObject.SetActive(false);
				Object.Destroy((Object)(object)((Component)upgradeMaterialDrop).gameObject);
				Object.Destroy((Object)(object)((Component)slotMaterial).gameObject);
				if (upgradeMaterialDrop.Type == UpgradeType.BatteryCapacity)
				{
					WeaponBatteryPatch.ApplyCapacity(current, weaponSlots.State);
				}
				RunUpgradeInventory.RememberWeapon(current, weaponSlots);
				int index = num3 ?? (weaponSlots.State.SlotCount - 1);
				UpgradeSlot slot = weaponSlots.State.GetSlot(index);
				string text = (num3.HasValue ? "leveled slot" : "created slot");
				ManualLogSource? log2 = _log;
				if (log2 != null)
				{
					log2.LogInfo((object)$"Truck upgrade station {text}: {slot.Type} Lv{slot.Level} on {((Object)current).name}. Total slots: {weaponSlots.State.SlotCount}.");
				}
			}
		}

		private void CheckExchange(UpgradeMaterialDrop first, UpgradeMaterialDrop second)
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			if (((Object)first).GetInstanceID() > ((Object)second).GetInstanceID())
			{
				UpgradeMaterialDrop upgradeMaterialDrop = second;
				second = first;
				first = upgradeMaterialDrop;
			}
			if ((Object)(object)_pendingMaterial != (Object)(object)first || (Object)(object)_pendingExchange != (Object)(object)second)
			{
				_pendingMaterial = first;
				_pendingExchange = second;
				_readySince = Time.time;
				_attempted = false;
			}
			if (!IsSettled(((Component)first).GetComponent<Rigidbody>()) || !IsSettled(((Component)second).GetComponent<Rigidbody>()))
			{
				_readySince = Time.time;
			}
			else
			{
				if (_attempted || Time.time - _readySince < 0.75f)
				{
					return;
				}
				_attempted = true;
				try
				{
					SlotMaterial result = UpgradeMaterialDrop.SpawnSlotMaterial(((Component)this).transform.position + Vector3.up * 0.38f);
					RunUpgradeInventory.RecordExchange(first, second, result);
					_materials.Remove(first);
					_materials.Remove(second);
					((Component)first).gameObject.SetActive(false);
					((Component)second).gameObject.SetActive(false);
					Object.Destroy((Object)(object)((Component)first).gameObject);
					Object.Destroy((Object)(object)((Component)second).gameObject);
					ManualLogSource? log = _log;
					if (log != null)
					{
						log.LogInfo((object)$"Truck upgrade station exchanged two {first.Type} materials for one slot cube.");
					}
				}
				catch (Exception ex)
				{
					ManualLogSource? log2 = _log;
					if (log2 != null)
					{
						log2.LogWarning((object)("Truck upgrade station could not exchange materials: " + ex.Message));
					}
				}
			}
		}

		private static int? FindMatchingSlot(WeaponUpgradeState state, UpgradeType type)
		{
			int? result = null;
			int num = int.MaxValue;
			for (int i = 0; i < state.SlotCount; i++)
			{
				UpgradeSlot slot = state.GetSlot(i);
				if (slot.Type == type && (!result.HasValue || slot.Level < num))
				{
					result = i;
					num = slot.Level;
				}
			}
			return result;
		}

		private static bool IsSettled(Rigidbody body)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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_0053: Unknown result type (might be due to invalid IL or missing references)
			Component component = ((Component)body).GetComponent(_grabbable);
			if ((Object)(object)component != (Object)null)
			{
				object obj = _grabbedLocal?.GetValue(component);
				if (obj is bool && !(bool)obj)
				{
					Vector3 val = body.linearVelocity;
					if (((Vector3)(ref val)).sqrMagnitude < 0.01f)
					{
						val = body.angularVelocity;
						return ((Vector3)(ref val)).sqrMagnitude < 0.04f;
					}
				}
			}
			return false;
		}

		private void AddBasinPart(string name, Vector3 position, Vector3 size, Color color)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GameObject.CreatePrimitive((PrimitiveType)3);
			((Object)obj).name = name;
			obj.transform.SetParent(((Component)this).transform, false);
			obj.transform.localPosition = position;
			obj.transform.localScale = size;
			MaterialPropertyBlock val = new MaterialPropertyBlock();
			val.SetColor("_Color", color);
			val.SetColor("_BaseColor", color);
			((Renderer)obj.GetComponent<MeshRenderer>()).SetPropertyBlock(val);
		}

		private static bool InsideTruck(Vector3 position, int roomMask)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(position, 0.03f, roomMask, (QueryTriggerInteraction)2);
			for (int i = 0; i < array.Length; i++)
			{
				Component componentInParent = ((Component)array[i]).GetComponentInParent(_roomVolume);
				if ((Object)(object)componentInParent != (Object)null)
				{
					object obj = _truckFlag?.GetValue(componentInParent);
					if (obj is bool && (bool)obj)
					{
						return true;
					}
				}
			}
			return false;
		}

		private void OnTriggerEnter(Collider other)
		{
			UpgradeMaterialDrop componentInParent = ((Component)other).GetComponentInParent<UpgradeMaterialDrop>();
			_materials.RemoveWhere((UpgradeMaterialDrop entry) => (Object)(object)entry == (Object)null);
			if ((Object)(object)componentInParent != (Object)null && _materials.Add(componentInParent))
			{
				ManualLogSource? log = _log;
				if (log != null)
				{
					log.LogInfo((object)$"Truck upgrade station detected material: {componentInParent.Type}. Materials inside: {_materials.Count}.");
				}
			}
		}

		private void OnTriggerExit(Collider other)
		{
			UpgradeMaterialDrop componentInParent = ((Component)other).GetComponentInParent<UpgradeMaterialDrop>();
			if ((Object)(object)componentInParent != (Object)null && _materials.Remove(componentInParent))
			{
				ManualLogSource? log = _log;
				if (log != null)
				{
					log.LogInfo((object)$"Truck upgrade station removed material: {componentInParent.Type}. Materials inside: {_materials.Count}.");
				}
			}
		}
	}
	internal sealed class UpgradeMaterialDrop : MonoBehaviour
	{
		internal UpgradeType Type { get; private set; }

		internal bool Banked { get; set; }

		internal static void Spawn(UpgradeType type, Vector3 position)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			SpawnMaterial(type, position + Vector3.up * 0.5f);
		}

		internal static SlotMaterial SpawnSlotMaterial(Vector3 position)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			return SpawnMaterial(null, position).GetComponent<SlotMaterial>();
		}

		internal static GameObje