Decompiled source of EnchantFromContainers v1.2.0

plugins/EnchantFromContainers.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using EpicLoot;
using EpicLoot.CraftingV2;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")]
[assembly: AssemblyCompany("EnchantFromContainers")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("EnchantFromContainers")]
[assembly: AssemblyTitle("EnchantFromContainers")]
[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 EnchantFromContainers
{
	[BepInPlugin("hearthandrune.enchantfromcontainers", "Enchant From Containers", "1.2.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch]
		private static class ContainerTracking
		{
			[HarmonyPatch(typeof(Container), "Awake")]
			[HarmonyPostfix]
			private static void Awake(Container __instance)
			{
				Containers.Add(__instance);
			}

			[HarmonyPatch(typeof(Container), "OnDestroyed")]
			[HarmonyPrefix]
			private static void OnDestroyed(Container __instance)
			{
				Containers.Remove(__instance);
			}
		}

		[HarmonyPatch]
		private static class IdentifyScope
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				Type t = typeof(EnchantingUIController);
				yield return AccessTools.Method(t, "GetUnidentifiedItems", (Type[])null, (Type[])null);
				yield return AccessTools.Method(t, "LootRollSelectedItems", (Type[])null, (Type[])null);
			}

			private static void Prefix()
			{
				_identifyScope = true;
			}

			private static Exception Finalizer(Exception __exception)
			{
				_identifyScope = false;
				return __exception;
			}
		}

		public const string Guid = "hearthandrune.enchantfromcontainers";

		private const string ProviderId = "EnchantFromContainers";

		private static ConfigEntry<bool> _enabled;

		private static ConfigEntry<float> _range;

		private static ConfigEntry<bool> _debug;

		private static ManualLogSource _log;

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

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

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

		private Harmony _harmony;

		private static bool _identifyScope;

		private void Awake()
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			_log = ((BaseUnityPlugin)this).Logger;
			_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Let the Epic Loot enchanting table use materials from nearby chests.");
			_range = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Range", 50f, "How far (metres) from the player a chest can be and still be used.");
			_debug = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Debug", false, "Log every count and removal.");
			_harmony = new Harmony("hearthandrune.enchantfromcontainers");
			_harmony.PatchAll(typeof(ContainerTracking));
			_harmony.PatchAll(typeof(IdentifyScope));
			bool flag = API.RegisterInventoryProvider("EnchantFromContainers", (Func<List<ItemData>>)GetItems, (Func<string, int>)CountItem, (Func<string, int, int>)RemoveItem, (Func<ItemData, int, int>)RemoveExactItem);
			((BaseUnityPlugin)this).Logger.LogInfo((object)(flag ? "Registered Epic Loot inventory provider for nearby chests." : "Epic Loot refused the inventory provider registration."));
		}

		private void OnDestroy()
		{
			API.UnregisterInventoryProvider("EnchantFromContainers");
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private static bool IsMaterial(ItemData item)
		{
			if (item != null && item.m_shared != null && item.m_shared.m_maxStackSize > 1 && !ItemDataExtensions.IsMagic(item) && !ItemDataExtensions.IsUnidentified(item))
			{
				return item.m_worldLevel >= Game.m_worldLevel;
			}
			return false;
		}

		private static bool IsPlainMaterial(ItemData item, string name)
		{
			if (item?.m_shared != null && item.m_shared.m_name == name)
			{
				return IsMaterial(item);
			}
			return false;
		}

		private static ZNetView TakeOwnership(Container c)
		{
			ZNetView val = NViewRef.Invoke(c);
			val.ClaimOwnership();
			if (!val.IsOwner())
			{
				return null;
			}
			return val;
		}

		private static bool IsUnidentifiedInScope(ItemData item)
		{
			if (_identifyScope && item?.m_shared != null)
			{
				return ItemDataExtensions.IsUnidentified(item);
			}
			return false;
		}

		private static List<ItemData> GetItems()
		{
			List<ItemData> list = new List<ItemData>();
			foreach (Container item in NearbyContainers())
			{
				foreach (ItemData allItem in item.GetInventory().GetAllItems())
				{
					if (IsMaterial(allItem) || IsUnidentifiedInScope(allItem))
					{
						list.Add(allItem);
					}
				}
			}
			return list;
		}

		private static int RemoveExactItem(ItemData item, int amount)
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			if (item == null || amount <= 0 || (!IsMaterial(item) && !IsUnidentifiedInScope(item)))
			{
				return 0;
			}
			foreach (Container item2 in NearbyContainers())
			{
				Inventory inventory = item2.GetInventory();
				if (inventory.ContainsItem(item))
				{
					if ((Object)(object)TakeOwnership(item2) == (Object)null)
					{
						return 0;
					}
					int num = Math.Min(item.m_stack, amount);
					if (!inventory.RemoveItem(item, num))
					{
						return 0;
					}
					if (_debug.Value)
					{
						_log.LogInfo((object)$"Took {num} {item.m_shared.m_name} (exact) from chest at {((Component)item2).transform.position}");
					}
					return num;
				}
			}
			return 0;
		}

		private static List<Container> NearbyContainers()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: 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_0178: Unknown result type (might be due to invalid IL or missing references)
			List<Container> list = new List<Container>();
			Player localPlayer = Player.m_localPlayer;
			if (!_enabled.Value || (Object)(object)localPlayer == (Object)null)
			{
				return list;
			}
			Vector3 pos = ((Component)localPlayer).transform.position;
			long playerID = localPlayer.GetPlayerID();
			Containers.RemoveWhere((Container c) => (Object)(object)c == (Object)null);
			foreach (Container container in Containers)
			{
				if (container.GetInventory() == null)
				{
					continue;
				}
				ZNetView val = NViewRef.Invoke(container);
				if ((Object)(object)val == (Object)null || !val.IsValid())
				{
					continue;
				}
				Piece componentInParent = ((Component)container).GetComponentInParent<Piece>();
				if (!((Object)(object)componentInParent == (Object)null) && componentInParent.IsPlacedByPlayer())
				{
					float value = _range.Value;
					if ((!(value > 0f) || !(Vector3.Distance(pos, ((Component)container).transform.position) > value)) && (!container.IsInUse() || val.IsOwner()) && (!((Object)(object)container.m_wagon != (Object)null) || !container.m_wagon.InUse() || val.IsOwner()) && (bool)CheckAccessMethod.Invoke(container, new object[1] { playerID }) && (!container.m_checkGuardStone || PrivateArea.CheckAccess(((Component)container).transform.position, 0f, false, false)))
					{
						list.Add(container);
					}
				}
			}
			list.Sort((Container a, Container b) => Vector3.Distance(pos, ((Component)a).transform.position).CompareTo(Vector3.Distance(pos, ((Component)b).transform.position)));
			return list;
		}

		private static int CountItem(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return 0;
			}
			int num = 0;
			foreach (Container item in NearbyContainers())
			{
				foreach (ItemData allItem in item.GetInventory().GetAllItems())
				{
					if (IsPlainMaterial(allItem, name))
					{
						num += allItem.m_stack;
					}
				}
			}
			if (_debug.Value)
			{
				_log.LogInfo((object)$"Count {name}: {num} in nearby chests");
			}
			return num;
		}

		private static int RemoveItem(string name, int amount)
		{
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(name) || amount <= 0)
			{
				return 0;
			}
			int num = 0;
			foreach (Container item in NearbyContainers())
			{
				if (num >= amount)
				{
					break;
				}
				Inventory inventory = item.GetInventory();
				List<ItemData> list = inventory.GetAllItems().FindAll((ItemData i) => IsPlainMaterial(i, name));
				if (list.Count == 0 || (Object)(object)TakeOwnership(item) == (Object)null)
				{
					continue;
				}
				foreach (ItemData item2 in list)
				{
					if (num >= amount)
					{
						break;
					}
					int num2 = Math.Min(item2.m_stack, amount - num);
					if (inventory.RemoveItem(item2, num2))
					{
						num += num2;
					}
				}
				if (_debug.Value)
				{
					_log.LogInfo((object)$"Took {name} from chest at {((Component)item).transform.position}, total {num}/{amount}");
				}
			}
			if (num < amount)
			{
				_log.LogWarning((object)$"Could only take {num}/{amount} {name} from nearby chests.");
			}
			return num;
		}
	}
}