Decompiled source of NoHammerBuildMenu v0.14.0

NoHammerBuildMenu.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[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: IgnoresAccessChecksTo("")]
[assembly: AssemblyCompany("NoHammerBuildMenu")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Open the build menu without needing a hammer in your inventory, now with a build grid and a repair toggle!")]
[assembly: AssemblyFileVersion("0.14.0.0")]
[assembly: AssemblyInformationalVersion("0.14.0+8410062b80a483c0e76d7e3a85898c7f31fc0b42")]
[assembly: AssemblyProduct("NoHammerBuildMenu")]
[assembly: AssemblyTitle("NoHammerBuildMenu")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.14.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace NoHammerBuildMenu
{
	internal static class ChestMaterials
	{
		[HarmonyPatch(typeof(ItemDrop), "Awake")]
		private static class ItemDrop_Awake_Patch
		{
			[HarmonyPostfix]
			private static void Postfix(ItemDrop __instance)
			{
				if (!Drops.Contains(__instance))
				{
					Drops.Add(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(Container), "Awake")]
		private static class Container_Awake_Patch
		{
			[HarmonyPostfix]
			private static void Postfix(Container __instance)
			{
				if (__instance.GetInventory() != null && !Containers.Contains(__instance))
				{
					Containers.Add(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
		{
			typeof(Piece),
			typeof(RequirementMode)
		})]
		private static class Player_HaveRequirements_Patch
		{
			[HarmonyPrefix]
			private static void Prefix(Player __instance, RequirementMode mode, out bool __state)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				__state = (int)mode == 0 && Active(__instance);
				if (__state)
				{
					_countDepth++;
				}
			}

			[HarmonyFinalizer]
			private static void Finalizer(bool __state)
			{
				if (__state)
				{
					_countDepth--;
				}
			}
		}

		[HarmonyPatch(typeof(Hud), "SetupPieceInfo")]
		private static class Hud_SetupPieceInfo_Patch
		{
			[HarmonyPrefix]
			private static void Prefix(out bool __state)
			{
				__state = Active(Player.m_localPlayer);
				if (__state)
				{
					_countDepth++;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Hud __instance, Piece piece, bool __state)
			{
				if (!__state || (Object)(object)piece == (Object)null)
				{
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				_countDepth++;
				_countAllGround = true;
				try
				{
					for (int i = 0; i < piece.m_resources.Length && i < __instance.m_requirementItems.Length; i++)
					{
						Requirement val = piece.m_resources[i];
						int amount = val.GetAmount(0);
						if (!((Object)(object)val.m_resItem == (Object)null) && amount > 0)
						{
							Transform val2 = __instance.m_requirementItems[i].transform.Find("res_amount");
							TMP_Text val3 = (((Object)(object)val2 != (Object)null) ? ((Component)val2).GetComponent<TMP_Text>() : null);
							if (!((Object)(object)val3 == (Object)null))
							{
								int num = ((Humanoid)localPlayer).GetInventory().CountItems(val.m_resItem.m_itemData.m_shared.m_name, -1, true);
								val3.text = $"{num}/{amount}";
							}
						}
					}
				}
				finally
				{
					_countDepth--;
					_countAllGround = false;
				}
			}

			[HarmonyFinalizer]
			private static void Finalizer(bool __state)
			{
				if (__state)
				{
					_countDepth--;
				}
			}
		}

		[HarmonyPatch(typeof(Inventory), "CountItems")]
		private static class Inventory_CountItems_Patch
		{
			[HarmonyPostfix]
			private static void Postfix(Inventory __instance, string name, int quality, bool matchWorldLevel, ref int __result)
			{
				Player localPlayer = Player.m_localPlayer;
				if (_countDepth <= 0 || name == null || !Active(localPlayer) || __instance != ((Humanoid)localPlayer).GetInventory())
				{
					return;
				}
				foreach (Container item in GetNearby(localPlayer))
				{
					__result += item.GetInventory().CountItems(name, quality, matchWorldLevel);
				}
				foreach (ItemDrop groundMatch in GetGroundMatches(localPlayer, name, quality, matchWorldLevel))
				{
					if (_countAllGround || OwnedOrRequest(groundMatch))
					{
						__result += groundMatch.m_itemData.m_stack;
					}
				}
			}
		}

		[HarmonyPatch(typeof(Player), "ConsumeResources")]
		private static class Player_ConsumeResources_Patch
		{
			[HarmonyPrefix]
			private static void Prefix(Player __instance, Requirement[] requirements, out bool __state)
			{
				__state = Active(__instance) && ((Character)__instance).InPlaceMode() && (Object)(object)__instance.GetSelectedPiece() != (Object)null && __instance.GetSelectedPiece().m_resources == requirements;
				if (__state)
				{
					_consuming = true;
				}
			}

			[HarmonyFinalizer]
			private static void Finalizer(bool __state)
			{
				if (__state)
				{
					_consuming = false;
				}
			}
		}

		[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
		{
			typeof(string),
			typeof(int),
			typeof(int),
			typeof(bool)
		})]
		private static class Inventory_RemoveItem_Patch
		{
			[HarmonyPrefix]
			private static bool Prefix(Inventory __instance, string name, ref int amount, int itemQuality, bool worldLevelBased)
			{
				Player localPlayer = Player.m_localPlayer;
				if (!_consuming || !Active(localPlayer) || __instance != ((Humanoid)localPlayer).GetInventory())
				{
					return true;
				}
				int num = __instance.CountItems(name, itemQuality, worldLevelBased);
				if (num >= amount)
				{
					return true;
				}
				TakeFromChests(localPlayer, name, amount - num, itemQuality, worldLevelBased);
				if (num <= 0)
				{
					return false;
				}
				amount = num;
				return true;
			}
		}

		private static ConfigEntry<bool> _enabled;

		private static ConfigEntry<float> _radius;

		private static ConfigEntry<float> _groundRange;

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

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

		private static readonly FieldRef<Container, ZNetView> NviewRef = AccessTools.FieldRefAccess<Container, ZNetView>("m_nview");

		private static readonly List<ItemDrop> Drops = new List<ItemDrop>();

		private static readonly FieldRef<ItemDrop, ZNetView> DropNviewRef = AccessTools.FieldRefAccess<ItemDrop, ZNetView>("m_nview");

		private static int _nearbyFrame = -1;

		private static Vector3 _nearbyPos;

		private static int _countDepth;

		private static bool _consuming;

		private static bool _countAllGround;

		public static void BindConfig(ConfigFile config)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			_enabled = config.Bind<bool>("Chests", "Use Nearby Chests", true, new ConfigDescription("When building, take any materials you are missing from your inventory out of nearby chests. (Synced with server)", (AcceptableValueBase)null, new object[1] { Synced() }));
			_radius = config.Bind<float>("Chests", "Radius", 30f, new ConfigDescription("Distance in metres from the player within which chests are used for building materials. (Synced with server)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 128f), new object[1] { Synced() }));
			_groundRange = config.Bind<float>("Ground Items", "Radius", 30f, new ConfigDescription("Distance in metres from the player within which items lying on the ground are used for building materials. Set to 0 to disable. (Synced with server)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 64f), new object[1] { Synced() }));
		}

		private static ConfigurationManagerAttributes Synced()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			return new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			};
		}

		private static bool Active(Player player)
		{
			if (_enabled != null && (Object)(object)player != (Object)null && (Object)(object)player == (Object)(object)Player.m_localPlayer)
			{
				if (!_enabled.Value)
				{
					return _groundRange.Value > 0f;
				}
				return true;
			}
			return false;
		}

		private static List<ItemDrop> GetGroundMatches(Player player, string name, int quality, bool matchWorldLevel)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			List<ItemDrop> list = new List<ItemDrop>();
			if (_groundRange.Value <= 0f)
			{
				return list;
			}
			Vector3 pos = ((Component)player).transform.position;
			float num = _groundRange.Value * _groundRange.Value;
			Drops.RemoveAll((ItemDrop d) => (Object)(object)d == (Object)null);
			foreach (ItemDrop drop in Drops)
			{
				ItemData itemData = drop.m_itemData;
				ZNetView val = DropNviewRef.Invoke(drop);
				if (itemData != null && !((Object)(object)val == (Object)null) && val.IsValid() && !drop.IsPiece() && !(itemData.m_shared.m_name != name) && (quality < 0 || quality == itemData.m_quality) && (!matchWorldLevel || itemData.m_worldLevel >= Game.m_worldLevel))
				{
					Vector3 val2 = ((Component)drop).transform.position - pos;
					if (!(((Vector3)(ref val2)).sqrMagnitude > num))
					{
						list.Add(drop);
					}
				}
			}
			list.Sort(delegate(ItemDrop a, ItemDrop b)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val3 = ((Component)a).transform.position - pos;
				float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
				val3 = ((Component)b).transform.position - pos;
				return sqrMagnitude.CompareTo(((Vector3)(ref val3)).sqrMagnitude);
			});
			return list;
		}

		private static bool OwnedOrRequest(ItemDrop drop)
		{
			if (DropNviewRef.Invoke(drop).IsOwner())
			{
				return true;
			}
			drop.RequestOwn();
			return false;
		}

		private static int TakeFromGround(Player player, string name, int amount, int quality, bool matchWorldLevel)
		{
			foreach (ItemDrop groundMatch in GetGroundMatches(player, name, quality, matchWorldLevel))
			{
				if (amount <= 0)
				{
					break;
				}
				ZNetView val = DropNviewRef.Invoke(groundMatch);
				if (OwnedOrRequest(groundMatch))
				{
					int num = Mathf.Min(groundMatch.m_itemData.m_stack, amount);
					amount -= num;
					if (num >= groundMatch.m_itemData.m_stack)
					{
						val.Destroy();
					}
					else
					{
						groundMatch.SetStack(groundMatch.m_itemData.m_stack - num);
					}
				}
			}
			return amount;
		}

		private static List<Container> GetNearby(Player player)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			Vector3 pos = ((Component)player).transform.position;
			if (_nearbyFrame == Time.frameCount && _nearbyPos == pos)
			{
				return NearbyCache;
			}
			_nearbyFrame = Time.frameCount;
			_nearbyPos = pos;
			NearbyCache.Clear();
			if (!_enabled.Value)
			{
				return NearbyCache;
			}
			float num = _radius.Value * _radius.Value;
			Containers.RemoveAll((Container c) => (Object)(object)c == (Object)null);
			foreach (Container container in Containers)
			{
				Vector3 val = ((Component)container).transform.position - pos;
				if (((Vector3)(ref val)).sqrMagnitude <= num && CanTakeFrom(container))
				{
					NearbyCache.Add(container);
				}
			}
			NearbyCache.Sort(delegate(Container a, Container b)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val2 = ((Component)a).transform.position - pos;
				float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
				val2 = ((Component)b).transform.position - pos;
				return sqrMagnitude.CompareTo(((Vector3)(ref val2)).sqrMagnitude);
			});
			return NearbyCache;
		}

		private static bool CanTakeFrom(Container container)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			if (container.GetInventory() == null || (Object)(object)container.m_wagon != (Object)null || container.m_autoDestroyEmpty || (Object)(object)((Component)container).GetComponent<TombStone>() != (Object)null)
			{
				return false;
			}
			ZNetView val = NviewRef.Invoke(container);
			if ((Object)(object)val == (Object)null || !val.IsValid())
			{
				return false;
			}
			if ((Object)(object)((Component)container).GetComponent<Piece>() == (Object)null)
			{
				return false;
			}
			if (container.IsInUse() || val.GetZDO().GetInt(ZDOVars.s_inUse, 0) == 1)
			{
				return false;
			}
			if (container.CheckAccess(Game.instance.GetPlayerProfile().GetPlayerID()))
			{
				if (container.m_checkGuardStone)
				{
					return PrivateArea.CheckAccess(((Component)container).transform.position, 0f, false, false);
				}
				return true;
			}
			return false;
		}

		private static void TakeFromChests(Player player, string name, int amount, int quality, bool matchWorldLevel)
		{
			amount = TakeFromGround(player, name, amount, quality, matchWorldLevel);
			foreach (Container item in GetNearby(player))
			{
				if (amount <= 0)
				{
					break;
				}
				Inventory inventory = item.GetInventory();
				int num = Mathf.Min(inventory.CountItems(name, quality, matchWorldLevel), amount);
				if (num > 0)
				{
					if (!item.IsOwner())
					{
						NviewRef.Invoke(item).ClaimOwnership();
					}
					inventory.RemoveItem(name, num, quality, matchWorldLevel);
					amount -= num;
				}
			}
		}
	}
	internal enum GridPlane
	{
		None,
		Terrain,
		Top,
		Bottom,
		WallX,
		WallZ
	}
	internal sealed class GridOverlay
	{
		private static ConfigEntry<float> _radius;

		private static ConfigEntry<float> _fadeStart;

		private static ConfigEntry<float> _rebuildDistance;

		private static ConfigEntry<float> _lift;

		private static ConfigEntry<float> _segmentLength;

		private static ConfigEntry<float> _gridLineWidth;

		private static ConfigEntry<float> _minorLineScale;

		private static ConfigEntry<float> _chunkLineWidth;

		private static ConfigEntry<float> _chunkLineLift;

		private static ConfigEntry<Color> _lineColor;

		private static ConfigEntry<Color> _chunkLineColor;

		private static ConfigEntry<float> _chunkCentreLineWidth;

		private static ConfigEntry<Color> _chunkCentreLineColor;

		private GameObject _object;

		private Mesh _mesh;

		private bool _hasMesh;

		private bool _warned;

		private float _builtSize;

		private Vector2 _builtCenter;

		private GridPlane _builtPlane;

		private float _builtSign;

		private float _builtNormalValue;

		private const float MajorInterval = 2f;

		private static float Radius => _radius.Value;

		private static float FadeStart => Mathf.Min(_fadeStart.Value, Radius - 0.01f);

		private static float RebuildDistance => _rebuildDistance.Value;

		private static float Lift => _lift.Value;

		private static float SegmentLength => _segmentLength.Value;

		private static float GridLineWidth => _gridLineWidth.Value;

		private static float MinorLineWidth => GridLineWidth * _minorLineScale.Value;

		private static float ChunkLineWidth => _chunkLineWidth.Value;

		private static float ChunkLineLift => _chunkLineLift.Value;

		private static Color LineColor => _lineColor.Value;

		private static Color ChunkLineColor => _chunkLineColor.Value;

		private static float ChunkCentreLineWidth => _chunkCentreLineWidth.Value;

		private static Color ChunkCentreLineColor => _chunkCentreLineColor.Value;

		public static void BindConfig(ConfigFile config)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Expected O, but got Unknown
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Expected O, but got Unknown
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Expected O, but got Unknown
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Expected O, but got Unknown
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			_radius = config.Bind<float>("Grid Appearance", "Radius", 8f, new ConfigDescription("Half-extent in metres of the drawn grid around the aim point.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 32f), Array.Empty<object>()));
			_fadeStart = config.Bind<float>("Grid Appearance", "Fade Start", 4f, new ConfigDescription("Distance in metres from the grid centre where lines start to fade out (kept below Radius).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 32f), Array.Empty<object>()));
			_rebuildDistance = config.Bind<float>("Grid Appearance", "Rebuild Distance", 2f, new ConfigDescription("How far in metres the aim point can move from the grid centre before the grid is redrawn.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 16f), Array.Empty<object>()));
			_lift = config.Bind<float>("Grid Appearance", "Lift", 0.12f, new ConfigDescription("Height in metres above the surface, keeps lines clear of grass and z-fighting.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			_segmentLength = config.Bind<float>("Grid Appearance", "Segment Length", 0.5f, new ConfigDescription("Line subdivision in metres so lines can follow terrain. Smaller is smoother but heavier.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 4f), Array.Empty<object>()));
			_gridLineWidth = config.Bind<float>("Grid Appearance", "Line Width", 0.06f, new ConfigDescription("Width in metres of the grid lines at 2m intervals.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 1f), Array.Empty<object>()));
			_minorLineScale = config.Bind<float>("Grid Appearance", "Minor Line Width Scale", 0.5f, new ConfigDescription("Width of the grid lines between the 2m lines, as a fraction of Line Width. Set to 1 to draw every line the same thickness.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1f), Array.Empty<object>()));
			_chunkLineWidth = config.Bind<float>("Grid Appearance", "Chunk Line Width", 0.2f, new ConfigDescription("Width in metres of the thick lines drawn on world chunk (zone) borders.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 2f), Array.Empty<object>()));
			_chunkLineLift = config.Bind<float>("Grid Appearance", "Chunk Line Lift", 0.13f, new ConfigDescription("Height in metres above the surface of chunk border lines; keep slightly above Lift so they draw on top.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			_chunkCentreLineWidth = config.Bind<float>("Grid Appearance", "Chunk Centre Line Width", 0.12f, new ConfigDescription("Width in metres of the lines drawn through the centre of each world chunk (zone).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 2f), Array.Empty<object>()));
			_chunkCentreLineColor = config.Bind<Color>("Grid Appearance", "Chunk Centre Line Color", new Color(0.1f, 1f, 0.4f, 0.75f), "Colour (including alpha) of the lines through the centre of each world chunk.");
			_lineColor = config.Bind<Color>("Grid Appearance", "Line Color", new Color(1f, 1f, 1f, 0.3f), "Colour (including alpha) of the regular grid lines.");
			_chunkLineColor = config.Bind<Color>("Grid Appearance", "Chunk Line Color", new Color(1f, 0.1f, 0.1f, 0.75f), "Colour (including alpha) of the world chunk border lines.");
		}

		public void Show(Vector3 aim, float size, GridPlane plane, float sign)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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_00a0: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			if (!EnsureObject())
			{
				return;
			}
			Vector2 val = ToPlane(plane, aim);
			float num = NormalCoord(plane, aim);
			Vector2 center = default(Vector2);
			((Vector2)(ref center))..ctor(Mathf.Round(val.x / size) * size, Mathf.Round(val.y / size) * size);
			if (_hasMesh && Mathf.Approximately(size, _builtSize) && plane == _builtPlane && sign == _builtSign && (plane == GridPlane.Terrain || !(Mathf.Abs(num - _builtNormalValue) > 0.01f)))
			{
				Vector2 val2 = val - _builtCenter;
				if (!(((Vector2)(ref val2)).magnitude > RebuildDistance))
				{
					goto IL_00ab;
				}
			}
			Rebuild(center, size, plane, sign, num);
			goto IL_00ab;
			IL_00ab:
			_object.SetActive(true);
		}

		public void Hide()
		{
			if ((Object)(object)_object != (Object)null && _object.activeSelf)
			{
				_object.SetActive(false);
			}
		}

		public void Destroy()
		{
			if ((Object)(object)_object != (Object)null)
			{
				Object.Destroy((Object)(object)_object);
			}
			if ((Object)(object)_mesh != (Object)null)
			{
				Object.Destroy((Object)(object)_mesh);
			}
			_object = null;
			_mesh = null;
			_hasMesh = false;
		}

		private bool EnsureObject()
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			if ((Object)(object)_object != (Object)null)
			{
				return true;
			}
			Shader val = Shader.Find("Sprites/Default") ?? Shader.Find("Legacy Shaders/Particles/Alpha Blended") ?? Shader.Find("Hidden/Internal-Colored");
			if ((Object)(object)val == (Object)null)
			{
				if (!_warned)
				{
					Debug.LogWarning((object)"NoHammerBuildMenu: no usable shader found for the build grid overlay.");
				}
				_warned = true;
				return false;
			}
			_mesh = new Mesh
			{
				name = "NoHammerBuildMenu_Grid",
				indexFormat = (IndexFormat)1
			};
			_mesh.MarkDynamic();
			_object = new GameObject("NoHammerBuildMenu_Grid");
			Object.DontDestroyOnLoad((Object)(object)_object);
			_object.AddComponent<MeshFilter>().sharedMesh = _mesh;
			MeshRenderer val2 = _object.AddComponent<MeshRenderer>();
			Material val3 = new Material(val);
			((Renderer)val2).sharedMaterials = (Material[])(object)new Material[2] { val3, val3 };
			((Renderer)val2).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)val2).receiveShadows = false;
			_object.SetActive(false);
			return true;
		}

		private static Vector2 ToPlane(GridPlane plane, Vector3 p)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			return (Vector2)(plane switch
			{
				GridPlane.WallX => new Vector2(p.z, p.y), 
				GridPlane.WallZ => new Vector2(p.x, p.y), 
				_ => new Vector2(p.x, p.z), 
			});
		}

		private static float NormalCoord(GridPlane plane, Vector3 p)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			return plane switch
			{
				GridPlane.WallX => p.x, 
				GridPlane.WallZ => p.z, 
				_ => p.y, 
			};
		}

		private static Vector3 ToWorld(GridPlane plane, float a, float b, float n)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			return (Vector3)(plane switch
			{
				GridPlane.WallX => new Vector3(n, b, a), 
				GridPlane.WallZ => new Vector3(a, b, n), 
				_ => new Vector3(a, n, b), 
			});
		}

		private void Rebuild(Vector2 center, float size, GridPlane plane, float sign, float normalValue)
		{
			//IL_0064: 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)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			int num = Mathf.FloorToInt(Radius / size);
			int num2 = Mathf.CeilToInt(2f * Radius / SegmentLength);
			float step = 2f * Radius / (float)num2;
			List<Vector3> vertices = new List<Vector3>();
			List<Color> colors = new List<Color>();
			List<int> list = new List<int>();
			List<int> list2 = new List<int>();
			for (int i = -num; i <= num; i++)
			{
				float num3 = (float)i * size;
				AddRibbon(plane, sign, normalValue, 0, center.x + num3, center.y, num3, LineWidthAt(center.x + num3), Lift, LineColor, num2, step, vertices, colors, list);
				AddRibbon(plane, sign, normalValue, 1, center.y + num3, center.x, num3, LineWidthAt(center.y + num3), Lift, LineColor, num2, step, vertices, colors, list);
			}
			AddChunkLines(plane, sign, normalValue, center, num2, step, vertices, colors, list2);
			_mesh.Clear();
			_mesh.subMeshCount = 2;
			_mesh.SetVertices(vertices);
			_mesh.SetColors(colors);
			_mesh.SetIndices(list, (MeshTopology)0, 0, true, 0);
			_mesh.SetIndices(list2, (MeshTopology)0, 1, true, 0);
			_mesh.RecalculateBounds();
			_hasMesh = true;
			_builtSize = size;
			_builtCenter = center;
			_builtPlane = plane;
			_builtSign = sign;
			_builtNormalValue = normalValue;
		}

		private static float LineWidthAt(float coordinate)
		{
			if (!(Mathf.Abs(coordinate - Mathf.Round(coordinate / 2f) * 2f) < 0.001f))
			{
				return MinorLineWidth;
			}
			return GridLineWidth;
		}

		private static void AddChunkLines(GridPlane plane, float sign, float normalValue, Vector2 center, int segments, float step, List<Vector3> vertices, List<Color> colors, List<int> indices)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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)
			//IL_002d: 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_0073: Unknown result type (might be due to invalid IL or missing references)
			bool flag = (uint)(plane - 1) <= 2u;
			int num = ((!flag) ? 1 : 2);
			for (int i = 0; i < num; i++)
			{
				float centerAlong = ((i == 0) ? center.x : center.y);
				float centerAcross = ((i == 0) ? center.y : center.x);
				AddZoneLines(plane, sign, normalValue, i, 32f, centerAlong, centerAcross, ChunkLineWidth, ChunkLineColor, segments, step, vertices, colors, indices);
				AddZoneLines(plane, sign, normalValue, i, 0f, centerAlong, centerAcross, ChunkCentreLineWidth, ChunkCentreLineColor, segments, step, vertices, colors, indices);
			}
		}

		private static void AddZoneLines(GridPlane plane, float sign, float normalValue, int axis, float offset, float centerAlong, float centerAcross, float width, Color color, int segments, float step, List<Vector3> vertices, List<Color> colors, List<int> indices)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			int num = Mathf.CeilToInt((centerAlong - Radius - offset) / 64f);
			int num2 = Mathf.FloorToInt((centerAlong + Radius - offset) / 64f);
			for (int i = num; i <= num2; i++)
			{
				float num3 = (float)i * 64f + offset;
				AddRibbon(plane, sign, normalValue, axis, num3, centerAcross, num3 - centerAlong, width, ChunkLineLift, color, segments, step, vertices, colors, indices);
			}
		}

		private static void AddRibbon(GridPlane plane, float sign, float normalValue, int axis, float line, float centerAcross, float lineOffset, float width, float lift, Color baseColor, int segments, float step, List<Vector3> vertices, List<Color> colors, List<int> indices)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			float num = width / 2f;
			int count = vertices.Count;
			Color item = default(Color);
			for (int i = 0; i <= segments; i++)
			{
				float num2 = 0f - Radius + (float)i * step;
				float num3 = Mathf.Sqrt(lineOffset * lineOffset + num2 * num2);
				float num4 = Mathf.Clamp01(1f - (num3 - FadeStart) / (Radius - FadeStart));
				((Color)(ref item))..ctor(baseColor.r, baseColor.g, baseColor.b, baseColor.a * num4);
				for (int j = -1; j <= 1; j += 2)
				{
					float num5 = line + (float)j * num;
					float num6 = centerAcross + num2;
					float num7 = ((axis == 0) ? num5 : num6);
					float num8 = ((axis == 0) ? num6 : num5);
					float num9 = ((plane == GridPlane.Terrain) ? GroundHeight(num7, num8) : normalValue);
					vertices.Add(ToWorld(plane, num7, num8, num9 + sign * lift));
					colors.Add(item);
				}
				if (i > 0)
				{
					int num10 = count + (i - 1) * 2;
					indices.Add(num10);
					indices.Add(num10 + 1);
					indices.Add(num10 + 2);
					indices.Add(num10 + 1);
					indices.Add(num10 + 3);
					indices.Add(num10 + 2);
				}
			}
		}

		private static float GroundHeight(float x, float z)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)ZoneSystem.instance == (Object)null))
			{
				return ZoneSystem.instance.GetGroundHeight(new Vector3(x, 0f, z));
			}
			return 0f;
		}
	}
	internal static class KeyHintUI
	{
		private enum HintVisibility
		{
			Always,
			GridOnly,
			BuildOnly
		}

		private sealed class Hint
		{
			public string Label;

			public int Column;

			public string[] Keys;

			public HintVisibility Visibility;

			public GameObject Item;

			public CanvasGroup Group;
		}

		[HarmonyPatch(typeof(KeyHints), "UpdateHints")]
		private static class KeyHints_UpdateHints_Patch
		{
			[HarmonyPostfix]
			private static void Postfix(KeyHints __instance)
			{
				if (_container != null && (Object)(object)_container == (Object)null)
				{
					Reset();
				}
				Update(__instance, Player.m_localPlayer);
			}
		}

		private const string ContainerName = "NoHammerBuildMenu_KeyHints";

		private const string ScrollIcon = "@scroll";

		private const float LabelFontSize = 16f;

		private const float IconHeight = 32f;

		private const float IconScale = 1.8f;

		private const float ColumnSpacing = 40f;

		private const float RowSpacing = 16f;

		private static readonly List<Hint> Hints = new List<Hint>(5)
		{
			new Hint
			{
				Label = "$nhbm_hint_move",
				Column = 0,
				Keys = new string[2] { "Left Ctrl", "$button_mouse2" },
				Visibility = HintVisibility.Always
			},
			new Hint
			{
				Label = "$nhbm_hint_grid",
				Column = 0,
				Keys = new string[2] { "Left Ctrl", "$button_mouse1" },
				Visibility = HintVisibility.BuildOnly
			},
			new Hint
			{
				Label = "$nhbm_hint_repair",
				Column = 0,
				Keys = new string[2] { "Left Shift", "$button_mouse1" },
				Visibility = HintVisibility.Always
			},
			new Hint
			{
				Label = "$nhbm_hint_grid_distance",
				Column = 1,
				Keys = new string[2] { "Left Ctrl", "@scroll" },
				Visibility = HintVisibility.GridOnly
			},
			new Hint
			{
				Label = "$nhbm_hint_zoom",
				Column = 1,
				Keys = new string[2] { "Left Alt", "@scroll" },
				Visibility = HintVisibility.Always
			}
		};

		private static GameObject _container;

		private static RectTransform _rotateAnchor;

		private static RectTransform _rotateIcon;

		private static Image _rotateIconImage;

		private static bool _createFailed;

		private static bool _layoutDirty;

		private static TextMeshProUGUI _buildMenuLabel;

		private static string _buildMenuText;

		public static void Update(KeyHints keyHints, Player player)
		{
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Expected O, but got Unknown
			UpdateAbortHint(keyHints);
			if (!((Object)(object)keyHints.m_buildHints != (Object)null) || !keyHints.m_buildHints.activeInHierarchy || !((Object)(object)player != (Object)null) || !((Character)player).InPlaceMode() || ZInput.IsGamepadActive() || !NoHammerBuildMenuPlugin.IsHammerEquipped(player))
			{
				if ((Object)(object)_container != (Object)null && _container.activeSelf)
				{
					_container.SetActive(false);
				}
			}
			else
			{
				if ((Object)(object)_container == (Object)null && (_createFailed || !Create(keyHints)))
				{
					return;
				}
				bool flag = player.InRepairMode();
				bool gridEnabled = NoHammerBuildMenuPlugin.GridEnabled;
				foreach (Hint hint in Hints)
				{
					bool flag2 = true;
					bool flag3 = false;
					switch (hint.Visibility)
					{
					case HintVisibility.BuildOnly:
						flag2 = !flag;
						break;
					case HintVisibility.GridOnly:
						flag2 = !flag;
						flag3 = !gridEnabled;
						break;
					}
					if (hint.Item.activeSelf != flag2)
					{
						hint.Item.SetActive(flag2);
						_layoutDirty = true;
					}
					hint.Group.alpha = (flag3 ? 0f : 1f);
				}
				if (!_container.activeSelf)
				{
					_container.SetActive(true);
					_layoutDirty = true;
				}
				if (_layoutDirty)
				{
					LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform)_container.transform);
					_layoutDirty = false;
				}
				AlignToRotateHint();
			}
		}

		private static void UpdateAbortHint(KeyHints keyHints)
		{
			if ((Object)(object)_buildMenuLabel == (Object)null && (Object)(object)keyHints.m_buildHints != (Object)null)
			{
				Transform val = keyHints.m_buildHints.transform.Find("Keyboard/BuildMenu/Text");
				_buildMenuLabel = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<TextMeshProUGUI>() : null);
				_buildMenuText = null;
			}
			if ((Object)(object)_buildMenuLabel == (Object)null)
			{
				return;
			}
			if (PieceMover.Moving)
			{
				if (_buildMenuText == null)
				{
					_buildMenuText = ((TMP_Text)_buildMenuLabel).text;
				}
				((TMP_Text)_buildMenuLabel).text = Localization.instance.Localize("$nhbm_hint_abort");
			}
			else if (_buildMenuText != null)
			{
				((TMP_Text)_buildMenuLabel).text = _buildMenuText;
				_buildMenuText = null;
			}
		}

		private static void AlignToRotateHint()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: 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)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			_rotateAnchor.GetWorldCorners(array);
			Rect rect = _rotateIcon.rect;
			float num = Mathf.Min(((Rect)(ref rect)).width, ((Rect)(ref rect)).height * SpriteAspect(_rotateIconImage));
			float num2 = ((Transform)_rotateIcon).TransformPoint(Vector2.op_Implicit(((Rect)(ref rect)).center)).x + num / 2f * ((Transform)_rotateIcon).lossyScale.x;
			_container.transform.position = new Vector3(num2, array[2].y, array[2].z);
		}

		private static bool Create(KeyHints keyHints)
		{
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Expected O, but got Unknown
			//IL_04d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04df: Expected O, but got Unknown
			//IL_04e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04eb: Expected O, but got Unknown
			//IL_041c: Unknown result type (might be due to invalid IL or missing references)
			Transform val = keyHints.m_buildHints.transform.Find("Keyboard");
			Transform val2 = (((Object)(object)val != (Object)null) ? val.Find("Copy") : null);
			Transform val3 = (((Object)(object)val != (Object)null) ? val.Find("rotate") : null);
			Transform val4 = (((Object)(object)val2 != (Object)null) ? val2.Find("Text") : null);
			Transform val5 = (((Object)(object)val2 != (Object)null) ? val2.Find("Text (1)") : null);
			Transform val6 = (((Object)(object)val2 != (Object)null) ? val2.Find("key_bkg") : null);
			Transform val7 = (((Object)(object)val3 != (Object)null) ? val3.Find("mousew_icon") : null);
			HorizontalLayoutGroup val8 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<HorizontalLayoutGroup>() : null);
			if ((Object)(object)val4 == (Object)null || (Object)(object)val5 == (Object)null || (Object)(object)val6 == (Object)null || (Object)(object)val7 == (Object)null || (Object)(object)val8 == (Object)null)
			{
				_createFailed = true;
				Debug.LogWarning((object)"NoHammerBuildMenu: vanilla build key hints layout not as expected, not adding key hints.");
				return false;
			}
			RectTransform component = new GameObject("NoHammerBuildMenu_KeyHints", new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>();
			((Transform)component).SetParent(keyHints.m_buildHints.transform, false);
			component.pivot = new Vector2(1f, 0f);
			HorizontalLayoutGroup obj = ((Component)component).gameObject.AddComponent<HorizontalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)obj).spacing = 40f;
			((LayoutGroup)obj).childAlignment = (TextAnchor)8;
			((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = false;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = false;
			ContentSizeFitter obj2 = ((Component)component).gameObject.AddComponent<ContentSizeFitter>();
			obj2.horizontalFit = (FitMode)2;
			obj2.verticalFit = (FitMode)2;
			int num = 0;
			foreach (Hint hint in Hints)
			{
				num = Mathf.Max(num, hint.Column + 1);
			}
			Transform[] array = (Transform[])(object)new Transform[num];
			for (int i = 0; i < num; i++)
			{
				GameObject val9 = new GameObject("NoHammerBuildMenu_KeyHints_Column" + i, new Type[1] { typeof(RectTransform) });
				val9.transform.SetParent((Transform)(object)component, false);
				VerticalLayoutGroup obj3 = val9.AddComponent<VerticalLayoutGroup>();
				((HorizontalOrVerticalLayoutGroup)obj3).spacing = 16f;
				((LayoutGroup)obj3).childAlignment = (TextAnchor)((i == num - 1) ? 8 : 6);
				((HorizontalOrVerticalLayoutGroup)obj3).childControlWidth = true;
				((HorizontalOrVerticalLayoutGroup)obj3).childControlHeight = true;
				((HorizontalOrVerticalLayoutGroup)obj3).childForceExpandWidth = false;
				((HorizontalOrVerticalLayoutGroup)obj3).childForceExpandHeight = false;
				array[i] = val9.transform;
			}
			foreach (Hint hint2 in Hints)
			{
				GameObject val10 = Object.Instantiate<GameObject>(((Component)val2).gameObject, array[hint2.Column], false);
				((Object)val10).name = "NoHammerBuildMenu_Hint_" + hint2.Label.TrimStart(new char[1] { '$' });
				val10.SetActive(true);
				for (int num2 = val10.transform.childCount - 1; num2 >= 0; num2--)
				{
					Object.DestroyImmediate((Object)(object)((Component)val10.transform.GetChild(num2)).gameObject);
				}
				AddText(val4, val10.transform, Localization.instance.Localize(hint2.Label));
				for (int j = 0; j < hint2.Keys.Length; j++)
				{
					if (j > 0)
					{
						AddText(val5, val10.transform, "+");
					}
					if (hint2.Keys[j] == "@scroll")
					{
						GameObject val11 = Object.Instantiate<GameObject>(((Component)val7).gameObject, val10.transform, false);
						val11.SetActive(true);
						Image component2 = val11.GetComponent<Image>();
						component2.preserveAspect = true;
						float num3 = SpriteAspect(component2);
						LayoutElement obj4 = val11.GetComponent<LayoutElement>() ?? val11.AddComponent<LayoutElement>();
						float minWidth = (obj4.preferredWidth = 32f * num3 * 1.8f);
						obj4.minWidth = minWidth;
						minWidth = (obj4.preferredHeight = 32f);
						obj4.minHeight = minWidth;
						minWidth = (obj4.flexibleHeight = 0f);
						obj4.flexibleWidth = minWidth;
						val11.transform.localScale = new Vector3(1.8f, 1.8f, 1f);
					}
					else
					{
						GameObject obj5 = Object.Instantiate<GameObject>(((Component)val6).gameObject, val10.transform, false);
						obj5.SetActive(true);
						((TMP_Text)obj5.GetComponentInChildren<TextMeshProUGUI>()).text = Localization.instance.Localize(hint2.Keys[j]);
					}
				}
				hint2.Item = val10;
				hint2.Group = val10.GetComponent<CanvasGroup>() ?? val10.AddComponent<CanvasGroup>();
			}
			LayoutRebuilder.ForceRebuildLayoutImmediate(component);
			for (int k = 0; k < num; k++)
			{
				EqualiseColumnWidths(k);
			}
			_rotateAnchor = (RectTransform)val3;
			_rotateIcon = (RectTransform)val7;
			_rotateIconImage = ((Component)val7).GetComponent<Image>();
			_container = ((Component)component).gameObject;
			_layoutDirty = true;
			return true;
		}

		private static void EqualiseColumnWidths(int column)
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			List<Transform> list = new List<Transform>();
			foreach (Hint hint in Hints)
			{
				if (hint.Column == column)
				{
					list.Add(hint.Item.transform);
				}
			}
			int num = int.MaxValue;
			foreach (Transform item in list)
			{
				num = Mathf.Min(num, item.childCount);
			}
			for (int i = 0; i < num; i++)
			{
				float num2 = 0f;
				foreach (Transform item2 in list)
				{
					float num3 = num2;
					Rect rect = ((RectTransform)item2.GetChild(i)).rect;
					num2 = Mathf.Max(num3, ((Rect)(ref rect)).width);
				}
				foreach (Transform item3 in list)
				{
					GameObject gameObject = ((Component)item3.GetChild(i)).gameObject;
					(gameObject.GetComponent<LayoutElement>() ?? gameObject.AddComponent<LayoutElement>()).minWidth = num2;
				}
			}
		}

		private static float SpriteAspect(Image image)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)image.sprite != (Object)null))
			{
				return 0.6f;
			}
			Rect rect = image.sprite.rect;
			float width = ((Rect)(ref rect)).width;
			rect = image.sprite.rect;
			return width / ((Rect)(ref rect)).height;
		}

		private static void AddText(Transform template, Transform parent, string text)
		{
			GameObject obj = Object.Instantiate<GameObject>(((Component)template).gameObject, parent, false);
			obj.SetActive(true);
			LayoutElement component = obj.GetComponent<LayoutElement>();
			if ((Object)(object)component != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)component);
			}
			TextMeshProUGUI component2 = obj.GetComponent<TextMeshProUGUI>();
			((TMP_Text)component2).enableAutoSizing = false;
			((TMP_Text)component2).fontSize = 16f;
			((TMP_Text)component2).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)component2).text = text;
		}

		public static void Reset()
		{
			_container = null;
			_rotateAnchor = null;
			_rotateIcon = null;
			_rotateIconImage = null;
			_createFailed = false;
			_buildMenuLabel = null;
			_buildMenuText = null;
			foreach (Hint hint in Hints)
			{
				hint.Item = null;
				hint.Group = null;
			}
		}
	}
	internal static class PieceMover
	{
		private const string RemoveButton = "Remove";

		private const string PlaceButton = "Attack";

		private static ZNetView _source;

		private static string _prefabName;

		private static Piece _previousPiece;

		private static int _previousRotation;

		private static bool _blockRemoveUntilReleased;

		private static int _rightClickFrame = -10;

		private static readonly Color HighlightColor = new Color(0.941f, 0.69f, 0.29f);

		private static readonly int EmissionColor = Shader.PropertyToID("_EmissionColor");

		private static readonly List<Collider> SourceColliders = new List<Collider>();

		private static readonly List<Collider> HiddenColliders = new List<Collider>();

		private static StationExtension _hiddenExtension;

		private static readonly Dictionary<PlacementStatus, string> StatusMessages = new Dictionary<PlacementStatus, string>
		{
			[(PlacementStatus)3] = "$msg_nobuildzone",
			[(PlacementStatus)2] = "$msg_blocked",
			[(PlacementStatus)4] = "$msg_privatezone",
			[(PlacementStatus)5] = "$msg_needspace",
			[(PlacementStatus)6] = "$msg_noteleportarea",
			[(PlacementStatus)7] = "$msg_extensionmissingstation",
			[(PlacementStatus)8] = "$msg_wrongbiome",
			[(PlacementStatus)9] = "$msg_needcultivated",
			[(PlacementStatus)10] = "$msg_needdirt",
			[(PlacementStatus)11] = "$msg_notindungeon",
			[(PlacementStatus)13] = "$msg_snowtoodeep",
			[(PlacementStatus)14] = "$msg_nosnow"
		};

		internal static bool Moving => (Object)(object)_source != (Object)null;

		internal static bool RightClickConsumed
		{
			get
			{
				if (!Moving)
				{
					return _rightClickFrame == Time.frameCount;
				}
				return true;
			}
		}

		internal static bool BeforeUpdatePlacement(Player player, bool takeInput)
		{
			if (_blockRemoveUntilReleased)
			{
				if (ZInput.GetButton("Remove") || ZInput.GetButtonUp("Remove"))
				{
					player.m_blockRemove = true;
				}
				else
				{
					_blockRemoveUntilReleased = false;
				}
			}
			string text = (Moving ? AbortReason(player) : null);
			if (text != null)
			{
				Stop(player);
				((Character)player).Message((MessageType)1, text, 0, (Sprite)null, false);
			}
			bool moving = Moving;
			if (!takeInput || !((Character)player).InPlaceMode() || ((Character)player).IsDead() || Hud.IsPieceSelectionVisible() || Hud.InRadial() || ZInput.IsGamepadActive() || !NoHammerBuildMenuPlugin.IsHammerEquipped(player))
			{
				return moving;
			}
			if (NoHammerBuildMenuPlugin.CtrlHeld() && ZInput.GetButtonDown("Remove"))
			{
				_blockRemoveUntilReleased = true;
				player.m_blockRemove = true;
				PickUp(player);
			}
			else if (Moving && ZInput.GetButtonDown("Remove") && (Object)(object)player.GetHoveringPiece() == (Object)(object)((Component)_source).GetComponent<Piece>())
			{
				_blockRemoveUntilReleased = true;
				player.m_blockRemove = true;
				((Character)player).Message((MessageType)2, "$nhbm_move_cant_remove", 0, (Sprite)null, false);
			}
			else if (Moving && Input.GetMouseButtonDown(1))
			{
				_rightClickFrame = Time.frameCount;
				Stop(player);
				((Character)player).Message((MessageType)1, "$nhbm_move_aborted", 0, (Sprite)null, false);
			}
			else if (Moving && ZInput.GetButtonDown("Attack") && Time.time - player.m_lastToolUseTime > player.m_placeDelay)
			{
				PutDown(player);
			}
			if (!moving)
			{
				return Moving;
			}
			return true;
		}

		internal static void BlockVanillaPlacing(Player player)
		{
			player.m_placePressedTime = -9999f;
		}

		internal static void Reset()
		{
			ClearHighlight();
			_source = null;
			_prefabName = null;
			_previousPiece = null;
			_blockRemoveUntilReleased = false;
		}

		private static void PickUp(Player player)
		{
			//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_0061: Unknown result type (might be due to invalid IL or missing references)
			Piece hoveringPiece = player.GetHoveringPiece();
			if (!((Object)(object)hoveringPiece == (Object)null) && CanMove(player, hoveringPiece, out var nview))
			{
				if (!Moving)
				{
					_previousPiece = player.GetSelectedPiece();
					_previousRotation = player.m_placeRotation;
				}
				if (!player.SetSelectedPiece(hoveringPiece))
				{
					((Character)player).Message((MessageType)2, "$msg_missingrequirement", 0, (Sprite)null, false);
					return;
				}
				Quaternion rotation = ((Component)hoveringPiece).transform.rotation;
				player.m_placeRotation = (int)Math.Round(((Quaternion)(ref rotation)).eulerAngles.y / player.m_placeRotationDegrees);
				ClearHighlight();
				_source = nview;
				_prefabName = Utils.GetPrefabName(((Component)hoveringPiece).gameObject);
				((Character)player).Message((MessageType)1, Localization.instance.Localize("$nhbm_move_started", new string[1] { Localization.instance.Localize(hoveringPiece.m_name) }), 0, (Sprite)null, false);
			}
		}

		private static void PutDown(Player player)
		{
			//IL_0064: 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_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			player.m_lastToolUseTime = Time.time;
			Piece component = ((Component)_source).GetComponent<Piece>();
			if ((Object)(object)component == (Object)null || !CanMove(player, component, out var _))
			{
				return;
			}
			ItemData rightItem = ((Humanoid)player).GetRightItem();
			if (!((Character)player).HaveStamina(rightItem.m_shared.m_attack.m_attackStamina))
			{
				Hud.instance.StaminaBarEmptyFlash();
				return;
			}
			player.UpdatePlacementGhost(true);
			GameObject placementGhost = player.m_placementGhost;
			if ((int)player.m_placementStatus != 0 || (Object)(object)placementGhost == (Object)null)
			{
				((Character)player).Message((MessageType)2, StatusMessages.TryGetValue(player.m_placementStatus, out var value) ? value : "$msg_invalidplacement", 0, (Sprite)null, false);
				return;
			}
			Vector3 position = ((Component)component).transform.position;
			Vector3 position2 = placementGhost.transform.position;
			Quaternion rotation = placementGhost.transform.rotation;
			GameObject val = Recreate(_source, position2, rotation);
			if ((Object)(object)val == (Object)null)
			{
				((Character)player).Message((MessageType)2, "$nhbm_move_failed", 0, (Sprite)null, false);
				return;
			}
			ClearHighlight();
			_source.ClaimOwnership();
			ZNetScene.instance.Destroy(((Component)_source).gameObject);
			component.m_placeEffect.Create(position2, rotation, val.transform, 1f, -1, ((Character)player).GetZDOID());
			player.m_removeEffects.Create(position, Quaternion.identity, (Transform)null, 1f, -1, ((Character)player).GetZDOID());
			player.FaceLookDirection();
			((Character)player).m_zanim.SetTrigger(rightItem.m_shared.m_attack.m_attackAnimation);
			((Character)player).UseStamina(player.GetBuildStamina());
			if (rightItem.m_shared.m_useDurability)
			{
				rightItem.m_durability -= player.GetPlaceDurability(rightItem) * Game.m_durabilityRate;
			}
			_source = null;
			Stop(player);
			((Character)player).Message((MessageType)1, Localization.instance.Localize("$nhbm_moved", new string[1] { Localization.instance.Localize(component.m_name) }), 0, (Sprite)null, false);
		}

		internal static void UpdateHighlight()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			if (Moving && !((Object)(object)MaterialMan.instance == (Object)null))
			{
				float num = Mathf.Lerp(0.3f, 0.7f, (Mathf.Sin(Time.time * 5f) + 1f) * 0.5f);
				MaterialMan.instance.SetValue<Color>(((Component)_source).gameObject, EmissionColor, HighlightColor * num, false);
			}
		}

		private static void ClearHighlight()
		{
			if ((Object)(object)_source != (Object)null && (Object)(object)MaterialMan.instance != (Object)null)
			{
				MaterialMan.instance.ResetValue(((Component)_source).gameObject, EmissionColor);
			}
		}

		internal static void HideFromPlacementChecks()
		{
			if (!Moving)
			{
				return;
			}
			((Component)_source).GetComponentsInChildren<Collider>(SourceColliders);
			foreach (Collider sourceCollider in SourceColliders)
			{
				if (sourceCollider.enabled)
				{
					sourceCollider.enabled = false;
					HiddenColliders.Add(sourceCollider);
				}
			}
			SourceColliders.Clear();
			StationExtension componentInChildren = ((Component)_source).GetComponentInChildren<StationExtension>();
			if ((Object)(object)componentInChildren != (Object)null && StationExtension.m_allExtensions.Remove(componentInChildren))
			{
				_hiddenExtension = componentInChildren;
			}
		}

		internal static void RestoreAfterPlacementChecks()
		{
			foreach (Collider hiddenCollider in HiddenColliders)
			{
				if ((Object)(object)hiddenCollider != (Object)null)
				{
					hiddenCollider.enabled = true;
				}
			}
			HiddenColliders.Clear();
			if ((Object)(object)_hiddenExtension != (Object)null)
			{
				StationExtension.m_allExtensions.Add(_hiddenExtension);
				_hiddenExtension = null;
			}
		}

		private static GameObject Recreate(ZNetView source, Vector3 position, Quaternion rotation)
		{
			//IL_002a: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = source.GetZDO();
			int prefab = zDO.GetPrefab();
			GameObject prefab2 = ZNetScene.instance.GetPrefab(prefab);
			if ((Object)(object)prefab2 == (Object)null)
			{
				return null;
			}
			ZDO val = ZDOMan.instance.CreateNewZDO(position, prefab);
			val.Persistent = zDO.Persistent;
			val.Type = zDO.Type;
			val.Distant = zDO.Distant;
			val.SetPrefab(prefab);
			val.SetRotation(rotation);
			CopyData(zDO.m_uid, val);
			GameObject val2 = null;
			ZNetView.m_useInitZDO = true;
			ZNetView.m_initZDO = val;
			try
			{
				val2 = Object.Instantiate<GameObject>(prefab2, position, rotation);
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("NoHammerBuildMenu: failed to move " + ((Object)prefab2).name + ": " + ex));
			}
			finally
			{
				bool flag = ZNetView.m_initZDO != null;
				ZNetView.m_initZDO = null;
				ZNetView.m_useInitZDO = false;
				if ((Object)(object)val2 == (Object)null || flag)
				{
					if ((Object)(object)val2 != (Object)null)
					{
						Object.Destroy((Object)(object)val2);
					}
					ZDOMan.instance.DestroyZDO(val);
					val2 = null;
				}
			}
			return val2;
		}

		private static void CopyData(ZDOID from, ZDO to)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			List<KeyValuePair<int, float>> list = default(List<KeyValuePair<int, float>>);
			List<KeyValuePair<int, Vector3>> list2 = default(List<KeyValuePair<int, Vector3>>);
			List<KeyValuePair<int, Quaternion>> list3 = default(List<KeyValuePair<int, Quaternion>>);
			List<KeyValuePair<int, int>> list4 = default(List<KeyValuePair<int, int>>);
			List<KeyValuePair<int, long>> list5 = default(List<KeyValuePair<int, long>>);
			List<KeyValuePair<int, string>> list6 = default(List<KeyValuePair<int, string>>);
			List<KeyValuePair<int, byte[]>> list7 = default(List<KeyValuePair<int, byte[]>>);
			ZDOConnection val = default(ZDOConnection);
			ZDOExtraData.GetData(from, ref list, ref list2, ref list3, ref list4, ref list5, ref list6, ref list7, ref val);
			foreach (KeyValuePair<int, float> item in list)
			{
				to.Set(item.Key, item.Value);
			}
			foreach (KeyValuePair<int, Vector3> item2 in list2)
			{
				to.Set(item2.Key, item2.Value);
			}
			foreach (KeyValuePair<int, Quaternion> item3 in list3)
			{
				to.Set(item3.Key, item3.Value);
			}
			foreach (KeyValuePair<int, int> item4 in list4)
			{
				to.Set(item4.Key, item4.Value, false);
			}
			foreach (KeyValuePair<int, long> item5 in list5)
			{
				to.Set(item5.Key, item5.Value);
			}
			foreach (KeyValuePair<int, string> item6 in list6)
			{
				to.Set(item6.Key, item6.Value);
			}
			foreach (KeyValuePair<int, byte[]> item7 in list7)
			{
				to.Set(item7.Key, (byte[])item7.Value.Clone());
			}
		}

		private static bool CanMove(Player player, Piece piece, out ZNetView nview)
		{
			//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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			nview = ((Component)piece).GetComponent<ZNetView>();
			if ((Object)(object)nview == (Object)null || !nview.IsValid() || !piece.m_canBeRemoved || !IsMovableKind(piece))
			{
				((Character)player).Message((MessageType)2, "$nhbm_move_cant", 0, (Sprite)null, false);
				return false;
			}
			Vector3 position = ((Component)piece).transform.position;
			if (Location.IsInsideNoBuildLocation(position))
			{
				((Character)player).Message((MessageType)2, "$msg_nobuildzone", 0, (Sprite)null, false);
				return false;
			}
			if (!PrivateArea.CheckAccess(position, 0f, true, false))
			{
				((Character)player).Message((MessageType)2, "$msg_privatezone", 0, (Sprite)null, false);
				return false;
			}
			if (!player.CheckCanRemovePiece(piece))
			{
				return false;
			}
			Container componentInChildren = ((Component)piece).GetComponentInChildren<Container>();
			if ((Object)(object)componentInChildren != (Object)null)
			{
				if (!componentInChildren.CheckAccess(Game.instance.GetPlayerProfile().GetPlayerID()))
				{
					((Character)player).Message((MessageType)2, "$msg_cantopen", 0, (Sprite)null, false);
					return false;
				}
				if (componentInChildren.IsInUse() || nview.GetZDO().GetInt(ZDOVars.s_inUse, 0) == 1)
				{
					((Character)player).Message((MessageType)2, "$msg_inuse", 0, (Sprite)null, false);
					return false;
				}
			}
			return true;
		}

		private static bool IsMovableKind(Piece piece)
		{
			if (((Component)piece).GetComponentsInChildren<ZNetView>(true).Length == 1 && (Object)(object)((Component)piece).GetComponentInChildren<Ship>(true) == (Object)null && (Object)(object)((Component)piece).GetComponentInChildren<Vagon>(true) == (Object)null && (Object)(object)((Component)piece).GetComponentInChildren<Character>(true) == (Object)null && (Object)(object)((Component)piece).GetComponentInChildren<ItemDrop>(true) == (Object)null && (Object)(object)((Component)piece).GetComponentInChildren<TerrainModifier>(true) == (Object)null)
			{
				return ((Component)piece).GetComponentInChildren<IRemoved>(true) == null;
			}
			return false;
		}

		private static string AbortReason(Player player)
		{
			bool num = (Object)(object)_source == (Object)null || !_source.IsValid();
			bool flag = !((Character)player).InPlaceMode() || !NoHammerBuildMenuPlugin.IsHammerEquipped(player);
			bool flag2 = flag;
			if (!num)
			{
				if (flag2)
				{
					return "$nhbm_move_aborted_unequipped";
				}
				if (!SelectedIsMovedPiece(player))
				{
					return "$nhbm_move_aborted_selection";
				}
				return null;
			}
			return "$nhbm_move_aborted_gone";
		}

		private static bool SelectedIsMovedPiece(Player player)
		{
			Piece selectedPiece = player.GetSelectedPiece();
			if ((Object)(object)selectedPiece != (Object)null)
			{
				return Utils.GetPrefabName(((Component)selectedPiece).gameObject) == _prefabName;
			}
			return false;
		}

		private static void Stop(Player player)
		{
			if (((Character)player).InPlaceMode() && SelectedIsMovedPiece(player))
			{
				if ((Object)(object)_previousPiece != (Object)null)
				{
					player.SetSelectedPiece(_previousPiece);
				}
				player.m_placeRotation = _previousRotation;
			}
			ClearHighlight();
			_source = null;
			_prefabName = null;
			_previousPiece = null;
		}
	}
	[BepInPlugin("javidahmed64592.nohammerbuildmenu", "No Hammer Build Menu", "0.14.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class NoHammerBuildMenuPlugin : BaseUnityPlugin
	{
		public const string PluginGUID = "javidahmed64592.nohammerbuildmenu";

		public const string PluginName = "No Hammer Build Menu";

		public const string PluginVersion = "0.14.0";

		private const string HammerPrefabName = "Hammer";

		private const string ButtonName = "NoHammerBuildMenu_Toggle";

		private const string ButtonQueryName = "NoHammerBuildMenu_Toggle!javidahmed64592.nohammerbuildmenu";

		private static readonly float[] GridSizes = new float[5] { 0.25f, 0.5f, 1f, 2f, 4f };

		internal static ItemData _phantomHammer;

		private static ConfigEntry<bool> _gridEnabled;

		internal static ConfigEntry<float> _gridSize;

		private static readonly GridOverlay Overlay = new GridOverlay();

		internal static int _aimFrame = -10;

		internal static Vector3 _aimPoint;

		internal static GridPlane _aimPlane;

		internal static float _aimSign;

		private ConfigEntry<KeyCode> _keybind;

		private Harmony _harmony;

		private bool _knownRecipesRefreshed;

		private Piece _lastBuildPiece;

		internal static bool GridEnabled => _gridEnabled.Value;

		private void Awake()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			_keybind = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Keybinds", "Open Build Menu", (KeyCode)98, "Equips a virtual hammer and opens the build menu, without needing a real hammer in your inventory. Rebindable from the in-game controls menu.");
			InputManager.Instance.AddButton("javidahmed64592.nohammerbuildmenu", new ButtonConfig
			{
				Name = "NoHammerBuildMenu_Toggle",
				Config = _keybind
			});
			_gridEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Grid", "Enabled", true, "Show a world grid while building and snap pieces to its vertices.");
			_gridSize = ((BaseUnityPlugin)this).Config.Bind<float>("Grid", "Snap Distance", GridSizes[1], new ConfigDescription("Distance in metres between grid vertices (0.25, 0.5, 1, 2 or 4). While building, hold Ctrl and scroll to double or halve it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(GridSizes[0], GridSizes[GridSizes.Length - 1]), Array.Empty<object>()));
			GridOverlay.BindConfig(((BaseUnityPlugin)this).Config);
			ChestMaterials.BindConfig(((BaseUnityPlugin)this).Config);
			Translations.Load();
			if (Array.IndexOf(GridSizes, _gridSize.Value) < 0)
			{
				_gridSize.Value = GridSizes[1];
			}
			_harmony = new Harmony("javidahmed64592.nohammerbuildmenu");
			_harmony.PatchAll();
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			Overlay.Destroy();
		}

		private void Update()
		{
			if (_phantomHammer != null)
			{
				_phantomHammer.m_durability = _phantomHammer.m_shared.m_maxDurability;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				_phantomHammer = null;
				_knownRecipesRefreshed = false;
				_lastBuildPiece = null;
				PieceMover.Reset();
				Overlay.Hide();
				return;
			}
			EnsurePhantomHammer();
			if (!_knownRecipesRefreshed && _phantomHammer != null)
			{
				_knownRecipesRefreshed = true;
				localPlayer.UpdateKnownRecipesList();
			}
			if (Menu.IsVisible() || InventoryGui.IsVisible() || ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus()))
			{
				Overlay.Hide();
				return;
			}
			if (ZInput.GetButtonDown("NoHammerBuildMenu_Toggle!javidahmed64592.nohammerbuildmenu"))
			{
				ToggleBuildMenu(localPlayer);
			}
			if (((Character)localPlayer).InPlaceMode() && Input.GetMouseButtonDown(1) && !PieceMover.RightClickConsumed)
			{
				if (ShiftHeld())
				{
					ToggleRepairMode(localPlayer);
				}
				else if (CtrlHeld())
				{
					ToggleGrid(localPlayer);
				}
			}
			UpdateGrid(localPlayer);
		}

		private void LateUpdate()
		{
			PieceMover.UpdateHighlight();
		}

		private static void ToggleGrid(Player player)
		{
			_gridEnabled.Value = !_gridEnabled.Value;
			((Character)player).Message((MessageType)1, _gridEnabled.Value ? "$nhbm_grid_on" : "$nhbm_grid_off", 0, (Sprite)null, false);
		}

		private static void UpdateGrid(Player player)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (!GridActive(player) || Time.frameCount - _aimFrame > 2 || _aimPlane == GridPlane.None)
			{
				Overlay.Hide();
				return;
			}
			HandleGridScroll(player);
			Overlay.Show(_aimPoint, _gridSize.Value, _aimPlane, _aimSign);
		}

		internal static bool GridActive(Player player)
		{
			if (_gridEnabled.Value && ((Character)player).InPlaceMode() && !player.InRepairMode() && (Object)(object)player.m_placementGhost != (Object)null)
			{
				return IsHammerEquipped(player);
			}
			return false;
		}

		internal static bool IsHammerEquipped(Player player)
		{
			ItemData rightItem = ((Humanoid)player).GetRightItem();
			if (rightItem == null)
			{
				return false;
			}
			if (rightItem == _phantomHammer)
			{
				return true;
			}
			PieceTable val = rightItem.m_shared?.m_buildPieces;
			if ((Object)(object)val != (Object)null)
			{
				if (!ContainsHammer(rightItem.m_shared.m_name) && !ContainsHammer(((Object)(object)rightItem.m_dropPrefab != (Object)null) ? ((Object)rightItem.m_dropPrefab).name : null))
				{
					return ContainsHammer(((Object)val).name);
				}
				return true;
			}
			return false;
		}

		private static bool ContainsHammer(string name)
		{
			if (name != null)
			{
				return name.IndexOf("hammer", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			return false;
		}

		internal static bool ShiftHeld()
		{
			if (!Input.GetKey((KeyCode)304))
			{
				return Input.GetKey((KeyCode)303);
			}
			return true;
		}

		internal static bool CtrlHeld()
		{
			if (!Input.GetKey((KeyCode)306))
			{
				return Input.GetKey((KeyCode)305);
			}
			return true;
		}

		private static bool AltHeld()
		{
			if (!Input.GetKey((KeyCode)308))
			{
				return Input.GetKey((KeyCode)307);
			}
			return true;
		}

		internal static bool AltZoomActive(Player player)
		{
			if ((Object)(object)player == (Object)(object)Player.m_localPlayer && AltHeld() && ((Character)player).InPlaceMode())
			{
				return IsHammerEquipped(player);
			}
			return false;
		}

		private static void HandleGridScroll(Player player)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			float y = Input.mouseScrollDelta.y;
			if (y != 0f && CtrlHeld())
			{
				float num = ((y > 0f) ? (_gridSize.Value * 2f) : (_gridSize.Value / 2f));
				num = Mathf.Clamp(num, GridSizes[0], GridSizes[GridSizes.Length - 1]);
				if (!Mathf.Approximately(num, _gridSize.Value))
				{
					_gridSize.Value = num;
					((Character)player).Message((MessageType)1, Localization.instance.Localize("$nhbm_grid_distance", new string[1] { num.ToString("0.###", CultureInfo.InvariantCulture) }), 0, (Sprite)null, false);
				}
			}
		}

		private void ToggleRepairMode(Player player)
		{
			if (player.InRepairMode())
			{
				if ((Object)(object)_lastBuildPiece != (Object)null)
				{
					player.SetSelectedPiece(_lastBuildPiece);
				}
				return;
			}
			_lastBuildPiece = player.GetSelectedPiece();
			Piece val = player.GetBuildPieces()?.FirstOrDefault((Func<Piece, bool>)((Piece p) => p.m_repairPiece));
			if ((Object)(object)val != (Object)null)
			{
				player.SetSelectedPiece(val);
			}
		}

		private static void ToggleBuildMenu(Player player)
		{
			EnsurePhantomHammer();
			if (_phantomHammer != null)
			{
				if (((Humanoid)player).GetRightItem() != _phantomHammer)
				{
					((Humanoid)player).EquipItem(_phantomHammer, true);
				}
				else
				{
					((Humanoid)player).UnequipItem(_phantomHammer, true);
				}
			}
		}

		private static void EnsurePhantomHammer()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: 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_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			if (_phantomHammer == null && !((Object)(object)ObjectDB.instance == (Object)null))
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("Hammer");
				if (!((Object)(object)itemPrefab == (Object)null))
				{
					ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
					_phantomHammer = new ItemData
					{
						m_shared = component.m_itemData.m_shared,
						m_dropPrefab = itemPrefab,
						m_stack = 1,
						m_quality = 1,
						m_variant = 0,
						m_durability = component.m_itemData.m_shared.m_maxDurability,
						m_customData = new Dictionary<string, string>()
					};
				}
			}
		}
	}
	internal static class Translations
	{
		private const string ResourcePrefix = "NoHammerBuildMenu.Translations.";

		private const string ResourceSuffix = ".json";

		public static void Load()
		{
			CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string[] manifestResourceNames = executingAssembly.GetManifestResourceNames();
			foreach (string text in manifestResourceNames)
			{
				if (text.StartsWith("NoHammerBuildMenu.Translations.", StringComparison.Ordinal) && text.EndsWith(".json", StringComparison.Ordinal))
				{
					string text2 = text.Substring("NoHammerBuildMenu.Translations.".Length, text.Length - "NoHammerBuildMenu.Translations.".Length - ".json".Length);
					using StreamReader streamReader = new StreamReader(executingAssembly.GetManifestResourceStream(text));
					localization.AddJsonFile(text2, streamReader.ReadToEnd());
				}
			}
		}
	}
}
namespace NoHammerBuildMenu.Patches
{
	[HarmonyPatch(typeof(Humanoid), "SetupVisEquipment")]
	internal static class Humanoid_SetupVisEquipment_Patch
	{
		[HarmonyPrefix]
		private static void Prefix(Humanoid __instance, out ItemData __state)
		{
			ItemData phantomHammer = NoHammerBuildMenuPlugin._phantomHammer;
			__state = null;
			if (phantomHammer != null && __instance.GetRightItem() == phantomHammer)
			{
				__state = phantomHammer;
				__instance.m_rightItem = null;
			}
		}

		[HarmonyPostfix]
		private static void Postfix(Humanoid __instance, ItemData __state)
		{
			if (__state == null)
			{
				return;
			}
			__instance.m_rightItem = __state;
			Player val = (Player)(object)((__instance is Player) ? __instance : null);
			if (val != null)
			{
				VisEquipment visEquipment = ((Humanoid)val).m_visEquipment;
				if (visEquipment != null)
				{
					visEquipment.SetRightItem(StringExtensionMethods.GetStableHashCode(((Object)__state.m_dropPrefab).name), __state.m_quality);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Inventory), "ContainsItem")]
	internal static class Inventory_ContainsItem_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix(ItemData item, ref bool __result)
		{
			ItemData phantomHammer = NoHammerBuildMenuPlugin._phantomHammer;
			if (phantomHammer != null && item == phantomHammer)
			{
				__result = true;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Inventory), "GetAllPieceTables")]
	internal static class Inventory_GetAllPieceTables_Patch
	{
		[HarmonyPostfix]
		private static void Postfix(List<PieceTable> tables)
		{
			ItemData phantomHammer = NoHammerBuildMenuPlugin._phantomHammer;
			if ((Object)(object)phantomHammer?.m_shared?.m_buildPieces != (Object)null && !tables.Contains(phantomHammer.m_shared.m_buildPieces))
			{
				tables.Add(phantomHammer.m_shared.m_buildPieces);
			}
		}
	}
	[HarmonyPatch(typeof(Player), "CanRotatePiece")]
	internal static class Player_CanRotatePiece_Patch
	{
		[HarmonyPostfix]
		private static void Postfix(Player __instance, ref bool __result)
		{
			if (__result && NoHammerBuildMenuPlugin.AltZoomActive(__instance))
			{
				__result = false;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "PieceRayTest")]
	internal static class Player_PieceRayTest_Patch
	{
		private const float AxisAlignedWall = 0.9f;

		private static float SnapTo(float value, float size)
		{
			return Mathf.Round(value / size) * size;
		}

		[HarmonyPostfix]
		private static void Postfix(Player __instance, bool __result, ref Vector3 point, ref Vector3 normal, ref Piece piece)
		{
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			if (__result && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && NoHammerBuildMenuPlugin.GridActive(__instance))
			{
				float value = NoHammerBuildMenuPlugin._gridSize.Value;
				GridPlane aimPlane = GridPlane.Terrain;
				float aimSign = 1f;
				if ((Object)(object)piece == (Object)null)
				{
					point.x = SnapTo(point.x, value);
					point.z = SnapTo(point.z, value);
				}
				else if (Mathf.Abs(normal.y) > 0.5f)
				{
					point.x = SnapTo(point.x, value);
					point.z = SnapTo(point.z, value);
					aimPlane = ((normal.y > 0f) ? GridPlane.Top : GridPlane.Bottom);
					aimSign = Mathf.Sign(normal.y);
				}
				else if (Mathf.Abs(normal.x) > 0.9f)
				{
					point.y = SnapTo(point.y, value);
					point.z = SnapTo(point.z, value);
					aimPlane = GridPlane.WallX;
					aimSign = Mathf.Sign(normal.x);
				}
				else if (Mathf.Abs(normal.z) > 0.9f)
				{
					point.x = SnapTo(point.x, value);
					point.y = SnapTo(point.y, value);
					aimPlane = GridPlane.WallZ;
					aimSign = Mathf.Sign(normal.z);
				}
				else
				{
					point.y = SnapTo(point.y, value);
					aimPlane = GridPlane.None;
				}
				NoHammerBuildMenuPlugin._aimFrame = Time.frameCount;
				NoHammerBuildMenuPlugin._aimPoint = point;
				NoHammerBuildMenuPlugin._aimPlane = aimPlane;
				NoHammerBuildMenuPlugin._aimSign = aimSign;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "UpdateBuildGuiInput")]
	internal static class Player_UpdateBuildGuiInput_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix(Player __instance)
		{
			if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
			{
				return true;
			}
			bool flag = NoHammerBuildMenuPlugin.ShiftHeld() || NoHammerBuildMenuPlugin.CtrlHeld();
			if (!PieceMover.RightClickConsumed)
			{
				if (flag)
				{
					return !NoHammerBuildMenuPlugin.IsHammerEquipped(__instance);
				}
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Player), "UpdatePlacementGhost")]
	internal static class Player_UpdatePlacementGhost_Patch
	{
		[HarmonyPrefix]
		private static void Prefix(Player __instance)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
			{
				PieceMover.HideFromPlacementChecks();
			}
		}

		[HarmonyFinalizer]
		private static Exception Finalizer(Exception __exception)
		{
			PieceMover.RestoreAfterPlacementChecks();
			return __exception;
		}
	}
	[HarmonyPatch(typeof(Player), "UpdatePlacement")]
	internal static class Player_UpdatePlacement_Move_Patch
	{
		[HarmonyPrefix]
		private static void Prefix(Player __instance, bool takeInput, out bool __state)
		{
			__state = (Object)(object)__instance == (Object)(object)Player.m_localPlayer && PieceMover.BeforeUpdatePlacement(__instance, takeInput);
		}

		[HarmonyPostfix]
		private static void Postfix(Player __instance, bool __state)
		{
			if (__state)
			{
				PieceMover.BlockVanillaPlacing(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Player), "UpdatePlacement")]
	internal static class Player_UpdatePlacement_Patch
	{
		private static readonly FieldInfo ScrollField = AccessTools.Field(typeof(Player), "m_scrollCurrAmount");

		private static readonly FieldInfo RotationField = AccessTools.Field(typeof(Player), "m_placeRotation");

		[HarmonyPrefix]
		private static void Prefix(Player __instance, out (float scroll, int rotation)? __state)
		{
			__state = null;
			if (ScrollField != null && RotationField != null && NoHammerBuildMenuPlugin.AltZoomActive(__instance))
			{
				__state = ((float)ScrollField.GetValue(__instance), (int)RotationField.GetValue(__instance));
			}
		}

		[HarmonyPostfix]
		private static void Postfix(Player __instance, (float scroll, int rotation)? __state)
		{
			if (__state.HasValue)
			{
				ScrollField.SetValue(__instance, __state.Value.scroll);
				RotationField.SetValue(__instance, __state.Value.rotation);
			}
		}
	}
	[HarmonyPatch]
	internal static class ZInput_GetMouseScrollWheel_Patch
	{
		private static MethodInfo TargetMethod()
		{
			return AccessTools.Method(typeof(ZInput), "GetMouseScrollWheel", (Type[])null, (Type[])null);
		}

		private static bool Prepare()
		{
			return TargetMethod() != null;
		}

		[HarmonyPostfix]
		private static void Postfix(ref float __result)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && NoHammerBuildMenuPlugin.CtrlHeld() && NoHammerBuildMenuPlugin.GridActive(localPlayer))
			{
				__result = 0f;
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		internal IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}