Decompiled source of KeepYourGear v1.1.0

KeepYourGear.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
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 KeepYourGear;

[BepInPlugin("com.burks.keepyourgear", "Keep Your Gear", "1.1.0")]
public class KeepYourGearPlugin : BaseUnityPlugin
{
	public const string GUID = "com.burks.keepyourgear";

	public const string NAME = "Keep Your Gear";

	public const string VERSION = "1.1.0";

	public static ManualLogSource Log;

	public static ConfigEntry<bool> Enabled;

	public static ConfigEntry<bool> StayEquipped;

	public static ConfigEntry<string> KeepTypes;

	public static ConfigEntry<string> AlwaysKeep;

	public static ConfigEntry<string> AlwaysDrop;

	private static string _typesRaw;

	private static string _keepRaw;

	private static string _dropRaw;

	private static readonly HashSet<string> _types = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	private static readonly HashSet<string> _keep = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	private static readonly HashSet<string> _drop = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	private void Awake()
	{
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: Invalid comparison between Unknown and I4
		//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Keep equipment in your inventory when you die; everything else goes to the tombstone as usual.");
		StayEquipped = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "StayEquipped", true, "Gear you were wearing or holding when you died is still equipped when you respawn. If false it is kept but you have to put it back on.");
		KeepTypes = ((BaseUnityPlugin)this).Config.Bind<string>("General", "KeepItemTypes", "OneHandedWeapon,TwoHandedWeapon,TwoHandedWeaponLeft,Bow,Shield,Helmet,Chest,Legs,Shoulder,Hands,Utility,Trinket,Tool,Torch,Ammo", "Item types that count as equipment and stay with you. Remove Ammo to drop arrows and bolts. All types: Material, Consumable, OneHandedWeapon, Bow, Shield, Helmet, Chest, Ammo, Customization, Legs, Hands, Trophy, TwoHandedWeapon, Torch, Misc, Shoulder, Utility, Tool, Fish, TwoHandedWeaponLeft, AmmoNonEquipable, Trinket.");
		AlwaysKeep = ((BaseUnityPlugin)this).Config.Bind<string>("General", "AlwaysKeep", "", "Comma-separated item prefab names that always stay with you, whatever their type (example: MeadHealthMedium,Coins).");
		AlwaysDrop = ((BaseUnityPlugin)this).Config.Bind<string>("General", "AlwaysDrop", "", "Comma-separated item prefab names that always go to the tombstone, whatever their type (example: BombOoze).");
		if ((int)SystemInfo.graphicsDeviceType == 4)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Headless server detected; Keep Your Gear is client-side only, not patching.");
			return;
		}
		new Harmony("com.burks.keepyourgear").PatchAll(Assembly.GetExecutingAssembly());
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Keep Your Gear 1.1.0 loaded.");
	}

	private static void Fill(HashSet<string> set, string raw)
	{
		set.Clear();
		if (string.IsNullOrEmpty(raw))
		{
			return;
		}
		string[] array = raw.Split(',');
		for (int i = 0; i < array.Length; i++)
		{
			string text = array[i].Trim();
			if (text.Length > 0)
			{
				set.Add(text);
			}
		}
	}

	private static void Refresh()
	{
		if (_typesRaw != KeepTypes.Value)
		{
			_typesRaw = KeepTypes.Value;
			Fill(_types, _typesRaw);
		}
		if (_keepRaw != AlwaysKeep.Value)
		{
			_keepRaw = AlwaysKeep.Value;
			Fill(_keep, _keepRaw);
		}
		if (_dropRaw != AlwaysDrop.Value)
		{
			_dropRaw = AlwaysDrop.Value;
			Fill(_drop, _dropRaw);
		}
	}

	public static bool ShouldKeep(ItemData item)
	{
		if (item == null || item.m_shared == null)
		{
			return false;
		}
		Refresh();
		string text = null;
		try
		{
			if (item.m_dropPrefab != null)
			{
				text = ((Object)item.m_dropPrefab).name;
			}
		}
		catch
		{
			text = null;
		}
		if (text != null)
		{
			if (_drop.Contains(text))
			{
				return false;
			}
			if (_keep.Contains(text))
			{
				return true;
			}
		}
		return _types.Contains(((object)Unsafe.As<ItemType, ItemType>(ref item.m_shared.m_itemType)/*cast due to .constrained prefix*/).ToString());
	}
}
[HarmonyPatch(typeof(Inventory), "MoveInventoryToGrave")]
public static class GravePatch
{
	private static readonly FieldRef<Inventory, List<ItemData>> Items = AccessTools.FieldRefAccess<Inventory, List<ItemData>>("m_inventory");

	private static readonly MethodInfo ChangedMethod = AccessTools.Method(typeof(Inventory), "Changed", (Type[])null, (Type[])null);

	public static Func<Inventory, bool> IsLocalPlayerInventory = delegate(Inventory inv)
	{
		Player localPlayer = Player.m_localPlayer;
		return (Object)(object)localPlayer != (Object)null && ((Humanoid)localPlayer).GetInventory() == inv;
	};

	[HarmonyPrefix]
	[HarmonyPriority(800)]
	public static void Prefix(Inventory original, out List<ItemData> __state)
	{
		__state = null;
		try
		{
			if (!KeepYourGearPlugin.Enabled.Value || original == null || !IsLocalPlayerInventory(original))
			{
				return;
			}
			List<ItemData> list = Items.Invoke(original);
			List<ItemData> list2 = new List<ItemData>();
			int num = 0;
			for (int num2 = list.Count - 1; num2 >= 0; num2--)
			{
				ItemData val = list[num2];
				if (val != null)
				{
					if (val.m_equipped || (val.m_shared != null && val.m_shared.m_questItem))
					{
						num++;
					}
					else if (KeepYourGearPlugin.ShouldKeep(val))
					{
						list2.Add(val);
						list.RemoveAt(num2);
					}
				}
			}
			list2.Reverse();
			__state = list2;
			KeepYourGearPlugin.Log.LogInfo((object)("Death: keeping " + (list2.Count + num) + " item stack(s), " + list.Count + " left for the game to sort into the tombstone (it keeps any that are still equipped)."));
		}
		catch (Exception ex)
		{
			KeepYourGearPlugin.Log.LogWarning((object)("Could not set equipment aside, normal death rules apply: " + ex));
		}
	}

	[HarmonyFinalizer]
	public static void Finalizer(Inventory original, List<ItemData> __state)
	{
		if (__state == null || __state.Count == 0 || original == null)
		{
			return;
		}
		try
		{
			List<ItemData> list = Items.Invoke(original);
			foreach (ItemData item in __state)
			{
				if (!list.Contains(item))
				{
					list.Add(item);
				}
			}
			if (ChangedMethod != null)
			{
				ChangedMethod.Invoke(original, new object[2] { false, false });
			}
		}
		catch (Exception ex)
		{
			KeepYourGearPlugin.Log.LogError((object)("Failed to put equipment back after death: " + ex));
		}
	}
}
[HarmonyPatch(typeof(Player), "CreateTombStone")]
public static class EquippedPatch
{
	[HarmonyPrefix]
	[HarmonyPriority(800)]
	public static void Prefix(Player __instance, out List<ItemData> __state)
	{
		__state = null;
		try
		{
			if (!KeepYourGearPlugin.Enabled.Value || !KeepYourGearPlugin.StayEquipped.Value || (Object)(object)__instance == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			List<ItemData> list = new List<ItemData>();
			foreach (ItemData allItem in ((Humanoid)__instance).GetInventory().GetAllItems())
			{
				if (allItem != null && allItem.m_equipped && KeepYourGearPlugin.ShouldKeep(allItem))
				{
					list.Add(allItem);
				}
			}
			__state = list;
		}
		catch (Exception ex)
		{
			KeepYourGearPlugin.Log.LogWarning((object)("Could not note what was equipped: " + ex.Message));
		}
	}

	[HarmonyFinalizer]
	public static void Finalizer(Player __instance, List<ItemData> __state)
	{
		if (__state == null || __state.Count == 0 || (Object)(object)__instance == (Object)null)
		{
			return;
		}
		try
		{
			List<ItemData> allItems = ((Humanoid)__instance).GetInventory().GetAllItems();
			int num = 0;
			foreach (ItemData item in __state)
			{
				if (allItems.Contains(item))
				{
					item.m_equipped = true;
					num++;
				}
			}
			KeepYourGearPlugin.Log.LogInfo((object)("Death: " + num + " equipped item(s) will still be equipped on respawn."));
		}
		catch (Exception ex)
		{
			KeepYourGearPlugin.Log.LogWarning((object)("Could not re-mark equipped items: " + ex.Message));
		}
	}
}