Decompiled source of FarmFromStorage v1.0.0

plugins/FarmFromStorage.dll

Decompiled 21 hours ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using Microsoft.CodeAnalysis;
using ValheimMods.Common;
using ValheimMods.Common.Placement;

[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("Hoose")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) Hoose 2026")]
[assembly: AssemblyDescription("Plant with the Cultivator using accessible nearby storage.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+46b109dc144ce0b6d6bd6222062562ff9654cfc1")]
[assembly: AssemblyProduct("Valheim FarmFromStorage")]
[assembly: AssemblyTitle("FarmFromStorage")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FarmFromStorage
{
	[BepInPlugin("hoose.valheim.farmfromstorage", "FarmFromStorage", "1.0.0")]
	[BepInProcess("valheim.exe")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class FarmFromStoragePlugin : BaseUnityPlugin
	{
		public const string PluginName = "FarmFromStorage";

		public const string PluginAuthor = "Hoose";

		public const string PluginGuid = "hoose.valheim.farmfromstorage";

		public const string PluginVersion = "1.0.0";

		private const string StorageRadiusDescription = "How far, in meters, FarmFromStorage searches for storage around you (a sphere centred on your character). Allowed range: 1 to 100. Only closed storage currently owned by your client is used.";

		private ConfigEntry<float> _storageRadius;

		private PlacementStorage _placementStorage;

		private float StorageRadius => StorageRange.Clamp(_storageRadius?.Value ?? 20f);

		private void Awake()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			_storageRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Storage", "Storage radius", 20f, new ConfigDescription("How far, in meters, FarmFromStorage searches for storage around you (a sphere centred on your character). Allowed range: 1 to 100. Only closed storage currently owned by your client is used.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 100f), Array.Empty<object>()));
			_placementStorage = PlacementStorage.Register("Cultivator", (Func<float>)(() => StorageRadius), (Action<string>)((BaseUnityPlugin)this).Logger.LogWarning, (Action<string>)((BaseUnityPlugin)this).Logger.LogError);
			((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("{0} {1} loaded; Cultivator planting uses nearby owned storage ({2:0.#}m radius).", "FarmFromStorage", "1.0.0", StorageRadius));
		}

		private void OnDestroy()
		{
			PlacementStorage placementStorage = _placementStorage;
			if (placementStorage != null)
			{
				placementStorage.Dispose();
			}
		}
	}
}

plugins/ValheimMods.Common.dll

Decompiled 21 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: AssemblyCompany("Hoose")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) Hoose 2026")]
[assembly: AssemblyDescription("Shared runtime helpers for Hoose's Valheim mods.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+46b109dc144ce0b6d6bd6222062562ff9654cfc1")]
[assembly: AssemblyProduct("ValheimMods.Common")]
[assembly: AssemblyTitle("ValheimMods.Common")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ValheimMods.Common
{
	public sealed class ContainerRegistry
	{
		private readonly HashSet<Container> _containers = new HashSet<Container>();

		public IEnumerable<Container> Containers => _containers;

		public void Initialize()
		{
			Clear();
			Container[] array = Object.FindObjectsByType<Container>((FindObjectsSortMode)0);
			foreach (Container container in array)
			{
				Add(container);
			}
		}

		public void Add(Container container)
		{
			if ((Object)(object)container != (Object)null)
			{
				_containers.Add(container);
			}
		}

		public void Remove(Container container)
		{
			_containers.Remove(container);
		}

		public void Clear()
		{
			_containers.Clear();
		}

		public void PruneDestroyed(Action<Container> onDestroyed = null)
		{
			_containers.RemoveWhere(delegate(Container container)
			{
				if ((Object)(object)container != (Object)null)
				{
					return false;
				}
				onDestroyed?.Invoke(container);
				return true;
			});
		}

		public static bool IsAccessible(Container container, Player player, float radius, bool allowReserved = false)
		{
			//IL_0055: 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)
			//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_00d9: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)container != (Object)null && ((Behaviour)container).isActiveAndEnabled && (Object)(object)player != (Object)null && (Object)(object)container.m_nview != (Object)null && container.m_nview.IsValid() && container.GetInventory() != null)
			{
				Vector3 val = ((Component)container).transform.position - ((Component)player).transform.position;
				if (((Vector3)(ref val)).sqrMagnitude <= radius * radius && (allowReserved || !container.IsInUse()) && (container.IsOwner() || container.m_nview.GetZDO().GetInt(ZDOVars.s_inUse, 0) == 0) && ((Object)(object)container.m_wagon == (Object)null || !container.m_wagon.InUse()) && container.CheckAccess(player.GetPlayerID()))
				{
					if (container.m_checkGuardStone)
					{
						return PrivateArea.CheckAccess(((Component)container).transform.position, 0f, false, false);
					}
					return true;
				}
			}
			return false;
		}
	}
	internal static class RequirementAmountText
	{
		private sealed class NameLayout
		{
			private readonly TextWrappingModes _wrapping;

			private readonly bool _autoSizing;

			private readonly float _fontSize;

			private readonly float _fontSizeMin;

			private readonly float _fontSizeMax;

			public NameLayout(TMP_Text name)
			{
				//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)
				_wrapping = name.textWrappingMode;
				_autoSizing = name.enableAutoSizing;
				_fontSize = name.fontSize;
				_fontSizeMin = name.fontSizeMin;
				_fontSizeMax = name.fontSizeMax;
			}

			public void Restore(TMP_Text name)
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				name.enableAutoSizing = _autoSizing;
				name.fontSizeMin = _fontSizeMin;
				name.fontSizeMax = _fontSizeMax;
				name.textWrappingMode = _wrapping;
				if (!_autoSizing)
				{
					name.fontSize = _fontSize;
				}
			}
		}

		internal const string CountsLabelName = "hoose_res_counts";

		internal const string RaisedCountsLabelName = "hoose_res_counts_raised";

		internal const float MinNameScale = 0.5f;

		internal static readonly Color CountsColor = new Color(1f, 0.843f, 0f, 1f);

		private static readonly Dictionary<TMP_Text, NameLayout> _fittedNames = new Dictionary<TMP_Text, NameLayout>();

		internal static string FormatCounts(int carried, int stored)
		{
			if (carried <= 0 && stored <= 0)
			{
				return string.Empty;
			}
			string obj = ((carried > 0) ? carried.ToString() : string.Empty);
			string text = ((stored > 0) ? stored.ToString() : string.Empty);
			return obj + ":" + text;
		}

		internal static void Clear(Transform elementRoot)
		{
			Transform val = FindLabelRoot(elementRoot);
			TMP_Text val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponent<TMP_Text>());
			if ((Object)(object)val2 != (Object)null)
			{
				val2.text = string.Empty;
				PlaceAmount(elementRoot, val, raised: false);
			}
			RestoreName(elementRoot);
			Transform val3 = (((Object)(object)elementRoot == (Object)null) ? null : elementRoot.Find("hoose_res_counts"));
			TMP_Text val4 = (((Object)(object)val3 == (Object)null) ? null : ((Component)val3).GetComponent<TMP_Text>());
			if ((Object)(object)val4 != (Object)null)
			{
				val4.text = string.Empty;
			}
		}

		internal static void ClearAll(GameObject[] elements)
		{
			if (elements == null)
			{
				return;
			}
			foreach (GameObject val in elements)
			{
				if ((Object)(object)val != (Object)null)
				{
					Clear(val.transform);
				}
			}
		}

		internal static void Apply(Transform elementRoot, int carried, int stored, bool raiseAmount = false, bool fitName = false)
		{
			string text = FormatCounts(carried, stored);
			string text2 = (raiseAmount ? "hoose_res_counts_raised" : "hoose_res_counts");
			Transform val = (((Object)(object)elementRoot == (Object)null) ? null : elementRoot.Find(text2));
			if ((Object)(object)val == (Object)null)
			{
				if (text.Length == 0)
				{
					return;
				}
				val = CreateLabel(elementRoot, text2, !raiseAmount);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
			}
			TMP_Text component = ((Component)val).GetComponent<TMP_Text>();
			if (!((Object)(object)component == (Object)null))
			{
				component.text = text;
				if (raiseAmount)
				{
					PlaceAmount(elementRoot, val, text.Length > 0);
				}
				if (fitName && text.Length > 0)
				{
					FitName(elementRoot);
				}
			}
		}

		internal static TMP_Text FindLabel(Transform elementRoot)
		{
			Transform val = (((Object)(object)elementRoot == (Object)null) ? null : elementRoot.Find("hoose_res_counts"));
			if ((Object)(object)val == (Object)null)
			{
				val = FindLabelRoot(elementRoot);
			}
			if (!((Object)(object)val == (Object)null))
			{
				return ((Component)val).GetComponent<TMP_Text>();
			}
			return null;
		}

		private static Transform FindLabelRoot(Transform elementRoot)
		{
			if (!((Object)(object)elementRoot == (Object)null))
			{
				return elementRoot.Find("hoose_res_counts_raised");
			}
			return null;
		}

		private static Transform CreateLabel(Transform elementRoot, string labelName, bool placeBelow)
		{
			//IL_0083: 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_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			Transform val = (((Object)(object)elementRoot == (Object)null) ? null : elementRoot.Find("res_amount"));
			TMP_Text val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponent<TMP_Text>());
			if ((Object)(object)val2 == (Object)null)
			{
				return null;
			}
			GameObject val3 = Object.Instantiate<GameObject>(((Component)val).gameObject, elementRoot);
			((Object)val3).name = labelName;
			TMP_Text component = ((Component)val3.transform).GetComponent<TMP_Text>();
			if ((Object)(object)component == (Object)null)
			{
				return null;
			}
			component.enableAutoSizing = false;
			component.fontSize = val2.fontSize;
			component.overflowMode = (TextOverflowModes)0;
			component.textWrappingMode = (TextWrappingModes)0;
			((Graphic)component).color = CountsColor;
			if (placeBelow)
			{
				Transform transform = val3.transform;
				RectTransform val4 = (RectTransform)(object)((transform is RectTransform) ? transform : null);
				if (val4 != null)
				{
					Vector2 anchoredPosition = val4.anchoredPosition;
					Rect rect = val4.rect;
					val4.anchoredPosition = anchoredPosition - new Vector2(0f, ((Rect)(ref rect)).height);
				}
			}
			return val3.transform;
		}

		private static void FitName(Transform elementRoot)
		{
			Transform val = elementRoot.Find("res_name");
			TMP_Text val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponent<TMP_Text>());
			if (!((Object)(object)val2 == (Object)null) && !_fittedNames.ContainsKey(val2))
			{
				_fittedNames[val2] = new NameLayout(val2);
				if (!val2.enableAutoSizing)
				{
					val2.fontSizeMax = val2.fontSize;
					val2.fontSizeMin = val2.fontSize * 0.5f;
					val2.enableAutoSizing = true;
				}
				val2.textWrappingMode = (TextWrappingModes)0;
			}
		}

		private static void RestoreName(Transform elementRoot)
		{
			Transform val = (((Object)(object)elementRoot == (Object)null) ? null : elementRoot.Find("res_name"));
			TMP_Text val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponent<TMP_Text>());
			if ((Object)(object)val2 != (Object)null && _fittedNames.TryGetValue(val2, out var value))
			{
				_fittedNames.Remove(val2);
				value.Restore(val2);
			}
		}

		private static void PlaceAmount(Transform elementRoot, Transform labelRoot, bool raised)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			Transform obj = elementRoot.Find("res_amount");
			RectTransform val = (RectTransform)(object)((obj is RectTransform) ? obj : null);
			if (val == null)
			{
				return;
			}
			RectTransform val2 = (RectTransform)(object)((labelRoot is RectTransform) ? labelRoot : null);
			if (val2 != null)
			{
				Vector2 anchoredPosition;
				if (!raised)
				{
					anchoredPosition = val2.anchoredPosition;
				}
				else
				{
					Vector2 anchoredPosition2 = val2.anchoredPosition;
					Rect rect = val.rect;
					anchoredPosition = anchoredPosition2 + new Vector2(0f, ((Rect)(ref rect)).height);
				}
				val.anchoredPosition = anchoredPosition;
			}
		}
	}
	public static class StorageRange
	{
		public const float DefaultRadius = 20f;

		public const float MinimumRadius = 1f;

		public const float MaximumRadius = 100f;

		public const float StationReach = 20f;

		public static float Clamp(float radius)
		{
			if (!float.IsNaN(radius))
			{
				return Math.Min(100f, Math.Max(1f, radius));
			}
			return 20f;
		}
	}
}
namespace ValheimMods.Common.Placement
{
	[HarmonyPatch(typeof(Container), "Awake")]
	internal static class ContainerCreatedPatch
	{
		[HarmonyPostfix]
		private static void AfterAwake(Container __instance)
		{
			PlacementStorage.Registry.Add(__instance);
		}
	}
	[HarmonyPatch(typeof(Container), "OnDestroyed")]
	internal static class ContainerDestroyedPatch
	{
		[HarmonyPrefix]
		private static void BeforeDestroy(Container __instance)
		{
			PlacementStorage.Registry.Remove(__instance);
		}
	}
	[HarmonyPatch(typeof(Player), "UpdatePlacement", new Type[]
	{
		typeof(bool),
		typeof(float)
	})]
	internal static class PlacementContextPatch
	{
		[HarmonyPrefix]
		private static void BeforePlacement(Player __instance, out PlacementStorageContext.ScopeToken __state)
		{
			__state = PlacementStorageContext.BeginPlacement(__instance);
		}

		[HarmonyFinalizer]
		private static Exception AfterPlacement(Exception __exception, PlacementStorageContext.ScopeToken __state)
		{
			PlacementStorageContext.End(__state);
			return __exception;
		}
	}
	[HarmonyPatch(typeof(Player), "ConsumeResources", new Type[]
	{
		typeof(Requirement[]),
		typeof(int),
		typeof(int),
		typeof(int)
	})]
	internal static class PlacementCostConsumePatch
	{
		[HarmonyPostfix]
		private static void AfterConsumeResources(Player __instance)
		{
			PlacementStorageContext.Scope current = PlacementStorageContext.Current;
			if (current != null && (Object)(object)current.Player == (Object)(object)__instance)
			{
				current.ConsumeStorage();
			}
		}
	}
	[HarmonyPatch(typeof(Inventory), "CountItems", new Type[]
	{
		typeof(string),
		typeof(int),
		typeof(bool)
	})]
	internal static class PlacementCostCountPatch
	{
		[HarmonyPostfix]
		private static void IncludeStorage(Inventory __instance, string name, int quality, bool matchWorldLevel, ref int __result)
		{
			PlacementStorageContext.Scope current = PlacementStorageContext.Current;
			if (current == null || current.RequirementCheckDepth == 0 || current.SuppressCountAugmentation || __instance != ((Humanoid)current.Player).GetInventory())
			{
				return;
			}
			checked
			{
				foreach (Container container in current.Containers)
				{
					if (current.IsAccessible(container))
					{
						Inventory inventory = container.GetInventory();
						if (inventory != null)
						{
							__result += inventory.CountItems(name, quality, matchWorldLevel);
						}
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(Player), "TryPlacePiece", new Type[] { typeof(Piece) })]
	internal static class PlacementCostPlanPatch
	{
		[HarmonyPrefix]
		private static bool BeforePlacePiece(Player __instance, Piece piece, ref bool __result)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			PlacementStorageContext.Scope current = PlacementStorageContext.Current;
			if (current == null || (Object)(object)current.Player != (Object)(object)__instance || (Object)(object)piece == (Object)null || __instance.PlacementCostDisabled || ((Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetGlobalKey(piece.FreeBuildKey())))
			{
				return true;
			}
			PlacementResourcePlan placementResourcePlan = PlacementResourcePlan.Create(current, piece.m_resources, 0, -1, 1);
			if (placementResourcePlan == null)
			{
				current.Client.LogWarning("Placement resources changed before placement; the piece was not placed.");
				__result = false;
				return false;
			}
			if (!placementResourcePlan.UsesStorage)
			{
				return true;
			}
			if (!current.TryReserve(placementResourcePlan))
			{
				current.Client.LogWarning("Nearby storage became unavailable before placement; the piece was not placed.");
				__result = false;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Hud), "UpdateBuild")]
	internal static class PlacementMenuPatch
	{
		private static Hud _lastHud;

		private static PlacementStorage _lastClient;

		[HarmonyPrefix]
		private static void BeforeUpdateBuild(Hud __instance, Player player, ref bool forceUpdateAllBuildStatuses)
		{
			if ((Object)(object)__instance.m_buildUi == (Object)null || !((Component)__instance.m_buildUi).gameObject.activeSelf || !PlacementStorage.TryGetClient(player, out var client) || !client.IsCultivator)
			{
				_lastHud = null;
				_lastClient = null;
			}
			else if ((Object)(object)_lastHud != (Object)(object)__instance || _lastClient != client)
			{
				forceUpdateAllBuildStatuses = true;
				_lastHud = __instance;
				_lastClient = client;
			}
		}
	}
	[HarmonyPatch(typeof(Hud), "SetupPieceInfo")]
	internal static class PlacementPieceInfoPatch
	{
		internal static PlacementStorageContext.Scope DisplayScope { get; private set; }

		[HarmonyPrefix]
		private static void BeforePieceInfo(Hud __instance, out PlacementPieceInfoState __state)
		{
			RequirementAmountText.ClearAll(__instance.m_requirementItems);
			PlacementStorageContext.ScopeToken scopeToken = PlacementStorageContext.BeginRequirements(Player.m_localPlayer);
			__state = new PlacementPieceInfoState(scopeToken, DisplayScope);
			DisplayScope = scopeToken?.Scope;
		}

		[HarmonyFinalizer]
		private static Exception AfterPieceInfo(Exception __exception, PlacementPieceInfoState __state)
		{
			if (__state != null)
			{
				DisplayScope = __state.PreviousDisplayScope;
				PlacementStorageContext.End(__state.Token);
			}
			return __exception;
		}
	}
	internal sealed class PlacementPieceInfoState
	{
		internal PlacementStorageContext.ScopeToken Token { get; }

		internal PlacementStorageContext.Scope PreviousDisplayScope { get; }

		internal PlacementPieceInfoState(PlacementStorageContext.ScopeToken token, PlacementStorageContext.Scope previousDisplayScope)
		{
			Token = token;
			PreviousDisplayScope = previousDisplayScope;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
	internal static class PlacementRequirementDisplayPatch
	{
		[HarmonyPrefix]
		private static void ClearStorageAmount(Transform elementRoot)
		{
			RequirementAmountText.Clear(elementRoot);
		}

		[HarmonyPostfix]
		private static void ShowStorageAmount(Transform elementRoot, Requirement req, Player player, bool __result)
		{
			PlacementStorageContext.Scope displayScope = PlacementPieceInfoPatch.DisplayScope;
			if (!__result || displayScope == null || displayScope != PlacementStorageContext.Current || (Object)(object)displayScope.Player != (Object)(object)player || req == null || (Object)(object)req.m_resItem == (Object)null)
			{
				return;
			}
			string name = req.m_resItem.m_itemData.m_shared.m_name;
			int num = 0;
			bool suppressCountAugmentation = displayScope.SuppressCountAugmentation;
			displayScope.SuppressCountAugmentation = true;
			int carried;
			try
			{
				carried = ((Humanoid)player).GetInventory().CountItems(name, -1, true);
				foreach (Container container in displayScope.Containers)
				{
					Inventory inventory = container.GetInventory();
					if (inventory != null && displayScope.IsAccessible(container))
					{
						num = checked(num + inventory.CountItems(name, -1, true));
					}
				}
			}
			finally
			{
				displayScope.SuppressCountAugmentation = suppressCountAugmentation;
			}
			RequirementAmountText.Apply(elementRoot, carried, num, raiseAmount: true, fitName: true);
		}
	}
	[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
	{
		typeof(Piece),
		typeof(RequirementMode)
	})]
	internal static class PlacementRequirementPatch
	{
		[HarmonyPrefix]
		private static void BeforeRequirementCheck(Player __instance, RequirementMode mode, out PlacementStorageContext.ScopeToken __state)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			__state = (((int)mode == 0) ? PlacementStorageContext.BeginRequirements(__instance) : null);
		}

		[HarmonyFinalizer]
		private static Exception AfterRequirementCheck(Exception __exception, PlacementStorageContext.ScopeToken __state)
		{
			PlacementStorageContext.End(__state);
			return __exception;
		}
	}
	internal sealed class PlacementResourcePlan
	{
		private sealed class Source
		{
			internal Inventory Inventory { get; }

			internal Container Container { get; }

			internal Source(Inventory inventory, Container container)
			{
				Inventory = inventory;
				Container = container;
			}
		}

		private sealed class StoragePortion
		{
			internal Container Container { get; }

			internal Inventory Inventory { get; }

			internal string Name { get; }

			internal int Amount { get; set; }

			internal int ItemQuality { get; }

			internal StoragePortion(Container container, Inventory inventory, string name, int amount, int itemQuality)
			{
				Container = container;
				Inventory = inventory;
				Name = name;
				Amount = amount;
				ItemQuality = itemQuality;
			}
		}

		private readonly List<StoragePortion> _storagePortions = new List<StoragePortion>();

		private bool _consumed;

		internal bool UsesStorage => _storagePortions.Count > 0;

		internal IEnumerable<Container> StorageContainers
		{
			get
			{
				HashSet<Container> seen = new HashSet<Container>();
				foreach (StoragePortion storagePortion in _storagePortions)
				{
					if (seen.Add(storagePortion.Container))
					{
						yield return storagePortion.Container;
					}
				}
			}
		}

		internal static PlacementResourcePlan Create(PlacementStorageContext.Scope context, Requirement[] requirements, int qualityLevel, int itemQuality, int multiplier)
		{
			if (requirements == null)
			{
				return null;
			}
			PlacementResourcePlan placementResourcePlan = new PlacementResourcePlan();
			Dictionary<Inventory, Dictionary<string, int>> dictionary = new Dictionary<Inventory, Dictionary<string, int>>();
			Inventory inventory = ((Humanoid)context.Player).GetInventory();
			CraftingStation currentCraftingStation = context.Player.GetCurrentCraftingStation();
			List<Source> list = new List<Source>();
			if (inventory != null)
			{
				list.Add(new Source(inventory, null));
			}
			foreach (Container container in context.Containers)
			{
				if (context.IsAccessible(container))
				{
					list.Add(new Source(container.GetInventory(), container));
				}
			}
			bool suppressCountAugmentation = context.SuppressCountAugmentation;
			context.SuppressCountAugmentation = true;
			try
			{
				foreach (Requirement val in requirements)
				{
					if (val == null || (Object)(object)val.m_resItem == (Object)null || ((Object)(object)currentCraftingStation != (Object)null && currentCraftingStation.m_upgrader != val.m_upgraderResource) || ((Object)(object)currentCraftingStation == (Object)null && val.m_upgraderResource))
					{
						continue;
					}
					int num = val.GetAmount(qualityLevel) * multiplier;
					if (num <= 0)
					{
						continue;
					}
					string name = val.m_resItem.m_itemData.m_shared.m_name;
					int num2 = num;
					foreach (Source item in list)
					{
						if (item.Inventory == null)
						{
							continue;
						}
						if (!dictionary.TryGetValue(item.Inventory, out var value))
						{
							value = new Dictionary<string, int>();
							dictionary.Add(item.Inventory, value);
						}
						value.TryGetValue(name, out var value2);
						int val2 = item.Inventory.CountItems(name, itemQuality, true) - value2;
						int num3 = Math.Min(num2, val2);
						if (num3 > 0)
						{
							value[name] = value2 + num3;
							if ((Object)(object)item.Container != (Object)null)
							{
								placementResourcePlan.AddStorage(item.Container, item.Inventory, name, num3, itemQuality);
							}
							num2 -= num3;
							if (num2 == 0)
							{
								break;
							}
						}
					}
					if (num2 > 0)
					{
						return null;
					}
				}
				return placementResourcePlan;
			}
			finally
			{
				context.SuppressCountAugmentation = suppressCountAugmentation;
			}
		}

		internal bool ValidateStorage(PlacementStorageContext.Scope context)
		{
			Dictionary<Inventory, Dictionary<string, int>> dictionary = new Dictionary<Inventory, Dictionary<string, int>>();
			foreach (StoragePortion storagePortion in _storagePortions)
			{
				if (!context.IsAccessible(storagePortion.Container) || !storagePortion.Container.IsOwner())
				{
					return false;
				}
				if (!dictionary.TryGetValue(storagePortion.Inventory, out var value))
				{
					value = new Dictionary<string, int>();
					dictionary.Add(storagePortion.Inventory, value);
				}
				value.TryGetValue(storagePortion.Name, out var value2);
				value2 += storagePortion.Amount;
				value[storagePortion.Name] = value2;
				if (storagePortion.Inventory.CountItems(storagePortion.Name, storagePortion.ItemQuality, true) < value2)
				{
					return false;
				}
			}
			return true;
		}

		internal void ConsumeStorage(PlacementStorageContext.Scope context)
		{
			if (!UsesStorage || _consumed)
			{
				return;
			}
			if (!ValidateStorage(context))
			{
				context.Client.LogError("Placement storage changed before resource consumption; the placed piece may need manual correction.");
				throw new InvalidOperationException("Placement storage changed before resource consumption; the placed piece may need manual correction.");
			}
			foreach (StoragePortion storagePortion in _storagePortions)
			{
				int num = storagePortion.Inventory.CountItems(storagePortion.Name, storagePortion.ItemQuality, true);
				storagePortion.Inventory.RemoveItem(storagePortion.Name, storagePortion.Amount, storagePortion.ItemQuality, true);
				int num2 = storagePortion.Inventory.CountItems(storagePortion.Name, storagePortion.ItemQuality, true);
				if (num - num2 != storagePortion.Amount)
				{
					context.Client.LogError("Placement storage did not consume the planned resource amount.");
					throw new InvalidOperationException("Placement storage did not consume the planned resource amount.");
				}
			}
			_consumed = true;
		}

		private void AddStorage(Container container, Inventory inventory, string name, int amount, int itemQuality)
		{
			StoragePortion storagePortion = _storagePortions.Find((StoragePortion entry) => (Object)(object)entry.Container == (Object)(object)container && entry.Name == name && entry.ItemQuality == itemQuality);
			if (storagePortion == null)
			{
				_storagePortions.Add(new StoragePortion(container, inventory, name, amount, itemQuality));
			}
			else
			{
				storagePortion.Amount += amount;
			}
		}
	}
	public sealed class PlacementStorage : IDisposable
	{
		private const string HarmonyOwner = "hoose.valheim.sharedplacementstorage";

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

		private static Harmony _harmony;

		private readonly string _toolPrefab;

		private readonly Func<float> _radius;

		private readonly Action<string> _warning;

		private readonly Action<string> _error;

		internal static PlacementStorageRegistry Registry { get; } = new PlacementStorageRegistry();

		internal bool IsCultivator => _toolPrefab == "Cultivator";

		internal float Radius => StorageRange.Clamp(_radius());

		private PlacementStorage(string toolPrefab, Func<float> radius, Action<string> warning, Action<string> error)
		{
			_toolPrefab = toolPrefab;
			_radius = radius;
			_warning = warning;
			_error = error;
		}

		public static PlacementStorage Register(string toolPrefab, Func<float> radius, Action<string> warning, Action<string> error)
		{
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			if (string.IsNullOrWhiteSpace(toolPrefab))
			{
				throw new ArgumentException("A placement tool prefab name is required.", "toolPrefab");
			}
			if (radius == null || warning == null || error == null)
			{
				throw new ArgumentNullException("radius", "Placement-storage callbacks must not be null.");
			}
			if (_clients.ContainsKey(toolPrefab))
			{
				throw new InvalidOperationException("A placement-storage client is already registered for " + toolPrefab + ".");
			}
			if (_clients.Count == 0)
			{
				Patches patchInfo = Harmony.GetPatchInfo((MethodBase)AccessTools.Method(typeof(Inventory), "CountItems", new Type[3]
				{
					typeof(string),
					typeof(int),
					typeof(bool)
				}, (Type[])null));
				if (patchInfo != null && patchInfo.Owners.Contains("hoose.valheim.buildfromstorage"))
				{
					throw new InvalidOperationException("An older BuildFromStorage is installed. Update BuildFromStorage and all ValheimMods.Common.dll copies before enabling FarmFromStorage.");
				}
				Harmony val = new Harmony("hoose.valheim.sharedplacementstorage");
				try
				{
					Type[] array = (from type2 in typeof(PlacementStorage).Assembly.GetTypes()
						where type2.Namespace == typeof(PlacementStorage).Namespace && type2.IsDefined(typeof(HarmonyPatch), inherit: false)
						select type2).ToArray();
					Type[] array2 = array;
					foreach (Type type in array2)
					{
						val.CreateClassProcessor(type).Patch();
					}
					IEnumerable<MethodInfo> enumerable = from method in array.SelectMany((Type type2) => type2.GetMethods(BindingFlags.Static | BindingFlags.NonPublic))
						where method.IsDefined(typeof(HarmonyPrefix), inherit: false) || method.IsDefined(typeof(HarmonyPostfix), inherit: false) || method.IsDefined(typeof(HarmonyFinalizer), inherit: false)
						select method;
					HashSet<MethodInfo> hashSet = (from patch in val.GetPatchedMethods().Select((Func<MethodBase, Patches>)Harmony.GetPatchInfo).SelectMany((Patches info) => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers))
						where patch.owner == "hoose.valheim.sharedplacementstorage"
						select patch.PatchMethod).ToHashSet();
					foreach (MethodInfo item in enumerable)
					{
						if (!hashSet.Contains(item))
						{
							throw new InvalidOperationException("Shared placement patch was not registered: " + item.DeclaringType.Name + "." + item.Name + ".");
						}
					}
					Registry.Initialize();
					_harmony = val;
				}
				catch
				{
					val.UnpatchSelf();
					Registry.Clear();
					throw;
				}
			}
			PlacementStorage placementStorage = new PlacementStorage(toolPrefab, radius, warning, error);
			_clients.Add(toolPrefab, placementStorage);
			return placementStorage;
		}

		public void Dispose()
		{
			if (_clients.TryGetValue(_toolPrefab, out var value) && value == this)
			{
				if (PlacementStorageContext.Current?.Client == this)
				{
					PlacementStorageContext.Reset();
				}
				_clients.Remove(_toolPrefab);
				if (_clients.Count == 0)
				{
					PlacementStorageContext.Reset();
					Registry.Clear();
					_harmony.UnpatchSelf();
					_harmony = null;
				}
			}
		}

		internal static bool TryGetClient(Player player, out PlacementStorage client)
		{
			client = null;
			if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer)
			{
				return false;
			}
			GameObject val = ((Humanoid)player).GetRightItem()?.m_dropPrefab;
			if ((Object)(object)val != (Object)null)
			{
				return _clients.TryGetValue(((Object)val).name, out client);
			}
			return false;
		}

		internal void LogWarning(string message)
		{
			_warning(message);
		}

		internal void LogError(string message)
		{
			_error(message);
		}
	}
	internal static class PlacementStorageContext
	{
		internal sealed class Scope
		{
			private readonly float _radius;

			private readonly HashSet<Container> _reservedSet = new HashSet<Container>();

			private readonly List<Container> _reserved = new List<Container>();

			internal Player Player { get; }

			internal PlacementStorage Client { get; }

			internal List<Container> Containers { get; }

			internal PlacementResourcePlan Plan { get; private set; }

			internal bool SuppressCountAugmentation { get; set; }

			internal int RequirementCheckDepth { get; set; }

			internal Scope(Player player, PlacementStorage client)
			{
				Player = player;
				Client = client;
				_radius = client.Radius;
				Containers = PlacementStorage.Registry.Find(player, _radius);
			}

			internal bool IsAccessible(Container container)
			{
				return PlacementStorage.Registry.IsAccessible(container, Player, _radius, _reservedSet.Contains(container));
			}

			internal bool TryReserve(PlacementResourcePlan plan)
			{
				if (!plan.ValidateStorage(this))
				{
					return false;
				}
				foreach (Container storageContainer in plan.StorageContainers)
				{
					if (!IsAccessible(storageContainer))
					{
						return false;
					}
				}
				foreach (Container storageContainer2 in plan.StorageContainers)
				{
					if (_reservedSet.Add(storageContainer2))
					{
						_reserved.Add(storageContainer2);
						storageContainer2.m_inUse = true;
					}
				}
				Plan = plan;
				return true;
			}

			internal void ConsumeStorage()
			{
				Plan?.ConsumeStorage(this);
			}

			internal void Release()
			{
				foreach (Container item in _reserved)
				{
					if ((Object)(object)item != (Object)null)
					{
						item.m_inUse = false;
					}
				}
				_reserved.Clear();
				_reservedSet.Clear();
			}
		}

		internal sealed class ScopeToken
		{
			internal Scope Scope { get; }

			internal Scope Previous { get; }

			internal bool RequirementCheck { get; }

			internal bool OwnsScope { get; }

			internal ScopeToken(Scope scope, Scope previous, bool requirementCheck, bool ownsScope)
			{
				Scope = scope;
				Previous = previous;
				RequirementCheck = requirementCheck;
				OwnsScope = ownsScope;
			}
		}

		private static Scope _current;

		internal static Scope Current => _current;

		internal static ScopeToken BeginPlacement(Player player)
		{
			if (!PlacementStorage.TryGetClient(player, out var client) || player.PlacementCostDisabled)
			{
				return null;
			}
			if (_current != null && (Object)(object)_current.Player == (Object)(object)player)
			{
				return null;
			}
			Scope current = _current;
			_current = new Scope(player, client);
			return new ScopeToken(_current, current, requirementCheck: false, ownsScope: true);
		}

		internal static ScopeToken BeginRequirements(Player player)
		{
			if (!PlacementStorage.TryGetClient(player, out var client) || player.PlacementCostDisabled)
			{
				return null;
			}
			if (_current != null && (Object)(object)_current.Player == (Object)(object)player)
			{
				_current.RequirementCheckDepth++;
				return new ScopeToken(_current, null, requirementCheck: true, ownsScope: false);
			}
			Scope current = _current;
			_current = new Scope(player, client);
			_current.RequirementCheckDepth++;
			return new ScopeToken(_current, current, requirementCheck: true, ownsScope: true);
		}

		internal static void End(ScopeToken token)
		{
			if (token != null)
			{
				if (token.RequirementCheck)
				{
					token.Scope.RequirementCheckDepth--;
				}
				if (token.OwnsScope)
				{
					token.Scope.Release();
					_current = token.Previous;
				}
			}
		}

		internal static void Reset()
		{
			_current?.Release();
			_current = null;
		}
	}
	internal sealed class PlacementStorageRegistry
	{
		private readonly ContainerRegistry _registry = new ContainerRegistry();

		private List<Container> _cached;

		private int _frame = -1;

		private Player _player;

		private Vector3 _position;

		private float _radius;

		internal void Initialize()
		{
			Clear();
			_registry.Initialize();
		}

		internal void Add(Container container)
		{
			_registry.Add(container);
			Invalidate();
		}

		internal void Remove(Container container)
		{
			_registry.Remove(container);
			Invalidate();
		}

		internal void Clear()
		{
			_registry.Clear();
			_cached = null;
			_player = null;
			_frame = -1;
		}

		internal bool IsAccessible(Container container, Player player, float radius, bool allowReserved)
		{
			if ((Object)(object)container != (Object)null && container.IsOwner())
			{
				return ContainerRegistry.IsAccessible(container, player, radius, allowReserved);
			}
			return false;
		}

		internal List<Container> Find(Player player, float radius)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			radius = StorageRange.Clamp(radius);
			if (_cached != null && _frame == Time.frameCount && (Object)(object)_player == (Object)(object)player && _position == ((Component)player).transform.position && _radius == radius)
			{
				return _cached;
			}
			List<Container> list = new List<Container>();
			_registry.PruneDestroyed();
			foreach (Container container in _registry.Containers)
			{
				if (IsAccessible(container, player, radius, allowReserved: false))
				{
					container.Load();
					list.Add(container);
				}
			}
			Vector3 position = ((Component)player).transform.position;
			list.Sort(delegate(Container left, Container right)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_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)
				//IL_0027: 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_0032: 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)
				Vector3 val = ((Component)left).transform.position - position;
				float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
				val = ((Component)right).transform.position - position;
				int num = sqrMagnitude.CompareTo(((Vector3)(ref val)).sqrMagnitude);
				return (num == 0) ? ((Object)left).GetInstanceID().CompareTo(((Object)right).GetInstanceID()) : num;
			});
			_cached = list;
			_player = player;
			_position = position;
			_radius = radius;
			_frame = Time.frameCount;
			return list;
		}

		private void Invalidate()
		{
			_frame = -1;
		}
	}
}
namespace ValheimMods.Common.InputSelection
{
	public sealed class InputPickerControls
	{
		public Func<bool> Enabled { get; }

		public Func<InputPreferences> Preferences { get; }

		public Action<InputPreferences> Save { get; }

		public Func<string> Selected { get; }

		public Action<string> Select { get; }

		public Action<Player, bool> Observe { get; }

		public Func<string> Hint { get; }

		public Func<string> HeldType { get; }

		public Func<bool> Stopped { get; }

		public InputPickerControls(Func<bool> enabled, Func<InputPreferences> preferences, Action<InputPreferences> save, Func<string> selected, Action<string> select, Action<Player, bool> observe, Func<string> hint, Func<string> heldType, Func<bool> stopped)
		{
			Enabled = enabled ?? throw new ArgumentNullException("enabled");
			Preferences = preferences ?? throw new ArgumentNullException("preferences");
			Save = save ?? throw new ArgumentNullException("save");
			Selected = selected ?? throw new ArgumentNullException("selected");
			Select = select ?? throw new ArgumentNullException("select");
			Observe = observe ?? throw new ArgumentNullException("observe");
			Hint = hint ?? throw new ArgumentNullException("hint");
			HeldType = heldType ?? throw new ArgumentNullException("heldType");
			Stopped = stopped ?? throw new ArgumentNullException("stopped");
		}
	}
	public sealed class InputPickerPreview
	{
		private const string HarmonyOwner = "hoose.valheim.inputpickerpreview";

		private const int ItemsPerPage = 8;

		private const int GridColumns = 4;

		private static InputPickerPreview _instance;

		private readonly Harmony _harmony;

		private readonly InputPickerProviderRegistry _providers = new InputPickerProviderRegistry();

		private readonly InputPreviewSession _session = new InputPreviewSession();

		private InputPickerProvider _activeProvider;

		private InputPickerProvider _hintProvider;

		private InputPreviewSnapshot _current;

		private InputPreviewSnapshot _hintSnapshot;

		private Player _player;

		private string _selected;

		private float _nextRefresh;

		private float _nextHintRefresh;

		private int _page;

		private int _lastOpenAttempt = -1;

		private int _lastObserveFrame = -1;

		private bool _hintAllowed;

		private GUIStyle _titleStyle;

		private GUIStyle _itemStyle;

		private GUIStyle _detailStyle;

		private GUIStyle _helpStyle;

		internal static bool BlocksInput => _instance?._session.BlocksInput ?? false;

		internal static bool IsOpen => _instance?._session.IsOpen ?? false;

		private InputPickerPreview(Harmony harmony)
		{
			_harmony = harmony;
		}

		public static InputPickerRegistration Register(Func<bool> enabled, Func<KeyCode> key, Func<Player, InputPreviewSnapshot> snapshot, InputPickerControls controls = null)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			InputPickerProvider provider = new InputPickerProvider(enabled, key, snapshot, controls);
			if (_instance == null)
			{
				Harmony val = new Harmony("hoose.valheim.inputpickerpreview");
				try
				{
					val.CreateClassProcessor(typeof(PreviewPlayerInputPatch)).Patch();
					val.CreateClassProcessor(typeof(PreviewControllerInputPatch)).Patch();
					val.CreateClassProcessor(typeof(PreviewCursorPatch)).Patch();
					val.CreateClassProcessor(typeof(PreviewMenuPatch)).Patch();
					if (val.GetPatchedMethods().Count() != 4)
					{
						throw new InvalidOperationException("Not all four input picker preview patches were registered.");
					}
				}
				catch
				{
					val.UnpatchSelf();
					throw;
				}
				_instance = new InputPickerPreview(val);
			}
			InputPickerRegistration result = new InputPickerRegistration(_instance, provider);
			_instance._providers.Add(provider);
			return result;
		}

		internal bool IsDriver(InputPickerRegistration registration)
		{
			return _providers.Driver == registration.Provider;
		}

		internal void Update(InputPickerRegistration registration)
		{
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			if (!IsDriver(registration))
			{
				return;
			}
			if ((_activeProvider != null && !_activeProvider.Enabled()) || (Object)(object)Player.m_localPlayer == (Object)null || ((Object)(object)_player != (Object)null && (Object)(object)_player != (Object)(object)Player.m_localPlayer) || ((Object)(object)_player != (Object)null && (((Character)_player).IsDead() || ((Character)_player).IsTeleporting() || ((Character)_player).InCutscene())))
			{
				Close();
			}
			if (_session.CanProcessInput(Time.frameCount))
			{
				if (ZInput.GetKeyDown((KeyCode)27, true) || ZInput.GetKeyDown(_activeProvider.Key(), true) || ZInput.GetButtonDown("JoyButtonB") || ZInput.GetButtonDown("JoyMenu"))
				{
					Close();
				}
				else
				{
					Refresh();
					if (_session.IsOpen)
					{
						Navigate();
						InputPickerControls controls = _activeProvider.Controls;
						if (controls != null && controls.Enabled() && (ZInput.GetKeyDown((KeyCode)13, true) || ZInput.GetButtonDown("JoyUse")))
						{
							ApplySelection();
						}
					}
				}
			}
			_session.UpdateRelease(Time.frameCount, ControlsHeld());
			if (!_session.BlocksInput && _hintAllowed && Time.unscaledTime >= _nextHintRefresh)
			{
				_nextHintRefresh = Time.unscaledTime + 0.25f;
				_hintProvider = _providers.FindHintTarget(Player.m_localPlayer, out _hintSnapshot);
			}
		}

		internal void Draw(InputPickerRegistration registration)
		{
			//IL_0e8f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e9d: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03df: Expected O, but got Unknown
			//IL_03f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0406: Unknown result type (might be due to invalid IL or missing references)
			//IL_0412: Expected O, but got Unknown
			//IL_0425: Unknown result type (might be due to invalid IL or missing references)
			//IL_042a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0432: Unknown result type (might be due to invalid IL or missing references)
			//IL_0439: Unknown result type (might be due to invalid IL or missing references)
			//IL_0445: Expected O, but got Unknown
			//IL_04a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0458: Unknown result type (might be due to invalid IL or missing references)
			//IL_045d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0465: Unknown result type (might be due to invalid IL or missing references)
			//IL_046c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0478: Expected O, but got Unknown
			//IL_051c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0535: Unknown result type (might be due to invalid IL or missing references)
			//IL_053f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0559: Unknown result type (might be due to invalid IL or missing references)
			//IL_0564: Unknown result type (might be due to invalid IL or missing references)
			//IL_0592: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_06cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b28: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0dcd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ddc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0de6: Expected O, but got Unknown
			//IL_0724: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b7b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b8a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b94: Expected O, but got Unknown
			//IL_0e3b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e7b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ce0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cf9: Expected O, but got Unknown
			//IL_0bf0: Unknown result type (might be due to invalid IL or missing references)
			//IL_073d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0747: Expected O, but got Unknown
			//IL_0762: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c4d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c5c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c66: Expected O, but got Unknown
			//IL_0838: Unknown result type (might be due to invalid IL or missing references)
			//IL_088f: Unknown result type (might be due to invalid IL or missing references)
			//IL_08bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_08cb: Expected O, but got Unknown
			//IL_078b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0790: Unknown result type (might be due to invalid IL or missing references)
			//IL_0806: Unknown result type (might be due to invalid IL or missing references)
			//IL_080d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d53: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d62: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d6c: Expected O, but got Unknown
			//IL_0d8d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d9c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0da6: Expected O, but got Unknown
			//IL_0963: Unknown result type (might be due to invalid IL or missing references)
			//IL_097a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0984: Expected O, but got Unknown
			//IL_09db: Unknown result type (might be due to invalid IL or missing references)
			//IL_09ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_09f4: Expected O, but got Unknown
			//IL_0a42: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a5d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a6d: Expected O, but got Unknown
			//IL_0ab0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0abf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ac9: Expected O, but got Unknown
			if (!IsDriver(registration))
			{
				return;
			}
			if (!_session.IsOpen || _current == null)
			{
				InputPickerControls inputPickerControls = _hintProvider?.Controls;
				if (_session.BlocksInput || !_hintAllowed || _hintSnapshot == null || inputPickerControls == null || !inputPickerControls.Enabled())
				{
					return;
				}
				string text = inputPickerControls.Hint();
				if (!string.IsNullOrEmpty(text))
				{
					string text2 = inputPickerControls.Selected();
					string text3 = inputPickerControls.HeldType();
					string chosen = text3 ?? text2 ?? inputPickerControls.Preferences()?.Choose(from item in _hintSnapshot.Items
						where item.IsAvailable
						select ((Object)item.Item).name);
					InputPreviewItem inputPreviewItem = _hintSnapshot.Items.FirstOrDefault((InputPreviewItem item) => ((Object)item.Item).name == chosen);
					string text4 = ((inputPreviewItem == null) ? "none" : Localize(inputPreviewItem.Item.m_itemData.m_shared.m_name));
					string text5 = (inputPickerControls.Stopped() ? "Stopped (release use)" : ((text3 != null) ? "Holding" : ((text2 == null) ? "Auto" : "Selected")));
					string text6 = text5 + ": " + text4 + " " + $"(inventory {inputPreviewItem?.InventoryCount ?? 0}, storage {inputPreviewItem?.StorageCount ?? 0}) | {text}";
					GUI.Box(new Rect((float)(Screen.width - 700) / 2f, (float)(Screen.height - 155), 700f, 28f), text6);
				}
				return;
			}
			InputPickerControls inputPickerControls2 = _activeProvider?.Controls;
			bool flag = inputPickerControls2?.Enabled() ?? false;
			InputPreferences inputPreferences = (flag ? inputPickerControls2.Preferences() : null);
			string[] accepted = _current.Items.Select((InputPreviewItem entry) => ((Object)entry.Item).name).ToArray();
			List<string> list = inputPreferences?.Order(accepted).ToList();
			int num = Math.Max(1, (_current.Items.Count + 8 - 1) / 8);
			_page = Math.Min(_page, num - 1);
			int num2 = _page * 8;
			int num3 = Math.Min(8, _current.Items.Count - num2);
			int num4 = Math.Max(1, Math.Min(4, num3));
			int num5 = Math.Max(1, (num3 + 4 - 1) / 4);
			float num6 = Math.Max(528, 40 + num4 * 165 - 7);
			float num7 = (flag ? 116 : 70);
			float num8 = (flag ? 112 : 92);
			float num9 = num8 + (float)num5 * num7 + (float)((num5 - 1) * 7);
			float num10 = ((num > 1) ? 30 : 0);
			float num11 = num9 + 8f + num10;
			float num12 = num11 + 42f;
			float num13 = (flag ? 38 : 30);
			float num14 = num12 + num13 + 10f;
			if (_titleStyle == null)
			{
				_titleStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = 20,
					alignment = (TextAnchor)4
				};
			}
			if (_itemStyle == null)
			{
				_itemStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = 13,
					alignment = (TextAnchor)4,
					wordWrap = true
				};
			}
			if (_detailStyle == null)
			{
				_detailStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = 12,
					alignment = (TextAnchor)4,
					wordWrap = true
				};
			}
			if (_helpStyle == null)
			{
				_helpStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = 12,
					alignment = (TextAnchor)3,
					wordWrap = true
				};
			}
			float num15 = Mathf.Min(1.25f, Mathf.Min((float)Screen.width / (num6 + 60f), (float)Screen.height / (num14 + 30f)));
			Matrix4x4 matrix = GUI.matrix;
			int depth = GUI.depth;
			Color color = GUI.color;
			bool enabled = GUI.enabled;
			GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(num15, num15, 1f));
			GUI.depth = -100;
			try
			{
				float num16 = ((float)Screen.width / num15 - num6) / 2f;
				float num17 = ((float)Screen.height / num15 - num14) / 2f;
				Rect val = new Rect(num16, num17, num6, num14);
				GUI.color = new Color(0f, 0f, 0f, 0.45f);
				GUI.DrawTextureWithTexCoords(val, (Texture)(object)Texture2D.whiteTexture, new Rect(0f, 0f, 1f, 1f), true);
				GUI.color = color;
				GUI.Box(val, string.Empty);
				GUI.Label(new Rect(num16 + 15f, num17 + 12f, num6 - 30f, 35f), Localize(_current.Name) + " - " + (flag ? "input selection" : "input picker preview"), _titleStyle);
				GUI.Label(new Rect(num16 + 20f, num17 + 48f, num6 - 40f, (float)(flag ? 60 : 38)), flag ? ("Current: " + GetCurrentChoice(inputPickerControls2, _current) + ". Select a type, then Use highlighted.\nE uses it until changed, reset to Auto, or you leave.\nNothing moves from this menu.") : "Preview only: this view does not change what E adds.", _itemStyle);
				Rect val2 = default(Rect);
				Rect val3 = default(Rect);
				for (int num18 = 0; num18 < num3; num18++)
				{
					int index = num2 + num18;
					InputPreviewItem inputPreviewItem2 = _current.Items[index];
					int num19 = num18 % 4;
					int num20 = num18 / 4;
					float num21 = Math.Min(4, num3 - num20 * 4) * 165 - 7;
					((Rect)(ref val2))..ctor(num16 + (num6 - num21) / 2f + (float)(num19 * 165), num17 + num8 + (float)num20 * (num7 + 7f), 158f, num7);
					GUI.color = (Color)((_selected == ((Object)inputPreviewItem2.Item).name) ? new Color(1f, 0.88f, 0.58f) : color);
					GUI.Box(val2, string.Empty);
					GUI.enabled = enabled && (inputPreviewItem2.IsAvailable || flag);
					if (GUI.Button(new Rect(((Rect)(ref val2)).x + 4f, ((Rect)(ref val2)).y + 4f, ((Rect)(ref val2)).width - 8f, 34f), new GUIContent(string.Empty, flag ? "Highlight this type, then choose Use highlighted. It stays selected for this input until changed or reset to Auto. No item is added until you press E." : "Preview only: highlighting this type does not change E behavior.")))
					{
						_selected = ((Object)inputPreviewItem2.Item).name;
					}
					GUI.enabled = enabled;
					GUI.color = color;
					Sprite icon = inputPreviewItem2.Item.m_itemData.GetIcon();
					if ((Object)(object)icon != (Object)null)
					{
						Rect textureRect = icon.textureRect;
						Texture2D texture = icon.texture;
						((Rect)(ref val3))..ctor(((Rect)(ref textureRect)).x / (float)((Texture)texture).width, ((Rect)(ref textureRect)).y / (float)((Texture)texture).height, ((Rect)(ref textureRect)).width / (float)((Texture)texture).width, ((Rect)(ref textureRect)).height / (float)((Texture)texture).height);
						GUI.DrawTextureWithTexCoords(new Rect(((Rect)(ref val2)).x + 7f, ((Rect)(ref val2)).y + 7f, 28f, 28f), (Texture)(object)texture, val3);
					}
					GUI.Label(new Rect(((Rect)(ref val2)).x + 39f, ((Rect)(ref val2)).y + 5f, 113f, 32f), Localize(inputPreviewItem2.Item.m_itemData.m_shared.m_name), _itemStyle);
					GUI.Label(new Rect(((Rect)(ref val2)).x + 4f, ((Rect)(ref val2)).y + 37f, ((Rect)(ref val2)).width - 8f, 24f), new GUIContent($"Inventory {inputPreviewItem2.InventoryCount} | Storage {inputPreviewItem2.StorageCount}", "Current eligible counts, not a reservation. Availability can change before you press E."), _detailStyle);
					if (flag)
					{
						bool flag2 = inputPreferences != null;
						bool flag3 = flag2 && inputPreferences.IsExcluded(((Object)inputPreviewItem2.Item).name);
						int num22 = ((list != null) ? (list.IndexOf(((Object)inputPreviewItem2.Item).name) + 1) : 0);
						string text7 = ((!flag2) ? "Unavailable" : (flag3 ? "Never auto-add" : "Auto"));
						GUI.enabled = enabled && flag2;
						if (GUI.Button(new Rect(((Rect)(ref val2)).x + 5f, ((Rect)(ref val2)).y + 63f, ((Rect)(ref val2)).width - 10f, 21f), new GUIContent(text7, flag3 ? "This type is excluded from automatic choices only; you can still select it manually." : "This type is eligible for automatic choices. Click to exclude it from automatic selection.")))
						{
							inputPickerControls2.Save(inputPreferences.ToggleExcluded(((Object)inputPreviewItem2.Item).name));
						}
						GUI.enabled = enabled && flag2 && num22 > 1;
						if (GUI.Button(new Rect(((Rect)(ref val2)).x + 5f, ((Rect)(ref val2)).y + 88f, 50f, 24f), new GUIContent("Up", "Move this type earlier in the automatic input order.")))
						{
							inputPickerControls2.Save(inputPreferences.MoveUp(((Object)inputPreviewItem2.Item).name, accepted));
						}
						GUI.enabled = enabled && flag2;
						GUI.Label(new Rect(((Rect)(ref val2)).x + 57f, ((Rect)(ref val2)).y + 88f, 38f, 24f), new GUIContent($"#{num22}", "This is the automatic input priority. Automatic choice selects an item type first; inventory is searched before storage within that type."), _detailStyle);
						GUI.enabled = enabled && flag2 && num22 > 0 && num22 < list.Count;
						if (GUI.Button(new Rect(((Rect)(ref val2)).x + 97f, ((Rect)(ref val2)).y + 88f, 56f, 24f), new GUIContent("Down", "Move this type later in the automatic input order.")))
						{
							inputPickerControls2.Save(inputPreferences.MoveDown(((Object)inputPreviewItem2.Item).name, accepted));
						}
						GUI.enabled = enabled;
					}
				}
				if (_current.Items.Count == 0)
				{
					GUI.Label(new Rect(num16 + 20f, num17 + num8, num6 - 40f, num7), "No discovered inputs for this station.", _itemStyle);
				}
				if (num > 1)
				{
					float num23 = num17 + num9 + 8f;
					GUI.enabled = enabled && _page > 0;
					if (GUI.Button(new Rect(num16 + 30f, num23, 120f, 24f), new GUIContent("Previous", "Show the previous group of input types.")))
					{
						_page--;
						_selected = ((Object)_current.Items[_page * 8].Item).name;
					}
					GUI.enabled = enabled;
					GUI.Label(new Rect(num16 + (num6 - 170f) / 2f, num23, 170f, 24f), $"Page {_page + 1} of {num}", _detailStyle);
					GUI.enabled = enabled && _page < num - 1;
					if (GUI.Button(new Rect(num16 + num6 - 150f, num23, 120f, 24f), new GUIContent("Next", "Show the next group of input types.")))
					{
						_page++;
						_selected = ((Object)_current.Items[_page * 8].Item).name;
					}
					GUI.enabled = enabled;
				}
				float num24 = num17 + num11;
				if (flag)
				{
					float num25 = num16 + (num6 - 486f) / 2f;
					GUI.enabled = enabled && inputPreferences != null;
					if (GUI.Button(new Rect(num25, num24, 160f, 34f), new GUIContent("Use automatic choice", "Clear the manual type choice. This does not change priorities or exclusions.")))
					{
						inputPickerControls2.Select(null);
						Close();
					}
					GUI.enabled = enabled && inputPreferences != null && _current != null && _current.Items.Any((InputPreviewItem entry) => ((Object)entry.Item).name == _selected && entry.IsAvailable);
					if (GUI.Button(new Rect(num25 + 168f, num24, 185f, 34f), new GUIContent("Use highlighted (Enter)", "Use this exact type for this input until changed or reset to Auto. No item moves until you press E.")))
					{
						ApplySelection();
					}
					GUI.enabled = enabled;
					if (GUI.Button(new Rect(num25 + 361f, num24, 125f, 34f), new GUIContent("Close (Esc / B)", "Close without changing your manual type choice.")))
					{
						Close();
					}
				}
				else if (GUI.Button(new Rect(num16 + (num6 - 200f) / 2f, num24, 200f, 34f), new GUIContent("Close (Esc / B)", "Close the preview. E behavior is unchanged.")))
				{
					Close();
				}
				string text8 = GetHelpText(flag, inputPreferences, list, _current.Items, _selected);
				if (!string.IsNullOrWhiteSpace(GUI.tooltip))
				{
					text8 = GUI.tooltip;
				}
				Rect val4 = default(Rect);
				((Rect)(ref val4))..ctor(num16 + 20f, num17 + num12, num6 - 40f, num13);
				GUI.Box(val4, string.Empty);
				GUI.Label(new Rect(((Rect)(ref val4)).x + 6f, ((Rect)(ref val4)).y + 2f, ((Rect)(ref val4)).width - 12f, ((Rect)(ref val4)).height - 4f), text8, _helpStyle);
			}
			finally
			{
				GUI.matrix = matrix;
				GUI.depth = depth;
				GUI.color = color;
				GUI.enabled = enabled;
			}
		}

		internal void Unregister(InputPickerRegistration registration)
		{
			if (!_providers.Remove(registration.Provider))
			{
				registration.Detach();
				return;
			}
			if (_activeProvider == registration.Provider)
			{
				Close();
			}
			if (_hintProvider == registration.Provider)
			{
				_hintProvider = null;
				_hintSnapshot = null;
			}
			registration.Detach();
			if (_providers.IsEmpty)
			{
				_instance = null;
				Close();
				_harmony.UnpatchSelf();
				RestoreCursor();
			}
		}

		internal static void FilterPlayerInput(Player player, ref bool allowed)
		{
			if (_instance == null || (Object)(object)player != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			InputPickerPreview instance = _instance;
			if (!allowed && instance._session.IsOpen)
			{
				instance.Close();
			}
			if (allowed && !instance._session.BlocksInput && instance._lastOpenAttempt != Time.frameCount && !UnifiedPopup.IsVisible() && !Hud.IsPieceSelectionVisible() && !Hud.InRadial())
			{
				InputPreviewSnapshot snapshot;
				bool attempted;
				InputPickerProvider inputPickerProvider = instance._providers.FindOpenTarget(player, (KeyCode key) => ZInput.GetKeyDown(key, true), out snapshot, out attempted);
				if (attempted)
				{
					instance._lastOpenAttempt = Time.frameCount;
				}
				if (inputPickerProvider != null)
				{
					instance._activeProvider = inputPickerProvider;
					instance._player = player;
					instance._current = snapshot;
					InputPickerControls controls = inputPickerProvider.Controls;
					instance._selected = ((controls != null && controls.Enabled()) ? inputPickerProvider.Controls.Selected() : null);
					instance._page = 0;
					instance._nextRefresh = Time.unscaledTime + 0.25f;
					instance._session.Open(Time.frameCount);
					ZCursor.LockState = (CursorLockMode)0;
					ZCursor.Show();
				}
			}
			if (instance._session.BlocksInput)
			{
				allowed = false;
			}
			instance._hintAllowed = allowed;
			if (instance._lastObserveFrame == Time.frameCount)
			{
				return;
			}
			instance._lastObserveFrame = Time.frameCount;
			foreach (InputPickerProvider item in instance._providers.All)
			{
				item.Controls?.Observe(player, allowed);
			}
		}

		private static string Localize(string text)
		{
			return Localization.instance.Localize(text);
		}

		private static bool ControlsHeld()
		{
			if (!ZInput.GetButton("Use") && !ZInput.GetButton("JoyUse") && !ZInput.GetButton("Attack") && !ZInput.GetButton("JoyAttack") && !ZInput.GetButton("SecondaryAttack") && !ZInput.GetButton("JoySecondaryAttack") && !ZInput.GetButton("JoyButtonB") && !ZInput.GetButton("JoyMenu"))
			{
				return ZInput.GetKey((KeyCode)27, true);
			}
			return true;
		}

		private static void RestoreCursor()
		{
			if ((Object)(object)GameCamera.instance != (Object)null)
			{
				GameCamera.instance.UpdateMouseCapture();
			}
		}

		private void Refresh()
		{
			if (Time.unscaledTime < _nextRefresh)
			{
				return;
			}
			_nextRefresh = Time.unscaledTime + 0.25f;
			InputPreviewSnapshot inputPreviewSnapshot = _activeProvider.Snapshot(_player);
			if (inputPreviewSnapshot == null || (Object)(object)inputPreviewSnapshot.Station != (Object)(object)_current.Station)
			{
				Close();
				return;
			}
			_current = inputPreviewSnapshot;
			_page = Math.Min(_page, Math.Max(0, (_current.Items.Count - 1) / 8));
			if (!_current.Items.Any(delegate(InputPreviewItem entry)
			{
				if (!entry.IsAvailable)
				{
					InputPickerControls controls = _activeProvider.Controls;
					if (controls == null || !controls.Enabled())
					{
						return false;
					}
				}
				return ((Object)entry.Item).name == _selected;
			}))
			{
				_selected = null;
			}
		}

		private void Navigate()
		{
			int num = ((ZInput.GetKeyDown((KeyCode)276, true) || ZInput.GetButtonDown("JoyDPadLeft")) ? (-1) : ((ZInput.GetKeyDown((KeyCode)275, true) || ZInput.GetButtonDown("JoyDPadRight")) ? 1 : 0));
			if (num == 0)
			{
				return;
			}
			int num2 = -1;
			for (int i = 0; i < _current.Items.Count; i++)
			{
				if (((Object)_current.Items[i].Item).name == _selected)
				{
					num2 = i;
					break;
				}
			}
			if (num2 < 0)
			{
				num2 = ((num > 0) ? (_current.Items.Count - 1) : 0);
			}
			int num3 = 0;
			while (num3 < _current.Items.Count)
			{
				num2 = (num2 + num + _current.Items.Count) % _current.Items.Count;
				if (!_current.Items[num2].IsAvailable)
				{
					InputPickerControls controls = _activeProvider.Controls;
					if (controls == null || !controls.Enabled())
					{
						num3++;
						continue;
					}
				}
				_selected = ((Object)_current.Items[num2].Item).name;
				_page = num2 / 8;
				break;
			}
		}

		private void ApplySelection()
		{
			InputPickerControls inputPickerControls = _activeProvider?.Controls;
			if (inputPickerControls != null && inputPickerControls.Enabled() && inputPickerControls.Preferences() != null && _current != null && _current.Items.Any((InputPreviewItem entry) => ((Object)entry.Item).name == _selected && entry.IsAvailable))
			{
				inputPickerControls.Select(_selected);
				Close();
			}
		}

		private static string GetCurrentChoice(InputPickerControls controls, InputPreviewSnapshot snapshot)
		{
			string selected = controls.Selected();
			if (selected == null)
			{
				return "Auto";
			}
			InputPreviewItem inputPreviewItem = snapshot.Items.FirstOrDefault((InputPreviewItem entry) => ((Object)entry.Item).name == selected);
			if (inputPreviewItem != null)
			{
				return Localize(inputPreviewItem.Item.m_itemData.m_shared.m_name);
			}
			return "unavailable";
		}

		private static string GetHelpText(bool controlled, InputPreferences preferences, IReadOnlyList<string> order, IReadOnlyList<InputPreviewItem> items, string selected)
		{
			if (!controlled)
			{
				return "Preview only: counts are informational; this view does not change E behavior.";
			}
			if (preferences == null)
			{
				return "Preferences are invalid or unavailable. Automatic insertion is blocked; see the log.";
			}
			InputPreviewItem inputPreviewItem = items.FirstOrDefault((InputPreviewItem item) => ((Object)item.Item).name == selected);
			if (inputPreviewItem == null)
			{
				return "Auto uses priority order; inventory is preferred within a type. Never auto-add affects automatic choices only.";
			}
			int num = order.ToList().IndexOf(((Object)inputPreviewItem.Item).name) + 1;
			string arg = (preferences.IsExcluded(((Object)inputPreviewItem.Item).name) ? "never auto-added" : "allowed for Auto");
			return $"{Localize(inputPreviewItem.Item.m_itemData.m_shared.m_name)}: priority #{num}, {arg}. Manual selection can still choose excluded types.";
		}

		private void Close()
		{
			if (!_session.IsOpen)
			{
				_activeProvider = null;
				_current = null;
				_selected = null;
				_player = null;
			}
			else
			{
				_session.Close(Time.frameCount);
				_activeProvider = null;
				_current = null;
				_selected = null;
				_player = null;
				RestoreCursor();
			}
		}
	}
	internal sealed class InputPickerProvider
	{
		internal Func<bool> Enabled { get; }

		internal Func<KeyCode> Key { get; }

		internal Func<Player, InputPreviewSnapshot> Snapshot { get; }

		internal InputPickerControls Controls { get; }

		internal InputPickerProvider(Func<bool> enabled, Func<KeyCode> key, Func<Player, InputPreviewSnapshot> snapshot, InputPickerControls controls)
		{
			Enabled = enabled ?? throw new ArgumentNullException("enabled");
			Key = key ?? throw new ArgumentNullException("key");
			Snapshot = snapshot ?? throw new ArgumentNullException("snapshot");
			Controls = controls;
		}
	}
	internal sealed class InputPickerProviderRegistry
	{
		private readonly List<InputPickerProvider> _providers = new List<InputPickerProvider>();

		internal InputPickerProvider Driver
		{
			get
			{
				if (_providers.Count != 0)
				{
					return _providers[0];
				}
				return null;
			}
		}

		internal IReadOnlyList<InputPickerProvider> All => _providers;

		internal bool IsEmpty => _providers.Count == 0;

		internal void Add(InputPickerProvider provider)
		{
			if (provider == null)
			{
				throw new ArgumentNullException("provider");
			}
			if (_providers.Contains(provider))
			{
				throw new InvalidOperationException("The input picker provider is already registered.");
			}
			_providers.Add(provider);
		}

		internal bool Remove(InputPickerProvider provider)
		{
			return _providers.Remove(provider);
		}

		internal InputPickerProvider FindOpenTarget(Player player, Func<KeyCode, bool> keyPressed, out InputPreviewSnapshot snapshot, out bool attempted)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			attempted = false;
			foreach (InputPickerProvider provider in _providers)
			{
				if (!provider.Enabled())
				{
					continue;
				}
				KeyCode val = provider.Key();
				if ((int)val != 0 && keyPressed(val))
				{
					attempted = true;
					snapshot = provider.Snapshot(player);
					if (snapshot != null)
					{
						return provider;
					}
				}
			}
			snapshot = null;
			return null;
		}

		internal InputPickerProvider FindHintTarget(Player player, out InputPreviewSnapshot snapshot)
		{
			foreach (InputPickerProvider provider in _providers)
			{
				if (!provider.Enabled())
				{
					continue;
				}
				InputPickerControls controls = provider.Controls;
				if (controls != null && controls.Enabled())
				{
					snapshot = provider.Snapshot(player);
					if (snapshot != null)
					{
						return provider;
					}
				}
			}
			snapshot = null;
			return null;
		}
	}
	public sealed class InputPickerRegistration : IDisposable
	{
		private InputPickerPreview _owner;

		internal InputPickerProvider Provider { get; }

		internal InputPickerRegistration(InputPickerPreview owner, InputPickerProvider provider)
		{
			_owner = owner;
			Provider = provider;
		}

		public void Update()
		{
			_owner?.Update(this);
		}

		public void Draw()
		{
			_owner?.Draw(this);
		}

		public void Dispose()
		{
			_owner?.Unregister(this);
		}

		internal void Detach()
		{
			_owner = null;
		}
	}
	public sealed class InputPreferences
	{
		private readonly string[] _priority;

		private readonly HashSet<string> _excluded;

		private InputPreferences(string[] priority, IEnumerable<string> excluded)
		{
			_priority = priority;
			_excluded = new HashSet<string>(excluded, StringComparer.Ordinal);
		}

		public static InputPreferences Parse(string value)
		{
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			string[] array = value.Split('|');
			if (array.Length != 2)
			{
				throw new FormatException("Input preferences must contain priority|exclusions.");
			}
			return new InputPreferences(ParseList(array[0]), ParseList(array[1]));
		}

		public bool IsExcluded(string prefabName)
		{
			return _excluded.Contains(prefabName);
		}

		public bool IsConfigured(string prefabName)
		{
			if (!_priority.Contains(prefabName))
			{
				return _excluded.Contains(prefabName);
			}
			return true;
		}

		public string Serialize()
		{
			return string.Join(",", _priority) + "|" + string.Join(",", _excluded.OrderBy<string, string>((string name) => name, StringComparer.Ordinal));
		}

		public IReadOnlyList<string> Order(IEnumerable<string> accepted)
		{
			HashSet<string> hashSet = new HashSet<string>(accepted, StringComparer.Ordinal);
			List<string> list = _priority.Where(hashSet.Contains).ToList();
			list.AddRange(hashSet.Except(list).OrderBy<string, string>((string name) => name, StringComparer.Ordinal));
			return list;
		}

		public string Choose(IEnumerable<string> available)
		{
			return Order(available).FirstOrDefault((string name) => !IsExcluded(name));
		}

		public InputPreferences ToggleExcluded(string prefabName)
		{
			ValidateName(prefabName);
			HashSet<string> hashSet = new HashSet<string>(_excluded, StringComparer.Ordinal);
			if (!hashSet.Remove(prefabName))
			{
				hashSet.Add(prefabName);
			}
			return new InputPreferences(_priority, hashSet);
		}

		public InputPreferences MoveFirst(string prefabName, IEnumerable<string> accepted)
		{
			ValidateName(prefabName);
			return new InputPreferences(new string[1] { prefabName }.Concat(_priority).Concat(Order(accepted)).Distinct<string>(StringComparer.Ordinal)
				.ToArray(), _excluded);
		}

		public InputPreferences MoveUp(string prefabName, IEnumerable<string> accepted)
		{
			return Move(prefabName, accepted, -1);
		}

		public InputPreferences MoveDown(string prefabName, IEnumerable<string> accepted)
		{
			return Move(prefabName, accepted, 1);
		}

		private InputPreferences Move(string prefabName, IEnumerable<string> accepted, int direction)
		{
			ValidateName(prefabName);
			List<string> list = Order(accepted).ToList();
			int num = list.IndexOf(prefabName);
			if (num < 0)
			{
				throw new ArgumentException("The input type is not accepted by this station.", "prefabName");
			}
			int num2 = num + direction;
			if (num2 < 0 || num2 >= list.Count)
			{
				return this;
			}
			string value = list[num2];
			list[num2] = list[num];
			list[num] = value;
			HashSet<string> hashSet = new HashSet<string>(list, StringComparer.Ordinal);
			IEnumerable<string> enumerable = _priority.Concat(list).Distinct<string>(StringComparer.Ordinal);
			List<string> list2 = new List<string>();
			int num3 = 0;
			foreach (string item in enumerable)
			{
				if (hashSet.Contains(item))
				{
					list2.Add(list[num3]);
					num3++;
				}
				else
				{
					list2.Add(item);
				}
			}
			return new InputPreferences(list2.ToArray(), _excluded);
		}

		private static string[] ParseList(string value)
		{
			if (value.Length == 0)
			{
				return Array.Empty<string>();
			}
			string[] array = value.Split(',');
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			string[] array2 = array;
			foreach (string text in array2)
			{
				ValidateName(text);
				if (!hashSet.Add(text))
				{
					throw new FormatException("Duplicate input preference: " + text + ".");
				}
			}
			return array;
		}

		private static void ValidateName(string name)
		{
			if (string.IsNullOrWhiteSpace(name) || name != name.Trim() || name.Any(delegate(char character)
			{
				bool flag = char.IsControl(character);
				if (!flag)
				{
					bool flag2 = ((character == ',' || character == '|') ? true : false);
					flag = flag2;
				}
				return flag;
			}))
			{
				throw new FormatException("Input preference identifiers cannot be blank, padded or contain commas, pipes or control characters.");
			}
		}
	}
	public sealed class InputPreviewItem
	{
		public ItemDrop Item { get; }

		public int InventoryCount { get; }

		public int StorageCount { get; }

		public bool IsAvailable
		{
			get
			{
				if (InventoryCount <= 0)
				{
					return StorageCount > 0;
				}
				return true;
			}
		}

		public InputPreviewItem(ItemDrop item, int inventoryCount, int storageCount)
		{
			Item = item ?? throw new ArgumentNullException("item");
			InventoryCount = inventoryCount;
			StorageCount = storageCount;
		}

		public static int Count(Inventory inventory, string prefabName)
		{
			if (inventory == null || string.IsNullOrEmpty(prefabName))
			{
				throw new ArgumentException("Preview counts require an inventory and a prefab identifier.");
			}
			int num = 0;
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if ((Object)(object)allItem?.m_dropPrefab != (Object)null && ((Object)allItem.m_dropPrefab).name == prefabName && allItem.m_stack > 0)
				{
					num += allItem.m_stack;
				}
			}
			return num;
		}
	}
	internal sealed class InputPreviewSession
	{
		private int _closedFrame = -1;

		internal bool IsOpen { get; private set; }

		internal bool BlocksInput { get; private set; }

		internal int OpenedFrame { get; private set; } = -1;

		internal bool CanProcessInput(int frame)
		{
			if (IsOpen)
			{
				return frame > OpenedFrame;
			}
			return false;
		}

		internal void Open(int frame)
		{
			IsOpen = true;
			BlocksInput = true;
			OpenedFrame = frame;
		}

		internal void Close(int frame)
		{
			if (IsOpen)
			{
				IsOpen = false;
				_closedFrame = frame;
			}
		}

		internal void UpdateRelease(int frame, bool controlsHeld)
		{
			if (!IsOpen && frame > _closedFrame && !controlsHeld)
			{
				BlocksInput = false;
			}
		}
	}
	public sealed class InputPreviewSnapshot
	{
		public Component Station { get; }

		public string Name { get; }

		public IReadOnlyList<InputPreviewItem> Items { get; }

		public InputPreviewSnapshot(Component station, string name, IReadOnlyList<InputPreviewItem> items)
		{
			if (!((Object)(object)station != (Object)null))
			{
				throw new ArgumentNullException("station");
			}
			Station = station;
			Name = name ?? throw new ArgumentNullException("name");
			Items = items ?? throw new ArgumentNullException("items");
		}
	}
	public sealed class InputTypeSession
	{
		private readonly bool _continueAcrossTargets;

		private bool _held;

		private bool _stopped;

		private string _latched;

		private object _target;

		public object Context { get; private set; }

		public string Selected { get; private set; }

		public bool CanInsert
		{
			get
			{
				if (Context != null && _held)
				{
					return !_stopped;
				}
				return false;
			}
		}

		public string HeldType => _latched;

		public bool IsStopped
		{
			get
			{
				if (_held)
				{
					return _stopped;
				}
				return false;
			}
		}

		public InputTypeSession(bool continueAcrossTargets = false)
		{
			_continueAcrossTargets = continueAcrossTargets;
		}

		public void Observe(object context, bool held, bool pressed, bool interrupted)
		{
			bool flag = Context != context;
			Context = context;
			if (_continueAcrossTargets && _held && held && !pressed)
			{
				if (context != null && context != _target)
				{
					_target = context;
					Selected = null;
					_latched = null;
					_stopped = false;
				}
			}
			else
			{
				if (_target != context)
				{
					_target = context;
					Selected = null;
				}
				if (!held || pressed)
				{
					_latched = null;
					_stopped = false;
				}
				else if (flag && _held)
				{
					_stopped = true;
				}
			}
			_held = held;
			if (interrupted && held)
			{
				_stopped = true;
			}
		}

		public void Select(string prefabName)
		{
			Selected = prefabName;
			_latched = null;
			_stopped = _held;
		}

		public string Resolve(InputPreferences preferences, IEnumerable<string> available)
		{
			if (!CanInsert)
			{
				return null;
			}
			if (_continueAcrossTargets && Selected == null && _latched != null)
			{
				ICollection<string> obj = (available as ICollection<string>) ?? available.ToList();
				available = obj;
				if (!obj.Contains(_latched))
				{
					_latched = null;
				}
			}
			if (_latched == null)
			{
				_latched = Selected ?? preferences.Choose(available);
			}
			return _latched;
		}

		public bool Stop()
		{
			bool result = !_stopped;
			_stopped = true;
			return result;
		}

		public void Clear()
		{
			Context = null;
			Selected = null;
			_latched = null;
			_target = null;
			_stopped = false;
			_held = false;
		}
	}
	[HarmonyPatch(typeof(PlayerController), "TakeInput")]
	internal static class PreviewControllerInputPatch
	{
		[HarmonyPostfix]
		private static void AfterInputChecked(PlayerController __instance, ref bool __result)
		{
			if (InputPickerPreview.BlocksInput && (Object)(object)((Component)__instance).GetComponent<Player>() == (Object)(object)Player.m_localPlayer)
			{
				__result = false;
			}
		}
	}
	[HarmonyPatch(typeof(GameCamera), "UpdateMouseCapture")]
	internal static class PreviewCursorPatch
	{
		[HarmonyPrefix]
		private static bool BeforeCursorUpdated()
		{
			if (!InputPickerPreview.IsOpen)
			{
				return true;
			}
			ZCursor.LockState = (CursorLockMode)0;
			ZCursor.Show();
			return false;
		}
	}
	[HarmonyPatch(typeof(Menu), "Update")]
	internal static class PreviewMenuPatch
	{
		[HarmonyPrefix]
		private static bool BeforeMenuUpdated()
		{
			return !InputPickerPreview.BlocksInput;
		}
	}
	[HarmonyPatch(typeof(Player), "TakeInput")]
	internal static class PreviewPlayerInputPatch
	{
		[HarmonyPostfix]
		private static void AfterInputChecked(Player __instance, ref bool __result)
		{
			InputPickerPreview.FilterPlayerInput(__instance, ref __result);
		}
	}
}
namespace ValheimMods.Common.Crafting
{
	[HarmonyPatch(typeof(Player), "GetFirstRequiredItem")]
	internal static class AlternativeIngredientPatch
	{
		[HarmonyPrefix]
		private static bool BeforeSelection(Player __instance, Inventory inventory, Recipe recipe, int qualityLevel, ref int amount, ref int extraAmount, int craftMultiplier, ref ItemData __result)
		{
			using CraftingContext craftingContext = CraftingContext.Enter(__instance, recipe);
			if (craftingContext == null || inventory != ((Humanoid)__instance).GetInventory() || !recipe.m_requireOnlyOneIngredient)
			{
				return true;
			}
			__result = craftingContext.FirstIngredient(recipe, qualityLevel, craftMultiplier, out amount, out extraAmount);
			return false;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "OnCraftCancelPressed")]
	internal static class CancelCraftPatch
	{
		[HarmonyPrefix]
		private static void BeforeCancel()
		{
			StorageCrafting.Cancel();
		}
	}
	[HarmonyPatch(typeof(Container), "Awake")]
	internal static class ContainerCreatedPatch
	{
		[HarmonyPostfix]
		private static void AfterAwake(Container __instance)
		{
			NearbyStorage.Add(__instance);
		}
	}
	[HarmonyPatch(typeof(Container), "OnDestroyed")]
	internal static class ContainerDestroyedPatch
	{
		[HarmonyPrefix]
		private static void BeforeDestroy(Container __instance)
		{
			NearbyStorage.Remove(__instance);
		}
	}
	internal sealed class CraftingContext : IDisposable
	{
		private readonly CraftingContext _previous;

		internal static CraftingContext Current { get; private set; }

		internal Player LocalPlayer { get; }

		internal List<Container> Containers { get; }

		internal IngredientPlan Plan { get; set; }

		internal bool Reserved { get; set; }

		internal bool IncludeStorageCounts { get; set; }

		internal CraftingContext(Player player, List<Container> containers)
		{
			LocalPlayer = player;
			Containers = containers;
			_previous = Current;
			Current = this;
		}

		public void Dispose()
		{
			Current = _previous;
		}

		internal static bool IsStationRecipe(Player player, Recipe recipe)
		{
			if ((Object)(object)player != (Object)null && (Object)(object)player == (Object)(object)Player.m_localPlayer && (Object)(object)recipe != (Object)null && (Object)(object)recipe.m_craftingStation != (Object)null && (Object)(object)player.GetCurrentCraftingStation() != (Object)null)
			{
				return RecipeStorage.Supports(player, recipe);
			}
			return false;
		}

		internal static CraftingContext Enter(Player player, Recipe recipe)
		{
			if (!IsStationRecipe(player, recipe))
			{
				return null;
			}
			CraftingContext current = Current;
			List<Container> containers = (((Object)(object)current?.LocalPlayer == (Object)(object)player) ? current.Containers : NearbyStorage.Find(player));
			return new CraftingContext(player, containers)
			{
				Reserved = (current?.Reserved ?? false),
				Plan = current?.Plan,
				IncludeStorageCounts = true
			};
		}

		internal static bool Matches(ItemData item, string name, int quality, bool worldLevel)
		{
			if (item.m_stack > 0 && item.m_shared.m_name == name && (quality < 0 || item.m_quality == quality))
			{
				if (worldLevel)
				{
					return item.m_worldLevel >= Game.m_worldLevel;
				}
				return true;
			}
			return false;
		}

		internal IEnumerable<Inventory> Inventories()
		{
			yield return ((Humanoid)LocalPlayer).GetInventory();
			foreach (Container container in Containers)
			{
				if (NearbyStorage.IsAccessible(container, LocalPlayer, Reserved))
				{
					yield return container.GetInventory();
				}
			}
		}

		internal int CountStorage(string name, int quality, bool worldLevel)
		{
			int num = 0;
			foreach (Inventory item in Inventories())
			{
				if (item == ((Humanoid)LocalPlayer).GetInventory())
				{
					continue;
				}
				foreach (ItemData allItem in item.GetAllItems())
				{
					if (Matches(allItem, name, quality, worldLevel))
					{
						num = checked(num + allItem.m_stack);
					}
				}
			}
			return num;
		}

		internal ItemData FirstIngredient(Recipe recipe, int qualityLevel, int multiplier, out int amount, out int extraAmount)
		{
			CraftingStation currentCraftingStation = LocalPlayer.GetCurrentCraftingStation();
			Requirement[] resources = recipe.m_resources;
			foreach (Requirement val in resources)
			{
				if ((Object)(object)val.m_resItem == (Object)null || currentCraftingStation.m_upgrader != val.m_upgraderResource)
				{
					continue;
				}
				int num = checked(val.GetAmount(qualityLevel) * multiplier);
				if (num <= 0)
				{
					continue;
				}
				string name = val.m_resItem.m_itemData.m_shared.m_name;
				for (int j = 0; j <= val.m_resItem.m_itemData.m_shared.m_maxQuality; j++)
				{
					int num2 = 0;
					ItemData val2 = null;
					foreach (Inventory item in Inventories())
					{
						foreach (ItemData allItem in item.GetAllItems())
						{
							if (Matches(allItem, name, j, worldLevel: true))
							{
								if (val2 == null)
								{
									val2 = allItem;
								}
								num2 = checked(num2 + allItem.m_stack);
							}
						}
					}
					if (num2 >= num)
					{
						amount = num;
						extraAmount = val.m_extraAmountOnlyOneIngredient;
						return val2;
					}
				}
			}
			amount = 0;
			extraAmount = 0;
			return null;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
	internal static class CraftTransactionPatch
	{
		[HarmonyPrefix]
		private static bool BeforeCraft(InventoryGui __instance, Player player)
		{
			if (!CraftingContext.IsStationRecipe(player, __instance.m_craftRecipe) || StorageCrafting.IsExecuting)
			{
				return true;
			}
			if (StorageCrafting.IsPending)
			{
				return false;
			}
			if (player.NoCostCheat() || ZoneSystem.instance.GetGlobalKey((GlobalKeys)25))
			{
				return true;
			}
			RecipeStorage.StartCraft(__instance, player);
			return false;
		}

		[HarmonyFinalizer]
		private static void AfterCraft(Exception __exception)
		{
			if (__exception != null)
			{
				RecipeStorage.LogError($"Crafting failed: {__exception}");
			}
		}
	}
	internal sealed class IngredientPlan
	{
		private sealed class Portion
		{
			internal Inventory Inventory { get; set; }

			internal ItemData Item { get; set; }

			internal int Amount { get; set; }
		}

		private sealed class Ingredient
		{
			internal string Name { get; set; }

			internal int Quality { get; set; }

			internal int Amount { get; set; }

			internal bool Consumed { get; set; }

			internal List<Portion> Portions { get; } = new List<Portion>();
		}

		private readonly List<Ingredient> _ingredients = new List<Ingredient>();

		internal static IngredientPlan Create(CraftingContext context, Recipe recipe, int quality, int multiplier)
		{
			IngredientPlan ingredientPlan = new IngredientPlan();
			if (recipe.m_requireOnlyOneIngredient)
			{
				int amount;
				int extraAmount;
				ItemData val = context.FirstIngredient(recipe, quality, multiplier, out amount, out extraAmount);
				if (val == null)
				{
					return null;
				}
				ingredientPlan._ingredients.Add(new Ingredient
				{
					Name = val.m_shared.m_name,
					Quality = val.m_quality,
					Amount = amount
				});
			}
			else
			{
				CraftingStation currentCraftingStation = context.LocalPlayer.GetCurrentCraftingStation();
				Requirement[] resources = recipe.m_resources;
				foreach (Requirement val2 in resources)
				{
					if (!((Object)(object)val2.m_resItem == (Object)null) && currentCraftingStation.m_upgrader == val2.m_upgraderResource)
					{
						int num = checked(val2.GetAmount(quality) * multiplier);
						if (num > 0)
						{
							ingredientPlan._ingredients.Add(new Ingredient
							{
								Name = val2.m_resItem.m_itemData.m_shared.m_name,
								Quality = -1,
								Amount = num
							});
						}
					}
				}
			}
			Dictionary<ItemData, int> dictionary = new Dictionary<ItemData, int>();
			foreach (Ingredient ingredient in ingredientPlan._ingredients)
			{
				int num2 = ingredient.Amount;
				foreach (Inventory item in context.Inventories())
				{
					foreach (ItemData allItem in item.GetAllItems())
					{
						if (CraftingContext.Matches(allItem, ingredient.Name, ingredient.Quality, worldLevel: true))
						{
							dictionary.TryGetValue(allItem, out var value);
							int num3 = Math.Min(num2, allItem.m_stack - value);
							if (num3 > 0)
							{
								ingredient.Portions.Add(new Portion
								{
									Inventory = item,
									Item = allItem,
									Amount = num3
								});
								dictionary[allItem] = value + num3;
								num2 -= num3;
							}
						}
					}
				}
				if (num2 > 0)
				{
					return null;
				}
			}
			return ingredientPlan;
		}

		internal List<Container> StorageSources(CraftingContext context)
		{
			HashSet<Inventory> inventories = new HashSet<Inventory>();
			foreach (Ingredient ingredient in _ingredients)
			{
				foreach (Portion portion in ingredient.Portions)
				{
					inventories.Add(portion.Inventory);
				}
			}
			return context.Containers.FindAll((Container container) => inventories.Contains(container.GetInventory()));
		}

		internal void Consume(string name, int amount, int quality, bool worldLevel)
		{
			Ingredient ingredient = _ingredients.Find((Ingredient entry) => !entry.Consumed && entry.Name == name && entry.Amount == amount && entry.Quality == quality);
			if (ingredient == null || !worldLevel)
			{
				throw new InvalidOperationException($"Unexpected crafting consumption: {name}, amount {amount}, quality {quality}.");
			}
			foreach (Portion portion in ingredient.Portions)
			{
				if (!portion.Inventory.ContainsItem(portion.Item) || portion.Item.m_stack < portion.Amount)
				{
					throw new InvalidOperationException("Reserved crafting ingredient changed: " + name + ".");
				}
			}
			foreach (Portion portion2 in ingredient.Portions)
			{
				if (!portion2.Inventory.RemoveItem(portion2.Item, portion2.Amount))
				{
					throw new InvalidOperationException("Could not consume reserved crafting ingredient: " + name + ".");
				}
			}
			ingredient.Consumed = true;
		}
	}
	[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
	{
		typeof(string),
		typeof(int),
		typeof(int),
		typeof(bool)
	})]
	internal static class InventoryConsumePatch
	{
		[HarmonyPrefix]
		private static bool BeforeRemove(Inventory __instance, string name, int amount, int itemQuality, bool worldLevelBased)
		{
			CraftingContext current = CraftingContext.Current;
			if (!StorageCrafting.IsExecuting || current?.Plan == null || __instance != ((Humanoid)current.LocalPlayer).GetInventory())
			{
				return true;
			}
			current.Plan.Consume(name, amount, itemQuality, worldLevelBased);
			return false;
		}
	}
	[HarmonyPatch(typeof(Inventory), "CountItems", new Type[]
	{
		typeof(string),
		typeof(int),
		typeof(bool)
	})]
	internal static class InventoryCountPatch
	{
		[HarmonyPostfix]
		private static void AfterCount(Inventory __instance, string name, int quality, bool matchWorldLevel, ref int __result)
		{
			CraftingContext current = CraftingContext.Current;
			checked
			{
				if (current != null && current.IncludeStorageCounts && __instance == ((Humanoid)current.LocalPlayer).GetInventory())
				{
					__result += current.CountStorage(name, quality, matchWorldLevel);
				}
			}
		}
	}
	internal static class NearbyStorage
	{
		private static readonly ContainerRegistry _registry = new ContainerRegistry();

		private static List<Container> _cached;

		private static int _frame = -1;

		private static Player _player;

		private static Vector3 _position;

		private static float _radius;

		internal static void Initialize()
		{
			Clear();
			_registry.Initialize();
		}

		internal static void Add(Container container)
		{
			_registry.Add(container);
			_frame = -1;
		}

		internal static void Remove(Container container)
		{
			_registry.Remove(container);
			StorageCrafting.Forget(container);
			_frame = -1;
		}

		internal static void Clear()
		{
			_registry.Clear();
			_cached = null;
			_player = null;
			_frame = -1;
		}

		internal static bool IsAccessible(Container container, Player player, bool allowReserved = false)
		{
			return ContainerRegistry.IsAccessible(container, player, RecipeStorage.RadiusFor(player), allowReserved);
		}

		internal static List<Container> Find(Player player, bool refresh = false)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: 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)
			float num = RecipeStorage.RadiusFor(player);
			if (!refresh && _cached != null && _frame == Time.frameCount && (Object)(object)_player == (Object)(object)player && _position == ((Component)player).transform.position && _radius == num)
			{
				return _cached;
			}
			List<Container> list = new List<Container>();
			_registry.PruneDestroyed(StorageCrafting.Forget);
			foreach (Container container in _registry.Containers)
			{
				if (ContainerRegistry.IsAccessible(container, player, num))
				{
					container.Load();
					list.Add(container);
				}
			}
			Vector3 position = ((Component)player).transform.position;
			list.Sort(delegate(Container left, Container right)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_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)
				//IL_0027: 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_0032: 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)
				Vector3 val = ((Component)left).transform.position - position;
				float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
				val = ((Component)right).transform.position - position;
				int num2 = sqrMagnitude.CompareTo(((Vector3)(ref val)).sqrMagnitude);
				return (num2 == 0) ? ((Object)left).GetInstanceID().CompareTo(((Object)right).GetInstanceID()) : num2;
			});
			_cached = list;
			_player = player;
			_position = position;
			_radius = num;
			_frame = Time.frameCount;
			return list;
		}
	}
	[HarmonyPatch(typeof(Container), "Interact")]
	internal static class PendingContainerInteractionPatch
	{
		[HarmonyPrefix]
		private static bool BeforeInteract(Container __instance, Humanoid character, bool hold, ref bool __result)
		{
			if (!StorageCrafting.IsBusy(__instance))
			{
				StorageCrafting.PrepareManualOpen(__instance, character, hold);
				return true;
			}
			((Character)character).Message((MessageType)2, "$msg_inuse", 0, (Sprite)null, false);
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "OnCraftPressed")]
	internal static class PendingCraftPatch
	{
		[HarmonyPrefix]
		private static bool BeforePress()
		{
			if (!StorageCrafting.IsPending)
			{
				return true;
			}
			Player localPlayer = Player.m_localPlayer;
			if (localPlayer != null)
			{
				((Character)localPlayer).Message((MessageType)2, "$msg_inuse", 0, (Sprite)null, false);
			}
			return false;
		}
	}
	public sealed class RecipeStorage : IDisposable
	{
		private const string HarmonyOwner = "hoose.valheim.sharedrecipestorage";

		private static readonly Dictionary<bool, RecipeStorage> _clients = new Dictionary<bool, RecipeStorage>();

		private static Harmony _harmony;

		private static RecipeStorage _active;

		private readonly Action<IEnumerator> _startCoroutine;

		private readonly Action _stopCoroutines;

		private readonly Action<string> _warning;

		private readonly Action<string> _error;

		private readonly Func<bool> _enabled;

		private readonly Func<float> _radius;

		private readonly bool _food;

		private float Radius => StorageRange.Clamp(_radius?.Invoke() ?? 20f);

		private RecipeStorage(bool food, Action<IEnumerator> startCoroutine, Action stopCoroutines, Action<string> warning, Action<string> error, Func<bool> enabled, Func<float> radius)
		{
			_food = food;
			_startCoroutine = startCoroutine;
			_stopCoroutines = stopCoroutines;
			_warning = warning;
			_error = error;
			_enabled = enabled;
			_radius = radius;
		}

		public static RecipeStorage Register(bool food, Action<IEnumerator> startCoroutine, Action stopCoroutines, Action<string> warning, Action<string> error, Func<bool> enabled, Func<float> radius = null)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			if (startCoroutine == null || stopCoroutines == null || warning == null || error == null || enabled == null)
			{
				throw new ArgumentNullException("startCoroutine", "Recipe-storage callbacks must not be null.");
			}
			if (_clients.ContainsKey(food))
			{
				throw new InvalidOperationException("A recipe-storage client is already registered for this station category.");
			}
			if (_clients.Count == 0)
			{
				Harmony val = new Harmony("hoose.valheim.sharedrecipestorage");
				try
				{
					Type[] array = (from type2 in typeof(RecipeStorage).Assembly.GetTypes()
						where type2.Namespace == typeof(RecipeStorage).Namespace && type2.IsDefined(typeof(HarmonyPatch), inherit: false)
						select type2).ToArray();
					Type[] array2 = array;
					foreach (Type type in array2)
					{
						val.CreateClassProcessor(type).Patch();
					}
					IEnumerable<MethodInfo> enumerable = from method in array.SelectMany((Type type2) => type2.GetMethods(BindingFlags.Static | BindingFlags.NonPublic))
						where method.IsDefined(typeof(HarmonyPrefix), inherit: false) || method.IsDefined(typeof(HarmonyPostfix), inherit: false) || method.IsDefined(typeof(HarmonyFinalizer), inherit: false)
						select method;
					HashSet<MethodInfo> hashSet = (from patch in val.GetPatchedMethods().Select((Func<MethodBase, Patches>)Harmony.GetPatchInfo).SelectMany((Patches info) => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers))
						where patch.owner == "hoose.valheim.sharedrecipestorage"
						select patch.PatchMethod).ToHashSet();
					foreach (MethodInfo item in enumerable)
					{
						if (!hashSet.Contains(item))
						{
							throw new InvalidOperationException("Shared recipe patch was not registered: " + item.DeclaringType.Name + "." + item.Name + ".");
						}
					}
					NearbyStorage.Initialize();
					_harmony = val;
				}
				catch
				{
					val.UnpatchSelf();
					NearbyStorage.Clear();
					throw;
				}
			}
			RecipeStorage recipeStorage = new Recipe