Decompiled source of MySix ArmorStandSwap v1.0.16

MySix.ArmorStandSwap.dll

Decompiled a month 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 HarmonyLib;
using MySix.Core;
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: AssemblyVersion("0.0.0.0")]
namespace MySix
{
	internal static class ModVersion
	{
		public const string Value = "1.0.16";
	}
}
namespace MySix.ArmorStandSwap
{
	public enum ModifierKey
	{
		None,
		Shift,
		Ctrl,
		Alt,
		Always
	}
	[HarmonyPatch(typeof(ArmorStand), "UseItem")]
	public static class UseItemPatch
	{
		private sealed class PendingPress
		{
			public ArmorStand Stand;

			public Switch Caller;

			public bool Everything;

			public float Since;
		}

		private struct Exchange
		{
			public int Slot;

			public ItemData FromStand;

			public ItemData FromPlayer;

			public Vector2i PlayerSlot;
		}

		public static Setting<bool> Enabled;

		public static Setting<ModifierKey> FullSwapModifier;

		public static Setting<float> HoldSeconds;

		private static readonly FieldRef<ArmorStand, List<ArmorStandSlot>> Slots = AccessTools.FieldRefAccess<ArmorStand, List<ArmorStandSlot>>("m_slots");

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

		private static readonly FieldRef<ArmorStand, ItemData> QueuedItem = AccessTools.FieldRefAccess<ArmorStand, ItemData>("m_queuedItem");

		private static readonly FieldRef<ArmorStand, int> QueuedSlot = AccessTools.FieldRefAccess<ArmorStand, int>("m_queuedSlot");

		private static readonly MethodInfo UpdateAttach = AccessTools.Method(typeof(ArmorStand), "UpdateAttach", (Type[])null, (Type[])null);

		private static readonly MethodInfo CanAttach = AccessTools.Method(typeof(ArmorStand), "CanAttach", (Type[])null, (Type[])null);

		private static PendingPress _pending;

		private static bool _passToGame;

		private static readonly MethodInfo StandUseItem = AccessTools.Method(typeof(ArmorStand), "UseItem", (Type[])null, (Type[])null);

		private static readonly string[] WornFields = new string[8] { "m_helmetItem", "m_chestItem", "m_legItem", "m_shoulderItem", "m_utilityItem", "m_trinketItem", "m_rightItem", "m_leftItem" };

		private static readonly Dictionary<string, FieldRef<Humanoid, ItemData>> WornRefs = WornFields.ToDictionary((string n) => n, (string n) => AccessTools.FieldRefAccess<Humanoid, ItemData>(n));

		private static readonly string[] HeldFields = new string[2] { "m_rightItem", "m_leftItem" };

		private static bool Prefix(ArmorStand __instance, Switch caller, Humanoid user, ItemData item, ref bool __result)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if (Enabled == null || !Enabled.Value || item != null)
			{
				return true;
			}
			Player val = (Player)(object)((user is Player) ? user : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val != (Object)(object)Player.m_localPlayer)
			{
				return true;
			}
			if (!PrivateArea.CheckAccess(((Component)__instance).transform.position, 0f, true, false))
			{
				return true;
			}
			ZNetView val2 = NView.Invoke(__instance);
			if ((Object)(object)val2 == (Object)null || !val2.IsValid())
			{
				return true;
			}
			if (_passToGame)
			{
				return true;
			}
			if (UseButtonHeld())
			{
				if (_pending == null || (Object)(object)_pending.Stand != (Object)(object)__instance)
				{
					_pending = new PendingPress
					{
						Stand = __instance,
						Caller = caller,
						Everything = FullSwapHeld(val),
						Since = Time.time
					};
				}
				__result = true;
				return false;
			}
			if (!val2.IsOwner())
			{
				val2.ClaimOwnership();
			}
			__result = Swap(__instance, val, val2, FullSwapHeld(val));
			return false;
		}

		private static bool UseButtonHeld()
		{
			if (!ZInput.GetButton("Use"))
			{
				return ZInput.GetButton("JoyUse");
			}
			return true;
		}

		internal static void Tick()
		{
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			PendingPress pending = _pending;
			if (pending == null)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)pending.Stand == (Object)null || (Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead())
			{
				_pending = null;
				return;
			}
			if (UseButtonHeld())
			{
				float num = ((HoldSeconds != null) ? HoldSeconds.Value : 1f);
				if (Time.time - pending.Since < num)
				{
					return;
				}
				_pending = null;
				_passToGame = true;
				try
				{
					StandUseItem.Invoke(pending.Stand, new object[3] { pending.Caller, localPlayer, null });
					return;
				}
				finally
				{
					_passToGame = false;
				}
			}
			_pending = null;
			ZNetView val = NView.Invoke(pending.Stand);
			if (!((Object)(object)val == (Object)null) && val.IsValid() && PrivateArea.CheckAccess(((Component)pending.Stand).transform.position, 0f, true, false))
			{
				if (!val.IsOwner())
				{
					val.ClaimOwnership();
				}
				Swap(pending.Stand, localPlayer, val, pending.Everything);
			}
		}

		private static string ModifierName()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			bool flag = (int)Application.platform == 1 || (int)Application.platform == 0;
			switch ((FullSwapModifier != null) ? FullSwapModifier.Value : ModifierKey.Alt)
			{
			case ModifierKey.Shift:
				return "Shift";
			case ModifierKey.Ctrl:
				if (!flag)
				{
					return "Ctrl";
				}
				return "Control";
			case ModifierKey.Alt:
				if (!flag)
				{
					return "Alt";
				}
				return "Option";
			case ModifierKey.Always:
				return null;
			default:
				return null;
			}
		}

		private static bool FullSwapHeld(Player player)
		{
			if ((Object)(object)player != (Object)null && ((Character)player).IsBlocking())
			{
				return true;
			}
			switch ((FullSwapModifier != null) ? FullSwapModifier.Value : ModifierKey.Alt)
			{
			case ModifierKey.Always:
				return true;
			case ModifierKey.Shift:
				if (!Input.GetKey((KeyCode)304))
				{
					return Input.GetKey((KeyCode)303);
				}
				return true;
			case ModifierKey.Ctrl:
				if (!Input.GetKey((KeyCode)306))
				{
					return Input.GetKey((KeyCode)305);
				}
				return true;
			case ModifierKey.Alt:
				if (!Input.GetKey((KeyCode)308))
				{
					return Input.GetKey((KeyCode)307);
				}
				return true;
			default:
				return false;
			}
		}

		private static bool Swap(ArmorStand stand, Player player, ZNetView nview, bool everything)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			List<ArmorStandSlot> list = Slots.Invoke(stand);
			Inventory inventory = ((Humanoid)player).GetInventory();
			List<Exchange> list2 = new List<Exchange>();
			List<ItemData> list3 = new List<ItemData>();
			for (int i = 0; i < list.Count; i++)
			{
				ItemData val = ReadAttachedItem(stand, nview, i);
				if (val == null && !everything)
				{
					continue;
				}
				ItemData val2 = FindWornFor(player, stand, list[i], list3);
				if (val != null || val2 != null)
				{
					if (val2 != null)
					{
						list3.Add(val2);
					}
					list2.Add(new Exchange
					{
						Slot = i,
						FromStand = val,
						FromPlayer = val2,
						PlayerSlot = (Vector2i)(((??)val2?.m_gridPos) ?? new Vector2i(-1, -1))
					});
				}
			}
			int num = 0;
			foreach (ItemData item in Held(player))
			{
				if (item != null && !list3.Contains(item))
				{
					int num2 = FreeSlotFor(stand, list, item, list2);
					if (num2 < 0)
					{
						num++;
						continue;
					}
					list3.Add(item);
					list2.Add(new Exchange
					{
						Slot = num2,
						FromStand = null,
						FromPlayer = item
					});
				}
			}
			if (list2.Count == 0)
			{
				string text = ModifierName();
				((Character)player).Message((MessageType)2, (num > 0) ? Texts.Get("mysix_stand_noroom_held", Array.Empty<string>()) : (everything ? Texts.Get("mysix_stand_nothing", Array.Empty<string>()) : ((text == null) ? Texts.Get("mysix_stand_empty_block", Array.Empty<string>()) : Texts.Get("mysix_stand_empty_key", new string[1] { text }))), 0, (Sprite)null, false);
				return false;
			}
			int num3 = list2.Count((Exchange p) => p.FromStand != null && p.FromPlayer == null);
			int num4 = list2.Count((Exchange p) => p.FromStand != null && p.FromPlayer != null);
			int num5 = num3 + ((num4 > 0) ? 1 : 0);
			if (num5 > inventory.GetEmptySlots())
			{
				((Character)player).Message((MessageType)2, (num5 == 1) ? Texts.Get("mysix_stand_need_slot", Array.Empty<string>()) : Texts.Get("mysix_stand_need_slots", new string[2]
				{
					num5.ToString(),
					num3.ToString()
				}), 0, (Sprite)null, false);
				CorePlugin.Log.LogInfo((object)($"ArmorStandSwap: refused, {inventory.GetEmptySlots()} free slot(s) but " + $"{num5} needed ({num4} trade(s) sharing one slot, {num3} arriving " + "with no counterpart)"));
				return false;
			}
			int num6 = 0;
			foreach (Exchange item2 in list2)
			{
				ItemData val3 = null;
				if (item2.FromStand != null)
				{
					if (inventory.AddItem(item2.FromStand))
					{
						val3 = item2.FromStand;
					}
					if (val3 == null)
					{
						((Character)player).Message((MessageType)2, Texts.Get("mysix_stand_full", Array.Empty<string>()), 0, (Sprite)null, false);
						break;
					}
					stand.DestroyAttachment(item2.Slot);
				}
				if (item2.FromPlayer != null)
				{
					QueuedItem.Invoke(stand) = item2.FromPlayer;
					QueuedSlot.Invoke(stand) = item2.Slot;
					UpdateAttach.Invoke(stand, null);
				}
				if (val3 != null)
				{
					MoveToSlot(inventory, val3, item2.PlayerSlot);
					((Humanoid)player).EquipItem(val3, true);
				}
				num6++;
			}
			if (num6 > 0)
			{
				CorePlugin.Log.LogInfo((object)(string.Format("ArmorStandSwap: swapped {0} slot(s){1}", num6, everything ? " (full swap)" : "") + ((num > 0) ? $", {num} held item(s) had nowhere to go" : "")));
				((Character)player).Message((MessageType)2, (num <= 0) ? ((num6 == 1) ? Texts.Get("mysix_stand_swapped_one", Array.Empty<string>()) : Texts.Get("mysix_stand_swapped", new string[1] { num6.ToString() })) : ((num6 == 1) ? Texts.Get("mysix_stand_swapped_one_noroom", Array.Empty<string>()) : Texts.Get("mysix_stand_swapped_noroom", new string[1] { num6.ToString() })), 0, (Sprite)null, false);
			}
			return num6 > 0;
		}

		private static ItemData ReadAttachedItem(ArmorStand stand, ZNetView nview, int slot)
		{
			int attachedItem = stand.GetAttachedItem(slot);
			if (attachedItem == 0)
			{
				return null;
			}
			GameObject val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab(attachedItem) : null);
			ItemDrop val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val2 == (Object)null)
			{
				CorePlugin.Log.LogWarning((object)$"ArmorStandSwap: unknown item {attachedItem} on stand slot {slot}; leaving it alone");
				return null;
			}
			ItemData obj = val2.m_itemData.Clone();
			obj.m_dropPrefab = val;
			ItemDrop.LoadFromZDO(obj, nview.GetZDO(), slot);
			obj.m_stack = 1;
			obj.m_equipped = false;
			return obj;
		}

		private static ItemData FindWornFor(Player player, ArmorStand stand, ArmorStandSlot slot, List<ItemData> alreadyClaimed)
		{
			foreach (ItemData item in Worn(player))
			{
				if (item != null && !alreadyClaimed.Contains(item) && (bool)CanAttach.Invoke(stand, new object[2] { slot, item }))
				{
					return item;
				}
			}
			return null;
		}

		private static IEnumerable<ItemData> Worn(Player player)
		{
			string[] wornFields = WornFields;
			foreach (string key in wornFields)
			{
				yield return WornRefs[key].Invoke((Humanoid)(object)player);
			}
		}

		private static IEnumerable<ItemData> Held(Player player)
		{
			string[] heldFields = HeldFields;
			foreach (string key in heldFields)
			{
				yield return WornRefs[key].Invoke((Humanoid)(object)player);
			}
		}

		private static int FreeSlotFor(ArmorStand stand, List<ArmorStandSlot> slots, ItemData item, List<Exchange> plan)
		{
			int i;
			for (i = 0; i < slots.Count; i++)
			{
				if (stand.GetAttachedItem(i) == 0 && !plan.Any((Exchange p) => p.Slot == i) && (bool)CanAttach.Invoke(stand, new object[2]
				{
					slots[i],
					item
				}))
				{
					return i;
				}
			}
			return -1;
		}

		private static void MoveToSlot(Inventory inventory, ItemData item, Vector2i slot)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: 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_0037: 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_0051: Unknown result type (might be due to invalid IL or missing references)
			if (slot.x >= 0 && (item.m_gridPos.x != slot.x || item.m_gridPos.y != slot.y) && inventory.GetItemAt(slot.x, slot.y) == null && inventory.RemoveItem(item) && !inventory.AddItem(item, slot))
			{
				inventory.AddItem(item);
			}
		}
	}
	[BepInPlugin("com.mysix.armorstandswap", "MySix Armor Stand Swap", "1.0.16")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class ArmorStandSwapPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.mysix.armorstandswap";

		public const string PluginName = "MySix Armor Stand Swap";

		public const string PluginVersion = "1.0.16";

		private const int RequiredCoreApi = 2;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Expected O, but got Unknown
			if (CorePlugin.RequireApi("MySix Armor Stand Swap", 2))
			{
				Texts.Load(typeof(ArmorStandSwapPlugin).Assembly, "Texts.txt");
				UseItemPatch.Enabled = Settings.Register<bool>("MySix Armor Stand Swap", ((BaseUnityPlugin)this).Config.Bind<bool>("ArmorStandSwap", "Enabled", true, "Pressing E on an armour stand exchanges the pieces the stand is holding, and hands over whatever you are wielding. Using a hotbar item on the stand (keys 1-8) is unchanged."), (Scope)0, (string)null);
				UseItemPatch.FullSwapModifier = Settings.Register<ModifierKey>("MySix Armor Stand Swap", ((BaseUnityPlugin)this).Config.Bind<ModifierKey>("ArmorStandSwap", "FullSwapModifier", ModifierKey.Alt, "Blocking while you press E always swaps everything, on every platform and on a controller, and you can block with empty hands. This key does the same, for the times the game will not count you as blocking: while you are encumbered, staggering, mid-swing, dodging, or holding the hammer in placement mode. On a Mac it is the Option key. Alt by default because it is not a movement key, where Shift is sprint and Ctrl is crouch and either is easy to still be holding. Always makes every press a full swap; None leaves only blocking."), (Scope)1, (string)null);
				UseItemPatch.HoldSeconds = Settings.Register<float>("MySix Armor Stand Swap", ((BaseUnityPlugin)this).Config.Bind<float>("ArmorStandSwap", "HoldSeconds", 1f, "Hold E this long on a stand and it does what the unmodded game does instead of swapping: the piece you are looking at drops off the stand. A quicker press swaps, once you let go of E."), (Scope)1, (string)null);
				_harmony = new Harmony("com.mysix.armorstandswap");
				_harmony.PatchAll(typeof(ArmorStandSwapPlugin).Assembly);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"MySix Armor Stand Swap 1.0.16 loaded");
			}
		}

		private void Update()
		{
			UseItemPatch.Tick();
		}

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