Decompiled source of McCraftReach v1.1.0

McCraftReach.dll

Decompiled a month 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 HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("McCraftReach")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("McCraftReach")]
[assembly: AssemblyTitle("McCraftReach")]
[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 McCraftReach
{
	internal static class Reach
	{
		internal static int CraftingDepth;

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

		private static readonly FieldRef<Container, uint> CLastRev = AccessTools.FieldRefAccess<Container, uint>("m_lastRevision");

		private static readonly FieldRef<Container, Piece> CPiece = AccessTools.FieldRefAccess<Container, Piece>("m_piece");

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

		private static readonly Collider[] Buffer = (Collider[])(object)new Collider[1024];

		private static int _pieceMask = -1;

		private static readonly Dictionary<string, int> CountCache = new Dictionary<string, int>(StringComparer.Ordinal);

		private static float _cacheTime = -999f;

		private static Vector3 _cachePos;

		internal static Inventory PlayerInv
		{
			get
			{
				if (!Player.m_localPlayerExists)
				{
					return null;
				}
				return ((Humanoid)Player.m_localPlayer).GetInventory();
			}
		}

		private static List<Container> Nearby(Vector3 pos)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if (_pieceMask < 0)
			{
				_pieceMask = LayerMask.GetMask(new string[3] { "piece", "piece_nonsolid", "vehicle" });
			}
			HashSet<Container> hashSet = new HashSet<Container>();
			List<Container> list = new List<Container>();
			int num = Physics.OverlapSphereNonAlloc(pos, McCraftReachPlugin.Range.Value, Buffer, _pieceMask);
			for (int i = 0; i < num; i++)
			{
				Container componentInParent = ((Component)Buffer[i]).GetComponentInParent<Container>();
				if (!((Object)(object)componentInParent == (Object)null) && hashSet.Add(componentInParent) && Accessible(componentInParent))
				{
					list.Add(componentInParent);
				}
			}
			list.Sort(delegate(Container a, Container b)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val = ((Component)a).transform.position - pos;
				float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
				val = ((Component)b).transform.position - pos;
				return sqrMagnitude.CompareTo(((Vector3)(ref val)).sqrMagnitude);
			});
			return list;
		}

		private static bool Accessible(Container c)
		{
			//IL_005c: 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_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Invalid comparison between Unknown and I4
			ZNetView val = CNview.Invoke(c);
			if ((Object)(object)val == (Object)null || !val.IsValid())
			{
				return false;
			}
			if (c.GetInventory() == null)
			{
				return false;
			}
			if (!McCraftReachPlugin.RespectPrivacy.Value)
			{
				return true;
			}
			if (c.m_checkGuardStone && !PrivateArea.CheckAccess(((Component)c).transform.position, 0f, false, false))
			{
				return false;
			}
			if ((int)c.m_privacy == 0)
			{
				Piece val2 = CPiece.Invoke(c);
				long playerID = Game.instance.GetPlayerProfile().GetPlayerID();
				if ((Object)(object)val2 == (Object)null || val2.GetCreator() != playerID)
				{
					return false;
				}
			}
			else if ((int)c.m_privacy == 1)
			{
				return false;
			}
			return true;
		}

		internal static int ContainerCount(string name)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			if (!Player.m_localPlayerExists)
			{
				return 0;
			}
			Vector3 position = ((Component)Player.m_localPlayer).transform.position;
			if (!(Time.time - _cacheTime > 0.5f))
			{
				Vector3 val = position - _cachePos;
				if (!(((Vector3)(ref val)).sqrMagnitude > 16f))
				{
					goto IL_00f8;
				}
			}
			CountCache.Clear();
			foreach (Container item in Nearby(position))
			{
				foreach (ItemData allItem in item.GetInventory().GetAllItems())
				{
					string name2 = allItem.m_shared.m_name;
					CountCache.TryGetValue(name2, out var value);
					CountCache[name2] = value + allItem.m_stack;
				}
			}
			_cacheTime = Time.time;
			_cachePos = position;
			goto IL_00f8;
			IL_00f8:
			if (!CountCache.TryGetValue(name, out var value2))
			{
				return 0;
			}
			return value2;
		}

		internal static int RemoveFromContainers(string name, int amount, int quality)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (amount <= 0 || !Player.m_localPlayerExists)
			{
				return 0;
			}
			int num = amount;
			foreach (Container item in Nearby(((Component)Player.m_localPlayer).transform.position))
			{
				Inventory inventory = item.GetInventory();
				int num2 = CountIn(inventory, name, quality);
				if (num2 > 0 && Prepare(item))
				{
					int num3 = Mathf.Min(num2, num);
					inventory.RemoveItem(name, num3, quality, true);
					num -= num3;
					if (num <= 0)
					{
						break;
					}
				}
			}
			int num4 = amount - num;
			if (num4 > 0)
			{
				McCraftReachPlugin.Log.LogInfo((object)("CraftReach: pulled " + num4 + " " + name + " from containers."));
			}
			return num4;
		}

		internal static int CountIn(Inventory inv, string name, int quality)
		{
			int num = 0;
			foreach (ItemData allItem in inv.GetAllItems())
			{
				if (!(allItem.m_shared.m_name != name) && (quality <= 0 || allItem.m_quality == quality))
				{
					num += allItem.m_stack;
				}
			}
			return num;
		}

		private static bool Prepare(Container c)
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			ZNetView val = CNview.Invoke(c);
			if ((Object)(object)val == (Object)null || !val.IsValid())
			{
				return false;
			}
			if (val.IsOwner() ? c.IsInUse() : (val.GetZDO().GetInt(ZDOVars.s_inUse, 0) == 1))
			{
				return false;
			}
			if (!Accessible(c))
			{
				return false;
			}
			if (!val.IsOwner())
			{
				val.ClaimOwnership();
				if (!val.IsOwner())
				{
					return false;
				}
				ZDOMan.instance.ForceSendZDO(ZDOMan.GetSessionID(), val.GetZDO().m_uid);
				CLastRev.Invoke(c) = uint.MaxValue;
				CLoad?.Invoke(c, null);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "UpdateRecipe")]
	internal static class Patch_UpdateRecipe
	{
		private static void Prefix()
		{
			if (McCraftReachPlugin.ModEnabled.Value)
			{
				Reach.CraftingDepth++;
			}
		}

		private static void Finalizer()
		{
			if (Reach.CraftingDepth > 0)
			{
				Reach.CraftingDepth--;
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "UpdateRecipeList")]
	internal static class Patch_UpdateRecipeList
	{
		private static void Prefix()
		{
			if (McCraftReachPlugin.ModEnabled.Value)
			{
				Reach.CraftingDepth++;
			}
		}

		private static void Finalizer()
		{
			if (Reach.CraftingDepth > 0)
			{
				Reach.CraftingDepth--;
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
	internal static class Patch_DoCrafting
	{
		private static void Prefix()
		{
			if (McCraftReachPlugin.ModEnabled.Value)
			{
				Reach.CraftingDepth++;
			}
		}

		private static void Finalizer()
		{
			if (Reach.CraftingDepth > 0)
			{
				Reach.CraftingDepth--;
			}
		}
	}
	[HarmonyPatch(typeof(Inventory), "CountItems")]
	internal static class Patch_CountItems
	{
		private static void Postfix(Inventory __instance, string name, int quality, ref int __result)
		{
			if (Reach.CraftingDepth > 0 && __instance == Reach.PlayerInv && quality <= 1)
			{
				__result += Reach.ContainerCount(name);
			}
		}
	}
	[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
	{
		typeof(string),
		typeof(int),
		typeof(int),
		typeof(bool)
	})]
	internal static class Patch_RemoveItem
	{
		private static void Prefix(Inventory __instance, string name, int amount, int itemQuality, out int __state)
		{
			__state = 0;
			if (Reach.CraftingDepth > 0 && __instance == Reach.PlayerInv)
			{
				__state = Reach.CountIn(__instance, name, itemQuality);
			}
		}

		private static void Postfix(Inventory __instance, string name, int amount, int itemQuality, int __state)
		{
			if (Reach.CraftingDepth > 0 && __instance == Reach.PlayerInv)
			{
				int num = Mathf.Min(__state, amount);
				int num2 = amount - num;
				if (num2 > 0)
				{
					Reach.RemoveFromContainers(name, num2, itemQuality);
				}
			}
		}
	}
	[BepInPlugin("joaorodrigues.valheim.mccraftreach", "McCraftReach", "1.0.0")]
	[BepInProcess("valheim.exe")]
	public class McCraftReachPlugin : BaseUnityPlugin
	{
		public const string Guid = "joaorodrigues.valheim.mccraftreach";

		public const string Name = "McCraftReach";

		public const string Version = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> ModEnabled;

		internal static ConfigEntry<float> Range;

		internal static ConfigEntry<bool> RespectPrivacy;

		private void Awake()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "Enabled", true, "Craft and upgrade using materials from nearby containers, without pulling them out first.");
			Range = ((BaseUnityPlugin)this).Config.Bind<float>("1 - General", "Range", 50f, new ConfigDescription("Radius searched for containers, in meters.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 128f), Array.Empty<object>()));
			RespectPrivacy = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "RespectPrivacy", true, "Skip warded areas, private containers and group containers you don't own.");
			new Harmony("joaorodrigues.valheim.mccraftreach").PatchAll();
			Log.LogInfo((object)("McCraftReach 1.0.0 loaded. Range: " + Range.Value + "m"));
		}
	}
}