Decompiled source of ZenBeehive v1.1.0

plugins/ZenBeehive.dll

Decompiled 5 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using Zen;
using Zen.Compatibility;
using Zen.Lib;
using Zen.Lib.Config;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("ZenBeehive")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ZenBeehive")]
[assembly: AssemblyCopyright("Copyright \ufffd  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")]
[assembly: AssemblyFileVersion("0.0.1.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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]
	[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]
	[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 ZenBeehive
{
	internal class BeehiveInventory : VirtualInventory
	{
		private Beehive? _beehive;

		private Inventory? _inventory;

		private bool _allowAddItem;

		internal Beehive Beehive
		{
			get
			{
				if (!Object.op_Implicit((Object)(object)_beehive))
				{
					return _beehive = ((Component)this).GetComponent<Beehive>();
				}
				return _beehive;
			}
		}

		protected override Inventory Inventory
		{
			get
			{
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0025: Expected O, but got Unknown
				//IL_002a: Expected O, but got Unknown
				Inventory obj = _inventory;
				if (obj == null)
				{
					Inventory val = new Inventory(Beehive.m_piece.m_name, (Sprite)null, 1, 1);
					Inventory val2 = val;
					_inventory = val;
					obj = val2;
				}
				return obj;
			}
		}

		protected override ZNetView GetZNetView()
		{
			return Beehive.m_nview;
		}

		protected override bool IsAddItemValid(ItemData item)
		{
			return _allowAddItem;
		}

		protected override bool IsWarded()
		{
			return !Configs.IgnoreWards.Value;
		}

		protected override bool IsStackAllButtonVisible()
		{
			return false;
		}

		protected override bool OnHoldToStack()
		{
			if (!Configs.HoldToTakeAll.Value)
			{
				return false;
			}
			TakeAll();
			return true;
		}

		protected override void LoadInventory()
		{
			int honeyLevel = Beehive.GetHoneyLevel();
			GameObject honeyItemPrefab = Beehive.GetHoneyItemPrefab();
			if (honeyLevel > 0)
			{
				_allowAddItem = true;
				((VirtualInventory)this).Inventory.AddItem(honeyItemPrefab, honeyLevel);
				_allowAddItem = false;
			}
		}

		public void UpdateHoneyFromInventory()
		{
			SetHoneyLevel(((VirtualInventory)this).Inventory.NrOfItemsIncludingStacks());
		}

		private void SetHoneyLevel(int level)
		{
			if (level != Beehive.GetHoneyLevel())
			{
				Beehive.m_nview.ClaimOwnership();
				Beehive.ResetLevel();
				Beehive.IncreseLevel(level);
			}
		}

		public void TakeAll()
		{
			InventoryGui.instance.TakeAll();
			UpdateHoneyFromInventory();
		}

		protected override bool OnSelectedItemBefore(InventoryGui gui, InventoryGrid grid, ItemData? item, Modifier mod, Vector2i pos)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Invalid comparison between Unknown and I4
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)grid == (Object)(object)gui.ContainerGrid)
			{
				if (gui.m_dragItem != null)
				{
					gui.SetupDragItem((ItemData)null, (Inventory)null, 0);
					return false;
				}
			}
			else if ((Object)(object)grid == (Object)(object)gui.m_playerGrid)
			{
				if ((int)mod == 2)
				{
					return false;
				}
				if ((int)mod == 0)
				{
					if (gui.m_dragItem == null)
					{
						return true;
					}
					if (gui.m_dragInventory == gui.m_playerGrid.GetInventory())
					{
						return true;
					}
					ItemData itemAt = grid.GetInventory().GetItemAt(pos.x, pos.y);
					if (itemAt == null)
					{
						return true;
					}
					if ((Object)(object)itemAt.m_dropPrefab == (Object)(object)Beehive.GetHoneyItemPrefab())
					{
						return true;
					}
					return false;
				}
			}
			return true;
		}

		protected override void OnSelectedItemAfter(InventoryGui gui, InventoryGrid grid, ItemData? item, Modifier mod, Vector2i pos)
		{
			UpdateHoneyFromInventory();
		}

		protected override void OnDropOutsideAfter(InventoryGui gui)
		{
			UpdateHoneyFromInventory();
		}
	}
	[HarmonyPatch]
	internal static class BeehiveUI
	{
		private static bool IsHoneyOpen(out BeehiveInventory beeInv)
		{
			return VirtualInventory.TryGetOpened<BeehiveInventory>(ref beeInv);
		}

		public static GameObject GetHoneyItemPrefab(this Beehive beehive)
		{
			return ObjectDB.instance.GetItemPrefab(((Object)beehive.m_honeyItem).name);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Humanoid), "UseItem")]
		private static void Humanoid_UseItem()
		{
			if (IsHoneyOpen(out BeehiveInventory beeInv))
			{
				beeInv.UpdateHoneyFromInventory();
			}
		}

		[HarmonyReversePatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPatch(typeof(InventoryGui), "OnTakeAll")]
		public static void TakeAll(this InventoryGui __instance)
		{
			throw new NotImplementedException("Placeholder for original method");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(InventoryGui), "OnTakeAll")]
		private static void InventoryGui_OnTakeAll_Postfix(InventoryGui __instance)
		{
			if (IsHoneyOpen(out BeehiveInventory beeInv))
			{
				beeInv.UpdateHoneyFromInventory();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(InventoryGrid), "UpdateGui")]
		private static void InventoryGrid_UpdateGui(InventoryGrid __instance)
		{
			if (IsHoneyOpen(out BeehiveInventory beeInv))
			{
				Beehive beehive = beeInv.Beehive;
				Inventory inventory = __instance.GetInventory();
				if (((VirtualInventory)beeInv).IsInventory(inventory) && inventory.NrOfItems() != 0)
				{
					ItemData item = __instance.GetInventory().GetItem(0);
					__instance.m_elements[0].m_amount.text = $"{item.m_stack}/{beehive.m_maxHoney}";
				}
			}
		}

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(Beehive), "Interact")]
		[HarmonyPriority(100)]
		private static IEnumerable<CodeInstruction> Beehive_Interact(IEnumerable<CodeInstruction> codes)
		{
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(PrivateArea), "CheckAccess", (Type[])null, (Type[])null);
			Func<Vector3, float, bool, bool, bool> func = InterceptCheckAccess;
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(Beehive), "Extract", (Type[])null, (Type[])null);
			Action<Beehive> action = InterceptExtract;
			return Transpilers.MethodReplacer(Transpilers.MethodReplacer(codes, (MethodBase)methodInfo, (MethodBase)func.Method), (MethodBase)methodInfo2, (MethodBase)action.Method);
			static bool InterceptCheckAccess(Vector3 point, float radius, bool flash, bool wardCheck)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				if (!Configs.IgnoreWards.Value)
				{
					return PrivateArea.CheckAccess(point, radius, flash, wardCheck);
				}
				return true;
			}
			static void InterceptExtract(Beehive beehive)
			{
				if (!VirtualInventory.TryRequestOpenFrom(((Component)beehive).gameObject))
				{
					Logging<Plugin>.Error((object)"Beehive: InterceptExtract unable to open container, fallback to vanilla", (ushort)0);
					beehive.Extract();
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Beehive), "IncreseLevel")]
		private static void Beehive_IncreaseLevel(Beehive __instance)
		{
			if (IsHoneyOpen(out BeehiveInventory beeInv) && (Object)(object)beeInv.Beehive == (Object)(object)__instance)
			{
				((VirtualInventory)beeInv).RefreshInventory();
			}
		}
	}
	public static class Configs
	{
		private const string SECTION_BEEHIVE = "Beehive";

		public static readonly ConfigEntry<bool> HoldToTakeAll = Config.Define<bool>(true, "Beehive", "Hold To Take All", true, "Hold down the interact key when extracting to take all the contents at once.");

		public static readonly ConfigEntry<int> MaxHoney = Config.Define<int>(true, "Beehive", "Max Capacity", 0, Config.AcceptRange<int>(0, 999), "Max items that a hive can hold. Logout for changes to take effect. (Vanilla: 4)\r\nSet to 0 to disable this config.\r\nNote: Max capacity can not exceed the stack size for the Item Prefab.\r\nExample: If the Item Prefab's max stack size is 50 then it won't matter if you put 999 here.\r\nIt will never go above the item's max stack size limit.\r\n[restart game for changes to take effect]");

		public static readonly ConfigEntry<StringList> HiveItem;

		public static readonly ConfigEntry<int> SecPerUnit;

		public static readonly ConfigEntry<bool> IgnoreWards;

		static Configs()
		{
			//IL_004c: 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)
			//IL_005c: Expected O, but got Unknown
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_0071: Expected O, but got Unknown
			StringList val = new StringList();
			((List<string>)val).Add("piece_beehive:Honey");
			((List<string>)val).Add("piece_birdnest:Feathers");
			HiveItem = Config.Define<StringList>(true, "Beehive", "Hive Prefab Item", val, "The piece prefab and the item that grows within it. \r\n[logout for changes to take effect]");
			SecPerUnit = Config.Define<int>(true, "Beehive", "Seconds Per Unit", 0, Config.AcceptRange<int>(0, 10000), "The number of seconds it takes to grow one unit. (Vanilla: 1200)\r\nSet to 0 to disable this config.\r\n[restart game for changes to take effect]");
			IgnoreWards = Config.Define<bool>(true, "Beehive", "Ignore Wards", true, "Ignore warded areas (vanilla: false)\r\nIt's just a honey box that generates new honey over time, not a pot of gold.\r\nMost of the time it just goes unharvested since people are busy doing other things.\r\nTrust your neighbors, or share extra, or build a wall and gate to guard your honey.");
		}
	}
	[Disable(new Type[] { typeof(Beehive) })]
	[BepInPlugin("ZenDragon.ZenBeehive", "ZenBeehive", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	internal class Plugin : ZenMod<Plugin>
	{
		public const string PluginName = "ZenBeehive";

		public const string PluginVersion = "1.1.0";

		public const string PluginGUID = "ZenDragon.ZenBeehive";

		protected override void Setup()
		{
			base.ConfigSync += PrefabInit.SetupPrefab;
		}

		protected override void TitleScene(bool isFirstBoot)
		{
		}

		protected override void WorldStart()
		{
		}

		protected override void Shutdown()
		{
		}

		protected override void HotRestore()
		{
			Beehive[] array = Object.FindObjectsByType<Beehive>((FindObjectsSortMode)0);
			foreach (Beehive val in array)
			{
				if (Configs.HiveItem.Value.ToDictionary(':').TryGetValue(((Object)val).name, out var value))
				{
					PrefabInit.Init(val, value);
				}
				else
				{
					Logging<Plugin>.Warning((object)("no config value found for prefab: " + ((Object)val).name), 0);
				}
			}
		}

		protected override HelpInfo? GetHelpInfo()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			StringBuilder stringBuilder = new StringBuilder();
			if (Configs.HoldToTakeAll.Value)
			{
				stringBuilder.AppendLine(HelpInfo.Format<bool>(Configs.HoldToTakeAll, false, true, true));
			}
			return new HelpInfo("Bees & Birds", stringBuilder.ToString());
		}
	}
	internal static class PrefabInit
	{
		private static readonly string[] Prefabs = new string[2] { "piece_beehive", "piece_birdnest" };

		public static void SetupPrefab()
		{
			Beehive hive = default(Beehive);
			foreach (KeyValuePair<string, string> item in Configs.HiveItem.Value.ToDictionary(':'))
			{
				if (GlobalStatic.TryGetPrefab<Beehive>(item.Key, ref hive, false))
				{
					Init(hive, item.Value);
				}
				else
				{
					Logging<Plugin>.Error((object)(item.Key + " does not exist or does not contain a Beehive component"), (ushort)0);
				}
			}
		}

		public static void Init(Beehive hive, string itemPrefabName)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: 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)
			bool flag = default(bool);
			InterpolatedString<Plugin> val = new InterpolatedString<Plugin>(41, 1, ref flag);
			if (flag)
			{
				val.AppendLiteral("Setting up beehive prefab for container: ");
				val.AppendFormatted(((Object)hive).name);
			}
			Logging<Plugin>.Info(val, 0);
			BeehiveInventory orAddComponent = ExposedGameObjectExtension.GetOrAddComponent<BeehiveInventory>(((Component)hive).gameObject);
			((ZenMod<Plugin>)(object)ZenMod<Plugin>.Instance).HotLoad.Track((Object)(object)orAddComponent);
			ItemDrop honeyItem = default(ItemDrop);
			if (GlobalStatic.TryGetPrefab<ItemDrop>(itemPrefabName, ref honeyItem, false))
			{
				hive.m_honeyItem = honeyItem;
			}
			else
			{
				Logging<Plugin>.Warning((object)("Item not found: " + itemPrefabName + ", using vanilla value instead"), 0);
			}
			if (Configs.MaxHoney.Value > 0)
			{
				hive.m_maxHoney = Mathf.Min(hive.m_honeyItem.m_itemData.m_shared.m_maxStackSize, Configs.MaxHoney.Value);
			}
			if (Configs.SecPerUnit.Value > 0)
			{
				hive.m_secPerUnit = Configs.SecPerUnit.Value;
			}
		}
	}
}