Decompiled source of ReservedJsonSlots v1.1.2

BepInEx/plugins/JsonReservedSlots.dll

Decompiled 11 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using JsonReservedSlots.JsonTypes;
using JsonReservedSlots.Keybinds;
using LethalCompanyInputUtils.Api;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using ReservedItemSlotCore;
using ReservedItemSlotCore.Data;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("JsonReservedSlots")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("JsonReservedSlots")]
[assembly: AssemblyTitle("JsonReservedSlots")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 JsonReservedSlots
{
	[BepInPlugin("JacobG5.JsonReservedSlots", "JsonReservedSlots", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class JsonReservedSlotsCore : BaseUnityPlugin
	{
		private const string modGUID = "JacobG5.JsonReservedSlots";

		private const string modName = "JsonReservedSlots";

		private const string modVersion = "1.1.0";

		private readonly Harmony harmony = new Harmony("JacobG5.JsonReservedSlots");

		public static JsonReservedSlotsCore Instance;

		public ManualLogSource mls;

		public ConfigEntry<bool> createDefaults;

		public readonly string JsonReservedSlotsPath = Path.Combine(Paths.ConfigPath, "JsonReservedSlots");

		public readonly List<ReservedSlotInfo> reservedSlotInfos = new List<ReservedSlotInfo>();

		private ReservedJsonKeybinds jsonKeybinds;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("JacobG5.JsonReservedSlots");
			mls.LogInfo((object)JsonReservedSlotsPath);
			createDefaults = ((BaseUnityPlugin)this).Config.Bind<bool>("Core", "CreateDefaults", true, "Creates an example reserved slot json for Belt bags when directory doesn't exist.");
			if (!Directory.Exists(JsonReservedSlotsPath))
			{
				mls.LogInfo((object)"Generating Defaults.");
				CreateDefaultJsonSlots();
			}
			mls.LogInfo((object)"Reading Json Files...");
			ReadJsonSlots();
		}

		public void CreateDefaultJsonSlots()
		{
			//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_003f: 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_004d: Expected I4, but got Unknown
			Directory.CreateDirectory(JsonReservedSlotsPath);
			string text = "";
			foreach (PlayerBone value in Enum.GetValues(typeof(PlayerBone)))
			{
				text += $"{(object)value}: {(int)value}\n";
			}
			File.WriteAllText(JsonReservedSlotsPath + "\\PlayerBones.txt", text);
			if (createDefaults.Value)
			{
				ReservedSlotInfo reservedSlotInfo = new ReservedSlotInfo();
				reservedSlotInfo.reservedSlotName = "utility_belt";
				reservedSlotInfo.slotPriority = 50;
				reservedSlotInfo.purchasePrice = 150;
				reservedSlotInfo.itemsForSlot = new ReservedItemInfo[1]
				{
					new ReservedItemInfo
					{
						itemName = "Belt bag"
					}
				};
				ReservedSlotInfo reservedSlotInfo2 = reservedSlotInfo;
				string contents = JsonConvert.SerializeObject((object)reservedSlotInfo2, (Formatting)1);
				File.WriteAllText(JsonReservedSlotsPath + "\\UtilityBeltSlot.json", contents);
			}
		}

		public void ReadJsonSlots()
		{
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Invalid comparison between Unknown and I4
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Expected O, but got Unknown
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				string[] files = Directory.GetFiles(JsonReservedSlotsPath);
				foreach (string text in files)
				{
					if (!text.EndsWith(".json"))
					{
						continue;
					}
					mls.LogInfo((object)("Reading " + Path.GetFileName(text)));
					ReservedSlotInfo reservedSlotInfo = JsonConvert.DeserializeObject<ReservedSlotInfo>(File.ReadAllText(text));
					if (reservedSlotInfo != null)
					{
						if (!Utility.IsNullOrWhiteSpace(reservedSlotInfo.reservedSlotName))
						{
							if (Utility.IsNullOrWhiteSpace(reservedSlotInfo.displayName))
							{
								reservedSlotInfo.displayName = Path.GetFileNameWithoutExtension(text);
							}
							reservedSlotInfo.reservedSlotName = new string(reservedSlotInfo.reservedSlotName.ToLower().Replace(' ', '_'));
							List<ReservedItemInfo> list = reservedSlotInfo.itemsForSlot.ToList();
							list.RemoveAll((ReservedItemInfo itemInfo) => Utility.IsNullOrWhiteSpace(itemInfo.itemName));
							reservedSlotInfo.itemsForSlot = list.ToArray();
							reservedSlotInfos.Add(reservedSlotInfo);
						}
					}
					else
					{
						mls.LogInfo((object)(Path.GetFileName(text) + " could not be parsed!"));
					}
				}
			}
			catch (Exception arg)
			{
				mls.LogWarning((object)$"Something went wrong reading JSON files!\n{arg}");
			}
			foreach (ReservedSlotInfo reservedSlotInfo2 in reservedSlotInfos)
			{
				ReservedItemSlotData val = ReservedItemSlotData.CreateReservedItemSlotData(reservedSlotInfo2.reservedSlotName, reservedSlotInfo2.slotPriority, reservedSlotInfo2.purchasePrice);
				for (int j = 0; j < reservedSlotInfo2.itemsForSlot.Length; j++)
				{
					if ((int)reservedSlotInfo2.itemsForSlot[j].bone == 0)
					{
						val.AddItemToReservedItemSlot(new ReservedItemData(reservedSlotInfo2.itemsForSlot[j].itemName, (PlayerBone)0, default(Vector3), default(Vector3)));
					}
					else
					{
						val.AddItemToReservedItemSlot(new ReservedItemData(reservedSlotInfo2.itemsForSlot[j].itemName, reservedSlotInfo2.itemsForSlot[j].bone, reservedSlotInfo2.itemsForSlot[j].position.GetUnityVector(), reservedSlotInfo2.itemsForSlot[j].rotation.GetUnityVector()));
					}
				}
			}
			jsonKeybinds = new ReservedJsonKeybinds();
			jsonKeybinds.BindKeys();
		}
	}
}
namespace JsonReservedSlots.Keybinds
{
	internal class ReservedJsonKeybinds : LcInputActions
	{
		public override void CreateInputActions(in InputActionMapBuilder builder)
		{
			foreach (ReservedSlotInfo reservedSlotInfo in JsonReservedSlotsCore.Instance.reservedSlotInfos)
			{
				if (reservedSlotInfo.useKeybind != null)
				{
					Bind(builder, "Use", reservedSlotInfo, reservedSlotInfo.useKeybind);
				}
				if (reservedSlotInfo.equipKeybind != null)
				{
					Bind(builder, "Equip", reservedSlotInfo, reservedSlotInfo.equipKeybind);
				}
			}
		}

		public void BindKeys()
		{
			foreach (ReservedSlotInfo slotInfo in JsonReservedSlotsCore.Instance.reservedSlotInfos)
			{
				if (slotInfo.useKeybind != null)
				{
					slotInfo.useKeybindAction = ((LcInputActions)this).Asset[GetBindId(slotInfo, "Use")];
					if (slotInfo.useKeybind.toggle)
					{
						slotInfo.useKeybindAction.performed += delegate(CallbackContext context)
						{
							//IL_0006: Unknown result type (might be due to invalid IL or missing references)
							ToggleUse(slotInfo, context);
						};
					}
					else
					{
						slotInfo.useKeybindAction.performed += delegate(CallbackContext context)
						{
							//IL_0006: Unknown result type (might be due to invalid IL or missing references)
							ActivateUse(slotInfo, context, active: true);
						};
						slotInfo.useKeybindAction.canceled += delegate(CallbackContext context)
						{
							//IL_0006: Unknown result type (might be due to invalid IL or missing references)
							ActivateUse(slotInfo, context, active: false);
						};
					}
				}
				if (slotInfo.equipKeybind == null)
				{
					continue;
				}
				slotInfo.equipKeybindAction = ((LcInputActions)this).Asset[GetBindId(slotInfo, "Equip")];
				if (slotInfo.equipKeybind.toggle)
				{
					slotInfo.equipKeybindAction.performed += delegate(CallbackContext context)
					{
						//IL_0006: Unknown result type (might be due to invalid IL or missing references)
						ToggleEquip(slotInfo, context);
					};
					continue;
				}
				slotInfo.equipKeybindAction.performed += delegate(CallbackContext context)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					ToggleEquip(slotInfo, context);
				};
				slotInfo.equipKeybindAction.canceled += delegate(CallbackContext context)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					ToggleEquip(slotInfo, context, performed: false);
				};
			}
		}

		private void Bind(InputActionMapBuilder builder, string name, ReservedSlotInfo slotInfo, ReservedKeybindInfo bindInfo)
		{
			string bindId = GetBindId(slotInfo, name);
			JsonReservedSlotsCore.Instance.mls.LogInfo((object)("Creating " + name + " Keybind for " + slotInfo.displayName + " (ID: " + bindId + ")"));
			InputActionBindingBuilder val = builder.NewActionBinding();
			val.WithActionId(bindId).WithActionType((InputActionType)1).WithBindingName(name + " " + slotInfo.displayName);
			if (Utility.IsNullOrWhiteSpace(bindInfo.defaultBind))
			{
				val.WithKbmPathUnbound();
			}
			else
			{
				val.WithKbmPath("<Keyboard>/" + bindInfo.defaultBind);
			}
			val.WithGamepadPathUnbound().Finish();
		}

		private string GetBindId(ReservedSlotInfo slotInfo, string name)
		{
			return "reserved_json_" + slotInfo.reservedSlotName + "_" + name.ToLower();
		}

		private static bool KeybindsDisabled(PlayerControllerB localPlayer)
		{
			return (Object)(object)localPlayer == (Object)null || !Object.op_Implicit((Object)(object)localPlayer) || !localPlayer.isPlayerControlled || (((NetworkBehaviour)localPlayer).IsServer && !localPlayer.isHostPlayerObject) || localPlayer.isTypingChat || localPlayer.quickMenuManager.isMenuOpen || localPlayer.isPlayerDead || ShipBuildModeManager.Instance.InBuildMode || ReservedPlayerData.localPlayerData.timeSinceSwitchingSlots < 0.08f;
		}

		public static GrabbableObject? GetActiveOrSlotItem(PlayerControllerB player, ReservedSlotInfo slotInfo)
		{
			if ((Object)(object)player.currentlyHeldObjectServer != (Object)null && IsForSlot(slotInfo, player.currentlyHeldObjectServer))
			{
				return player.currentlyHeldObjectServer;
			}
			GrabbableObject slotItem = GetSlotItem(player, slotInfo);
			if ((Object)(object)slotItem != (Object)null)
			{
				return slotItem;
			}
			GrabbableObject[] itemSlots = player.ItemSlots;
			foreach (GrabbableObject val in itemSlots)
			{
				if ((Object)(object)val != (Object)null && IsForSlot(slotInfo, val))
				{
					return val;
				}
			}
			return null;
		}

		public static GrabbableObject? GetSlotItem(PlayerControllerB player, ReservedSlotInfo slotInfo)
		{
			ReservedItemSlotData val = default(ReservedItemSlotData);
			if (SessionManager.TryGetUnlockedItemSlotData(slotInfo.reservedSlotName, ref val) && ReservedPlayerData.allPlayerData.TryGetValue(player, out var value))
			{
				return value.GetReservedItem(val);
			}
			return null;
		}

		private static bool IsForSlot(ReservedSlotInfo slotInfo, GrabbableObject item)
		{
			if ((Object)(object)item.itemProperties == (Object)null)
			{
				return false;
			}
			ReservedItemInfo[] itemsForSlot = slotInfo.itemsForSlot;
			foreach (ReservedItemInfo reservedItemInfo in itemsForSlot)
			{
				if (item.itemProperties.itemName.Equals(reservedItemInfo.itemName, StringComparison.InvariantCultureIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		private static void ActivateUse(ReservedSlotInfo slotInfo, CallbackContext context, bool active)
		{
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if (!(active ? (!((CallbackContext)(ref context)).performed) : (!((CallbackContext)(ref context)).canceled)) && !KeybindsDisabled(localPlayerController))
			{
				GrabbableObject activeOrSlotItem = GetActiveOrSlotItem(localPlayerController, slotInfo);
				if ((Object)(object)activeOrSlotItem != (Object)null)
				{
					TriggerItem(localPlayerController, slotInfo, activeOrSlotItem, active);
				}
			}
		}

		private static void ToggleUse(ReservedSlotInfo slotInfo, CallbackContext context)
		{
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if (((CallbackContext)(ref context)).performed && !KeybindsDisabled(localPlayerController))
			{
				GrabbableObject activeOrSlotItem = GetActiveOrSlotItem(localPlayerController, slotInfo);
				if ((Object)(object)activeOrSlotItem != (Object)null)
				{
					TriggerItem(localPlayerController, slotInfo, activeOrSlotItem, !activeOrSlotItem.isBeingUsed);
				}
			}
		}

		private static void TriggerItem(PlayerControllerB player, ReservedSlotInfo slotInfo, GrabbableObject item, bool active)
		{
			item.UseItemOnClient(active);
			Traverse.Create((object)player).Field("timeSinceSwitchingSlots").SetValue((object)0);
			if (slotInfo.useKeybind != null && slotInfo.useKeybind.repocket && (Object)(object)item != (Object)(object)player.currentlyHeldObjectServer)
			{
				item.PocketItem();
			}
		}

		private static void ToggleEquip(ReservedSlotInfo slotInfo, CallbackContext context, bool performed = true)
		{
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			ReservedItemSlotData val = default(ReservedItemSlotData);
			if (!(performed ? (!((CallbackContext)(ref context)).performed) : (!((CallbackContext)(ref context)).canceled)) && !KeybindsDisabled(localPlayerController) && SessionManager.TryGetUnlockedItemSlotData(slotInfo.reservedSlotName, ref val))
			{
				ReservedHotbarManager.ForceToggleReservedHotbar((ReservedItemSlotData[])(object)new ReservedItemSlotData[1] { val });
			}
		}
	}
}
namespace JsonReservedSlots.JsonTypes
{
	public class ReservedSlotInfo
	{
		[JsonIgnore]
		public ReservedItemSlotData slotData;

		public string reservedSlotName;

		public string displayName = "";

		public int slotPriority = 500;

		public int purchasePrice = 120;

		public ReservedItemInfo[] itemsForSlot;

		[JsonIgnore]
		public InputAction useKeybindAction;

		public ReservedKeybindInfo? useKeybind = null;

		[JsonIgnore]
		public InputAction equipKeybindAction;

		public ReservedKeybindInfo? equipKeybind = null;
	}
	public class ReservedItemInfo
	{
		public string itemName;

		public PlayerBone bone = (PlayerBone)0;

		public ReservedVector position = new ReservedVector();

		public ReservedVector rotation = new ReservedVector();
	}
	public class ReservedVector
	{
		public float x = 0f;

		public float y = 0f;

		public float z = 0f;

		public Vector3 GetUnityVector()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(x, y, z);
		}
	}
	public class ReservedKeybindInfo
	{
		public string defaultBind = "";

		public bool toggle = false;

		public bool repocket = false;
	}
}