Decompiled source of StorageTweaks v1.1.1

StorageTweaks.dll

Decompiled 3 days 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 BepInEx.Configuration;
using HarmonyLib;
using ItemDrawers.Game;
using Microsoft.CodeAnalysis;
using UnityEngine;
using Valheiman.Api;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("StorageTweaks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1")]
[assembly: AssemblyProduct("StorageTweaks")]
[assembly: AssemblyTitle("StorageTweaks")]
[assembly: AssemblyVersion("1.1.1.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 StorageTweaks
{
	[BepInPlugin("groshyr.storagetweaks", "StorageTweaks", "1.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private sealed class DrawerCount
		{
			public string ItemName;

			public int Amount;

			public bool Valid;
		}

		private sealed class DrawerType
		{
			public string Prefab;

			public ConfigEntry<int> Limit;

			public ConfigEntry<string> ItemLimits;

			public Dictionary<string, int> ByItem = new Dictionary<string, int>();
		}

		private static readonly ConditionalWeakTable<Inventory, DrawerCount> Counts = new ConditionalWeakTable<Inventory, DrawerCount>();

		private static readonly List<DrawerType> DrawerTypes = new List<DrawerType>();

		private static readonly FieldRef<ConditionalWeakTable<Inventory, DrawerComponent>> Owners = AccessTools.StaticFieldRefAccess<ConditionalWeakTable<Inventory, DrawerComponent>>(AccessTools.Field(typeof(DrawerComponent), "InventoryOwners"));

		public const string Guid = "groshyr.storagetweaks";

		public const string ModName = "StorageTweaks";

		public const string Version = "1.1.1";

		private const string PovGuid = "treextr.pathofvalheiman";

		private const string CorewoodGuid = "MagicMike.CorewoodFortified";

		private const string DrawersGuid = "com.grillspett.itemdrawers";

		private void PatchCorewoodPurse(Harmony harmony)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("CorewoodFortified.LargeStorageControls");
			MethodInfo methodInfo = (((object)type != null) ? AccessTools.DeclaredMethod(type, "IsAlwaysKept", new Type[1] { typeof(ItemData) }, (Type[])null) : null);
			if (methodInfo == null || methodInfo.ReturnType != typeof(bool))
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"CorewoodFortified Deposit All not found (CorewoodFortified not installed?); the purse fix is skipped");
				return;
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "KeepPovCells", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"CorewoodFortified Deposit All now keeps the Path of Valheiman purse and equipment cells");
		}

		private static void KeepPovCells(ItemData item, ref bool __result)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (!__result && item != null && (Object)(object)localPlayer != (Object)null && Equipment.On && Equipment.IsCellPosition(localPlayer, item.m_gridPos))
			{
				__result = true;
			}
		}

		private void PatchDrawerCount(Harmony harmony)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("ItemDrawers.Game.ItemFacts");
			harmony.Patch((MethodBase)AccessTools.Method(type, "CountByPrefab", new Type[2]
			{
				typeof(Inventory),
				typeof(string)
			}, (Type[])null), new HarmonyMethod(typeof(Plugin), "CachedCount", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Inventory), "Changed", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "DropCount", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static bool CachedCount(Inventory inventory, string itemName, ref int __result)
		{
			if (inventory == null || string.IsNullOrEmpty(itemName))
			{
				return true;
			}
			if (!Owners.Invoke().TryGetValue(inventory, out var _))
			{
				__result = CountWithoutNames(inventory, itemName);
				return false;
			}
			DrawerCount orCreateValue = Counts.GetOrCreateValue(inventory);
			if (!orCreateValue.Valid || !string.Equals(orCreateValue.ItemName, itemName, StringComparison.Ordinal))
			{
				orCreateValue.ItemName = itemName;
				orCreateValue.Amount = CountWithoutNames(inventory, itemName);
				orCreateValue.Valid = true;
			}
			__result = orCreateValue.Amount;
			return false;
		}

		private static int CountWithoutNames(Inventory inventory, string itemName)
		{
			GameObject val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab(itemName) : null);
			int num = 0;
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				GameObject dropPrefab = allItem.m_dropPrefab;
				if (dropPrefab != null && ((val != null && dropPrefab == val) || ((Object)(object)dropPrefab != (Object)null && ((Object)dropPrefab).name == itemName)))
				{
					num += allItem.m_stack;
				}
			}
			return num;
		}

		private static void DropCount(Inventory __instance)
		{
			if (Counts.TryGetValue(__instance, out var value))
			{
				value.Valid = false;
			}
		}

		private void BindDrawer(string prefab, string section, string what, int limit)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			DrawerType type = new DrawerType
			{
				Prefab = prefab
			};
			type.Limit = ((BaseUnityPlugin)this).Config.Bind<int>(section, "Limit", limit, new ConfigDescription("How many items a " + what + " holds, of whatever it is assigned (unless the item has its own limit below). The server's value applies to everyone.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1000000), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			type.ItemLimits = ((BaseUnityPlugin)this).Config.Bind<string>(section, "Item limits", "", new ConfigDescription("Own limits for single items in a " + what + ", as PrefabName:amount separated by commas, e.g. \"Coins:1000000, Wood:20000\". Prefab names are the game's item names (as in spawn commands). The server's value applies to everyone.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			type.ItemLimits.SettingChanged += delegate
			{
				ParseItemLimits(type);
			};
			ParseItemLimits(type);
			DrawerTypes.Add(type);
		}

		private void ParseItemLimits(DrawerType type)
		{
			type.ByItem = new Dictionary<string, int>();
			string[] array = type.ItemLimits.Value.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string text in array)
			{
				string[] array2 = text.Split(new char[1] { ':' });
				if (array2.Length == 2 && array2[0].Trim().Length > 0 && int.TryParse(array2[1].Trim(), out var result) && result > 0)
				{
					type.ByItem[array2[0].Trim()] = result;
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)(type.Prefab + ": ignoring item limit \"" + text.Trim() + "\" (expected PrefabName:amount)"));
				}
			}
		}

		private void PatchDrawers(Harmony harmony)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Expected O, but got Unknown
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Expected O, but got Unknown
			BindDrawer("rid_drawer_wood", "Wood drawer", "wood drawer", 10000);
			BindDrawer("rid_drawer_stone", "Stone drawer", "stone drawer", 25000);
			BindDrawer("rid_drawer_blackmarble", "Black marble drawer", "black marble drawer", 100000);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Container), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "LongRow", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(DrawerComponent), "DepositByPrefab", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "ClampDeposit", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Inventory), "AddItem", new Type[1] { typeof(ItemData) }, (Type[])null), new HarmonyMethod(typeof(Plugin), "AddWhatFits", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Inventory), "AddItem", new Type[2]
			{
				typeof(ItemData),
				typeof(Vector2i)
			}, (Type[])null), new HarmonyMethod(typeof(Plugin), "AddAtIfFits", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Inventory), "FindEmptySlot", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "FirstFreeSlot", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.PropertyGetter(typeof(DrawerComponent), "Capacity"), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "ShowLimit", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Item Drawers hold " + string.Join(", ", DrawerTypes.Select((DrawerType t) => string.Concat($"{t.Prefab} {t.Limit.Value}", string.Concat(t.ByItem.Select((KeyValuePair<string, int> i) => $" ({i.Key} {i.Value})"))))) + " items"));
		}

		private static DrawerType TypeOf(DrawerComponent drawer)
		{
			string name = ((Object)((Component)drawer).gameObject).name;
			foreach (DrawerType drawerType in DrawerTypes)
			{
				if (name.StartsWith(drawerType.Prefab, StringComparison.Ordinal))
				{
					return drawerType;
				}
			}
			return null;
		}

		private static int LimitOf(DrawerComponent drawer, string itemName)
		{
			DrawerType drawerType = TypeOf(drawer);
			if (drawerType == null)
			{
				return 0;
			}
			if (string.IsNullOrEmpty(itemName) || !drawerType.ByItem.TryGetValue(itemName, out var value))
			{
				return drawerType.Limit.Value;
			}
			return value;
		}

		private static int Room(Inventory inventory, string itemName)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (inventory == null || !Owners.Invoke().TryGetValue(inventory, out var value) || (Object)(object)value == (Object)null)
			{
				return -1;
			}
			int num = LimitOf(value, string.IsNullOrEmpty(itemName) ? value.Snapshot.ItemName : itemName);
			if (num <= 0)
			{
				return -1;
			}
			int num2 = 0;
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				num2 += allItem.m_stack;
			}
			return Math.Max(0, num - num2);
		}

		private static string NameOf(ItemData item)
		{
			if (!((Object)(object)item?.m_dropPrefab != (Object)null))
			{
				return null;
			}
			return ((Object)item.m_dropPrefab).name;
		}

		private static void LongRow(Container __instance)
		{
			DrawerComponent val = (DrawerComponent)(object)((__instance is DrawerComponent) ? __instance : null);
			if (val != null)
			{
				DrawerType drawerType = TypeOf(val);
				if (drawerType != null)
				{
					int val2 = ((drawerType.ByItem.Count > 0) ? Math.Max(drawerType.Limit.Value, drawerType.ByItem.Values.Max()) : drawerType.Limit.Value);
					__instance.m_width = Math.Max(__instance.m_width, val2);
				}
			}
		}

		private static bool ClampDeposit(Inventory inv, string itemName, ref int amount, ref int __result)
		{
			int num = Room(inv, itemName);
			if (num < 0)
			{
				return true;
			}
			if (num == 0)
			{
				__result = 0;
				return false;
			}
			amount = Math.Min(amount, num);
			return true;
		}

		private static bool AddWhatFits(Inventory __instance, ItemData item, ref bool __result)
		{
			int num = Room(__instance, NameOf(item));
			if (num < 0 || item == null || item.m_stack <= num)
			{
				return true;
			}
			if (num > 0)
			{
				ItemData val = item.Clone();
				val.m_stack = num;
				if (__instance.AddItem(val))
				{
					item.m_stack -= num;
				}
			}
			__result = false;
			return false;
		}

		private static bool AddAtIfFits(Inventory __instance, ItemData item, ref bool __result)
		{
			int num = Room(__instance, NameOf(item));
			if (num < 0 || item == null || item.m_stack <= num)
			{
				return true;
			}
			__result = false;
			return false;
		}

		private static bool FirstFreeSlot(Inventory __instance, ref Vector2i __result)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			if (!Owners.Invoke().TryGetValue(__instance, out var _) || __instance.GetHeight() != 1)
			{
				return true;
			}
			List<ItemData> allItems = __instance.GetAllItems();
			bool[] array = new bool[allItems.Count + 1];
			foreach (ItemData item in allItems)
			{
				int x = item.m_gridPos.x;
				if (item.m_gridPos.y == 0 && x >= 0 && x < array.Length)
				{
					array[x] = true;
				}
			}
			int num = Array.IndexOf(array, value: false);
			__result = ((num >= 0 && num < __instance.GetWidth()) ? new Vector2i(num, 0) : new Vector2i(-1, -1));
			return false;
		}

		private static void ShowLimit(DrawerComponent __instance, ref int __result)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			int num = LimitOf(__instance, __instance.Snapshot.ItemName);
			if (num > 0)
			{
				__result = num;
			}
		}

		private void Awake()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			Harmony harmony = new Harmony("groshyr.storagetweaks");
			PatchCorewoodPurse(harmony);
			PatchDrawers(harmony);
			PatchDrawerCount(harmony);
		}
	}
}