Decompiled source of ItemTracker v1.0.0

ItemTracker.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace ItemTracker;

[BepInPlugin("com.burks.itemtracker", "Item Tracker", "1.0.0")]
public class ItemTrackerPlugin : BaseUnityPlugin
{
	private struct Pending
	{
		public string Name;

		public int Main;

		public int Bag;

		public float At;
	}

	public const string GUID = "com.burks.itemtracker";

	public const string NAME = "Item Tracker";

	public const string VERSION = "1.0.0";

	public static ManualLogSource Log;

	public static ConfigEntry<bool> LogPickups;

	public static ConfigEntry<bool> LogRemovals;

	public static ConfigEntry<bool> LogAmmo;

	private static MethodInfo _bagApi;

	private static readonly List<Pending> _pending = new List<Pending>();

	private void Awake()
	{
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Invalid comparison between Unknown and I4
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		LogPickups = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "LogPickups", true, "Log every item you pick up and where it ended up.");
		LogRemovals = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "LogRemovals", true, "Log everything that removes items from your inventory or backpack, and which mod did it.");
		LogAmmo = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "LogAmmo", false, "Also log arrows/bolts used up (very spammy).");
		if ((int)SystemInfo.graphicsDeviceType != 4)
		{
			Type type = Type.GetType("AdventureBackpacks.API.ABAPI, AdventureBackpacks");
			if (type != null)
			{
				_bagApi = AccessTools.Method(type, "GetEquippedBackpackInventory", new Type[1] { typeof(Player) }, (Type[])null);
			}
			new Harmony("com.burks.itemtracker").PatchAll(Assembly.GetExecutingAssembly());
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Item Tracker 1.0.0 loaded" + ((_bagApi != null) ? " (backpack tracking on)." : " (no Adventure Backpacks found).")));
		}
	}

	internal static Inventory Bag(Player p)
	{
		try
		{
			return (Inventory)((_bagApi == null || (Object)(object)p == (Object)null) ? null : /*isinst with value type is only supported in some contexts*/);
		}
		catch
		{
			return null;
		}
	}

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

	internal static string Nice(string name)
	{
		if (Localization.instance == null)
		{
			return name;
		}
		return Localization.instance.Localize(name);
	}

	internal static void Check(string name, int main, int bag)
	{
		_pending.Add(new Pending
		{
			Name = name,
			Main = main,
			Bag = bag,
			At = Time.time + 2f
		});
	}

	private void Update()
	{
		if (_pending.Count == 0)
		{
			return;
		}
		Player localPlayer = Player.m_localPlayer;
		for (int num = _pending.Count - 1; num >= 0; num--)
		{
			Pending pending = _pending[num];
			if (!(Time.time < pending.At))
			{
				_pending.RemoveAt(num);
				if (!((Object)(object)localPlayer == (Object)null))
				{
					int num2 = Count(((Humanoid)localPlayer).GetInventory(), pending.Name);
					int num3 = Count(Bag(localPlayer), pending.Name);
					if (num2 + num3 < pending.Main + pending.Bag)
					{
						Log.LogWarning((object)$"2 s after picking up {Nice(pending.Name)}: you now have {num2} on you + {num3} in the bag, was {pending.Main} + {pending.Bag} right after pickup. Something removed {pending.Main + pending.Bag - num2 - num3}.");
					}
				}
			}
		}
	}

	internal static string Caller()
	{
		StringBuilder stringBuilder = new StringBuilder();
		StackFrame[] frames = new StackTrace(2, fNeedFileInfo: false).GetFrames();
		int num = 0;
		if (frames == null)
		{
			return "?";
		}
		StackFrame[] array = frames;
		for (int i = 0; i < array.Length; i++)
		{
			MethodBase method = array[i].GetMethod();
			if (method == null)
			{
				continue;
			}
			string text = ((method.DeclaringType != null) ? method.DeclaringType.FullName : "");
			if (!text.StartsWith("ItemTracker") && !text.StartsWith("HarmonyLib") && !text.StartsWith("MonoMod") && !text.StartsWith("System."))
			{
				if (stringBuilder.Length > 0)
				{
					stringBuilder.Append(" <- ");
				}
				stringBuilder.Append(((text.Length > 0) ? (text + ".") : "") + method.Name.Replace("DMD<", "").Replace(">", ""));
				if (++num >= 6)
				{
					break;
				}
			}
		}
		return stringBuilder.ToString();
	}
}
[HarmonyPatch(typeof(Humanoid), "Pickup")]
public static class PickupPatch
{
	public static void Prefix(Humanoid __instance, GameObject go, out object[] __state)
	{
		__state = null;
		try
		{
			if (ItemTrackerPlugin.LogPickups.Value && !((Object)(object)__instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && !((Object)(object)go == (Object)null))
			{
				ItemDrop component = go.GetComponent<ItemDrop>();
				if (!((Object)(object)component == (Object)null) && component.m_itemData != null && component.m_itemData.m_shared != null)
				{
					string name = component.m_itemData.m_shared.m_name;
					Player localPlayer = Player.m_localPlayer;
					__state = new object[5]
					{
						name,
						component.m_itemData.m_stack,
						ItemTrackerPlugin.Count(((Humanoid)localPlayer).GetInventory(), name),
						ItemTrackerPlugin.Count(ItemTrackerPlugin.Bag(localPlayer), name),
						((Humanoid)localPlayer).GetInventory().GetTotalWeight()
					};
				}
			}
		}
		catch
		{
			__state = null;
		}
	}

	public static void Postfix(bool __result, object[] __state)
	{
		if (__state == null)
		{
			return;
		}
		try
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null))
			{
				string name = (string)__state[0];
				int num = (int)__state[1];
				int num2 = (int)__state[2];
				int num3 = (int)__state[3];
				int num4 = ItemTrackerPlugin.Count(((Humanoid)localPlayer).GetInventory(), name);
				int num5 = ItemTrackerPlugin.Count(ItemTrackerPlugin.Bag(localPlayer), name);
				int num6 = num4 - num2 + (num5 - num3);
				string text = ((!__result) ? "NOT picked up" : ((num6 >= num) ? "ok" : ((num6 <= 0) ? "PICKED UP BUT NOT ON YOU" : "only part arrived")));
				string text2 = $"Pickup {ItemTrackerPlugin.Nice(name)} x{num}: on you {num2}->{num4}, bag {num3}->{num5}, weight {(float)__state[4]:0.0}->{((Humanoid)localPlayer).GetInventory().GetTotalWeight():0.0} ({text})";
				if (text == "ok")
				{
					ItemTrackerPlugin.Log.LogInfo((object)text2);
				}
				else
				{
					ItemTrackerPlugin.Log.LogWarning((object)text2);
				}
				if (__result)
				{
					ItemTrackerPlugin.Check(name, num4, num5);
				}
			}
		}
		catch (Exception ex)
		{
			ItemTrackerPlugin.Log.LogWarning((object)("Pickup check failed: " + ex.Message));
		}
	}
}
[HarmonyPatch]
public static class RemovePatch
{
	private static IEnumerable<MethodBase> TargetMethods()
	{
		yield return AccessTools.Method(typeof(Inventory), "RemoveItem", new Type[1] { typeof(ItemData) }, (Type[])null);
		yield return AccessTools.Method(typeof(Inventory), "RemoveItem", new Type[2]
		{
			typeof(ItemData),
			typeof(int)
		}, (Type[])null);
		yield return AccessTools.Method(typeof(Inventory), "RemoveItem", new Type[4]
		{
			typeof(string),
			typeof(int),
			typeof(int),
			typeof(bool)
		}, (Type[])null);
		yield return AccessTools.Method(typeof(Inventory), "RemoveItem", new Type[1] { typeof(int) }, (Type[])null);
		yield return AccessTools.Method(typeof(Inventory), "RemoveOneItem", new Type[1] { typeof(ItemData) }, (Type[])null);
		yield return AccessTools.Method(typeof(Inventory), "RemoveAll", (Type[])null, (Type[])null);
	}

	public static void Prefix(Inventory __instance, MethodBase __originalMethod, object[] __args)
	{
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Expected O, but got Unknown
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Invalid comparison between Unknown and I4
		try
		{
			if (!ItemTrackerPlugin.LogRemovals.Value || __instance == null)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			string text = ((__instance == ((Humanoid)localPlayer).GetInventory()) ? "inventory" : ((__instance == ItemTrackerPlugin.Bag(localPlayer)) ? "backpack" : null));
			if (text == null)
			{
				return;
			}
			ItemData val = null;
			if (__args.Length != 0 && __args[0] is ItemData)
			{
				val = (ItemData)__args[0];
			}
			else if (__args.Length != 0 && __args[0] is int && __originalMethod.Name == "RemoveItem")
			{
				int num = (int)__args[0];
				List<ItemData> allItems = __instance.GetAllItems();
				if (num >= 0 && num < allItems.Count)
				{
					val = allItems[num];
				}
			}
			string text2;
			if (val == null || val.m_shared == null)
			{
				text2 = ((__args.Length == 0 || !(__args[0] is string)) ? "everything" : (ItemTrackerPlugin.Nice((string)__args[0]) + " x" + __args[1]));
			}
			else
			{
				if (!ItemTrackerPlugin.LogAmmo.Value && (int)val.m_shared.m_itemType == 9)
				{
					return;
				}
				int num2 = ((__args.Length > 1 && __args[1] is int) ? ((int)__args[1]) : val.m_stack);
				if (__originalMethod.Name == "RemoveOneItem")
				{
					num2 = 1;
				}
				text2 = ItemTrackerPlugin.Nice(val.m_shared.m_name) + " x" + num2 + " (stack had " + val.m_stack + ")";
			}
			ItemTrackerPlugin.Log.LogInfo((object)("Removed from " + text + ": " + text2 + "  by " + ItemTrackerPlugin.Caller()));
		}
		catch
		{
		}
	}
}