Decompiled source of ValheimBuildPuller v1.4.2

ValheimBuildPuller.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ValheimBuildPuller
{
	[BepInPlugin("com.filipe.valheimbuildpuller", "ValheimBuildPuller", "1.4.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(Hud), "SetupPieceInfo")]
		public static class HudSetupPieceInfoPatch
		{
			public static void Postfix(Hud __instance, Piece piece)
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				if (EnableMod.Value && !((Object)(object)piece == (Object)null) && piece.m_resources != null && piece.m_resources.Length != 0 && !((Object)(object)__instance.m_pieceDescription == (Object)null))
				{
					string text = $"\n<color=#FFCC00>[{PullHotkey.Value}] Puxar Materiais ({ContainerRange.Value:0}m)</color>";
					if (!__instance.m_pieceDescription.text.Contains("Puxar Materiais"))
					{
						TMP_Text pieceDescription = __instance.m_pieceDescription;
						pieceDescription.text += text;
					}
				}
			}
		}

		[HarmonyPatch(typeof(BuildUi), "OpenBuildMenu")]
		public static class BuildUiOpenBuildMenuPatch
		{
			public static void Postfix(BuildUi __instance)
			{
				if (EnableMod.Value && ShowButtonInMenu.Value)
				{
					EnsureBuildUiButtonCreated(__instance);
					if ((Object)(object)s_menuButtonGo != (Object)null)
					{
						s_menuButtonGo.SetActive(true);
						s_menuButtonGo.transform.SetAsLastSibling();
						UpdateMenuButtonLabel(GetTargetPiece(Player.m_localPlayer));
					}
				}
			}
		}

		[HarmonyPatch(typeof(BuildUi), "OnHoverPiece")]
		public static class BuildUiOnHoverPiecePatch
		{
			public static void Postfix(BuildUi __instance, BuildUiPieceButton button)
			{
				if (EnableMod.Value && ShowButtonInMenu.Value && (Object)(object)s_menuButtonGo != (Object)null && s_menuButtonGo.activeSelf)
				{
					UpdateMenuButtonLabel(((Object)(object)button != (Object)null && (Object)(object)button.Piece != (Object)null) ? button.Piece : GetTargetPiece(Player.m_localPlayer));
				}
			}
		}

		[HarmonyPatch(typeof(BuildUi), "Close")]
		public static class BuildUiClosePatch
		{
			public static void Postfix()
			{
				if ((Object)(object)s_menuButtonGo != (Object)null)
				{
					s_menuButtonGo.SetActive(false);
				}
			}
		}

		[HarmonyPatch(typeof(Hud), "UpdateBuild", new Type[]
		{
			typeof(Player),
			typeof(bool)
		})]
		public static class HudUpdateBuildPatch
		{
			public static void Postfix(Hud __instance, Player player, bool forceUpdateAllBuildStatuses)
			{
				//IL_0155: Unknown result type (might be due to invalid IL or missing references)
				if (!EnableMod.Value || !ShowButtonInMenu.Value)
				{
					if ((Object)(object)s_hudButtonGo != (Object)null)
					{
						s_hudButtonGo.SetActive(false);
					}
					return;
				}
				if ((Object)(object)player == (Object)null || !((Character)player).InPlaceMode() || (Object)(object)__instance.m_buildHud == (Object)null || !__instance.m_buildHud.activeInHierarchy)
				{
					if ((Object)(object)s_hudButtonGo != (Object)null)
					{
						s_hudButtonGo.SetActive(false);
					}
					return;
				}
				if ((Object)(object)__instance.m_buildUi != (Object)null && ((Component)__instance.m_buildUi).gameObject.activeInHierarchy)
				{
					if ((Object)(object)s_hudButtonGo != (Object)null)
					{
						s_hudButtonGo.SetActive(false);
					}
					return;
				}
				Piece targetPiece = GetTargetPiece(player);
				if ((Object)(object)targetPiece == (Object)null || targetPiece.m_resources == null || targetPiece.m_resources.Length == 0)
				{
					if ((Object)(object)s_hudButtonGo != (Object)null)
					{
						s_hudButtonGo.SetActive(false);
					}
					return;
				}
				EnsureHudButtonCreated(__instance);
				if ((Object)(object)s_hudButtonGo != (Object)null)
				{
					s_hudButtonGo.SetActive(true);
					s_hudButtonGo.transform.SetAsLastSibling();
					string arg = ((Localization.instance != null) ? Localization.instance.Localize(targetPiece.m_name) : targetPiece.m_name);
					if ((Object)(object)s_hudButtonText != (Object)null)
					{
						s_hudButtonText.text = $"[{PullHotkey.Value}] Puxar {arg}";
					}
				}
			}

			private static void EnsureHudButtonCreated(Hud hud)
			{
				//IL_0037: 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)
				if ((Object)(object)s_hudButtonGo != (Object)null || (Object)(object)hud.m_buildHud == (Object)null)
				{
					return;
				}
				s_hudButtonGo = CreateNativeValheimButton(hud.m_buildHud.transform, "ValheimBuildPuller_HudButton", new Vector2(0f, 15f), new Vector2(240f, 34f), delegate
				{
					Player localPlayer = Player.m_localPlayer;
					if ((Object)(object)localPlayer != (Object)null)
					{
						Piece targetPiece = GetTargetPiece(localPlayer);
						PullPieceMaterials(localPlayer, targetPiece);
					}
				});
				if ((Object)(object)s_hudButtonGo != (Object)null)
				{
					s_hudButton = s_hudButtonGo.GetComponent<Button>();
					s_hudButtonText = s_hudButtonGo.GetComponentInChildren<TMP_Text>();
				}
			}
		}

		public const string ModGUID = "com.filipe.valheimbuildpuller";

		public const string ModName = "ValheimBuildPuller";

		public const string ModVersion = "1.4.2";

		public static ConfigEntry<bool> EnableMod;

		public static ConfigEntry<KeyCode> PullHotkey;

		public static ConfigEntry<bool> RequireShift;

		public static ConfigEntry<float> ContainerRange;

		public static ConfigEntry<bool> ShowButtonInMenu;

		private static Harmony m_harmony;

		private static GameObject s_menuButtonGo;

		private static Button s_menuButton;

		private static TMP_Text s_menuButtonText;

		private static GameObject s_hudButtonGo;

		private static Button s_hudButton;

		private static TMP_Text s_hudButtonText;

		private static readonly FieldInfo s_hudHoveredPiece = AccessTools.Field(typeof(Hud), "m_hoveredPiece");

		private static readonly FieldInfo s_buildUiHoveredBtn = AccessTools.Field(typeof(BuildUi), "m_currentHoveredPieceButton");

		private static readonly FieldInfo s_buildUiLastSelectedBtn = AccessTools.Field(typeof(BuildUi), "m_lastSelectedPieceBtn");

		private static readonly MethodInfo s_inventoryChanged = AccessTools.Method(typeof(Inventory), "Changed", new Type[2]
		{
			typeof(bool),
			typeof(bool)
		}, (Type[])null);

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

		private static readonly MethodInfo s_containerCheckAccess = AccessTools.Method(typeof(Container), "CheckAccess", new Type[1] { typeof(long) }, (Type[])null);

		private static readonly MethodInfo s_containerSave = AccessTools.Method(typeof(Container), "Save", (Type[])null, (Type[])null);

		private static readonly FieldInfo s_containerNView = AccessTools.Field(typeof(Container), "m_nview");

		private void Awake()
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Expected O, but got Unknown
			EnableMod = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EnableMod", true, "Ativa a funcionalidade de puxar materiais de construção dos baús.");
			PullHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "PullHotkey", (KeyCode)117, "Tecla única para puxar materiais (Tecla U).");
			RequireShift = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "RequireShift", false, "Se verdadeiro, exige segurar Shift junto com a tecla.");
			ContainerRange = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ContainerRange", 100f, "Raio em metros para buscar baús, barcos e carroças.");
			ShowButtonInMenu = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "ShowButtonInMenu", true, "Exibe o botão de madeira estilizado nativo na Janela de Seleção e no HUD de Construção.");
			m_harmony = new Harmony("com.filipe.valheimbuildpuller");
			m_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"ValheimBuildPuller v1.4.2 carregado com sucesso! (Raio 100m, puxada completa de todos os itens, arte nativa no menu e HUD)");
		}

		private void OnDestroy()
		{
			Harmony harmony = m_harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			if ((Object)(object)s_menuButtonGo != (Object)null)
			{
				Object.Destroy((Object)(object)s_menuButtonGo);
			}
			if ((Object)(object)s_hudButtonGo != (Object)null)
			{
				Object.Destroy((Object)(object)s_hudButtonGo);
			}
		}

		private void Update()
		{
			//IL_009b: 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)
			if (!EnableMod.Value)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead() || !((Character)localPlayer).InPlaceMode() || ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus()) || Console.IsVisible() || ((Object)(object)Hud.instance != (Object)null && (Object)(object)Hud.instance.m_buildUi != (Object)null && Hud.instance.m_buildUi.SearchFieldFocused))
			{
				return;
			}
			bool flag = false;
			try
			{
				flag = ZInput.GetKeyDown(PullHotkey.Value, true);
			}
			catch
			{
				flag = Input.GetKeyDown(PullHotkey.Value);
			}
			if (!flag)
			{
				return;
			}
			if (RequireShift.Value)
			{
				bool flag2 = false;
				try
				{
					flag2 = ZInput.GetKey((KeyCode)304, true) || ZInput.GetKey((KeyCode)303, true);
				}
				catch
				{
					flag2 = Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303);
				}
				if (!flag2)
				{
					return;
				}
			}
			Piece targetPiece = GetTargetPiece(localPlayer);
			PullPieceMaterials(localPlayer, targetPiece);
		}

		public static Piece GetTargetPiece(Player player)
		{
			if ((Object)(object)player == (Object)null)
			{
				return null;
			}
			Hud instance = Hud.instance;
			if ((Object)(object)instance != (Object)null)
			{
				if ((Object)(object)instance.m_buildUi != (Object)null && ((Component)instance.m_buildUi).gameObject.activeInHierarchy && s_buildUiHoveredBtn != null)
				{
					object? value = s_buildUiHoveredBtn.GetValue(instance.m_buildUi);
					BuildUiPieceButton val = (BuildUiPieceButton)((value is BuildUiPieceButton) ? value : null);
					if ((Object)(object)val != (Object)null && (Object)(object)val.Piece != (Object)null)
					{
						return val.Piece;
					}
				}
				if (s_hudHoveredPiece != null)
				{
					object? value2 = s_hudHoveredPiece.GetValue(instance);
					Piece val2 = (Piece)((value2 is Piece) ? value2 : null);
					if ((Object)(object)val2 != (Object)null)
					{
						return val2;
					}
				}
				if ((Object)(object)instance.m_buildUi != (Object)null && s_buildUiLastSelectedBtn != null)
				{
					object? value3 = s_buildUiLastSelectedBtn.GetValue(instance.m_buildUi);
					GameObject val3 = (GameObject)((value3 is GameObject) ? value3 : null);
					if ((Object)(object)val3 != (Object)null)
					{
						BuildUiPieceButton component = val3.GetComponent<BuildUiPieceButton>();
						if ((Object)(object)component != (Object)null && (Object)(object)component.Piece != (Object)null)
						{
							return component.Piece;
						}
					}
				}
			}
			return player.GetSelectedPiece();
		}

		private static bool CheckContainerAccess(Container container, long playerId)
		{
			if ((Object)(object)container == (Object)null)
			{
				return false;
			}
			if (IsContainerExcluded(container))
			{
				return false;
			}
			if (s_containerCheckAccess != null)
			{
				try
				{
					return (bool)s_containerCheckAccess.Invoke(container, new object[1] { playerId });
				}
				catch
				{
					return true;
				}
			}
			return true;
		}

		private static bool IsContainerExcluded(Container container)
		{
			if ((Object)(object)container == (Object)null)
			{
				return true;
			}
			string text = ((container.m_name != null) ? container.m_name.ToLower() : "");
			if (text.Contains("[private]") || text.Contains("[no-pull]") || text.Contains("[ignore]"))
			{
				return true;
			}
			Sign componentInChildren = ((Component)container).GetComponentInChildren<Sign>();
			if ((Object)(object)componentInChildren != (Object)null)
			{
				string text2 = componentInChildren.GetText();
				if (!string.IsNullOrEmpty(text2))
				{
					string text3 = text2.ToLower();
					if (text3.Contains("[private]") || text3.Contains("[no-pull]") || text3.Contains("[ignore]"))
					{
						return true;
					}
				}
			}
			return false;
		}

		private static void SaveContainer(Container container, long playerId)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			if ((Object)(object)container == (Object)null)
			{
				return;
			}
			try
			{
				if (s_containerSave != null)
				{
					s_containerSave.Invoke(container, null);
				}
				if (s_containerNView != null)
				{
					ZNetView val = (ZNetView)s_containerNView.GetValue(container);
					if ((Object)(object)val != (Object)null && val.IsValid())
					{
						val.InvokeRPC(ZNetView.Everybody, "RPC_Discovered", new object[2] { playerId, 0 });
					}
				}
			}
			catch
			{
			}
		}

		private static void NotifyInventoriesChanged(Player player, Container container)
		{
			try
			{
				if ((Object)(object)container != (Object)null && container.GetInventory() != null && s_inventoryChanged != null)
				{
					s_inventoryChanged.Invoke(container.GetInventory(), new object[2] { false, false });
				}
			}
			catch
			{
			}
			try
			{
				if (!((Object)(object)player != (Object)null))
				{
					return;
				}
				Inventory inventory = ((Humanoid)player).GetInventory();
				if (inventory != null && s_inventoryChanged != null)
				{
					s_inventoryChanged.Invoke(inventory, new object[2] { false, false });
				}
				if (s_playerOnInvChanged != null)
				{
					s_playerOnInvChanged.Invoke(player, new object[0]);
				}
				if ((Object)(object)InventoryGui.instance != (Object)null)
				{
					MethodInfo methodInfo = AccessTools.Method(typeof(InventoryGui), "UpdateCraftingPanel", (Type[])null, (Type[])null);
					if (methodInfo != null)
					{
						methodInfo.Invoke(InventoryGui.instance, new object[0]);
					}
				}
			}
			catch
			{
			}
		}

		private static bool ItemMatchesRequirement(ItemData item, Requirement req)
		{
			if (item == null || req == null || (Object)(object)req.m_resItem == (Object)null)
			{
				return false;
			}
			if (item.m_shared != null && req.m_resItem.m_itemData != null && req.m_resItem.m_itemData.m_shared != null)
			{
				string name = item.m_shared.m_name;
				string name2 = req.m_resItem.m_itemData.m_shared.m_name;
				if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(name2) && string.Equals(name, name2, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			string name3 = ((Object)req.m_resItem).name;
			if (!string.IsNullOrEmpty(name3))
			{
				if ((Object)(object)item.m_dropPrefab != (Object)null && string.Equals(((Object)item.m_dropPrefab).name.Replace("(Clone)", ""), name3, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
				if (item.m_shared != null && !string.IsNullOrEmpty(item.m_shared.m_name) && string.Equals(item.m_shared.m_name.TrimStart('$'), name3, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		public static void PullPieceMaterials(Player player, Piece targetPiece)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_0314: Unknown result type (might be due to invalid IL or missing references)
			//IL_031a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null)
			{
				return;
			}
			if ((Object)(object)targetPiece == (Object)null)
			{
				((Character)player).Message((MessageType)2, "Selecione ou aponte para uma construção!", 0, (Sprite)null, false);
				return;
			}
			if (targetPiece.m_resources == null || targetPiece.m_resources.Length == 0)
			{
				((Character)player).Message((MessageType)2, "Esta peça não requer materiais!", 0, (Sprite)null, false);
				return;
			}
			List<Container> nearbyContainers = GetNearbyContainers(((Component)player).transform.position, ContainerRange.Value);
			if (nearbyContainers.Count == 0)
			{
				((Character)player).Message((MessageType)2, $"Nenhum baú encontrado no raio de {ContainerRange.Value:0}m!", 0, (Sprite)null, false);
				return;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			long playerID = player.GetPlayerID();
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			bool flag = false;
			bool flag2 = false;
			string text = ((Localization.instance != null) ? Localization.instance.Localize(targetPiece.m_name) : targetPiece.m_name);
			Requirement[] resources = targetPiece.m_resources;
			foreach (Requirement val in resources)
			{
				if (val == null || (Object)(object)val.m_resItem == (Object)null || val.m_amount <= 0)
				{
					continue;
				}
				string key = ((val.m_resItem.m_itemData?.m_shared?.m_name != null) ? Localization.instance.Localize(val.m_resItem.m_itemData.m_shared.m_name) : ((Object)val.m_resItem).name);
				int num = val.m_amount;
				int num2 = 0;
				foreach (Container item in nearbyContainers)
				{
					if (num <= 0)
					{
						break;
					}
					if ((Object)(object)item == (Object)null || item.IsInUse() || !CheckContainerAccess(item, playerID))
					{
						continue;
					}
					Inventory inventory2 = item.GetInventory();
					if (inventory2 == null)
					{
						continue;
					}
					List<ItemData> list = new List<ItemData>(inventory2.GetAllItems());
					bool flag3 = false;
					foreach (ItemData item2 in list)
					{
						if (num <= 0)
						{
							break;
						}
						if (!ItemMatchesRequirement(item2, val))
						{
							continue;
						}
						int num3 = Math.Min(item2.m_stack, num);
						bool flag4 = false;
						if (num3 == item2.m_stack)
						{
							if (inventory.AddItem(item2))
							{
								inventory2.RemoveItem(item2);
								flag4 = true;
							}
						}
						else
						{
							ItemData val2 = item2.Clone();
							val2.m_stack = num3;
							if (inventory.AddItem(val2))
							{
								inventory2.RemoveItem(item2, num3);
								flag4 = true;
							}
						}
						if (flag4)
						{
							flag3 = true;
							num -= num3;
							num2 += num3;
							flag = true;
						}
						else
						{
							flag2 = true;
						}
					}
					if (flag3)
					{
						SaveContainer(item, playerID);
						NotifyInventoriesChanged(player, item);
					}
				}
				if (num2 > 0)
				{
					dictionary[key] = num2;
				}
			}
			if (flag)
			{
				NotifyInventoriesChanged(player, null);
				try
				{
					if (player.m_autopickupEffects != null)
					{
						player.m_autopickupEffects.Create(((Component)player).transform.position, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
					}
				}
				catch
				{
				}
				List<string> list2 = new List<string>();
				foreach (KeyValuePair<string, int> item3 in dictionary)
				{
					list2.Add($"+{item3.Value} {item3.Key}");
				}
				string text2 = string.Join(", ", list2);
				if (flag2)
				{
					((Character)player).Message((MessageType)2, "[" + text + "]:\n" + text2 + "\n(Inventário cheio!)", 0, (Sprite)null, false);
				}
				else
				{
					((Character)player).Message((MessageType)2, "Materiais para [" + text + "]:\n" + text2, 0, (Sprite)null, false);
				}
			}
			else if (flag2)
			{
				((Character)player).Message((MessageType)2, "Inventário cheio! Não foi possível adicionar mais itens.", 0, (Sprite)null, false);
			}
			else
			{
				((Character)player).Message((MessageType)2, $"Nenhum dos materiais de [{text}] foi encontrado nos baús próximos ({ContainerRange.Value:0}m).", 0, (Sprite)null, false);
			}
		}

		private static List<Container> GetNearbyContainers(Vector3 center, float range)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			List<Container> list = new List<Container>();
			HashSet<Container> hashSet = new HashSet<Container>();
			List<Piece> list2 = new List<Piece>();
			Piece.GetAllPiecesInRadius(center, range, list2);
			foreach (Piece item in list2)
			{
				if (!((Object)(object)item == (Object)null))
				{
					Container component = ((Component)item).GetComponent<Container>();
					if ((Object)(object)component != (Object)null && component.GetInventory() != null && hashSet.Add(component))
					{
						list.Add(component);
					}
				}
			}
			Container[] array = Object.FindObjectsByType<Container>((FindObjectsSortMode)0);
			if (array != null)
			{
				Container[] array2 = array;
				foreach (Container val in array2)
				{
					if ((Object)(object)val != (Object)null && val.GetInventory() != null && Vector3.Distance(((Component)val).transform.position, center) <= range && hashSet.Add(val))
					{
						list.Add(val);
					}
				}
			}
			return list;
		}

		private static GameObject CreateNativeValheimButton(Transform parent, string buttonName, Vector2 anchoredPos, Vector2 sizeDelta, Action onClick)
		{
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: 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_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Expected O, but got Unknown
			//IL_0313: Unknown result type (might be due to invalid IL or missing references)
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_0330: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameObject val = null;
				if ((Object)(object)InventoryGui.instance != (Object)null && (Object)(object)InventoryGui.instance.m_takeAllButton != (Object)null)
				{
					val = ((Component)InventoryGui.instance.m_takeAllButton).gameObject;
				}
				else if ((Object)(object)Hud.instance != (Object)null && (Object)(object)Hud.instance.m_buildUi != (Object)null)
				{
					Button componentInChildren = ((Component)Hud.instance.m_buildUi).GetComponentInChildren<Button>();
					if ((Object)(object)componentInChildren != (Object)null)
					{
						val = ((Component)componentInChildren).gameObject;
					}
				}
				GameObject val2;
				if ((Object)(object)val != (Object)null)
				{
					val2 = Object.Instantiate<GameObject>(val, parent, false);
					((Object)val2).name = buttonName;
					MonoBehaviour[] components = val2.GetComponents<MonoBehaviour>();
					foreach (MonoBehaviour val3 in components)
					{
						if (!(val3 is Button) && !(val3 is Image) && !(val3 is Graphic))
						{
							Object.Destroy((Object)(object)val3);
						}
					}
				}
				else
				{
					val2 = new GameObject(buttonName, new Type[3]
					{
						typeof(RectTransform),
						typeof(Image),
						typeof(Button)
					});
					val2.transform.SetParent(parent, false);
					Image component = val2.GetComponent<Image>();
					Sprite val4 = ((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>()).FirstOrDefault((Func<Sprite, bool>)((Sprite s) => ((Object)s).name == "button_wood" || ((Object)s).name == "Button_Wood" || ((Object)s).name == "button_normal"));
					if ((Object)(object)val4 != (Object)null)
					{
						component.sprite = val4;
						component.type = (Type)1;
					}
					else
					{
						((Graphic)component).color = new Color(0.25f, 0.18f, 0.12f, 0.95f);
					}
				}
				val2.transform.SetAsLastSibling();
				RectTransform component2 = val2.GetComponent<RectTransform>();
				component2.anchorMin = new Vector2(0.5f, 0f);
				component2.anchorMax = new Vector2(0.5f, 0f);
				component2.pivot = new Vector2(0.5f, 0.5f);
				component2.anchoredPosition = anchoredPos;
				component2.sizeDelta = sizeDelta;
				Button val5 = val2.GetComponent<Button>();
				if ((Object)(object)val5 == (Object)null)
				{
					val5 = val2.AddComponent<Button>();
				}
				((UnityEventBase)val5.onClick).RemoveAllListeners();
				((UnityEvent)val5.onClick).AddListener((UnityAction)delegate
				{
					onClick?.Invoke();
				});
				TMP_Text val6 = val2.GetComponentInChildren<TMP_Text>();
				if ((Object)(object)val6 == (Object)null)
				{
					Text componentInChildren2 = val2.GetComponentInChildren<Text>();
					if ((Object)(object)componentInChildren2 != (Object)null)
					{
						Object.Destroy((Object)(object)componentInChildren2);
					}
					GameObject val7 = new GameObject("Text", new Type[2]
					{
						typeof(RectTransform),
						typeof(TextMeshProUGUI)
					});
					val7.transform.SetParent(val2.transform, false);
					val6 = val7.GetComponent<TMP_Text>();
					if ((Object)(object)Hud.instance?.m_buildSelection != (Object)null)
					{
						val6.font = Hud.instance.m_buildSelection.font;
					}
				}
				if ((Object)(object)val6 != (Object)null)
				{
					val6.text = "Puxar Materiais [U]";
					val6.fontSize = 14f;
					val6.alignment = (TextAlignmentOptions)514;
					((Graphic)val6).color = new Color(1f, 0.88f, 0.45f, 1f);
					RectTransform rectTransform = val6.rectTransform;
					rectTransform.anchorMin = Vector2.zero;
					rectTransform.anchorMax = Vector2.one;
					rectTransform.offsetMin = new Vector2(6f, 2f);
					rectTransform.offsetMax = new Vector2(-6f, -2f);
				}
				return val2;
			}
			catch (Exception arg)
			{
				Debug.LogError((object)$"[ValheimBuildPuller] Erro ao criar botão {buttonName}: {arg}");
				return null;
			}
		}

		private static void EnsureBuildUiButtonCreated(BuildUi buildUi)
		{
			//IL_002d: 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)
			if ((Object)(object)s_menuButtonGo != (Object)null || (Object)(object)buildUi == (Object)null)
			{
				return;
			}
			s_menuButtonGo = CreateNativeValheimButton(((Component)buildUi).transform, "ValheimBuildPuller_BuildUiButton", new Vector2(0f, 26f), new Vector2(300f, 42f), delegate
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null)
				{
					Piece targetPiece = GetTargetPiece(localPlayer);
					PullPieceMaterials(localPlayer, targetPiece);
				}
			});
			if ((Object)(object)s_menuButtonGo != (Object)null)
			{
				s_menuButton = s_menuButtonGo.GetComponent<Button>();
				s_menuButtonText = s_menuButtonGo.GetComponentInChildren<TMP_Text>();
			}
		}

		private static void UpdateMenuButtonLabel(Piece piece)
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)s_menuButtonText == (Object)null)
			{
				return;
			}
			if ((Object)(object)piece != (Object)null && piece.m_resources != null && piece.m_resources.Length != 0)
			{
				string arg = ((Localization.instance != null) ? Localization.instance.Localize(piece.m_name) : piece.m_name);
				s_menuButtonText.text = $"Puxar Materiais: {arg} [{PullHotkey.Value}]";
				if ((Object)(object)s_menuButton != (Object)null)
				{
					((Selectable)s_menuButton).interactable = true;
				}
			}
			else
			{
				s_menuButtonText.text = $"Puxar Materiais [{PullHotkey.Value}]";
				if ((Object)(object)s_menuButton != (Object)null)
				{
					((Selectable)s_menuButton).interactable = (Object)(object)piece != (Object)null;
				}
			}
		}
	}
}