Decompiled source of WiresBalancedCraftFromNearbyChests v0.1.13

WiresBalancedCraftFromNearbyChests.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("WiresBalancedCraftFromNearbyChests")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+d09cf15f6087595620bc3a68c0541798e4299ed9")]
[assembly: AssemblyProduct("WiresBalancedCraftFromNearbyChests")]
[assembly: AssemblyTitle("WiresBalancedCraftFromNearbyChests")]
[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 WiresBalancedCraftFromNearbyChests
{
	[HarmonyPatch(typeof(ZDO), "Set", new Type[]
	{
		typeof(int),
		typeof(string)
	})]
	internal static class ChestTitleZdoSetPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ZDO __instance, int hash)
		{
			if (__instance == null || hash != ZDOVars.s_text)
			{
				return;
			}
			try
			{
				ContainerRegistry.NotifyTitleChanged(__instance);
			}
			finally
			{
			}
		}
	}
	[HarmonyPatch(typeof(ZNetView), "OnDestroy")]
	internal static class RegistryObjectDestroyPatch
	{
		[HarmonyPrefix]
		private static void Prefix(ZNetView __instance)
		{
			try
			{
				PrefixTimed(__instance);
			}
			finally
			{
			}
		}

		private static void PrefixTimed(ZNetView __instance)
		{
			if ((Object)(object)__instance == (Object)null || !ContainerRegistry.TrackedViews.Remove(((Object)__instance).GetInstanceID()))
			{
				return;
			}
			Container[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<Container>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if ((Object)(object)componentsInChildren[i] != (Object)null)
				{
					ContainerRegistry.Unregister(componentsInChildren[i]);
				}
			}
			Smelter componentInChildren = ((Component)__instance).GetComponentInChildren<Smelter>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				RefillTargetRegistry.Unregister((Component)(object)componentInChildren);
			}
			Fireplace componentInChildren2 = ((Component)__instance).GetComponentInChildren<Fireplace>(true);
			if ((Object)(object)componentInChildren2 != (Object)null)
			{
				RefillTargetRegistry.Unregister((Component)(object)componentInChildren2);
			}
			CookingStation componentInChildren3 = ((Component)__instance).GetComponentInChildren<CookingStation>(true);
			if ((Object)(object)componentInChildren3 != (Object)null)
			{
				RefillTargetRegistry.Unregister((Component)(object)componentInChildren3);
			}
			Fermenter componentInChildren4 = ((Component)__instance).GetComponentInChildren<Fermenter>(true);
			if ((Object)(object)componentInChildren4 != (Object)null)
			{
				RefillTargetRegistry.Unregister((Component)(object)componentInChildren4);
			}
			Turret componentInChildren5 = ((Component)__instance).GetComponentInChildren<Turret>(true);
			if ((Object)(object)componentInChildren5 != (Object)null)
			{
				RefillTargetRegistry.Unregister((Component)(object)componentInChildren5);
			}
			ShieldGenerator componentInChildren6 = ((Component)__instance).GetComponentInChildren<ShieldGenerator>(true);
			if ((Object)(object)componentInChildren6 != (Object)null)
			{
				RefillTargetRegistry.Unregister((Component)(object)componentInChildren6);
			}
			Catapult componentInChildren7 = ((Component)__instance).GetComponentInChildren<Catapult>(true);
			if ((Object)(object)componentInChildren7 != (Object)null)
			{
				RefillTargetRegistry.Unregister((Component)(object)componentInChildren7);
			}
		}
	}
	[HarmonyPatch(typeof(ZDO), "Set", new Type[]
	{
		typeof(string),
		typeof(string)
	})]
	internal static class ChestTitleZdoStringSetPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ZDO __instance, string name)
		{
			if (__instance != null && string.Equals(name, "text", StringComparison.Ordinal))
			{
				ContainerRegistry.NotifyTitleChanged(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(CraftingStation), "Start")]
	internal static class CraftingStationStartGraphPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			ConnectionVisuals.NotifyGraphChanged();
		}
	}
	[HarmonyPatch(typeof(CraftingStation), "OnDestroy")]
	internal static class CraftingStationDestroyGraphPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			ConnectionVisuals.NotifyGraphChanged();
		}
	}
	internal static class ConnectionParticleSafety
	{
		private static readonly HashSet<int> LoggedPrefabs = new HashSet<int>();

		internal static void Prepare(GameObject instance, GameObject prefab)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			int num = 0;
			ParticleSystem[] componentsInChildren = instance.GetComponentsInChildren<ParticleSystem>(true);
			foreach (ParticleSystem val in componentsInChildren)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				VelocityOverLifetimeModule velocityOverLifetime = val.velocityOverLifetime;
				if (((VelocityOverLifetimeModule)(ref velocityOverLifetime)).enabled)
				{
					MinMaxCurve x = ((VelocityOverLifetimeModule)(ref velocityOverLifetime)).x;
					MinMaxCurve y = ((VelocityOverLifetimeModule)(ref velocityOverLifetime)).y;
					MinMaxCurve z = ((VelocityOverLifetimeModule)(ref velocityOverLifetime)).z;
					if (((MinMaxCurve)(ref x)).mode != ((MinMaxCurve)(ref y)).mode || ((MinMaxCurve)(ref x)).mode != ((MinMaxCurve)(ref z)).mode)
					{
						((VelocityOverLifetimeModule)(ref velocityOverLifetime)).x = ToTwoCurves(x);
						((VelocityOverLifetimeModule)(ref velocityOverLifetime)).y = ToTwoCurves(y);
						((VelocityOverLifetimeModule)(ref velocityOverLifetime)).z = ToTwoCurves(z);
						num++;
					}
				}
			}
			if (num > 0 && (Object)(object)prefab != (Object)null && LoggedPrefabs.Add(((Object)prefab).GetInstanceID()) && Plugin.Log != null)
			{
				Plugin.Log.LogInfo((object)("Normalized mismatched particle velocity axes in " + num + " connection effect(s) from " + ((Object)prefab).name + " (only Balanced Craft clones were modified)."));
			}
		}

		private static MinMaxCurve ToTwoCurves(MinMaxCurve value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected I4, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			ParticleSystemCurveMode mode = ((MinMaxCurve)(ref value)).mode;
			switch ((int)mode)
			{
			case 2:
				return value;
			case 1:
				return new MinMaxCurve(((MinMaxCurve)(ref value)).curveMultiplier, ((MinMaxCurve)(ref value)).curve, ((MinMaxCurve)(ref value)).curve);
			case 3:
				return new MinMaxCurve(1f, ConstantCurve(((MinMaxCurve)(ref value)).constantMin), ConstantCurve(((MinMaxCurve)(ref value)).constantMax));
			default:
			{
				AnimationCurve val = ConstantCurve(((MinMaxCurve)(ref value)).constant);
				return new MinMaxCurve(1f, val, val);
			}
			}
		}

		private static AnimationCurve ConstantCurve(float value)
		{
			return AnimationCurve.Linear(0f, value, 1f, value);
		}

		internal static void Cleanup()
		{
			LoggedPrefabs.Clear();
		}
	}
	internal static class ConnectionVisuals
	{
		private enum VisualMode
		{
			None,
			Station,
			RefillTarget,
			ChestStation,
			ChestRefill,
			Tool
		}

		private struct BeamKey : IEquatable<BeamKey>
		{
			internal int ContainerId;

			internal int TargetId;

			internal bool FromPlayer;

			public bool Equals(BeamKey other)
			{
				if (ContainerId == other.ContainerId && TargetId == other.TargetId)
				{
					return FromPlayer == other.FromPlayer;
				}
				return false;
			}

			public override bool Equals(object obj)
			{
				if (obj is BeamKey)
				{
					return Equals((BeamKey)obj);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return (((ContainerId * 397) ^ TargetId) * 397) ^ (FromPlayer ? 1 : 0);
			}
		}

		private sealed class Beam
		{
			internal BeamKey Key;

			internal Container Container;

			internal Component Target;

			internal bool FromPlayer;

			internal GameObject Prefab;

			internal GameObject Instance;
		}

		private sealed class FadingBeam
		{
			internal GameObject Instance;

			internal GameObject Prefab;

			internal BeamKey Key;

			internal ParticleSystem[] Particles;

			internal float Started;
		}

		private static readonly Dictionary<BeamKey, Beam> Beams = new Dictionary<BeamKey, Beam>();

		private static readonly List<FadingBeam> Fading = new List<FadingBeam>();

		private const float MaxFadeSeconds = 6f;

		private static readonly HashSet<BeamKey> Desired = new HashSet<BeamKey>();

		private static readonly List<BeamKey> RemoveKeys = new List<BeamKey>();

		private static readonly Dictionary<int, Stack<GameObject>> Pool = new Dictionary<int, Stack<GameObject>>();

		private static readonly FieldInfo AllExtensionsField = AccessTools.Field(typeof(StationExtension), "m_allExtensions");

		private static readonly string[] KnownExtensionPrefabs = new string[10] { "piece_workbench_ext1", "piece_workbench_ext2", "piece_workbench_ext3", "piece_workbench_ext4", "forge_ext1", "forge_ext2", "forge_ext3", "forge_ext4", "forge_ext5", "forge_ext6" };

		private const float LazyGraphDelay = 0.12f;

		private const float MovingGraphRefreshSeconds = 0.25f;

		private const int BeamCreatesPerFrame = 1;

		private static GameObject _genericConnectionPrefab;

		private static VisualMode _mode;

		private static int _focusId;

		private static string _routeId;

		private static CraftingStation _station;

		private static Component _refillTarget;

		private static Container _chest;

		private static ItemData _tool;

		private static bool _dirty = true;

		private static float _rebuildNotBefore;

		private static float _nextMovingGraphRefresh;

		private static GameObject _lastHover;

		private static bool _lastInBuildUi;

		private static ItemData _lastTool;

		private static bool _contextActive;

		private static bool _contextCacheInvalid;

		private static readonly Dictionary<int, Collider> Colliders = new Dictionary<int, Collider>();

		internal static bool Busy
		{
			get
			{
				if (Fading.Count > 0 || _dirty)
				{
					return true;
				}
				if (Beams.Count == 0)
				{
					return false;
				}
				foreach (Beam value in Beams.Values)
				{
					if (value != null && (Object)(object)value.Instance == (Object)null && (Object)(object)value.Prefab != (Object)null && (Object)(object)value.Container != (Object)null)
					{
						return true;
					}
				}
				if (_mode != VisualMode.Tool)
				{
					return HasMovingBeam();
				}
				return true;
			}
		}

		internal static void HoverUpdated(Player player)
		{
			if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			if (!VisualsEnabled())
			{
				if (_contextActive)
				{
					_contextActive = false;
					_lastHover = null;
					_lastTool = null;
					_lastInBuildUi = false;
					_contextCacheInvalid = true;
					CleanupActive();
					ResetContext();
					_dirty = false;
				}
				return;
			}
			_contextActive = true;
			GameObject hoverObject = ((Humanoid)player).GetHoverObject();
			bool flag = Hud.InBuildUi();
			ItemData rightItem = ((Humanoid)player).RightItem;
			if (_contextCacheInvalid || hoverObject != _lastHover || flag != _lastInBuildUi || rightItem != _lastTool)
			{
				_contextCacheInvalid = false;
				_lastHover = hoverObject;
				_lastInBuildUi = flag;
				_lastTool = rightItem;
				PollContext(player);
			}
			if (_mode != VisualMode.None && Time.time >= _nextMovingGraphRefresh && ContextUsesMovingContainers())
			{
				_nextMovingGraphRefresh = Time.time + 0.25f;
				_dirty = true;
				_rebuildNotBefore = 0f;
				Plugin.Wake();
			}
		}

		internal static void Update()
		{
			UpdateFading();
			Player localPlayer = Player.m_localPlayer;
			if (!VisualsEnabled() || (Object)(object)localPlayer == (Object)null)
			{
				_dirty = false;
				return;
			}
			if (_dirty && Time.time >= _rebuildNotBefore)
			{
				Rebuild(localPlayer);
				_dirty = false;
			}
			ProcessBeamCreationBudget(localPlayer);
			if (Beams.Count > 0 && (_mode == VisualMode.Tool || HasMovingBeam()))
			{
				UpdateBeamTransforms(localPlayer);
			}
		}

		private static bool VisualsEnabled()
		{
			if (ModConfig.Enabled != null && ModConfig.Enabled.Value && ModConfig.ShowConnections != null)
			{
				return ModConfig.ShowConnections.Value;
			}
			return false;
		}

		private static bool ContextUsesMovingContainers()
		{
			if ((Object)(object)_chest != (Object)null && ContainerRegistry.IsMoving(_chest))
			{
				return true;
			}
			string text = _routeId;
			if (string.IsNullOrEmpty(text) && _mode == VisualMode.Station && (Object)(object)_station != (Object)null)
			{
				text = RouteRegistry.EnsureStation(_station)?.Id;
			}
			return ContainerRegistry.HasMovingForRoute(text);
		}

		private static bool HasMovingBeam()
		{
			foreach (Beam value in Beams.Values)
			{
				if (value != null && ContainerRegistry.IsMoving(value.Container))
				{
					return true;
				}
			}
			return false;
		}

		private static void PollContext(Player player)
		{
			GameObject hoverObject = ((Humanoid)player).GetHoverObject();
			if ((Object)(object)hoverObject != (Object)null)
			{
				CraftingStation componentInParent = hoverObject.GetComponentInParent<CraftingStation>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					SetContext(VisualMode.Station, ((Object)componentInParent).GetInstanceID(), null, componentInParent, null, null, null);
					return;
				}
				Component val = RefillTargetRegistry.FindHoveredTarget(hoverObject);
				if ((Object)(object)val != (Object)null)
				{
					RouteDefinition routeDefinition = RefillRouting.Resolve(val);
					if (routeDefinition != null)
					{
						SetContext(VisualMode.RefillTarget, ((Object)val).GetInstanceID(), routeDefinition.Id, null, val, null, null);
						return;
					}
				}
				Container componentInParent2 = hoverObject.GetComponentInParent<Container>();
				if ((Object)(object)componentInParent2 != (Object)null)
				{
					RouteDefinition routeDefinition2 = RouteRegistry.Get(ContainerRegistry.GetAssignedRouteId(componentInParent2));
					if (routeDefinition2 != null && routeDefinition2.Kind == RouteKind.Station)
					{
						SetContext(VisualMode.ChestStation, ((Object)componentInParent2).GetInstanceID(), routeDefinition2.Id, null, null, componentInParent2, null);
						return;
					}
					if (routeDefinition2 != null && routeDefinition2.Kind == RouteKind.Refill)
					{
						SetContext(VisualMode.ChestRefill, ((Object)componentInParent2).GetInstanceID(), routeDefinition2.Id, null, null, componentInParent2, null);
						return;
					}
				}
			}
			ItemData rightItem = ((Humanoid)player).RightItem;
			if (Hud.InBuildUi() && rightItem != null && rightItem.m_shared != null && (Object)(object)rightItem.m_shared.m_buildPieces != (Object)null)
			{
				RouteDefinition routeDefinition3 = RouteRegistry.EnsureTool(rightItem);
				if (routeDefinition3 != null)
				{
					int focusId = (((Object)(object)rightItem.m_dropPrefab != (Object)null) ? ((Object)rightItem.m_dropPrefab).GetInstanceID() : ((object)rightItem).GetHashCode());
					SetContext(VisualMode.Tool, focusId, routeDefinition3.Id, null, null, null, rightItem);
					return;
				}
			}
			SetContext(VisualMode.None, 0, null, null, null, null, null);
		}

		private static void SetContext(VisualMode mode, int focusId, string routeId, CraftingStation station, Component refillTarget, Container chest, ItemData tool)
		{
			bool num = _mode != mode || _focusId != focusId || !string.Equals(_routeId, routeId, StringComparison.Ordinal);
			_mode = mode;
			_focusId = focusId;
			_routeId = routeId;
			_station = station;
			_refillTarget = refillTarget;
			_chest = chest;
			_tool = tool;
			if (num)
			{
				_dirty = true;
				_rebuildNotBefore = 0f;
				Plugin.Wake();
			}
		}

		private static void Rebuild(Player player)
		{
			try
			{
				RebuildTimed(player);
			}
			finally
			{
			}
		}

		private static void RebuildTimed(Player player)
		{
			Desired.Clear();
			switch (_mode)
			{
			case VisualMode.Station:
				BuildStation(_station);
				break;
			case VisualMode.RefillTarget:
				BuildRefillTarget(_refillTarget);
				break;
			case VisualMode.ChestStation:
				BuildChestStation(_chest);
				break;
			case VisualMode.ChestRefill:
				BuildChestRefill(_chest);
				break;
			case VisualMode.Tool:
				BuildTool(player, _tool);
				break;
			}
			RemoveUndesired();
			UpdateBeamTransforms(player);
		}

		private static void BuildStation(CraftingStation station)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)station == (Object)null)
			{
				return;
			}
			RouteDefinition routeDefinition = RouteRegistry.EnsureStation(station);
			if (routeDefinition != null)
			{
				float stationBuildRange = station.GetStationBuildRange();
				List<Container> matching = ContainerRegistry.GetMatching(new RouteContext
				{
					Definition = routeDefinition,
					Origin = ((Component)station).transform.position,
					Range = stationBuildRange,
					Station = station
				});
				GameObject prefab = FindGenericConnectionPrefab();
				for (int i = 0; i < matching.Count; i++)
				{
					WantBeam(matching[i], (Component)(object)station, fromPlayer: false, prefab);
				}
			}
		}

		private static void BuildRefillTarget(Component target)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)target == (Object)null)
			{
				return;
			}
			RouteDefinition routeDefinition = RefillRouting.Resolve(target);
			if (routeDefinition != null)
			{
				float sharedStationRadius = RangeProvider.GetSharedStationRadius();
				List<Container> matching = ContainerRegistry.GetMatching(new RouteContext
				{
					Definition = routeDefinition,
					Origin = target.transform.position,
					Range = sharedStationRadius
				});
				GameObject prefab = FindGenericConnectionPrefab();
				for (int i = 0; i < matching.Count; i++)
				{
					WantBeam(matching[i], target, fromPlayer: false, prefab);
				}
			}
		}

		private static void BuildChestStation(Container chest)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)chest == (Object)null || !ContainerRegistry.IsUsable(chest))
			{
				return;
			}
			HashSet<string> assignedRouteIds = ContainerRegistry.GetAssignedRouteIds(chest);
			if (assignedRouteIds == null || assignedRouteIds.Count == 0)
			{
				return;
			}
			foreach (CraftingStation instance in CraftingStation.Instances)
			{
				CraftingStation val = instance;
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				RouteDefinition routeDefinition = RouteRegistry.EnsureStation(val);
				if (routeDefinition != null && assignedRouteIds.Contains(routeDefinition.Id))
				{
					float stationBuildRange = val.GetStationBuildRange();
					if (WithinHorizontalRange(((Component)chest).transform.position, ((Component)val).transform.position, stationBuildRange))
					{
						WantBeam(chest, (Component)(object)val, fromPlayer: false, FindGenericConnectionPrefab());
					}
				}
			}
		}

		private static void BuildChestRefill(Container chest)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)chest == (Object)null || !ContainerRegistry.IsUsable(chest))
			{
				return;
			}
			HashSet<string> assignedRouteIds = ContainerRegistry.GetAssignedRouteIds(chest);
			if (assignedRouteIds == null || assignedRouteIds.Count == 0)
			{
				return;
			}
			float sharedStationRadius = RangeProvider.GetSharedStationRadius();
			foreach (RouteDefinition item in RouteRegistry.All)
			{
				if (item == null || item.Kind != RouteKind.Refill || !assignedRouteIds.Contains(item.Id))
				{
					continue;
				}
				if (item.Id == "refill:fermenter")
				{
					RefillTargetRegistry.EnsureFermenterTargets();
				}
				foreach (Component target in RefillTargetRegistry.GetTargets(item))
				{
					if (!((Object)(object)target == (Object)null) && WithinHorizontalRange(((Component)chest).transform.position, target.transform.position, sharedStationRadius))
					{
						WantBeam(chest, target, fromPlayer: false, FindGenericConnectionPrefab());
					}
				}
			}
		}

		private static void BuildTool(Player player, ItemData tool)
		{
			//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)
			if ((Object)(object)player == (Object)null || tool == null)
			{
				return;
			}
			RouteDefinition routeDefinition = RouteRegistry.EnsureTool(tool);
			if (routeDefinition != null)
			{
				float sharedStationRadius = RangeProvider.GetSharedStationRadius();
				List<Container> matching = ContainerRegistry.GetMatching(new RouteContext
				{
					Definition = routeDefinition,
					Origin = ((Component)player).transform.position,
					Range = sharedStationRadius,
					Tool = tool
				});
				GameObject prefab = FindGenericConnectionPrefab();
				for (int i = 0; i < matching.Count; i++)
				{
					WantBeam(matching[i], null, fromPlayer: true, prefab);
				}
			}
		}

		private static bool WithinHorizontalRange(Vector3 a, Vector3 b, float range)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = a - b;
			val.y = 0f;
			return ((Vector3)(ref val)).sqrMagnitude <= range * range;
		}

		private static void WantBeam(Container chest, Component target, bool fromPlayer, GameObject prefab)
		{
			if (!((Object)(object)chest == (Object)null) && !((Object)(object)prefab == (Object)null))
			{
				BeamKey beamKey = new BeamKey
				{
					ContainerId = ((Object)chest).GetInstanceID(),
					TargetId = (((Object)(object)target != (Object)null) ? ((Object)target).GetInstanceID() : 0),
					FromPlayer = fromPlayer
				};
				Desired.Add(beamKey);
				EnsureBeam(beamKey, chest, target, fromPlayer, prefab);
			}
		}

		private static void EnsureBeam(BeamKey key, Container chest, Component target, bool fromPlayer, GameObject prefab)
		{
			if (Beams.TryGetValue(key, out var value))
			{
				if (value != null && (Object)(object)value.Prefab == (Object)(object)prefab)
				{
					value.Container = chest;
					value.Target = target;
					value.FromPlayer = fromPlayer;
					return;
				}
				ReleaseBeam(value);
				Beams.Remove(key);
			}
			Beams.Add(key, new Beam
			{
				Key = key,
				Container = chest,
				Target = target,
				FromPlayer = fromPlayer,
				Prefab = prefab,
				Instance = null
			});
		}

		private static GameObject AcquireInstance(GameObject prefab, BeamKey requestedKey)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)prefab == (Object)null)
			{
				return null;
			}
			GameObject val = null;
			if ((Object)(object)val == (Object)null)
			{
				int instanceID = ((Object)prefab).GetInstanceID();
				if (Pool.TryGetValue(instanceID, out var value))
				{
					while (value.Count > 0 && (Object)(object)val == (Object)null)
					{
						val = value.Pop();
					}
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				val = Object.Instantiate<GameObject>(prefab, Vector3.zero, Quaternion.identity);
				if ((Object)(object)val != (Object)null)
				{
					val.SetActive(false);
					ConnectionParticleSafety.Prepare(val, prefab);
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				val.SetActive(false);
			}
			return val;
		}

		private static void ActivateBeam(GameObject instance)
		{
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			instance.SetActive(true);
			ParticleSystem[] componentsInChildren = instance.GetComponentsInChildren<ParticleSystem>(true);
			foreach (ParticleSystem val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null) && ((Component)val).gameObject.activeInHierarchy)
				{
					val.Stop(false, (ParticleSystemStopBehavior)0);
					val.Play(false);
				}
			}
		}

		private static void ReleaseBeam(Beam beam)
		{
			if (beam == null || (Object)(object)beam.Instance == (Object)null)
			{
				return;
			}
			GameObject instance = beam.Instance;
			beam.Instance = null;
			if ((Object)(object)beam.Prefab == (Object)null)
			{
				Object.Destroy((Object)(object)instance);
				return;
			}
			ParticleSystem[] componentsInChildren = instance.GetComponentsInChildren<ParticleSystem>(true);
			bool flag = false;
			if (instance.activeInHierarchy)
			{
				ParticleSystem[] array = componentsInChildren;
				foreach (ParticleSystem val in array)
				{
					if (!((Object)(object)val == (Object)null) && ((Component)val).gameObject.activeInHierarchy)
					{
						val.Stop(false, (ParticleSystemStopBehavior)1);
						if (val.IsAlive(false))
						{
							flag = true;
						}
					}
				}
			}
			if (!flag)
			{
				ReturnToPool(instance, beam.Prefab);
				return;
			}
			Plugin.Wake();
			Fading.Add(new FadingBeam
			{
				Instance = instance,
				Prefab = beam.Prefab,
				Key = beam.Key,
				Particles = componentsInChildren,
				Started = Time.unscaledTime
			});
		}

		private static void UpdateFading()
		{
			try
			{
				UpdateFadingTimed();
			}
			finally
			{
			}
		}

		private static void UpdateFadingTimed()
		{
			for (int num = Fading.Count - 1; num >= 0; num--)
			{
				FadingBeam fadingBeam = Fading[num];
				if ((Object)(object)fadingBeam.Instance == (Object)null)
				{
					Fading.RemoveAt(num);
				}
				else
				{
					bool flag = false;
					if (Time.unscaledTime - fadingBeam.Started < 6f)
					{
						ParticleSystem[] particles = fadingBeam.Particles;
						foreach (ParticleSystem val in particles)
						{
							if ((Object)(object)val != (Object)null && val.IsAlive(false))
							{
								flag = true;
								break;
							}
						}
					}
					if (!flag)
					{
						Fading.RemoveAt(num);
						ReturnToPool(fadingBeam.Instance, fadingBeam.Prefab);
					}
				}
			}
		}

		private static void ReturnToPool(GameObject instance, GameObject prefab)
		{
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			instance.SetActive(false);
			if ((Object)(object)prefab == (Object)null)
			{
				Object.Destroy((Object)(object)instance);
				return;
			}
			int instanceID = ((Object)prefab).GetInstanceID();
			if (!Pool.TryGetValue(instanceID, out var value))
			{
				value = new Stack<GameObject>();
				Pool.Add(instanceID, value);
			}
			if (value.Count < 64)
			{
				value.Push(instance);
			}
			else
			{
				Object.Destroy((Object)(object)instance);
			}
		}

		private static void RemoveUndesired()
		{
			RemoveKeys.Clear();
			foreach (KeyValuePair<BeamKey, Beam> beam in Beams)
			{
				if (!Desired.Contains(beam.Key) || beam.Value == null || (Object)(object)beam.Value.Container == (Object)null)
				{
					RemoveKeys.Add(beam.Key);
				}
			}
			for (int i = 0; i < RemoveKeys.Count; i++)
			{
				if (Beams.TryGetValue(RemoveKeys[i], out var value))
				{
					ReleaseBeam(value);
				}
				Beams.Remove(RemoveKeys[i]);
			}
		}

		private static void ProcessBeamCreationBudget(Player player)
		{
			int num = 0;
			foreach (Beam value in Beams.Values)
			{
				if (num >= 1)
				{
					break;
				}
				if (value != null && !((Object)(object)value.Instance != (Object)null) && !((Object)(object)value.Prefab == (Object)null) && !((Object)(object)value.Container == (Object)null))
				{
					value.Instance = AcquireInstance(value.Prefab, value.Key);
					if (!((Object)(object)value.Instance == (Object)null))
					{
						UpdateBeamTransform(value, player);
						ActivateBeam(value.Instance);
						num++;
					}
				}
			}
		}

		private static void UpdateBeamTransforms(Player player)
		{
			try
			{
				UpdateBeamTransformsTimed(player);
			}
			finally
			{
			}
		}

		private static void UpdateBeamTransformsTimed(Player player)
		{
			foreach (Beam value in Beams.Values)
			{
				UpdateBeamTransform(value, player);
			}
		}

		private static void UpdateBeamTransform(Beam beam, Player player)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			if (beam == null || (Object)(object)beam.Container == (Object)null || (Object)(object)beam.Instance == (Object)null)
			{
				return;
			}
			Vector3 val;
			Vector3 val2;
			if (beam.FromPlayer)
			{
				if ((Object)(object)player == (Object)null)
				{
					return;
				}
				val = ((Component)player).transform.position + Vector3.up;
				val2 = GetContainerPoint(beam.Container);
			}
			else
			{
				if ((Object)(object)beam.Target == (Object)null)
				{
					return;
				}
				val = GetContainerPoint(beam.Container);
				val2 = GetTargetPoint(beam.Target);
			}
			Vector3 val3 = val2 - val;
			if (!(((Vector3)(ref val3)).sqrMagnitude < 0.0001f))
			{
				Transform transform = beam.Instance.transform;
				transform.position = val;
				transform.rotation = Quaternion.LookRotation(((Vector3)(ref val3)).normalized);
				transform.localScale = new Vector3(1f, 1f, ((Vector3)(ref val3)).magnitude);
			}
		}

		private static Collider ColliderOf(Component owner)
		{
			int instanceID = ((Object)owner).GetInstanceID();
			if (Colliders.TryGetValue(instanceID, out var value) && ((Object)(object)value == (Object)null || Object.op_Implicit((Object)(object)value)))
			{
				return value;
			}
			value = owner.GetComponentInChildren<Collider>();
			if ((Object)(object)value == (Object)null && !(owner is Container))
			{
				Piece componentInParent = owner.GetComponentInParent<Piece>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					value = ((Component)componentInParent).GetComponentInChildren<Collider>();
				}
			}
			if (Colliders.Count > 512)
			{
				Colliders.Clear();
			}
			Colliders[instanceID] = value;
			return value;
		}

		private static Vector3 GetTargetPoint(Component target)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			CraftingStation val = (CraftingStation)(object)((target is CraftingStation) ? target : null);
			if ((Object)(object)val != (Object)null)
			{
				return val.GetConnectionEffectPoint();
			}
			Collider val2 = ColliderOf(target);
			if ((Object)(object)val2 != (Object)null)
			{
				Bounds bounds = val2.bounds;
				return ((Bounds)(ref bounds)).center;
			}
			return target.transform.position + Vector3.up * 0.5f;
		}

		private static Vector3 GetContainerPoint(Container container)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0019: Unknown result type (might be due to invalid IL or missing references)
			Collider val = ColliderOf((Component)(object)container);
			if ((Object)(object)val != (Object)null)
			{
				Bounds bounds = val.bounds;
				return ((Bounds)(ref bounds)).center;
			}
			return ((Component)container).transform.position + Vector3.up * 0.5f;
		}

		private static List<StationExtension> GetLoadedExtensions()
		{
			if (!(AllExtensionsField != null))
			{
				return null;
			}
			return AllExtensionsField.GetValue(null) as List<StationExtension>;
		}

		private static GameObject FindGenericConnectionPrefab()
		{
			if ((Object)(object)_genericConnectionPrefab != (Object)null)
			{
				return _genericConnectionPrefab;
			}
			ZNetScene instance = ZNetScene.instance;
			if ((Object)(object)instance != (Object)null)
			{
				GameObject prefab = instance.GetPrefab("vfx_ExtensionConnection");
				if ((Object)(object)prefab != (Object)null)
				{
					_genericConnectionPrefab = prefab;
					return prefab;
				}
			}
			if ((Object)(object)instance != (Object)null)
			{
				for (int i = 0; i < KnownExtensionPrefabs.Length; i++)
				{
					GameObject prefab2 = instance.GetPrefab(KnownExtensionPrefabs[i]);
					if (!((Object)(object)prefab2 == (Object)null))
					{
						StationExtension componentInChildren = prefab2.GetComponentInChildren<StationExtension>(true);
						if (!((Object)(object)componentInChildren == (Object)null) && IsStandardConnection(componentInChildren.m_connectionPrefab))
						{
							_genericConnectionPrefab = componentInChildren.m_connectionPrefab;
							return _genericConnectionPrefab;
						}
					}
				}
			}
			List<StationExtension> loadedExtensions = GetLoadedExtensions();
			GameObject val = null;
			if (loadedExtensions != null)
			{
				for (int j = 0; j < loadedExtensions.Count; j++)
				{
					StationExtension val2 = loadedExtensions[j];
					if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.m_connectionPrefab == (Object)null))
					{
						if (IsStandardConnection(val2.m_connectionPrefab))
						{
							_genericConnectionPrefab = val2.m_connectionPrefab;
							return _genericConnectionPrefab;
						}
						if ((Object)(object)val == (Object)null)
						{
							val = val2.m_connectionPrefab;
						}
					}
				}
			}
			return val;
		}

		private static bool IsStandardConnection(GameObject prefab)
		{
			if ((Object)(object)prefab != (Object)null)
			{
				return ((Object)prefab).name == "vfx_ExtensionConnection";
			}
			return false;
		}

		internal static void ForceNextContextRefresh()
		{
			_contextCacheInvalid = true;
		}

		internal static void NotifyGraphChanged()
		{
			_contextCacheInvalid = true;
			if (_contextActive)
			{
				_dirty = true;
				_rebuildNotBefore = Mathf.Max(_rebuildNotBefore, Time.time + 0.12f);
				Plugin.Wake();
			}
		}

		internal static void NotifyChestChanged(Container chest)
		{
			NotifyGraphChanged();
			if (!((Object)(object)chest == (Object)null) && !string.IsNullOrEmpty(ContainerRegistry.GetAssignedRouteId(chest)))
			{
				SpawnRenameBurst(chest);
			}
		}

		private static void SpawnRenameBurst(Container chest)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = FindGenericConnectionPrefab();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			GameObject val2 = Object.Instantiate<GameObject>(val, GetContainerPoint(chest), Quaternion.identity);
			if (!((Object)(object)val2 == (Object)null))
			{
				val2.SetActive(false);
				ConnectionParticleSafety.Prepare(val2, val);
				val2.transform.localScale = Vector3.one * 0.3f;
				val2.SetActive(true);
				if ((Object)(object)Plugin.Instance != (Object)null)
				{
					((MonoBehaviour)Plugin.Instance).StartCoroutine(EndBurst(val2));
				}
				else
				{
					Object.Destroy((Object)(object)val2, 3f);
				}
			}
		}

		private static IEnumerator EndBurst(GameObject instance)
		{
			yield return (object)new WaitForSeconds(0.55f);
			if ((Object)(object)instance == (Object)null)
			{
				yield break;
			}
			ParticleSystem[] particles = instance.GetComponentsInChildren<ParticleSystem>(true);
			ParticleSystem[] array = particles;
			foreach (ParticleSystem val in array)
			{
				if ((Object)(object)val != (Object)null)
				{
					val.Stop(false, (ParticleSystemStopBehavior)1);
				}
			}
			float until = Time.unscaledTime + 6f;
			while ((Object)(object)instance != (Object)null && Time.unscaledTime < until)
			{
				bool flag = false;
				array = particles;
				foreach (ParticleSystem val2 in array)
				{
					if ((Object)(object)val2 != (Object)null && val2.IsAlive(false))
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					break;
				}
				yield return null;
			}
			if ((Object)(object)instance != (Object)null)
			{
				Object.Destroy((Object)(object)instance);
			}
		}

		private static void CleanupActive()
		{
			foreach (Beam value in Beams.Values)
			{
				ReleaseBeam(value);
			}
			Beams.Clear();
			Desired.Clear();
			RemoveKeys.Clear();
		}

		private static void ResetContext()
		{
			_mode = VisualMode.None;
			_focusId = 0;
			_routeId = null;
			_station = null;
			_refillTarget = null;
			_chest = null;
			_tool = null;
			_dirty = true;
			_rebuildNotBefore = 0f;
			_nextMovingGraphRefresh = 0f;
		}

		internal static void Cleanup()
		{
			CleanupActive();
			foreach (Stack<GameObject> value in Pool.Values)
			{
				while (value.Count > 0)
				{
					GameObject val = value.Pop();
					if ((Object)(object)val != (Object)null)
					{
						Object.Destroy((Object)(object)val);
					}
				}
			}
			Pool.Clear();
			foreach (FadingBeam item in Fading)
			{
				if ((Object)(object)item.Instance != (Object)null)
				{
					Object.Destroy((Object)(object)item.Instance);
				}
			}
			Fading.Clear();
			ConnectionParticleSafety.Cleanup();
			_genericConnectionPrefab = null;
			ResetContext();
			_lastHover = null;
			_lastTool = null;
			_contextCacheInvalid = false;
			_contextActive = false;
			Colliders.Clear();
		}
	}
	internal static class ContainerRegistry
	{
		private const float CacheSeconds = 0.25f;

		private const float ReconcileIntervalSeconds = 0.25f;

		private static readonly HashSet<Container> Known = new HashSet<Container>();

		private static readonly List<Container> Reconcile = new List<Container>();

		private static readonly Queue<Container> PendingIndex = new Queue<Container>();

		private static readonly Dictionary<string, HashSet<Container>> ByRoute = new Dictionary<string, HashSet<Container>>(StringComparer.Ordinal);

		private static readonly Dictionary<int, HashSet<string>> RoutesByContainer = new Dictionary<int, HashSet<string>>();

		private static readonly Dictionary<int, string> TitleByContainer = new Dictionary<int, string>();

		private static readonly Dictionary<ZDOID, Container> ByZdo = new Dictionary<ZDOID, Container>();

		private static readonly List<Container> Matching = new List<Container>();

		private static readonly Func<Container, long, bool> CheckAccess = AccessTools.MethodDelegate<Func<Container, long, bool>>(AccessTools.Method(typeof(Container), "CheckAccess", new Type[1] { typeof(long) }, (Type[])null), (object)null, true);

		internal static int MatchingVersion;

		private static readonly Dictionary<Container, string> SortTitles = new Dictionary<Container, string>();

		private static float _nextRefresh;

		private static float _nextReconcile;

		private static int _reconcileCursor;

		private static bool _fullReindexPending;

		private static int _fullReindexCursor;

		private static string _cachedRouteId;

		private static Vector3 _cachedOrigin;

		private static float _cachedRange;

		internal static readonly HashSet<int> TrackedViews = new HashSet<int>();

		internal static bool Busy
		{
			get
			{
				if (PendingIndex.Count <= 0)
				{
					return _fullReindexPending;
				}
				return true;
			}
		}

		internal static void Register(Container container)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)container == (Object)null) && Known.Add(container))
			{
				Reconcile.Add(container);
				PendingIndex.Enqueue(container);
				Plugin.Wake();
				ZNetView val = GetNetView(container);
				if ((Object)(object)val == (Object)null)
				{
					val = ((Component)container).GetComponentInParent<ZNetView>();
				}
				if ((Object)(object)val != (Object)null)
				{
					TrackedViews.Add(((Object)val).GetInstanceID());
				}
				ZNetView netView = GetNetView(container);
				if ((Object)(object)netView != (Object)null && netView.IsValid() && netView.GetZDO() != null)
				{
					ByZdo[netView.GetZDO().m_uid] = container;
				}
			}
		}

		internal static void Unregister(Container container)
		{
			if (!((Object)(object)container == (Object)null))
			{
				Known.Remove(container);
				Reconcile.Remove(container);
				RemoveIndex(container);
				Invalidate();
				ConnectionVisuals.NotifyGraphChanged();
			}
		}

		internal static void Clear()
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			TrackedViews.Clear();
			Known.Clear();
			Reconcile.Clear();
			PendingIndex.Clear();
			ByRoute.Clear();
			RoutesByContainer.Clear();
			TitleByContainer.Clear();
			ByZdo.Clear();
			Matching.Clear();
			_nextRefresh = 0f;
			_nextReconcile = 0f;
			_reconcileCursor = 0;
			_fullReindexPending = false;
			_fullReindexCursor = 0;
			_cachedRouteId = null;
			_cachedOrigin = Vector3.zero;
			_cachedRange = 0f;
		}

		internal static void Invalidate()
		{
			_nextRefresh = 0f;
			_cachedRouteId = null;
		}

		internal static void ReindexAll()
		{
			ByRoute.Clear();
			RoutesByContainer.Clear();
			TitleByContainer.Clear();
			_fullReindexPending = Reconcile.Count > 0;
			_fullReindexCursor = 0;
			if (_fullReindexPending)
			{
				Plugin.Wake();
			}
			Invalidate();
			ConnectionVisuals.NotifyGraphChanged();
		}

		internal static void TickPending()
		{
			while (PendingIndex.Count > 0)
			{
				Container val = PendingIndex.Dequeue();
				if (!((Object)(object)val == (Object)null))
				{
					Reindex(val, force: false);
					return;
				}
			}
			if (!_fullReindexPending)
			{
				return;
			}
			while (_fullReindexCursor < Reconcile.Count)
			{
				Container val2 = Reconcile[_fullReindexCursor++];
				if (!((Object)(object)val2 == (Object)null))
				{
					Reindex(val2, force: true);
					return;
				}
			}
			_fullReindexPending = false;
			_fullReindexCursor = 0;
		}

		internal static void TickReconcile()
		{
			if (Busy || Reconcile.Count == 0 || Time.time < _nextReconcile)
			{
				return;
			}
			_nextReconcile = Time.time + 0.25f;
			if (_reconcileCursor >= Reconcile.Count)
			{
				_reconcileCursor = 0;
			}
			int reconcileCursor = _reconcileCursor;
			Container val = Reconcile[reconcileCursor];
			if ((Object)(object)val == (Object)null)
			{
				Reconcile.RemoveAt(reconcileCursor);
				if (_reconcileCursor >= Reconcile.Count)
				{
					_reconcileCursor = 0;
				}
			}
			else
			{
				_reconcileCursor++;
				Reindex(val, force: false);
			}
		}

		internal static void NotifyTitleChanged(Container container)
		{
			if (!((Object)(object)container == (Object)null))
			{
				int instanceID = ((Object)container).GetInstanceID();
				TitleByContainer.TryGetValue(instanceID, out var value);
				string b = GetCustomTitle(container) ?? "";
				if (!string.Equals(value, b, StringComparison.Ordinal))
				{
					Reindex(container, force: true);
					Invalidate();
					ConnectionVisuals.NotifyChestChanged(container);
				}
			}
		}

		internal static void NotifyTitleChanged(ZDO zdo)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if (zdo != null && ByZdo.TryGetValue(zdo.m_uid, out var value) && (Object)(object)value != (Object)null)
			{
				NotifyTitleChanged(value);
			}
		}

		internal static string GetAssignedRouteId(Container container)
		{
			HashSet<string> assignedRouteIds = GetAssignedRouteIds(container);
			if (assignedRouteIds == null || assignedRouteIds.Count == 0)
			{
				return null;
			}
			string text = RouteRegistry.ClassifyTitle(GetCustomTitle(container));
			if (!string.IsNullOrEmpty(text) && assignedRouteIds.Contains(text))
			{
				return text;
			}
			foreach (RouteDefinition item in RouteRegistry.All)
			{
				if (item != null && assignedRouteIds.Contains(item.Id))
				{
					return item.Id;
				}
			}
			return null;
		}

		internal static HashSet<string> GetAssignedRouteIds(Container container)
		{
			if ((Object)(object)container == (Object)null)
			{
				return null;
			}
			int instanceID = ((Object)container).GetInstanceID();
			if (!TitleByContainer.ContainsKey(instanceID))
			{
				Reindex(container, force: true);
			}
			else
			{
				Reindex(container, force: false);
			}
			if (!RoutesByContainer.TryGetValue(instanceID, out var value))
			{
				return null;
			}
			return value;
		}

		internal static List<Container> GetMatching(RouteContext context)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			if (context == null || context.Definition == null)
			{
				Matching.Clear();
				return Matching;
			}
			if (_cachedRouteId == context.Definition.Id && Mathf.Abs(_cachedRange - context.Range) < 0.01f)
			{
				if (context.Tool == null)
				{
					Vector3 val = _cachedOrigin - context.Origin;
					if (!(((Vector3)(ref val)).sqrMagnitude < 0.0625f))
					{
						goto IL_008b;
					}
				}
				if (Time.time < _nextRefresh)
				{
					return Matching;
				}
			}
			goto IL_008b;
			IL_008b:
			_cachedRouteId = context.Definition.Id;
			_cachedOrigin = context.Origin;
			_cachedRange = context.Range;
			_nextRefresh = Time.time + 0.25f;
			Refresh(context);
			return Matching;
		}

		internal static bool IsAssignedTo(Container container, RouteDefinition route)
		{
			if ((Object)(object)container == (Object)null || route == null)
			{
				return false;
			}
			ZNetView netView = GetNetView(container);
			if ((Object)(object)netView == (Object)null || !netView.IsValid() || netView.GetZDO() == null)
			{
				return false;
			}
			return GetAssignedRouteIds(container)?.Contains(route.Id) ?? false;
		}

		internal static bool IsUsable(Container container)
		{
			if ((Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)Game.instance == (Object)null)
			{
				return false;
			}
			return IsUsable(container, Game.instance.GetPlayerProfile().GetPlayerID());
		}

		internal static bool IsUsable(Container container, long playerId)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)container == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null || container.GetInventory() == null)
			{
				return false;
			}
			ZNetView netView = GetNetView(container);
			if ((Object)(object)netView == (Object)null || !netView.IsValid())
			{
				return false;
			}
			if (CheckAccess != null && !CheckAccess(container, playerId))
			{
				return false;
			}
			if (container.m_checkGuardStone && !PrivateArea.CheckAccess(((Component)container).transform.position, 0f, false, false))
			{
				return false;
			}
			ZDO zDO = netView.GetZDO();
			if (!MultiUserChestCompat.Active && zDO != null && !netView.IsOwner() && zDO.GetInt(ZDOVars.s_inUse, 0) == 1)
			{
				return false;
			}
			return true;
		}

		internal static bool IsMoving(Container container)
		{
			if ((Object)(object)container != (Object)null)
			{
				return (Object)(object)container.m_rootObjectOverride != (Object)null;
			}
			return false;
		}

		internal static bool HasMovingForRoute(string routeId)
		{
			if (string.IsNullOrEmpty(routeId))
			{
				return false;
			}
			if (!ByRoute.TryGetValue(routeId, out var value))
			{
				return false;
			}
			foreach (Container item in value)
			{
				if (IsMoving(item))
				{
					return true;
				}
			}
			return false;
		}

		internal static ZNetView GetNetView(Container container)
		{
			if ((Object)(object)container == (Object)null)
			{
				return null;
			}
			if (!((Object)(object)container.m_rootObjectOverride != (Object)null))
			{
				return ((Component)container).GetComponent<ZNetView>();
			}
			return container.m_rootObjectOverride;
		}

		internal static bool TryTakeOwnership(Container container)
		{
			ZNetView netView = GetNetView(container);
			if ((Object)(object)netView == (Object)null || !netView.IsValid())
			{
				return false;
			}
			if (!netView.IsOwner())
			{
				netView.ClaimOwnership();
			}
			return netView.IsOwner();
		}

		private static void Reindex(Container container, bool force)
		{
			try
			{
				ReindexTimed(container, force);
			}
			finally
			{
			}
		}

		private static void ReindexTimed(Container container, bool force)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)container == (Object)null)
			{
				return;
			}
			ZNetView netView = GetNetView(container);
			if ((Object)(object)netView == (Object)null || !netView.IsValid() || netView.GetZDO() == null)
			{
				return;
			}
			ZDO zDO = netView.GetZDO();
			ByZdo[zDO.m_uid] = container;
			string text = zDO.GetString(ZDOVars.s_text, "") ?? "";
			int instanceID = ((Object)container).GetInstanceID();
			if (!force && TitleByContainer.TryGetValue(instanceID, out var value) && string.Equals(value, text, StringComparison.Ordinal))
			{
				return;
			}
			RoutesByContainer.TryGetValue(instanceID, out var value2);
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			string text2 = RouteRegistry.ClassifyTitle(text);
			if (!string.IsNullOrEmpty(text2))
			{
				hashSet.Add(text2);
			}
			SharedRouteRegistry.AddMatchingRoutes(text, hashSet);
			bool flag = ((value2 == null) ? (hashSet.Count > 0) : (!value2.SetEquals(hashSet)));
			if (value2 != null)
			{
				foreach (string item in value2)
				{
					if (ByRoute.TryGetValue(item, out var value3))
					{
						value3.Remove(container);
						if (value3.Count == 0)
						{
							ByRoute.Remove(item);
						}
					}
				}
			}
			if (hashSet.Count > 0)
			{
				foreach (string item2 in hashSet)
				{
					if (!ByRoute.TryGetValue(item2, out var value4))
					{
						value4 = new HashSet<Container>();
						ByRoute.Add(item2, value4);
					}
					value4.Add(container);
				}
				RoutesByContainer[instanceID] = hashSet;
			}
			else
			{
				RoutesByContainer.Remove(instanceID);
			}
			TitleByContainer[instanceID] = text;
			if (flag)
			{
				Invalidate();
				ConnectionVisuals.NotifyGraphChanged();
			}
		}

		private static void RemoveIndex(Container container)
		{
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)container == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)container).GetInstanceID();
			if (RoutesByContainer.TryGetValue(instanceID, out var value))
			{
				foreach (string item in value)
				{
					if (ByRoute.TryGetValue(item, out var value2))
					{
						value2.Remove(container);
						if (value2.Count == 0)
						{
							ByRoute.Remove(item);
						}
					}
				}
			}
			RoutesByContainer.Remove(instanceID);
			TitleByContainer.Remove(instanceID);
			ZNetView netView = GetNetView(container);
			if ((Object)(object)netView != (Object)null && netView.GetZDO() != null)
			{
				ByZdo.Remove(netView.GetZDO().m_uid);
			}
		}

		private static void Refresh(RouteContext context)
		{
			try
			{
				RefreshTimed(context);
			}
			finally
			{
			}
		}

		private static void RefreshTimed(RouteContext context)
		{
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: 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)
			Matching.Clear();
			MatchingVersion++;
			float num = context.Range * context.Range;
			if (!ByRoute.TryGetValue(context.Definition.Id, out var value) || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)Game.instance == (Object)null)
			{
				return;
			}
			long playerID = Game.instance.GetPlayerProfile().GetPlayerID();
			foreach (Container item in value)
			{
				if (!((Object)(object)item == (Object)null))
				{
					Vector3 val = ((Component)item).transform.position - context.Origin;
					val.y = 0f;
					if (!(((Vector3)(ref val)).sqrMagnitude > num) && IsUsable(item, playerID))
					{
						Matching.Add(item);
					}
				}
			}
			SortTitles.Clear();
			for (int i = 0; i < Matching.Count; i++)
			{
				SortTitles[Matching[i]] = GetCustomTitle(Matching[i]);
			}
			Matching.Sort(delegate(Container a, Container b)
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Unknown result type (might be due to invalid IL or missing references)
				string left = SortTitles[a];
				string right = SortTitles[b];
				int num2 = WindowsLogicalCompare(left, right);
				if (num2 != 0)
				{
					return num2;
				}
				Vector3 val2 = ((Component)a).transform.position - context.Origin;
				float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
				val2 = ((Component)b).transform.position - context.Origin;
				float sqrMagnitude2 = ((Vector3)(ref val2)).sqrMagnitude;
				return sqrMagnitude.CompareTo(sqrMagnitude2);
			});
		}

		internal static string GetCustomTitle(Container container)
		{
			ZNetView netView = GetNetView(container);
			if ((Object)(object)netView == (Object)null || !netView.IsValid() || netView.GetZDO() == null)
			{
				return "";
			}
			return netView.GetZDO().GetString(ZDOVars.s_text, "");
		}

		private static int WindowsLogicalCompare(string left, string right)
		{
			left = left ?? "";
			right = right ?? "";
			if (left.Length != right.Length)
			{
				if (left.StartsWith(right, StringComparison.OrdinalIgnoreCase))
				{
					return -1;
				}
				if (right.StartsWith(left, StringComparison.OrdinalIgnoreCase))
				{
					return 1;
				}
			}
			int i = 0;
			int j = 0;
			while (i < left.Length && j < right.Length)
			{
				char c = left[i];
				char c2 = right[j];
				if (char.IsDigit(c) && char.IsDigit(c2))
				{
					int num = i;
					int num2 = j;
					for (; i < left.Length && left[i] == '0'; i++)
					{
					}
					for (; j < right.Length && right[j] == '0'; j++)
					{
					}
					int num3 = i;
					int num4 = j;
					for (; i < left.Length && char.IsDigit(left[i]); i++)
					{
					}
					for (; j < right.Length && char.IsDigit(right[j]); j++)
					{
					}
					int num5 = i - num3;
					int num6 = j - num4;
					if (num5 != num6)
					{
						return num5.CompareTo(num6);
					}
					for (int k = 0; k < num5; k++)
					{
						int num7 = left[num3 + k].CompareTo(right[num4 + k]);
						if (num7 != 0)
						{
							return num7;
						}
					}
					int num8 = i - num;
					int num9 = j - num2;
					if (num8 != num9)
					{
						return num8.CompareTo(num9);
					}
				}
				else
				{
					char c3 = char.ToUpperInvariant(c);
					char c4 = char.ToUpperInvariant(c2);
					if (c3 != c4)
					{
						return c3.CompareTo(c4);
					}
					i++;
					j++;
				}
			}
			return (left.Length - i).CompareTo(right.Length - j);
		}
	}
	internal static class MethodSwaps
	{
		internal static readonly MethodInfo CountItemsFrom = AccessTools.Method(typeof(Inventory), "CountItems", new Type[3]
		{
			typeof(string),
			typeof(int),
			typeof(bool)
		}, (Type[])null);

		internal static readonly MethodInfo CountItemsTo = AccessTools.Method(typeof(InventoryBridge), "CountItems", (Type[])null, (Type[])null);

		internal static readonly MethodInfo HaveItemFrom = AccessTools.Method(typeof(Inventory), "HaveItem", new Type[2]
		{
			typeof(string),
			typeof(bool)
		}, (Type[])null);

		internal static readonly MethodInfo HaveItemTo = AccessTools.Method(typeof(InventoryBridge), "HaveItem", (Type[])null, (Type[])null);

		internal static readonly MethodInfo GetItemFrom = AccessTools.Method(typeof(Inventory), "GetItem", new Type[3]
		{
			typeof(string),
			typeof(int),
			typeof(bool)
		}, (Type[])null);

		internal static readonly MethodInfo GetItemTo = AccessTools.Method(typeof(InventoryBridge), "GetItem", (Type[])null, (Type[])null);

		internal static readonly MethodInfo RemoveItemFrom = AccessTools.Method(typeof(Inventory), "RemoveItem", new Type[4]
		{
			typeof(string),
			typeof(int),
			typeof(int),
			typeof(bool)
		}, (Type[])null);

		internal static readonly MethodInfo RemoveItemTo = AccessTools.Method(typeof(InventoryBridge), "RemoveItem", (Type[])null, (Type[])null);
	}
	internal static class Redirect
	{
		internal static IEnumerable<CodeInstruction> Calls(IEnumerable<CodeInstruction> instructions, params KeyValuePair<MethodInfo, MethodInfo>[] swaps)
		{
			foreach (CodeInstruction instruction in instructions)
			{
				for (int i = 0; i < swaps.Length; i++)
				{
					if (CodeInstructionExtensions.Calls(instruction, swaps[i].Key))
					{
						instruction.opcode = OpCodes.Call;
						instruction.operand = swaps[i].Value;
						break;
					}
				}
				yield return instruction;
			}
		}

		internal static KeyValuePair<MethodInfo, MethodInfo> Swap(MethodInfo from, MethodInfo to)
		{
			return new KeyValuePair<MethodInfo, MethodInfo>(from, to);
		}
	}
	[HarmonyPatch(typeof(Container), "Awake")]
	internal static class ContainerAwakePatch
	{
		[HarmonyPostfix]
		private static void Postfix(Container __instance)
		{
			ContainerRegistry.Register(__instance);
		}
	}
	[HarmonyPatch(typeof(Player), "HaveRequirementItems", new Type[]
	{
		typeof(Recipe),
		typeof(bool),
		typeof(int),
		typeof(int)
	})]
	internal static class HaveRequirementItemsPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return Redirect.Calls(instructions, Redirect.Swap(MethodSwaps.CountItemsFrom, MethodSwaps.CountItemsTo));
		}
	}
	[HarmonyPatch]
	internal static class GetFirstRequiredItemPatch
	{
		private static MethodBase TargetMethod()
		{
			return AccessTools.Method(typeof(Player), "GetFirstRequiredItem", (Type[])null, (Type[])null);
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return Redirect.Calls(instructions, Redirect.Swap(MethodSwaps.CountItemsFrom, MethodSwaps.CountItemsTo), Redirect.Swap(MethodSwaps.GetItemFrom, MethodSwaps.GetItemTo));
		}
	}
	[HarmonyPatch(typeof(Player), "ConsumeResources")]
	internal static class ConsumeResourcesPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return Redirect.Calls(instructions, Redirect.Swap(MethodSwaps.RemoveItemFrom, MethodSwaps.RemoveItemTo));
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "DoCrafting", new Type[] { typeof(Player) })]
	internal static class DoCraftingPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return Redirect.Calls(instructions, Redirect.Swap(MethodSwaps.RemoveItemFrom, MethodSwaps.RemoveItemTo));
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
	internal static class SetupRequirementPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return Redirect.Calls(instructions, Redirect.Swap(MethodSwaps.CountItemsFrom, MethodSwaps.CountItemsTo));
		}
	}
	[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
	{
		typeof(Piece),
		typeof(RequirementMode)
	})]
	internal static class HavePieceRequirementsPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			RoutingContext.EnterBuild();
		}

		[HarmonyFinalizer]
		private static void Finalizer()
		{
			RoutingContext.ExitBuild();
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return Redirect.Calls(instructions, Redirect.Swap(MethodSwaps.HaveItemFrom, MethodSwaps.HaveItemTo), Redirect.Swap(MethodSwaps.CountItemsFrom, MethodSwaps.CountItemsTo));
		}
	}
	[HarmonyPatch(typeof(Player), "UpdatePlacement", new Type[]
	{
		typeof(bool),
		typeof(float)
	})]
	internal static class UpdatePlacementPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			RoutingContext.EnterBuild();
		}

		[HarmonyFinalizer]
		private static void Finalizer()
		{
			RoutingContext.ExitBuild();
		}
	}
	[HarmonyPatch(typeof(Hud), "SetupPieceInfo", new Type[] { typeof(Piece) })]
	internal static class SetupPieceInfoPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			RoutingContext.EnterBuild();
		}

		[HarmonyFinalizer]
		private static void Finalizer()
		{
			RoutingContext.ExitBuild();
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return Redirect.Calls(instructions, Redirect.Swap(MethodSwaps.CountItemsFrom, MethodSwaps.CountItemsTo));
		}
	}
	[HarmonyPatch(typeof(ZNet), "Shutdown")]
	internal static class ZNetShutdownPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			RefillTargetRegistry.Clear();
			ContainerRegistry.Clear();
			RoutingContext.Reset();
			ConnectionVisuals.Cleanup();
			KeywordSync.Reset();
			MultiUserChestCompat.Reset();
			RangeProvider.Invalidate();
			RouteRegistry.ClearInstanceCache();
		}
	}
	internal static class InventoryBridge
	{
		private struct CountKey : IEquatable<CountKey>
		{
			private readonly string _name;

			private readonly int _quality;

			private readonly bool _world;

			internal CountKey(string name, int quality, bool world)
			{
				_name = name;
				_quality = quality;
				_world = world;
			}

			public bool Equals(CountKey other)
			{
				if (_quality == other._quality && _world == other._world)
				{
					return string.Equals(_name, other._name);
				}
				return false;
			}

			public override bool Equals(object obj)
			{
				if (obj is CountKey)
				{
					return Equals((CountKey)obj);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return (((_name != null) ? _name.GetHashCode() : 0) * 397) ^ (_quality * 31) ^ (_world ? 1 : 0);
			}
		}

		internal static int InventoryVersion;

		private static int _cacheMatching = -1;

		private static int _cacheInventories = -1;

		private static RouteDefinition _cacheRoute;

		private static readonly Dictionary<CountKey, int> CountCache = new Dictionary<CountKey, int>();

		private static bool TryGetContext(Inventory inventory, out RouteContext context)
		{
			context = null;
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || inventory == null || inventory != ((Humanoid)localPlayer).GetInventory())
			{
				return false;
			}
			return RoutingContext.TryGet(out context);
		}

		public static int CountItems(Inventory inventory, string name, int quality, bool matchWorldLevel)
		{
			try
			{
				return CountItemsTimed(inventory, name, quality, matchWorldLevel);
			}
			finally
			{
			}
		}

		private static int CountItemsTimed(Inventory inventory, string name, int quality, bool matchWorldLevel)
		{
			int num = inventory.CountItems(name, quality, matchWorldLevel);
			if (!TryGetContext(inventory, out var context))
			{
				return num;
			}
			List<Container> matching = ContainerRegistry.GetMatching(context);
			if (MultiUserChestCompat.Executing)
			{
				int num2 = 0;
				for (int i = 0; i < matching.Count; i++)
				{
					Inventory effectiveInventory = MultiUserChestCompat.GetEffectiveInventory(matching[i]);
					if (effectiveInventory != null)
					{
						num2 += effectiveInventory.CountItems(name, quality, matchWorldLevel);
					}
				}
				return num + num2;
			}
			if (_cacheMatching != ContainerRegistry.MatchingVersion || _cacheInventories != InventoryVersion || _cacheRoute != context.Definition)
			{
				CountCache.Clear();
				_cacheMatching = ContainerRegistry.MatchingVersion;
				_cacheInventories = InventoryVersion;
				_cacheRoute = context.Definition;
			}
			CountKey key = new CountKey(name, quality, matchWorldLevel);
			if (CountCache.TryGetValue(key, out var value))
			{
				return num + value;
			}
			int num3 = 0;
			for (int j = 0; j < matching.Count; j++)
			{
				Inventory inventory2 = matching[j].GetInventory();
				if (inventory2 != null)
				{
					num3 += inventory2.CountItems(name, quality, matchWorldLevel);
				}
			}
			CountCache[key] = num3;
			return num + num3;
		}

		public static bool HaveItem(Inventory inventory, string name, bool matchWorldLevel)
		{
			try
			{
				return HaveItemTimed(inventory, name, matchWorldLevel);
			}
			finally
			{
			}
		}

		private static bool HaveItemTimed(Inventory inventory, string name, bool matchWorldLevel)
		{
			if (inventory.HaveItem(name, matchWorldLevel))
			{
				return true;
			}
			if (!TryGetContext(inventory, out var context))
			{
				return false;
			}
			List<Container> matching = ContainerRegistry.GetMatching(context);
			for (int i = 0; i < matching.Count; i++)
			{
				Inventory effectiveInventory = MultiUserChestCompat.GetEffectiveInventory(matching[i]);
				if (effectiveInventory != null && effectiveInventory.HaveItem(name, matchWorldLevel))
				{
					return true;
				}
			}
			return false;
		}

		public static ItemData GetItem(Inventory inventory, string name, int quality, bool isPrefabName)
		{
			try
			{
				return GetItemTimed(inventory, name, quality, isPrefabName);
			}
			finally
			{
			}
		}

		private static ItemData GetItemTimed(Inventory inventory, string name, int quality, bool isPrefabName)
		{
			ItemData item = inventory.GetItem(name, quality, isPrefabName);
			if (item != null)
			{
				return item;
			}
			if (!TryGetContext(inventory, out var context))
			{
				return null;
			}
			List<Container> matching = ContainerRegistry.GetMatching(context);
			for (int i = 0; i < matching.Count; i++)
			{
				Inventory effectiveInventory = MultiUserChestCompat.GetEffectiveInventory(matching[i]);
				if (effectiveInventory != null)
				{
					item = effectiveInventory.GetItem(name, quality, isPrefabName);
					if (item != null)
					{
						return item;
					}
				}
			}
			return null;
		}

		public static void RemoveItem(Inventory inventory, string name, int amount, int itemQuality, bool worldLevelBased)
		{
			try
			{
				RemoveItemTimed(inventory, name, amount, itemQuality, worldLevelBased);
			}
			finally
			{
			}
		}

		private static void RemoveItemTimed(Inventory inventory, string name, int amount, int itemQuality, bool worldLevelBased)
		{
			if (!TryGetContext(inventory, out var context))
			{
				inventory.RemoveItem(name, amount, itemQuality, worldLevelBased);
				return;
			}
			if (context.Definition != null && context.Definition.Kind == RouteKind.Refill && MultiUserChestCompat.Active)
			{
				MultiUserChestCompat.PendingAction pendingAction = MultiUserChestCompat.PrepareName(context, name, amount, itemQuality, worldLevelBased);
				if (pendingAction != null)
				{
					throw new MucPendingException(pendingAction);
				}
			}
			int num = amount;
			if (context.Tool != null)
			{
				ContainerRegistry.Invalidate();
			}
			int num2 = inventory.CountItems(name, itemQuality, worldLevelBased);
			int num3 = Mathf.Min(num, num2);
			if (num3 > 0)
			{
				inventory.RemoveItem(name, num3, itemQuality, worldLevelBased);
				num -= num3;
			}
			if (num <= 0)
			{
				return;
			}
			List<Container> matching = ContainerRegistry.GetMatching(context);
			for (int i = 0; i < matching.Count; i++)
			{
				if (num <= 0)
				{
					break;
				}
				Container val = matching[i];
				Inventory effectiveInventory = MultiUserChestCompat.GetEffectiveInventory(val);
				if (effectiveInventory == null)
				{
					continue;
				}
				int num4 = effectiveInventory.CountItems(name, itemQuality, worldLevelBased);
				if (num4 > 0)
				{
					Inventory inventory2 = val.GetInventory();
					if (effectiveInventory != inventory2 || ContainerRegistry.TryTakeOwnership(val))
					{
						int num5 = Mathf.Min(num4, num);
						effectiveInventory.RemoveItem(name, num5, itemQuality, worldLevelBased);
						num -= num5;
					}
				}
			}
			if (num > 0 && Plugin.Log != null)
			{
				Plugin.Log.LogWarning((object)("Could not consume " + num + "x " + name + " after checking the player and " + matching.Count + " matching chest(s)."));
			}
		}

		public static int CountItemsByName(Inventory inventory, string[] names, int quality, bool matchWorldLevel, bool stacksOnly)
		{
			int num = inventory.CountItemsByName(names, quality, matchWorldLevel, stacksOnly);
			if (!TryGetContext(inventory, out var context))
			{
				return num;
			}
			List<Container> matching = ContainerRegistry.GetMatching(context);
			for (int i = 0; i < matching.Count; i++)
			{
				Inventory effectiveInventory = MultiUserChestCompat.GetEffectiveInventory(matching[i]);
				if (effectiveInventory != null)
				{
					num += effectiveInventory.CountItemsByName(names, quality, matchWorldLevel, stacksOnly);
				}
			}
			return num;
		}

		public static ItemData GetAmmoItem(Inventory inventory, string ammoName, string matchPrefabName)
		{
			ItemData ammoItem = inventory.GetAmmoItem(ammoName, matchPrefabName);
			if (ammoItem != null)
			{
				return ammoItem;
			}
			if (!TryGetContext(inventory, out var context))
			{
				return null;
			}
			List<Container> matching = ContainerRegistry.GetMatching(context);
			for (int i = 0; i < matching.Count; i++)
			{
				Inventory effectiveInventory = MultiUserChestCompat.GetEffectiveInventory(matching[i]);
				if (effectiveInventory != null)
				{
					ammoItem = effectiveInventory.GetAmmoItem(ammoName, matchPrefabName);
					if (ammoItem != null)
					{
						return ammoItem;
					}
				}
			}
			return null;
		}

		public static bool RemoveItemData(Inventory inventory, ItemData item, int amount)
		{
			try
			{
				return RemoveItemDataTimed(inventory, item, amount);
			}
			finally
			{
			}
		}

		private static bool RemoveItemDataTimed(Inventory inventory, ItemData item, int amount)
		{
			if (inventory == null || item == null)
			{
				return false;
			}
			if (inventory.ContainsItem(item))
			{
				return inventory.RemoveItem(item, amount);
			}
			if (!TryGetContext(inventory, out var context))
			{
				return inventory.RemoveItem(item, amount);
			}
			if (context.Definition != null && context.Definition.Kind == RouteKind.Refill && MultiUserChestCompat.Active)
			{
				MultiUserChestCompat.PendingAction pendingAction = MultiUserChestCompat.PrepareExactItem(context, item, amount);
				if (pendingAction != null)
				{
					throw new MucPendingException(pendingAction);
				}
			}
			if (context.Tool != null)
			{
				ContainerRegistry.Invalidate();
			}
			List<Container> matching = ContainerRegistry.GetMatching(context);
			for (int i = 0; i < matching.Count; i++)
			{
				Container val = matching[i];
				Inventory effectiveInventory = MultiUserChestCompat.GetEffectiveInventory(val);
				if (effectiveInventory != null && effectiveInventory.ContainsItem(item))
				{
					Inventory inventory2 = val.GetInventory();
					if (effectiveInventory == inventory2 && !ContainerRegistry.TryTakeOwnership(val))
					{
						return false;
					}
					return effectiveInventory.RemoveItem(item, amount);
				}
			}
			return false;
		}

		public static bool RemoveOneItem(Inventory inventory, ItemData item)
		{
			return RemoveItemData(inventory, item, 1);
		}
	}
	[HarmonyPatch(typeof(Inventory), "Changed")]
	internal static class InventoryChangedVersionPatch
	{
		private static void Postfix()
		{
			InventoryBridge.InventoryVersion++;
		}
	}
	internal static class KeywordSync
	{
		private const string RequestRpc = "WBCFNC_KeywordRequest";

		private const string ConfigRpc = "WBCFNC_Keywords";

		private static readonly Dictionary<string, string[]> ServerKeywords = new Dictionary<string, string[]>(StringComparer.Ordinal);

		private static bool _registered;

		internal static bool ServerEnforced { get; private set; }

		internal static string[] GetKeywords(string routeId, string[] localValues)
		{
			if (ServerEnforced && routeId != null && ServerKeywords.TryGetValue(routeId, out var value))
			{
				return value;
			}
			return localValues ?? new string[0];
		}

		internal static void Register()
		{
			if (!_registered && ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.Register("WBCFNC_KeywordRequest", (Action<long>)OnConfigRequested);
				ZRoutedRpc.instance.Register<ZPackage>("WBCFNC_Keywords", (Action<long, ZPackage>)OnConfigReceived);
				_registered = true;
			}
		}

		internal static void RequestFromServer()
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer() && ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC("WBCFNC_KeywordRequest", Array.Empty<object>());
			}
		}

		internal static void NotifyLocalKeywordChanged()
		{
			ContainerRegistry.Invalidate();
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && ZRoutedRpc.instance != null)
			{
				ZPackage val = BuildPackage();
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "WBCFNC_Keywords", new object[1] { val });
			}
		}

		internal static void Reset()
		{
			_registered = false;
			ServerEnforced = false;
			ServerKeywords.Clear();
		}

		private static void OnConfigRequested(long sender)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(sender, "WBCFNC_Keywords", new object[1] { BuildPackage() });
			}
		}

		private static ZPackage BuildPackage()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			List<RouteDefinition> list = new List<RouteDefinition>(RouteRegistry.All);
			List<SharedRouteGroup> list2 = new List<SharedRouteGroup>(SharedRouteRegistry.All);
			val.Write(list.Count + list2.Count);
			for (int i = 0; i < list.Count; i++)
			{
				RouteDefinition routeDefinition = list[i];
				WriteKeywordSet(val, routeDefinition.Id, routeDefinition.KeywordEntries);
			}
			for (int j = 0; j < list2.Count; j++)
			{
				SharedRouteGroup sharedRouteGroup = list2[j];
				WriteKeywordSet(val, sharedRouteGroup.SyncId, sharedRouteGroup.KeywordEntries);
			}
			return val;
		}

		private static void WriteKeywordSet(ZPackage package, string id, ConfigEntry<string>[] entries)
		{
			package.Write(id ?? "");
			for (int i = 0; i < 3; i++)
			{
				string text = "";
				if (entries != null && i < entries.Length && entries[i] != null)
				{
					text = entries[i].Value ?? "";
				}
				package.Write(text);
			}
		}

		private static void OnConfigReceived(long sender, ZPackage package)
		{
			if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || package == null)
			{
				return;
			}
			ServerKeywords.Clear();
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string[] array = new string[3];
				for (int j = 0; j < array.Length; j++)
				{
					array[j] = package.ReadString() ?? "";
				}
				if (!string.IsNullOrEmpty(text))
				{
					ServerKeywords[text] = array;
				}
			}
			ServerEnforced = true;
			ContainerRegistry.ReindexAll();
			if (Plugin.Log != null)
			{
				Plugin.Log.LogInfo((object)("Using " + ServerKeywords.Count + " station/tool chest keyword(s) from the server."));
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "Awake")]
	internal static class ZNetAwakeKeywordSyncPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			KeywordSync.Reset();
			KeywordSync.Register();
		}
	}
	[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
	internal static class ZNetPeerInfoKeywordSyncPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			KeywordSync.Register();
			KeywordSync.RequestFromServer();
		}
	}
	internal enum ChestNameHover
	{
		Vanilla,
		CustomName,
		TypeThenCustomName,
		CustomNameThenType
	}
	internal static class ModConfig
	{
		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> ShowConnections;

		internal static ConfigEntry<bool> EnableCustomNames;

		internal static ConfigEntry<ChestNameHover> HoverNameFormat;

		internal static ConfigEntry<bool> ShowRenameHint;

		internal static ConfigFile File;

		internal static void Bind(ConfigFile config)
		{
			File = config;
			Enabled = config.Bind<bool>("General", "Enabled", true, "Enable crafting and building from correctly named nearby chests.");
			ShowConnections = config.Bind<bool>("Visuals", "Show connections", true, "Show vanilla-style connection effects for linked chests.");
			EnableCustomNames = config.Bind<bool>("Chest Renaming", "Enable custom names", true, "Enable the standalone chest renaming fallback when another compatible chest renamer is not installed.");
			HoverNameFormat = config.Bind<ChestNameHover>("Chest Renaming", "Hover name format", ChestNameHover.TypeThenCustomName, "Chest name format shown in hover when the standalone rename fallback is active.");
			ShowRenameHint = config.Bind<bool>("Chest Renaming", "Show rename hint in hover", true, "Show the Alt+Use rename hint when the standalone rename fallback is active.");
		}

		internal static ConfigEntry<string>[] BindStationKeywords(string key, params string[] defaults)
		{
			return BindKeywordSlots("Station Keywords", key, defaults, "Chest titles containing this alternative are assigned to this crafting station. Matching is case-insensitive; spaces are literal. Leave blank to disable this alternative. If another route already uses the same alias, this field is automatically cleared.");
		}

		internal static ConfigEntry<string>[] BindToolKeywords(string key, params string[] defaults)
		{
			return BindKeywordSlots("Build Tool Keywords", key, defaults, "Chest titles containing this alternative are assigned to this build tool. Matching is case-insensitive; spaces are literal. Leave blank to disable this alternative. If another route already uses the same alias, this field is automatically cleared.");
		}

		internal static ConfigEntry<string>[] BindRefillKeywords(string key, params string[] defaults)
		{
			return BindKeywordSlots("Refill Keywords", key, defaults, "Chest titles containing this alternative are assigned to this refill/feed route. Matching is case-insensitive; spaces are literal. Leave blank to disable this alternative. If another route already uses the same alias, this field is automatically cleared.");
		}

		internal static ConfigEntry<string>[] BindSharedKeywords(string key, params string[] defaults)
		{
			return BindKeywordSlots("Shared Keywords", key, defaults, "Chest titles containing this alternative are shared by all routes in this group. Matching is case-insensitive; spaces are literal. Leave blank to disable this alternative.");
		}

		private static ConfigEntry<string>[] BindKeywordSlots(string section, string key, string[] defaults, string description)
		{
			ConfigEntry<string>[] array = new ConfigEntry<string>[3];
			for (int i = 0; i < array.Length; i++)
			{
				string text = ((defaults != null && i < defaults.Length) ? (defaults[i] ?? "") : "");
				array[i] = File.Bind<string>(section, key + " " + (i + 1), text, description);
			}
			return array;
		}
	}
	internal static class MucActionPreflight
	{
		internal static readonly FieldInfo CraftRecipeField = AccessTools.Field(typeof(InventoryGui), "m_craftRecipe");

		internal static readonly FieldInfo CraftUpgradeItemField = AccessTools.Field(typeof(InventoryGui), "m_craftUpgradeItem");

		internal static readonly FieldInfo CraftVariantField = AccessTools.Field(typeof(InventoryGui), "m_craftVariant");

		internal static readonly FieldInfo MultiCraftingField = AccessTools.Field(typeof(InventoryGui), "m_multiCrafting");

		internal static readonly FieldInfo MultiCraftAmountField = AccessTools.Field(typeof(InventoryGui), "m_multiCraftAmount");

		internal static List<MultiUserChestCompat.Demand> RequirementDemands(Requirement[] requirements, int quality, int multiplier, CraftingStation station)
		{
			List<MultiUserChestCompat.Demand> list = new List<MultiUserChestCompat.Demand>();
			if (requirements == null)
			{
				return list;
			}
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
			foreach (Requirement val in requirements)
			{
				if (val != null && !((Object)(object)val.m_resItem == (Object)null) && (!((Object)(object)station != (Object)null) || station.m_upgrader == val.m_upgraderResource) && (!((Object)(object)station == (Object)null) || !val.m_upgraderResource))
				{
					int num = val.GetAmount(quality) * multiplier;
					if (num > 0)
					{
						string name = val.m_resItem.m_itemData.m_shared.m_name;
						dictionary.TryGetValue(name, out var value);
						dictionary[name] = value + num;
					}
				}
			}
			foreach (KeyValuePair<string, int> item in dictionary)
			{
				list.Add(new MultiUserChestCompat.Demand
				{
					Name = item.Key,
					Amount = item.Value,
					Quality = -1,
					MatchWorldLevel = true
				});
			}
			return list;
		}

		internal static void Missing(Player player)
		{
			if ((Object)(object)player != (Object)null)
			{
				((Character)player).Message((MessageType)2, "$msg_missingrequirement", 0, (Sprite)null, false);
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "DoCrafting", new Type[] { typeof(Player) })]
	internal static class MucCraftActionPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(InventoryGui __instance, Player player, MethodBase __originalMethod)
		{
			if (!MultiUserChestCompat.Active || MultiUserChestCompat.Executing)
			{
				return true;
			}
			if (MultiUserChestCompat.Busy)
			{
				return false;
			}
			if ((Object)(object)__instance == (Object)null || (Object)(object)player == (Object)null || player.NoCostCheat() || (Object)(object)ZoneSystem.instance == (Object)null || ZoneSystem.instance.GetGlobalKey((GlobalKeys)25))
			{
				return true;
			}
			Recipe recipe = default(Recipe);
			ref Recipe reference = ref recipe;
			object? value = MucActionPreflight.CraftRecipeField.GetValue(__instance);
			reference = (Recipe)((value is Recipe) ? value : null);
			if ((Object)(object)recipe == (Object)null)
			{
				return true;
			}
			ItemData upgrade = default(ItemData);
			ref ItemData reference2 = ref upgrade;
			object? value2 = MucActionPreflight.CraftUpgradeItemField.GetValue(__instance);
			reference2 = (ItemData)((value2 is ItemData) ? value2 : null);
			int num = ((upgrade == null) ? 1 : (upgrade.m_quality + 1));
			bool multi = (bool)MucActionPreflight.MultiCraftingField.GetValue(__instance);
			int multiplier = ((!multi) ? 1 : ((int)MucActionPreflight.MultiCraftAmountField.GetValue(__instance)));
			int variant = (int)MucActionPreflight.CraftVariantField.GetValue(__instance);
			CraftingStation station = player.GetCurrentCraftingStation();
			if (!RoutingContext.TryGet(out var context))
			{
				return true;
			}
			MultiUserChestCompat.PendingAction pendingAction;
			if (recipe.m_requireOnlyOneIngredient)
			{
				int num2 = default(int);
				ItemData val = default(ItemData);
				recipe.GetAmount(num, ref num2, ref val, multiplier);
				pendingAction = ((val != null && num2 > 0) ? MultiUserChestCompat.PrepareExactItem(context, val, num2) : null);
			}
			else
			{
				List<MultiUserChestCompat.Demand> demands = MucActionPreflight.RequirementDemands(recipe.m_resources, num, multiplier, station);
				pendingAction = MultiUserChestCompat.Prepare(context, demands);
			}
			if (pendingAction == null)
			{
				return true;
			}
			Func<bool> stillValid = delegate
			{
				if ((Object)(object)__instance == (Object)null || (Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || ((Character)player).IsDead() || !InventoryGui.IsVisible())
				{
					return false;
				}
				if (MucActionPreflight.CraftRecipeField.GetValue(__instance) != recipe)
				{
					return false;
				}
				if (MucActionPreflight.CraftUpgradeItemField.GetValue(__instance) != upgrade)
				{
					return false;
				}
				if ((int)MucActionPreflight.CraftVariantField.GetValue(__instance) != variant)
				{
					return false;
				}
				if ((bool)MucActionPreflight.MultiCraftingField.GetValue(__instance) != multi)
				{
					return false;
				}
				if (multi && (int)MucActionPreflight.MultiCraftAmountField.GetValue(__instance) != multiplier)
				{
					return false;
				}
				if ((Object)(object)player.GetCurrentCraftingStation() != (Object)(object)station)
				{
					return false;
				}
				return (Object)(object)station == (Object)null || station.CheckUsable(player, false);
			};
			Action ready = delegate
			{
				__originalMethod.Invoke(__instance, new object[1] { player });
			};
			MultiUserChestCompat.Attach(pendingAction, stillValid, ready, delegate
			{
				MucActionPreflight.Missing(player);
			});
			return false;
		}
	}
	[HarmonyPatch(typeof(Player), "TryPlacePiece")]
	internal static class MucBuildActionPatch
	{
		private static readonly FieldInfo PlacementGhostField = AccessTools.Field(typeof(Player), "m_placementGhost");

		private static readonly FieldInfo LastToolUseField = AccessTools.Field(typeof(Player), "m_lastToolUseTime");

		private static readonly FieldInfo BuildRemoveDebtField = AccessTools.Field(typeof(Player), "m_buildRemoveDebt");

		private static readonly MethodInfo GetBuildStaminaMethod = AccessTools.Method(typeof(Player), "GetBuildStamina", (Type[])null, (Type[])null);

		private static readonly MethodInfo GetPlaceDurabilityMethod = AccessTools.Method(typeof(Player), "GetPlaceDurability", new Type[1] { typeof(ItemData) }, (Type[])null);

		[HarmonyPrefix]
		private static bool Prefix(Player __instance, Piece piece, ref bool __result)
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			if (!MultiUserChestCompat.Active || MultiUserChestCompat.Executing)
			{
				return true;
			}
			if (MultiUserChestCompat.Busy)
			{
				__result = false;
				return false;
			}
			if ((Object)(object)__instance == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)piece == (Object)null || __instance.NoCostCheat() || (Object)(object)ZoneSystem.instance == (Object)null || ZoneSystem.instance.GetGlobalKey(piece.FreeBuildKey()))
			{
				return true;
			}
			GameObject val = (GameObject)((PlacementGhostField != null) ? /*isinst with value type is only supported in some contexts*/: null);
			if ((Object)(object)val == (Object)null)
			{
				return true;
			}
			ItemData tool = ((Humanoid)__instance).RightItem;
			if (tool == null || tool.m_shared == null || (Object)(object)tool.m_shared.m_buildPieces == (Object)null)
			{
				return true;
			}
			Vector3 position = val.transform.position;
			Quaternion rotation = val.transform.rotation;
			RoutingContext.EnterBuild();
			RouteContext context;
			try
			{
				if (!RoutingContext.TryGet(out context))
				{
					return true;
				}
			}
			finally
			{
				RoutingContext.ExitBuild();
			}
			List<MultiUserChestCompat.Demand> demands = MucActionPreflight.RequirementDemands(piece.m_resources, 0, 1, null);
			MultiUserChestCompat.PendingAction pendingAction = MultiUserChestCompat.Prepare(context, demands);
			if (pendingAction == null)
			{
				return true;
			}
			Func<bool> stillValid = delegate
			{
				//IL_009e: 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_00a9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)__instance == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || ((Character)__instance).IsDead() || !((Character)__instance).InPlaceMode() || (Object)(object)__instance.GetSelectedPiece() != (Object)(object)piece || ((Humanoid)__instance).RightItem != tool)
				{
					return false;
				}
				GameObject val2 = (GameObject)((PlacementGhostField != null) ? /*isinst with value type is only supported in some contexts*/: null);
				if ((Object)(object)val2 == (Object)null)
				{
					return false;
				}
				Vector3 val3 = val2.transform.position - position;
				if (((Vector3)(ref val3)).sqrMagnitude >= 0.01f || Quaternion.Angle(val2.transform.rotation, rotation) >= 1f)
				{
					return false;
				}
				float buildStamina = GetBuildStamina(__instance);
				return ((Character)__instance).HaveStamina(buildStamina);
			};
			Action ready = delegate
			{
				CompleteBuild(__instance, piece, tool);
			};
			MultiUserChestCompat.Attach(pendingAction, stillValid, ready, delegate
			{
				MucActionPreflight.Missing(__instance);
			});
			__result = false;
			return false;
		}

		private static void CompleteBuild(Player player, Piece piece, ItemData tool)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Invalid comparison between Unknown and I4
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Invalid comparison between Unknown and I4
			if ((Object)(object)player == (Object)null || (Object)(object)piece == (Object)null || tool == null)
			{
				return;
			}
			RoutingContext.EnterBuild();
			try
			{
				if (!player.HaveRequirements(piece, (RequirementMode)0))
				{
					MucActionPreflight.Missing(player);
				}
				else
				{
					if (!player.TryPlacePiece(piece))
					{
						return;
					}
					if ((Object)(object)Hud.instance != (Object)null && (Object)(object)Hud.instance.m_buildUi != (Object)null)
					{
						Hud.instance.m_buildUi.AddRecentPiece(piece);
					}
					if (LastToolUseField != null)
					{
						LastToolUseField.SetValue(player, Time.time);
					}
					if (!ZoneSystem.instance.GetGlobalKey(piece.FreeBuildKey()))
					{
						player.ConsumeResources(piece.m_resources, 0, -1, 1);
					}
					((Character)player).UseStamina(GetBuildStamina(player));
					PieceTable buildPieces = tool.m_shared.m_buildPieces;
					if ((Object)(object)buildPieces != (Object)null && (int)buildPieces.m_skill != 0)
					{
						if ((int)buildPieces.m_skill == 107)
						{
							Game.instance.IncrementPlayerStat((PlayerStatType)168, 1f, false);
						}
						int num = ((BuildRemoveDebtField != null) ? ((int)BuildRemoveDebtField.GetValue(player)) : 0);
						if (num > 0)
						{
							BuildRemoveDebtField.SetValue(player, num - 1);
						}
						else
						{
							((Character)player).RaiseSkill(buildPieces.m_skill, 1f);
							if ((int)buildPieces.m_skill == 107)
							{
								Game.instance.IncrementPlayerStat((PlayerStatType)169, 1f, false);
							}
						}
					}
					if (tool.m_shared.m_useDurability)
					{
						tool.m_durability -= GetPlaceDurability(player, tool) * Game.m_durabilityRate;
					}
					tool.m_shared.m_buildEffect.Create(((Component)player).transform.position, Quaternion.identity, (Transform)null, 1f, -1, ((Character)player).GetZDOID());
				}
			}
			finally
			{
				RoutingContext.ExitBuild();
			}
		}

		private static float GetBuildStamina(Player player)
		{
			if ((Object)(object)player == (Object)null || GetBuildStaminaMethod == null)
			{
				return 0f;
			}
			object obj = GetBuildStaminaMethod.Invoke(player, null);
			if (!(obj is float))
			{
				return 0f;
			}
			return (float)obj;
		}

		private static float GetPlaceDurability(Player player, ItemData tool)
		{
			if ((Object)(object)player == (Object)null || tool == null || GetPlaceDurabilityMethod == null)
			{
				return 0f;
			}
			object obj = GetPlaceDurabilityMethod.Invoke(player, new object[1] { tool });
			if (!(obj is float))
			{
				return 0f;
			}
			return (float)obj;
		}
	}
	internal sealed class MucPendingException : Exception
	{
		internal readonly MultiUserChestCompat.PendingAction Pending;

		internal MucPendingException(MultiUserChestCompat.PendingAction pending)
		{
			Pending = pending;
		}
	}
	internal static class MultiUserChestCompat
	{
		internal sealed class Demand
		{
			internal string Name;

			internal int Amount;

			internal int Quality = -1;

			internal bool MatchWorldLevel = true;

			internal string PrefabName;

			internal Container SourceOnly;

			internal bool IgnorePlayer;
		}

		internal sealed class PendingAction
		{
			internal RouteContext Context;

			internal readonly List<Demand> Demands = new List<Demand>();

			internal readonly Dictionary<Container, Inventory> Reserves = new Dictionary<Container, Inventory>();

			internal readonly HashSet<Container> Concurrent = new HashSet<Container>();

			internal readonly List<int> RequestIds = new List<int>();

			internal Func<bool> StillValid;

			internal Action Ready;

			internal Action Failed;

			internal float Started;

			internal bool Blocked;
		}

		private sealed class RefundJob
		{
			internal Container Container;

			internal Inventory Reserve;

			internal readonly List<int> RequestIds = new List<int>();

			internal float NextTry;
		}

		internal const string PluginGuid = "com.maxsch.valheim.MultiUserChest";

		private static bool _initialized;

		private static bool _available;

		private static MethodInfo _removeItemFromChest;

		private static MethodInfo _addItemToChest;

		private static MethodInfo _getPackageGeneric;

		private static Type _iPackageType;

		private static PendingAction _pending;

		private static PendingAction _active;

		private static readonly List<RefundJob> Refunds = new List<RefundJob>();

		private static MethodInfo _getPackageClosed;

		internal static bool Executing => _active != null;

		internal static bool Busy => _pending != null;

		internal static bool Active
		{
			get
			{
				EnsureInitialized();
				return _available;
			}
		}

		internal static bool NeedsUpdate
		{
			get
			{
				if (_pending == null)
				{
					if (Active)
					{
						return Refunds.Count > 0;
					}
					return false;
				}
				return true;
			}
		}

		private static void EnsureInitialized()
		{
			if (_initialized)
			{
				return;
			}
			_initialized = true;
			if (!Chainloader.PluginInfos.ContainsKey("com.maxsch.valheim.MultiUserChest"))
			{
				return;
			}
			try
			{
				Assembly assembly = ((object)Chainloader.PluginInfos["com.maxsch.valheim.MultiUserChest"].Instance).GetType().Assembly;
				Type type = assembly.GetType("MultiUserChest.ContainerHandler");
				Type type2 = assembly.GetType("MultiUserChest.PackageHandler");
				_iPackageType = assembly.GetType("MultiUserChest.IPackage");
				if (type != null)
				{
					MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public);
					foreach (MethodInfo methodInfo in methods)
					{
						if (methodInfo.Name == "RemoveItemFromChest" && methodInfo.GetParameters().Length == 7)
						{
							_removeItemFromChest = methodInfo;
						}
						if (methodInfo.Name == "AddItemToChest" && methodInfo.GetParameters().Length == 6)
						{
							_addItemToChest = methodInfo;
						}