Decompiled source of VenTE Tweaks v0.3.1

plugins/VenTE-Tweaks.dll

Decompiled 2 days 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 BepInEx.Logging;
using HarmonyLib;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using VenTETweaks.Features;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("VenTE-Tweaks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+6cac550ab3f4f8afe08be351a2b1a6182a39b0d3")]
[assembly: AssemblyProduct("VenTE-Tweaks")]
[assembly: AssemblyTitle("VenTE-Tweaks")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace VenTETweaks
{
	internal static class ConfigHelper
	{
		public static ConfigEntry<T> BindSynced<T>(string section, string key, T value, string description, AcceptableValueBase range = null)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			return Plugin.Cfg.Bind<T>(section, key, value, new ConfigDescription(description + " [server-synced]", range, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
		}

		public static ConfigEntry<T> BindLocal<T>(string section, string key, T value, string description, AcceptableValueBase range = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			return Plugin.Cfg.Bind<T>(section, key, value, new ConfigDescription(description, range, Array.Empty<object>()));
		}
	}
	internal static class ConfigWatcher
	{
		private static FileSystemWatcher _watcher;

		private static volatile bool _dirty;

		private static float _reloadAt;

		public static void Init(ConfigFile cfg)
		{
			RemoveObsoleteEntries(cfg);
			string configFilePath = cfg.ConfigFilePath;
			_watcher = new FileSystemWatcher(Path.GetDirectoryName(configFilePath), Path.GetFileName(configFilePath))
			{
				NotifyFilter = (NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite),
				IncludeSubdirectories = false
			};
			_watcher.Changed += OnFileEvent;
			_watcher.Created += OnFileEvent;
			_watcher.Renamed += OnFileEvent;
			_watcher.EnableRaisingEvents = true;
		}

		private static void OnFileEvent(object sender, FileSystemEventArgs e)
		{
			_dirty = true;
		}

		public static void Update(ConfigFile cfg)
		{
			if (_dirty)
			{
				_dirty = false;
				_reloadAt = Time.unscaledTime + 0.5f;
			}
			if (_reloadAt <= 0f || Time.unscaledTime < _reloadAt)
			{
				return;
			}
			_reloadAt = 0f;
			if (!File.Exists(cfg.ConfigFilePath))
			{
				return;
			}
			bool saveOnConfigSet = cfg.SaveOnConfigSet;
			try
			{
				cfg.SaveOnConfigSet = false;
				cfg.Reload();
				Plugin.Log.LogInfo((object)"Config file changed on disk, reloaded.");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Config reload failed (file kept as is): " + ex.Message));
			}
			finally
			{
				cfg.SaveOnConfigSet = saveOnConfigSet;
			}
			RemoveObsoleteEntries(cfg);
		}

		private static void RemoveObsoleteEntries(ConfigFile cfg)
		{
			Dictionary<ConfigDefinition, string> value = Traverse.Create((object)cfg).Property("OrphanedEntries", (object[])null).GetValue<Dictionary<ConfigDefinition, string>>();
			if (value != null && value.Count != 0)
			{
				Plugin.Log.LogInfo((object)("Removing obsolete config entries: " + string.Join(", ", value.Keys)));
				value.Clear();
				bool saveOnConfigSet = cfg.SaveOnConfigSet;
				cfg.SaveOnConfigSet = false;
				cfg.Save();
				cfg.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		public static void Dispose()
		{
			_watcher?.Dispose();
			_watcher = null;
		}
	}
	internal static class InputHelper
	{
		public static bool Down(this KeyboardShortcut s)
		{
			//IL_0002: 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_0017: Unknown result type (might be due to invalid IL or missing references)
			if ((int)((KeyboardShortcut)(ref s)).MainKey != 0 && Input.GetKeyDown(((KeyboardShortcut)(ref s)).MainKey))
			{
				return ModifiersHeld(s);
			}
			return false;
		}

		public static bool Held(this KeyboardShortcut s)
		{
			//IL_0002: 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_0017: Unknown result type (might be due to invalid IL or missing references)
			if ((int)((KeyboardShortcut)(ref s)).MainKey != 0 && Input.GetKey(((KeyboardShortcut)(ref s)).MainKey))
			{
				return ModifiersHeld(s);
			}
			return false;
		}

		private static bool ModifiersHeld(KeyboardShortcut s)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			foreach (KeyCode modifier in ((KeyboardShortcut)(ref s)).Modifiers)
			{
				if (!Input.GetKey(modifier))
				{
					return false;
				}
			}
			return true;
		}
	}
	[BepInPlugin("VenTE-Tweaks", "VenTE-Tweaks", "0.3.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGUID = "VenTE-Tweaks";

		public const string PluginName = "VenTE-Tweaks";

		public const string PluginVersion = "0.3.1";

		private Harmony _harmony;

		internal static Plugin Instance { get; private set; }

		internal static ManualLogSource Log { get; private set; }

		internal static ConfigFile Cfg => ((BaseUnityPlugin)Instance).Config;

		private void Awake()
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			NoToolStamina.Init();
			HammerTools.Init();
			TorchWithTools.Init();
			DoorSync.Init();
			BuildRotation.Init();
			BuildZoom.Init();
			AreaPieceInfo.Init();
			StationTweaks.Init();
			DayCycle.Init();
			ConfigWatcher.Init(((BaseUnityPlugin)this).Config);
			_harmony = new Harmony("VenTE-Tweaks");
			_harmony.PatchAll(typeof(Plugin).Assembly);
			Log.LogInfo((object)"VenTE-Tweaks 0.3.1 loaded");
		}

		private void Update()
		{
			ConfigWatcher.Update(((BaseUnityPlugin)this).Config);
			HammerTools.Update();
			BuildRotation.Update();
			AreaPieceInfo.Update();
		}

		private void OnGUI()
		{
			AreaPieceInfo.OnGUI();
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			ConfigWatcher.Dispose();
		}
	}
}
namespace VenTETweaks.Features
{
	internal static class AreaPieceInfo
	{
		[HarmonyPatch(typeof(Player), "Repair")]
		private static class AreaRepairPatch
		{
			private static bool Prefix(Player __instance, ItemData toolItem)
			{
				//IL_0042: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
				if (!_on || !AreaRepair.Value || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || !((Character)__instance).InPlaceMode())
				{
					return true;
				}
				Piece hoveringPiece = __instance.GetHoveringPiece();
				if ((Object)(object)hoveringPiece == (Object)null)
				{
					return true;
				}
				if (!PrivateArea.CheckAccess(((Component)hoveringPiece).transform.position, 0f, true, false))
				{
					return false;
				}
				Refresh(__instance, highlight: false);
				int num = 0;
				int num2 = 0;
				foreach (var (val, val2, _) in Shown)
				{
					if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null) && CanRepairSilently(__instance, val) && val2.Repair())
					{
						num++;
						if (num2++ < 10)
						{
							val.m_placeEffect.Create(((Component)val).transform.position, ((Component)val).transform.rotation, (Transform)null, 1f, -1, ((Character)__instance).GetZDOID());
						}
						if (RepairCostPerPiece.Value || num == 1)
						{
							Charge(__instance, toolItem);
						}
					}
				}
				if (num == 0)
				{
					((Character)__instance).Message((MessageType)1, "Nothing to repair in the area", 0, (Sprite)null, false);
					return false;
				}
				__instance.FaceLookDirection();
				((Character)__instance).m_zanim.SetTrigger(toolItem.m_shared.m_attack.m_attackAnimation);
				((Character)__instance).Message((MessageType)1, (num == 1) ? Localization.instance.Localize("$msg_repaired", new string[1] { hoveringPiece.m_name }) : $"Repaired {num} pieces", 0, (Sprite)null, false);
				return false;
			}

			private static bool CanRepairSilently(Player player, Piece piece)
			{
				//IL_004e: 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 (!player.m_noPlacementCost && (Object)(object)piece.m_craftingStation != (Object)null && !ZoneSystem.instance.GetGlobalKey((GlobalKeys)27) && !Object.op_Implicit((Object)(object)CraftingStation.HaveBuildStationInRange(piece.m_craftingStation.m_name, ((Component)player).transform.position)))
				{
					return false;
				}
				return PrivateArea.CheckAccess(((Component)piece).transform.position, 0f, false, false);
			}

			private static void Charge(Player player, ItemData tool)
			{
				((Character)player).UseStamina(player.GetBuildStamina());
				((Character)player).UseEitr(tool.m_shared.m_attack.m_attackEitr);
				if (tool.m_shared.m_useDurability)
				{
					tool.m_durability -= tool.m_shared.m_useDurabilityDrain * Game.m_durabilityRate;
				}
			}
		}

		private const string Section = "Area Mode";

		public static ConfigEntry<KeyCode> ToggleKey;

		public static ConfigEntry<bool> ShowStability;

		public static ConfigEntry<bool> ShowHealthBars;

		public static ConfigEntry<bool> OnlyDamagedBars;

		public static ConfigEntry<bool> ShowPercent;

		public static ConfigEntry<float> Radius;

		public static ConfigEntry<int> MaxPieces;

		public static ConfigEntry<bool> AreaRepair;

		public static ConfigEntry<bool> RepairCostPerPiece;

		private static bool _on;

		private static float _nextRefresh;

		private static readonly List<Piece> Scratch = new List<Piece>();

		private static readonly List<(Piece piece, WearNTear wnt, Vector3 anchor)> Shown = new List<(Piece, WearNTear, Vector3)>();

		private static GUIStyle _labelStyle;

		private static readonly Dictionary<WearNTear, Vector3> AnchorCache = new Dictionary<WearNTear, Vector3>();

		public static bool IsOn => _on;

		public static void Init()
		{
			ToggleKey = ConfigHelper.BindLocal<KeyCode>("Area Mode", "ToggleKey", (KeyCode)104, "While holding a build tool, toggle area mode: stability and health of all pieces around the targeted piece, and area repair.");
			ShowStability = ConfigHelper.BindLocal("Area Mode", "ShowStability", value: true, "Tint pieces with the vanilla stability color (blue = grounded, green to red = weaker).");
			ShowHealthBars = ConfigHelper.BindLocal("Area Mode", "ShowHealthBars", value: true, "Draw a small health bar over each piece.");
			OnlyDamagedBars = ConfigHelper.BindLocal("Area Mode", "OnlyDamagedBars", value: false, "Only draw health bars for pieces that are not at full health.");
			ShowPercent = ConfigHelper.BindLocal("Area Mode", "ShowPercent", value: false, "Show the health percentage next to each bar.");
			Radius = ConfigHelper.BindSynced("Area Mode", "Radius", 10f, "Radius in meters around the targeted piece.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 40f));
			MaxPieces = ConfigHelper.BindSynced("Area Mode", "MaxPieces", 200, "Maximum number of pieces shown/repaired (closest first).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(10, 1000));
			AreaRepair = ConfigHelper.BindSynced("Area Mode", "AreaRepair", value: true, "In area mode the repair tool repairs all highlighted pieces. Outside area mode repair is always single-piece.");
			RepairCostPerPiece = ConfigHelper.BindSynced("Area Mode", "RepairCostPerPiece", value: false, "If true, stamina and hammer durability are charged for every repaired piece; if false, once per click.");
		}

		public static void Update()
		{
			//IL_0027: 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)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || !((Character)localPlayer).InPlaceMode())
			{
				Shown.Clear();
				return;
			}
			if ((int)ToggleKey.Value != 0 && Input.GetKeyDown(ToggleKey.Value) && ((Character)localPlayer).TakeInput() && !Hud.IsPieceSelectionVisible())
			{
				_on = !_on;
				((Character)localPlayer).Message((MessageType)1, _on ? "Area mode: ON" : "Area mode: OFF", 0, (Sprite)null, false);
				if (!_on)
				{
					Shown.Clear();
				}
			}
			if (_on && !(Time.time < _nextRefresh))
			{
				_nextRefresh = Time.time + 0.15f;
				Refresh(localPlayer, ShowStability.Value);
			}
		}

		private static void Refresh(Player p, bool highlight)
		{
			//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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: 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_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			Shown.Clear();
			Piece hoveringPiece = p.GetHoveringPiece();
			if ((Object)(object)hoveringPiece == (Object)null)
			{
				return;
			}
			Vector3 center = ((Component)hoveringPiece).transform.position;
			Scratch.Clear();
			Piece.GetAllPiecesInRadius(center, Radius.Value, Scratch);
			Scratch.Sort(delegate(Piece a, Piece 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 - center;
				float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
				val3 = ((Component)b).transform.position - center;
				return sqrMagnitude.CompareTo(((Vector3)(ref val3)).sqrMagnitude);
			});
			WearNTear val = default(WearNTear);
			foreach (Piece item in Scratch)
			{
				if (Shown.Count >= MaxPieces.Value)
				{
					break;
				}
				if ((Object)(object)item == (Object)null || !((Component)item).TryGetComponent<WearNTear>(ref val) || !Object.op_Implicit((Object)(object)val.m_nview) || !val.m_nview.IsValid())
				{
					continue;
				}
				if (highlight)
				{
					val.Highlight();
				}
				if (!AnchorCache.TryGetValue(val, out var value))
				{
					if (AnchorCache.Count > 5000)
					{
						AnchorCache.Clear();
					}
					value = (AnchorCache[val] = AnchorOf(item));
				}
				Shown.Add((item, val, value));
			}
			Scratch.Clear();
		}

		private static Vector3 AnchorOf(Piece piece)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			Bounds bounds = default(Bounds);
			((Bounds)(ref bounds))..ctor(((Component)piece).transform.position, Vector3.zero);
			bool flag = false;
			Collider[] componentsInChildren = ((Component)piece).GetComponentsInChildren<Collider>();
			foreach (Collider val in componentsInChildren)
			{
				if (!val.isTrigger && val.enabled)
				{
					if (!flag)
					{
						bounds = val.bounds;
						flag = true;
					}
					else
					{
						((Bounds)(ref bounds)).Encapsulate(val.bounds);
					}
				}
			}
			return ((Bounds)(ref bounds)).center;
		}

		public static void OnGUI()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Invalid comparison between Unknown and I4
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//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_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			if (!_on || !ShowHealthBars.Value || Shown.Count == 0 || (int)Event.current.type != 7)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || !((Character)localPlayer).TakeInput() || Hud.IsPieceSelectionVisible())
			{
				return;
			}
			Camera mainCamera = Utils.GetMainCamera();
			if ((Object)(object)mainCamera == (Object)null)
			{
				return;
			}
			if (_labelStyle == null)
			{
				GUIStyle val = new GUIStyle(GUI.skin.label)
				{
					fontSize = 11,
					alignment = (TextAnchor)3
				};
				val.normal.textColor = Color.white;
				_labelStyle = val;
			}
			Color color = GUI.color;
			foreach (var item3 in Shown)
			{
				WearNTear item = item3.wnt;
				Vector3 item2 = item3.anchor;
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				float num = Mathf.Clamp01(item.GetHealthPercentage());
				if (OnlyDamagedBars.Value && num >= 0.999f)
				{
					continue;
				}
				Vector3 val2 = mainCamera.WorldToScreenPoint(item2);
				if (!(val2.z <= 0f))
				{
					float num2 = val2.x - 18f;
					float num3 = (float)Screen.height - val2.y - 2.5f;
					GUI.color = new Color(0f, 0f, 0f, 0.75f);
					GUI.DrawTexture(new Rect(num2 - 1f, num3 - 1f, 38f, 7f), (Texture)(object)Texture2D.whiteTexture);
					GUI.color = Color.Lerp(new Color(0.9f, 0.15f, 0.1f), new Color(0.2f, 0.85f, 0.2f), num);
					GUI.DrawTexture(new Rect(num2, num3, 36f * num, 5f), (Texture)(object)Texture2D.whiteTexture);
					if (ShowPercent.Value)
					{
						GUI.color = Color.white;
						GUI.Label(new Rect(num2 + 36f + 3f, num3 - 7f, 40f, 18f), Mathf.RoundToInt(num * 100f) + "%", _labelStyle);
					}
				}
			}
			GUI.color = color;
		}
	}
	internal static class BuildRotation
	{
		[HarmonyPatch]
		private static class RandomRotationPatch
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				yield return AccessTools.Method(typeof(Player), "SetupPlacementGhost", (Type[])null, (Type[])null);
				yield return AccessTools.Method(typeof(Player), "PlacePiece", (Type[])null, (Type[])null);
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> codes)
			{
				return Transpilers.MethodReplacer(codes, (MethodBase)AccessTools.Method(typeof(Random), "Range", new Type[2]
				{
					typeof(int),
					typeof(int)
				}, (Type[])null), (MethodBase)AccessTools.Method(typeof(RandomRotationPatch), "RandomRange", (Type[])null, (Type[])null));
			}

			private static int RandomRange(int min, int max)
			{
				Player localPlayer = Player.m_localPlayer;
				if (max == 16 && (Object)(object)localPlayer != (Object)null && localPlayer.m_placeRotationDegrees > 0f)
				{
					max = Mathf.RoundToInt(360f / localPlayer.m_placeRotationDegrees);
				}
				return Random.Range(min, max);
			}
		}

		private const string Section = "Build Rotation";

		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<string> Segments;

		public static ConfigEntry<KeyboardShortcut> NextKey;

		public static ConfigEntry<KeyboardShortcut> PrevKey;

		private static readonly List<(int count, string label)> Options = new List<(int, string)>();

		private static int _index;

		public static void Init()
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			Enabled = ConfigHelper.BindLocal("Build Rotation", "Enabled", value: true, "Allow changing the number of rotation steps while building.");
			Segments = ConfigHelper.BindLocal("Build Rotation", "Segments", "16:Default, 32:Fine, 10:Pentagonal, 12:Hexagonal", "Rotation step options as count:label. The count is how many steps make a full circle (16 = vanilla 22.5°).");
			NextKey = ConfigHelper.BindLocal<KeyboardShortcut>("Build Rotation", "NextKey", new KeyboardShortcut((KeyCode)275, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Switch to the next rotation step option.");
			PrevKey = ConfigHelper.BindLocal<KeyboardShortcut>("Build Rotation", "PrevKey", new KeyboardShortcut((KeyCode)276, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Switch to the previous rotation step option.");
			ParseSegments();
			Segments.SettingChanged += delegate
			{
				ParseSegments();
			};
		}

		private static void ParseSegments()
		{
			Options.Clear();
			string[] array = Segments.Value.Split(',');
			foreach (string text in array)
			{
				string[] array2 = text.Split(':');
				if (int.TryParse(array2[0].Trim(), out var result) && result >= 2 && result <= 360)
				{
					Options.Add((result, (array2.Length > 1) ? array2[1].Trim() : result.ToString()));
				}
				else if (text.Trim().Length > 0)
				{
					Plugin.Log.LogWarning((object)("[Build Rotation] Ignoring invalid segment entry '" + text.Trim() + "'"));
				}
			}
			_index = 0;
		}

		public static void Update()
		{
			//IL_003d: 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)
			Player localPlayer = Player.m_localPlayer;
			if (Enabled.Value && !((Object)(object)localPlayer == (Object)null) && Options.Count != 0 && ((Character)localPlayer).InPlaceMode() && ((Character)localPlayer).TakeInput())
			{
				int num = (NextKey.Value.Down() ? 1 : (PrevKey.Value.Down() ? (-1) : 0));
				if (num != 0)
				{
					_index = ((_index + num) % Options.Count + Options.Count) % Options.Count;
					(int count, string label) tuple = Options[_index];
					int item = tuple.count;
					string item2 = tuple.label;
					float num2 = 360f / (float)item;
					float num3 = (float)localPlayer.m_placeRotation * localPlayer.m_placeRotationDegrees;
					localPlayer.m_placeRotationDegrees = num2;
					localPlayer.m_placeRotation = Mathf.RoundToInt(num3 / num2) % item;
					((Character)localPlayer).Message((MessageType)1, $"Rotation: {item2} ({item} steps, {num2:0.##}°)", 0, (Sprite)null, false);
				}
			}
		}
	}
	internal static class BuildZoom
	{
		private enum Context
		{
			None,
			Camera,
			Placement
		}

		[HarmonyPatch(typeof(GameCamera), "UpdateCamera")]
		private static class CameraPatch
		{
			private static void Prefix(GameCamera __instance)
			{
				Player localPlayer = Player.m_localPlayer;
				if (__instance.m_freeFly || !Active(localPlayer))
				{
					return;
				}
				if (ModifierHeld && ((Character)localPlayer).TakeInput() && !Hud.IsPieceSelectionVisible() && !Hud.InRadial() && !((Character)localPlayer).InCutscene())
				{
					float num = Mathf.Clamp(ZInput.GetMouseScrollWheel(), -0.05f, 0.05f);
					if (num != 0f)
					{
						float num2 = (((Object)(object)localPlayer.GetControlledShip() != (Object)null) ? __instance.m_maxDistanceBoat : __instance.m_maxDistance);
						__instance.m_distance = Mathf.Clamp(__instance.m_distance - num * __instance.m_zoomSens, __instance.m_minDistance, num2);
					}
				}
				_ctx = Context.Camera;
			}

			private static void Finalizer()
			{
				_ctx = Context.None;
			}
		}

		[HarmonyPatch(typeof(Player), "UpdatePlacement")]
		private static class PlacementPatch
		{
			private static void Prefix(Player __instance)
			{
				if (Active(__instance) && ModifierHeld)
				{
					_ctx = Context.Placement;
				}
			}

			private static void Finalizer()
			{
				_ctx = Context.None;
			}
		}

		[HarmonyPatch(typeof(ZInput), "GetMouseScrollWheel")]
		private static class ScrollPatch
		{
			private static void Postfix(ref float __result)
			{
				if (_ctx != Context.None)
				{
					__result = 0f;
				}
			}
		}

		private const string Section = "Build Camera";

		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<KeyCode> ZoomModifier;

		private static Context _ctx;

		private static bool ModifierHeld
		{
			get
			{
				//IL_0005: 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)
				if ((int)ZoomModifier.Value != 0)
				{
					return Input.GetKey(ZoomModifier.Value);
				}
				return false;
			}
		}

		public static void Init()
		{
			Enabled = ConfigHelper.BindLocal("Build Camera", "ZoomRequiresModifier", value: true, "While holding a build tool, the mouse wheel only zooms the camera when ZoomModifier is held (vanilla zooms whenever nothing rotatable is targeted).");
			ZoomModifier = ConfigHelper.BindLocal<KeyCode>("Build Camera", "ZoomModifier", (KeyCode)306, "Hold this key while scrolling in build mode to zoom the camera. Piece rotation is paused while it is held.");
		}

		private static bool Active(Player p)
		{
			if (Enabled.Value && (Object)(object)p != (Object)null && (Object)(object)p == (Object)(object)Player.m_localPlayer && ((Character)p).InPlaceMode())
			{
				return !ZInput.IsGamepadActive();
			}
			return false;
		}
	}
	internal static class DayCycle
	{
		[HarmonyPatch(typeof(EnvMan), "RescaleDayFraction")]
		private static class RescalePatch
		{
			private static bool Prefix(float fraction, ref float __result)
			{
				float morning = Morning;
				float num = 1f - morning;
				if (fraction >= morning && fraction <= num)
				{
					__result = 0.25f + (fraction - morning) / (num - morning) * 0.5f;
				}
				else if (fraction < morning)
				{
					__result = fraction / morning * 0.25f;
				}
				else
				{
					__result = 0.75f + (fraction - num) / morning * 0.25f;
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(EnvMan), "GetMorningStartSec")]
		private static class MorningStartPatch
		{
			private static bool Prefix(EnvMan __instance, int day, ref double __result)
			{
				__result = (double)day * (double)__instance.m_dayLengthSec + (double)__instance.m_dayLengthSec * (double)Morning;
				return false;
			}
		}

		[HarmonyPatch(typeof(EnvMan), "SkipToMorning")]
		private static class SkipToMorningPatch
		{
			private static bool Prefix(EnvMan __instance)
			{
				double timeSeconds = ZNet.instance.GetTimeSeconds();
				int day = __instance.GetDay(timeSeconds - (double)__instance.m_dayLengthSec * (double)Morning);
				double morningStartSec = __instance.GetMorningStartSec(day + 1);
				__instance.m_skipTime = true;
				__instance.m_skipToTime = morningStartSec;
				__instance.m_timeSkipSpeed = (morningStartSec - timeSeconds) / 12.0;
				ZLog.Log((object)$"Time {timeSeconds}, day:{day}    nextm:{morningStartSec}  skipspeed:{__instance.m_timeSkipSpeed}");
				return false;
			}
		}

		private const float VanillaMorning = 0.15f;

		public static ConfigEntry<float> DayShare;

		private static float Morning => (1f - Mathf.Clamp(DayShare.Value, 0.5f, 0.95f)) / 2f;

		public static void Init()
		{
			DayShare = ConfigHelper.BindSynced("Day Cycle", "DayShare", 0.8f, "Share of the day cycle (20 real minutes) that is daytime, 06:00-18:00 on the clock. 0.7 = vanilla (14 min day / 6 min night), 0.8 = 16 min day / 4 min night. Less night also means less time for night spawns and night cold.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 0.95f));
		}
	}
	internal static class DoorSync
	{
		[HarmonyPatch(typeof(Door), "Awake")]
		private static class AwakePatch
		{
			private static void Postfix(Door __instance)
			{
				Doors.Add(__instance);
			}
		}

		[HarmonyPatch(typeof(Door), "Open")]
		private static class OpenPatch
		{
			private static void Prefix(Door __instance, out int __state)
			{
				__state = GetState(__instance);
			}

			private static void Postfix(Door __instance, Vector3 userDir, int __state)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: 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_005a: Unknown result type (might be due to invalid IL or missing references)
				if (_syncing || !Enabled.Value)
				{
					return;
				}
				KeyboardShortcut value = BypassKey.Value;
				KeyCode mainKey = ((KeyboardShortcut)(ref value)).MainKey;
				if ((int)mainKey != 0 && Input.GetKey(mainKey))
				{
					return;
				}
				Door val = FindPartner(__instance);
				if ((Object)(object)val == (Object)null || GetState(val) != 0 != (__state != 0))
				{
					return;
				}
				_syncing = true;
				try
				{
					val.Open(userDir);
				}
				finally
				{
					_syncing = false;
				}
			}
		}

		private const string Section = "Double Doors";

		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<KeyboardShortcut> BypassKey;

		public static ConfigEntry<string> IgnoredDoors;

		private static readonly HashSet<Door> Doors = new HashSet<Door>();

		private static HashSet<string> _ignored = new HashSet<string>();

		private static bool _syncing;

		public static void Init()
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			Enabled = ConfigHelper.BindSynced("Double Doors", "Enabled", value: true, "Mirrored double doors open and close together.");
			IgnoredDoors = ConfigHelper.BindSynced("Double Doors", "IgnoredDoors", "wood_door, ashwood_door", "Comma-separated door prefab names that are never synced.");
			BypassKey = ConfigHelper.BindLocal<KeyboardShortcut>("Double Doors", "BypassKey", new KeyboardShortcut((KeyCode)308, Array.Empty<KeyCode>()), "Hold this key while using a door to open only that door.");
			ParseIgnored();
			IgnoredDoors.SettingChanged += delegate
			{
				ParseIgnored();
			};
		}

		private static void ParseIgnored()
		{
			_ignored = new HashSet<string>(from s in IgnoredDoors.Value.Split(',')
				select s.Trim() into s
				where s.Length > 0
				select s);
		}

		private static int GetState(Door door)
		{
			if (!((Object)(object)door.m_nview != (Object)null) || !door.m_nview.IsValid())
			{
				return 0;
			}
			return door.m_nview.GetZDO().GetInt(ZDOVars.s_state, 0);
		}

		private static Door FindPartner(Door self)
		{
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: 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_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)self.m_nview == (Object)null || !self.m_nview.IsValid() || (Object)(object)self.m_keyItem != (Object)null)
			{
				return null;
			}
			string prefabName = self.m_nview.GetPrefabName();
			if (_ignored.Contains(prefabName))
			{
				return null;
			}
			Doors.RemoveWhere((Door d) => (Object)(object)d == (Object)null);
			Transform transform = ((Component)self).transform;
			Door result = null;
			float num = float.MaxValue;
			foreach (Door door in Doors)
			{
				if ((Object)(object)door == (Object)(object)self || (Object)(object)door.m_nview == (Object)null || !door.m_nview.IsValid() || (Object)(object)door.m_keyItem != (Object)null || door.m_nview.GetPrefabName() != prefabName)
				{
					continue;
				}
				Vector3 val = ((Component)door).transform.position - transform.position;
				if (!(Mathf.Abs(val.y) > 0.5f))
				{
					val.y = 0f;
					float magnitude = ((Vector3)(ref val)).magnitude;
					if (!(magnitude < 0.05f) && !(magnitude > 2.5f) && !(magnitude >= num) && !(Vector3.Angle(((Component)door).transform.forward, -transform.forward) > 45f) && !(Mathf.Abs(Vector3.Dot(((Vector3)(ref val)).normalized, transform.forward)) > 0.5f))
					{
						result = door;
						num = magnitude;
					}
				}
			}
			return result;
		}
	}
	internal static class HammerTools
	{
		[HarmonyPatch(typeof(Humanoid), "UnequipItem")]
		private static class ForgetManuallyUnequippedPatch
		{
			private static void Postfix(Humanoid __instance, ItemData item)
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				if (item != null && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && HoldingHammer((Player)__instance))
				{
					if (item == _prevRight)
					{
						_prevRight = null;
					}
					if (item == _prevLeft)
					{
						_prevLeft = null;
					}
					if (item == _pendingLeft)
					{
						_pendingLeft = null;
					}
				}
			}
		}

		[HarmonyPatch(typeof(Player), "ClearActionQueue")]
		private static class KeepHotkeyActionsPatch
		{
			private static bool Prefix(Player __instance)
			{
				if (!EquipWhileMoving.Value || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
				{
					return true;
				}
				HotkeyActions.RemoveWhere((MinorActionData a) => !__instance.m_actionQueue.Contains(a));
				if (HotkeyActions.Count == 0)
				{
					return true;
				}
				__instance.m_actionQueue.RemoveAll((MinorActionData a) => !HotkeyActions.Contains(a));
				return false;
			}
		}

		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		private static class ObjectDBAwakePatch
		{
			private static void Postfix(ObjectDB __instance)
			{
				ApplyToolEquipDuration(__instance);
			}
		}

		[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
		private static class ObjectDBCopyPatch
		{
			[HarmonyPriority(0)]
			private static void Postfix(ObjectDB __instance)
			{
				ApplyToolEquipDuration(__instance);
			}
		}

		[HarmonyPatch(typeof(Hud), "SelectPiece")]
		private static class ManualSelectPatch
		{
			private static void Postfix()
			{
				_prevCategory = null;
			}
		}

		private const string Section = "Hammer";

		private const string HammerName = "$item_hammer";

		public static ConfigEntry<KeyboardShortcut> HammerKey;

		public static ConfigEntry<bool> HoldForRepair;

		public static ConfigEntry<float> HoldTime;

		public static ConfigEntry<KeyboardShortcut> RepairKey;

		public static ConfigEntry<bool> EquipWhileMoving;

		public static ConfigEntry<bool> RestorePreviousItems;

		public static ConfigEntry<float> ToolEquipDuration;

		private static ItemData _prevRight;

		private static ItemData _prevLeft;

		private static float _hammerKeyDownTime = -1f;

		private static bool _holdConsumed;

		private static bool _pendingRepairSelect;

		private static float _pendingRepairDeadline;

		private static PieceCategory? _prevCategory;

		private static Vector2Int _prevIndex;

		private static ItemData _pendingLeft;

		private static float _pendingLeftDeadline;

		private static readonly HashSet<MinorActionData> HotkeyActions = new HashSet<MinorActionData>();

		private static readonly Dictionary<SharedData, float> OrigEquipDuration = new Dictionary<SharedData, float>();

		public static void Init()
		{
			//IL_0011: 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)
			HammerKey = ConfigHelper.BindLocal<KeyboardShortcut>("Hammer", "HammerKey", new KeyboardShortcut((KeyCode)98, Array.Empty<KeyCode>()), "Tap: equip your best hammer from anywhere in the inventory; tap again to put it away and re-equip previous items.");
			HoldForRepair = ConfigHelper.BindLocal("Hammer", "HoldHammerKeyForRepair", value: true, "Holding the hammer key switches to the repair tool (equipping the hammer if needed). Hold again to switch back.");
			HoldTime = ConfigHelper.BindLocal("Hammer", "HoldTime", 0.4f, "Seconds the hammer key must be held to count as a hold.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.15f, 2f));
			RepairKey = ConfigHelper.BindLocal<KeyboardShortcut>("Hammer", "RepairModeKey", KeyboardShortcut.Empty, "Dedicated key to toggle repair mode (equips the hammer if needed). Empty = not bound.");
			RestorePreviousItems = ConfigHelper.BindLocal("Hammer", "RestorePreviousItems", value: true, "When putting the hammer away with the hammer key, re-equip what you were holding before. If false, the hammer is just unequipped (a torch kept in the off-hand stays).");
			EquipWhileMoving = ConfigHelper.BindLocal("Hammer", "EquipWhileMoving", value: true, "Equips started with the hammer/repair keys are not cancelled by sprinting, jumping or attacking (vanilla cancels them).");
			ToolEquipDuration = ConfigHelper.BindLocal("Hammer", "ToolEquipDuration", 0.3f, "Equip time (with animation) for tools that vanilla equips instantly (hammer, hoe, cultivator...). 0 = vanilla (instant, no animation).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f));
			ToolEquipDuration.SettingChanged += delegate
			{
				ApplyToolEquipDuration(ObjectDB.instance);
			};
		}

		public static void Update()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			ProcessPendingRepairSelect(localPlayer);
			ProcessPendingLeft(localPlayer);
			if (!((Character)localPlayer).TakeInput() || Hud.IsPieceSelectionVisible())
			{
				_hammerKeyDownTime = -1f;
				return;
			}
			HandleHammerKey(localPlayer);
			KeyboardShortcut value = RepairKey.Value;
			if ((int)((KeyboardShortcut)(ref value)).MainKey != 0 && RepairKey.Value.Down())
			{
				ToggleRepairMode(localPlayer);
			}
		}

		private static void HandleHammerKey(Player player)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: 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_004f: Unknown result type (might be due to invalid IL or missing references)
			KeyboardShortcut value = HammerKey.Value;
			if ((int)((KeyboardShortcut)(ref value)).MainKey == 0)
			{
				return;
			}
			if (value.Down())
			{
				_hammerKeyDownTime = Time.time;
				_holdConsumed = false;
			}
			if (_hammerKeyDownTime < 0f)
			{
				return;
			}
			if (HoldForRepair.Value && !_holdConsumed && Input.GetKey(((KeyboardShortcut)(ref value)).MainKey) && Time.time - _hammerKeyDownTime >= HoldTime.Value)
			{
				_holdConsumed = true;
				ToggleRepairMode(player);
			}
			if (Input.GetKeyUp(((KeyboardShortcut)(ref value)).MainKey))
			{
				if (!_holdConsumed)
				{
					ToggleHammer(player);
				}
				_hammerKeyDownTime = -1f;
			}
		}

		private static bool IsHammer(ItemData item)
		{
			return item?.m_shared?.m_name == "$item_hammer";
		}

		private static bool HoldingHammer(Player player)
		{
			return IsHammer(((Humanoid)player).GetRightItem());
		}

		private static ItemData FindBestHammer(Player player)
		{
			return (from i in ((Humanoid)player).GetInventory().GetAllItems()
				where IsHammer(i) && (!i.m_shared.m_useDurability || i.m_durability > 0f)
				orderby i.m_quality descending, i.m_durability descending
				select i).FirstOrDefault();
		}

		private static bool ToggleHammer(Player player)
		{
			ItemData rightItem = ((Humanoid)player).GetRightItem();
			if (IsHammer(rightItem))
			{
				RestorePrevious(player, rightItem);
				return true;
			}
			ItemData val = FindBestHammer(player);
			if (val == null)
			{
				((Character)player).Message((MessageType)2, "$msg_missingitem: $item_hammer", 0, (Sprite)null, false);
				return false;
			}
			_prevRight = ((Humanoid)player).GetRightItem();
			_prevLeft = ((Humanoid)player).GetLeftItem();
			_prevCategory = null;
			_pendingLeft = null;
			HotkeyToggle(player, val);
			return true;
		}

		private static void RestorePrevious(Player player, ItemData hammer)
		{
			Inventory inventory = ((Humanoid)player).GetInventory();
			bool value = RestorePreviousItems.Value;
			ItemData val = ((value && _prevRight != null && inventory.ContainsItem(_prevRight)) ? _prevRight : null);
			ItemData val2 = ((value && _prevLeft != null && inventory.ContainsItem(_prevLeft)) ? _prevLeft : null);
			_prevRight = (_prevLeft = null);
			_prevCategory = null;
			if (val != null && ((Humanoid)player).IsItemEquiped(val))
			{
				val = null;
			}
			if (val2 != null && ((Humanoid)player).IsItemEquiped(val2))
			{
				val2 = null;
			}
			if (val != null)
			{
				HotkeyToggle(player, val);
				_pendingLeft = val2;
				_pendingLeftDeadline = Time.time + 10f;
			}
			else if (val2 != null)
			{
				HotkeyToggle(player, val2);
				_pendingLeft = null;
			}
			else
			{
				HotkeyToggle(player, hammer);
			}
		}

		private static void HotkeyToggle(Player player, ItemData item)
		{
			int count = player.m_actionQueue.Count;
			((Humanoid)player).ToggleEquipped(item);
			if (player.m_actionQueue.Count > count)
			{
				HotkeyActions.Add(player.m_actionQueue[player.m_actionQueue.Count - 1]);
			}
		}

		private static void ProcessPendingLeft(Player player)
		{
			if (_pendingLeft == null)
			{
				return;
			}
			if (Time.time > _pendingLeftDeadline || !((Humanoid)player).GetInventory().ContainsItem(_pendingLeft))
			{
				_pendingLeft = null;
			}
			else if (!HoldingHammer(player) && !((Character)player).InAttack() && !((Character)player).InDodge())
			{
				ItemData pendingLeft = _pendingLeft;
				_pendingLeft = null;
				if (!((Humanoid)player).IsItemEquiped(pendingLeft))
				{
					((Humanoid)player).EquipItem(pendingLeft, true);
				}
			}
		}

		private static void ApplyToolEquipDuration(ObjectDB db)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Invalid comparison between Unknown and I4
			if ((Object)(object)db == (Object)null)
			{
				return;
			}
			ItemDrop val = default(ItemDrop);
			foreach (GameObject item in db.m_items)
			{
				if ((Object)(object)item == (Object)null || !item.TryGetComponent<ItemDrop>(ref val))
				{
					continue;
				}
				SharedData shared = val.m_itemData.m_shared;
				if ((int)shared.m_itemType == 19)
				{
					if (!OrigEquipDuration.TryGetValue(shared, out var value))
					{
						value = (OrigEquipDuration[shared] = shared.m_equipDuration);
					}
					shared.m_equipDuration = ((value <= 0f) ? ToolEquipDuration.Value : value);
				}
			}
		}

		private static void ToggleRepairMode(Player player)
		{
			//IL_0062: 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 (!HoldingHammer(player))
			{
				if (ToggleHammer(player))
				{
					_pendingRepairSelect = true;
					_pendingRepairDeadline = Time.time + 5f;
				}
				return;
			}
			PieceTable buildPieces = player.m_buildPieces;
			if ((Object)(object)buildPieces == (Object)null)
			{
				return;
			}
			Piece selectedPiece = buildPieces.GetSelectedPiece();
			if ((Object)(object)selectedPiece != (Object)null && selectedPiece.m_repairPiece)
			{
				if (_prevCategory.HasValue)
				{
					buildPieces.SetCategory(_prevCategory.Value);
					player.SetSelectedPiece(_prevIndex);
					player.SetupPlacementGhost();
					_prevCategory = null;
				}
			}
			else
			{
				SelectRepairTool(player);
			}
		}

		private static void ProcessPendingRepairSelect(Player player)
		{
			if (_pendingRepairSelect)
			{
				if (Time.time > _pendingRepairDeadline)
				{
					_pendingRepairSelect = false;
				}
				else if (HoldingHammer(player) && !((Object)(object)player.m_buildPieces == (Object)null))
				{
					_pendingRepairSelect = false;
					SelectRepairTool(player);
				}
			}
		}

		private static void SelectRepairTool(Player player)
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			PieceTable buildPieces = player.m_buildPieces;
			Piece val = null;
			foreach (List<Piece> item in buildPieces.m_availablePiecesByCategory)
			{
				val = ((IEnumerable<Piece>)item).FirstOrDefault((Func<Piece, bool>)((Piece p) => (Object)(object)p != (Object)null && p.m_repairPiece));
				if ((Object)(object)val != (Object)null)
				{
					break;
				}
			}
			Vector2Int selectedPiece = default(Vector2Int);
			PieceCategory category = default(PieceCategory);
			if (!((Object)(object)val == (Object)null) && buildPieces.GetPieceIndex(val, ref selectedPiece, ref category))
			{
				_prevCategory = buildPieces.GetSelectedCategory();
				_prevIndex = buildPieces.GetSelectedIndex();
				buildPieces.SetCategory(category);
				player.SetSelectedPiece(selectedPiece);
				player.SetupPlacementGhost();
			}
		}
	}
	internal static class NoToolStamina
	{
		[HarmonyPatch(typeof(Player), "GetBuildStamina")]
		private static class GetBuildStaminaPatch
		{
			private static void Postfix(Player __instance, ref float __result)
			{
				if (Applies(__instance))
				{
					__result *= CostMultiplier.Value;
				}
			}
		}

		[HarmonyPatch(typeof(Player), "UpdatePlacement")]
		private static class UpdatePlacementPatch
		{
			private static void Prefix()
			{
				_inPlacement = true;
			}

			private static void Finalizer()
			{
				_inPlacement = false;
			}
		}

		[HarmonyPatch(typeof(Player), "HaveStamina")]
		private static class HaveStaminaPatch
		{
			private static bool Prefix(Player __instance, ref float amount, ref bool __result)
			{
				if (!_inPlacement || !Applies(__instance))
				{
					return true;
				}
				if (CostMultiplier.Value <= 0f)
				{
					__result = true;
					return false;
				}
				amount *= CostMultiplier.Value;
				return true;
			}
		}

		private const string Section = "Tool Stamina";

		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<float> CostMultiplier;

		public static ConfigEntry<bool> Hammer;

		public static ConfigEntry<bool> Hoe;

		public static ConfigEntry<bool> Cultivator;

		public static ConfigEntry<bool> OtherBuildTools;

		private static bool _inPlacement;

		public static void Init()
		{
			Enabled = ConfigHelper.BindSynced("Tool Stamina", "Enabled", value: true, "Reduce stamina cost of using build tools (placing, removing, repairing).");
			CostMultiplier = ConfigHelper.BindSynced("Tool Stamina", "CostMultiplier", 0f, "Multiplier for tool stamina cost. 0 = free, 0.5 = half, 1 = vanilla.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f));
			Hammer = ConfigHelper.BindSynced("Tool Stamina", "Hammer", value: true, "Apply to the hammer.");
			Hoe = ConfigHelper.BindSynced("Tool Stamina", "Hoe", value: true, "Apply to the hoe.");
			Cultivator = ConfigHelper.BindSynced("Tool Stamina", "Cultivator", value: true, "Apply to the cultivator.");
			OtherBuildTools = ConfigHelper.BindSynced("Tool Stamina", "OtherBuildTools", value: false, "Apply to any other item that has a build menu (e.g. serving tray, tools added by other mods).");
		}

		private static bool Applies(Player player)
		{
			if (!Enabled.Value || (Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer)
			{
				return false;
			}
			ItemData rightItem = ((Humanoid)player).GetRightItem();
			if ((Object)(object)rightItem?.m_shared?.m_buildPieces == (Object)null)
			{
				return false;
			}
			return rightItem.m_shared.m_name switch
			{
				"$item_hammer" => Hammer.Value, 
				"$item_hoe" => Hoe.Value, 
				"$item_cultivator" => Cultivator.Value, 
				_ => OtherBuildTools.Value, 
			};
		}
	}
	internal static class StationTweaks
	{
		private struct StationOrig
		{
			public float Range;

			public float PerLevel;
		}

		private struct ExtensionOrig
		{
			public float Space;

			public float MaxDistance;
		}

		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static class ZNetSceneAwakePatch
		{
			[HarmonyPriority(0)]
			private static void Postfix()
			{
				ApplyAll();
			}
		}

		private const string Section = "Crafting Stations";

		public static ConfigEntry<float> BuildRangeMultiplier;

		public static ConfigEntry<float> RangePerUpgradeMultiplier;

		public static ConfigEntry<string> BuildRangeOverrides;

		public static ConfigEntry<float> UpgradeSpaceMultiplier;

		public static ConfigEntry<float> UpgradeMaxDistanceMultiplier;

		private static readonly Dictionary<string, StationOrig> StationOrigs = new Dictionary<string, StationOrig>();

		private static readonly Dictionary<string, ExtensionOrig> ExtensionOrigs = new Dictionary<string, ExtensionOrig>();

		private static Dictionary<string, float> _overrides = new Dictionary<string, float>();

		private static bool _logged;

		public static void Init()
		{
			BuildRangeMultiplier = ConfigHelper.BindSynced("Crafting Stations", "BuildRangeMultiplier", 1f, "Multiplier for the base build range of all crafting stations (vanilla values are listed in the log on world load).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f));
			RangePerUpgradeMultiplier = ConfigHelper.BindSynced("Crafting Stations", "RangePerUpgradeMultiplier", 1f, "Multiplier for the extra build range each station upgrade adds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f));
			BuildRangeOverrides = ConfigHelper.BindSynced("Crafting Stations", "BuildRangeOverrides", "", "Base build range in meters per station prefab, replacing the multiplier for that station. Example: piece_workbench=30, forge=25. Prefab names are listed in the log on world load.");
			UpgradeSpaceMultiplier = ConfigHelper.BindSynced("Crafting Stations", "UpgradeSpaceMultiplier", 1f, "Multiplier for the free space a station upgrade needs from other upgrades (center to center). Lower = upgrades can be placed closer together. 0 = no spacing check.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f));
			UpgradeMaxDistanceMultiplier = ConfigHelper.BindSynced("Crafting Stations", "UpgradeMaxDistanceMultiplier", 1f, "Multiplier for how far an upgrade may be from its station.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 3f));
			ParseOverrides();
			BuildRangeOverrides.SettingChanged += delegate
			{
				ParseOverrides();
				ApplyAll();
			};
			BuildRangeMultiplier.SettingChanged += delegate
			{
				ApplyAll();
			};
			RangePerUpgradeMultiplier.SettingChanged += delegate
			{
				ApplyAll();
			};
			UpgradeSpaceMultiplier.SettingChanged += delegate
			{
				ApplyAll();
			};
			UpgradeMaxDistanceMultiplier.SettingChanged += delegate
			{
				ApplyAll();
			};
			SynchronizationManager.OnConfigurationSynchronized += delegate
			{
				ApplyAll();
			};
		}

		private static void ParseOverrides()
		{
			Dictionary<string, float> dictionary = new Dictionary<string, float>(StringComparer.OrdinalIgnoreCase);
			string[] array = BuildRangeOverrides.Value.Split(',');
			foreach (string text in array)
			{
				string[] array2 = text.Split('=');
				if (array2.Length == 2 && float.TryParse(array2[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) && result > 0f)
				{
					dictionary[array2[0].Trim()] = result;
				}
				else if (text.Trim().Length > 0)
				{
					Plugin.Log.LogWarning((object)("[Crafting Stations] Ignoring invalid override '" + text.Trim() + "' (expected name=meters)"));
				}
			}
			_overrides = dictionary;
		}

		private static void ApplyAll()
		{
			ZNetScene instance = ZNetScene.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			CraftingStation s = default(CraftingStation);
			StationExtension e = default(StationExtension);
			Piece p = default(Piece);
			foreach (GameObject prefab in instance.m_prefabs)
			{
				if (!((Object)(object)prefab == (Object)null))
				{
					if (prefab.TryGetComponent<CraftingStation>(ref s))
					{
						ApplyStation(((Object)prefab).name, s, capture: true);
					}
					if (prefab.TryGetComponent<StationExtension>(ref e) && prefab.TryGetComponent<Piece>(ref p))
					{
						ApplyExtension(((Object)prefab).name, e, p, capture: true);
					}
				}
			}
			foreach (CraftingStation allStation in CraftingStation.m_allStations)
			{
				if ((Object)(object)allStation != (Object)null)
				{
					ApplyStation(Utils.GetPrefabName(((Component)allStation).gameObject), allStation, capture: false);
				}
			}
			Piece p2 = default(Piece);
			foreach (StationExtension allExtension in StationExtension.m_allExtensions)
			{
				if ((Object)(object)allExtension != (Object)null && ((Component)allExtension).TryGetComponent<Piece>(ref p2))
				{
					ApplyExtension(Utils.GetPrefabName(((Component)allExtension).gameObject), allExtension, p2, capture: false);
				}
			}
			LogOnce();
		}

		private static void ApplyStation(string name, CraftingStation s, bool capture)
		{
			if (!StationOrigs.TryGetValue(name, out var value))
			{
				if (!capture)
				{
					return;
				}
				value = (StationOrigs[name] = new StationOrig
				{
					Range = s.m_rangeBuild,
					PerLevel = s.m_extraRangePerLevel
				});
			}
			s.m_rangeBuild = (_overrides.TryGetValue(name, out var value2) ? value2 : (value.Range * BuildRangeMultiplier.Value));
			s.m_extraRangePerLevel = value.PerLevel * RangePerUpgradeMultiplier.Value;
			s.m_updateExtensionTimer = 2f;
		}

		private static void ApplyExtension(string name, StationExtension e, Piece p, bool capture)
		{
			if (!ExtensionOrigs.TryGetValue(name, out var value))
			{
				if (!capture)
				{
					return;
				}
				value = (ExtensionOrigs[name] = new ExtensionOrig
				{
					Space = p.m_spaceRequirement,
					MaxDistance = e.m_maxStationDistance
				});
			}
			p.m_spaceRequirement = value.Space * UpgradeSpaceMultiplier.Value;
			e.m_maxStationDistance = value.MaxDistance * UpgradeMaxDistanceMultiplier.Value;
		}

		private static void LogOnce()
		{
			if (!_logged && StationOrigs.Count != 0)
			{
				_logged = true;
				Plugin.Log.LogInfo((object)("[Crafting Stations] Vanilla stations (prefab: build range + per upgrade): " + string.Join(", ", from kv in StationOrigs
					orderby kv.Key
					select $"{kv.Key}: {kv.Value.Range:0.#}+{kv.Value.PerLevel:0.#}")));
				Plugin.Log.LogInfo((object)("[Crafting Stations] Vanilla upgrades (prefab: space needed / max distance to station): " + string.Join(", ", from kv in ExtensionOrigs
					orderby kv.Key
					select $"{kv.Key}: {kv.Value.Space:0.##}/{kv.Value.MaxDistance:0.#}")));
			}
		}
	}
	internal static class TorchWithTools
	{
		[HarmonyPatch(typeof(Humanoid), "EquipItem")]
		private static class EquipItemPatch
		{
			private static void Prefix(Humanoid __instance, out (ItemData left, ItemData right) __state)
			{
				__state = (left: __instance.m_leftItem, right: __instance.m_rightItem);
			}

			private static void Postfix(Humanoid __instance, ItemData item, bool __result, (ItemData left, ItemData right) __state)
			{
				if (!__result || !Enabled.Value || item == null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
				{
					return;
				}
				(ItemData left, ItemData right) tuple = __state;
				ItemData item2 = tuple.left;
				ItemData item3 = tuple.right;
				Inventory inventory = __instance.GetInventory();
				if (IsBuildTool(item))
				{
					ItemData val = (IsTorch(item2) ? item2 : (IsTorch(item3) ? item3 : null));
					if (val != null && inventory.ContainsItem(val))
					{
						__instance.m_leftItem = val;
						val.m_equipped = true;
						__instance.SetupEquipment();
					}
				}
				else if (IsTorch(item) && IsBuildTool(item3) && inventory.ContainsItem(item3))
				{
					__instance.m_rightItem = item3;
					item3.m_equipped = true;
					__instance.m_leftItem = item;
					item.m_equipped = true;
					__instance.SetupEquipment();
				}
			}
		}

		public static ConfigEntry<bool> Enabled;

		public static void Init()
		{
			Enabled = ConfigHelper.BindSynced("Torch With Tools", "Enabled", value: true, "A torch can be held in the off-hand while using the hammer, hoe or cultivator.");
		}

		private static bool IsBuildTool(ItemData item)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			if (item != null && (int)item.m_shared.m_itemType == 19)
			{
				return (Object)(object)item.m_shared.m_buildPieces != (Object)null;
			}
			return false;
		}

		private static bool IsTorch(ItemData item)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			if (item != null)
			{
				return (int)item.m_shared.m_itemType == 15;
			}
			return false;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}