Decompiled source of BulkSmelt v3.0.4

BulkSmelt.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("BulkSmelt")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Bulk Smelter Loading Mod")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("BulkSmelt")]
[assembly: AssemblyTitle("BulkSmelt")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[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 BulkSmelt
{
	[BepInPlugin("ChillCodeClub.BulkSmelt", "BulkSmelt", "3.0.4")]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(Smelter), "OnAddFuel")]
		private static class FuelPatch
		{
			private static bool Prefix(Smelter __instance, Humanoid user, MethodBase __originalMethod)
			{
				if (!ShouldBulk((Component)(object)__instance))
				{
					return true;
				}
				if (__instance.m_fuelItem?.m_itemData?.m_shared == null)
				{
					Debug.LogWarning((object)("[BulkSmelt] FuelPatch: m_fuelItem is null on " + ((Object)__instance).name + " - letting vanilla handle it."));
					return true;
				}
				_isProcessing = true;
				try
				{
					string text = __instance.m_fuelItem.m_itemData.m_shared.m_name.ToLower();
					int limit;
					if (text.Contains("wood"))
					{
						limit = MaxWood.Value;
					}
					else if (text.Contains("tissue"))
					{
						limit = MaxSoftTissue.Value;
					}
					else
					{
						limit = MaxCoal.Value;
					}
					if (limit <= 0)
					{
						limit = __instance.m_maxFuel;
					}
					ZNetView nview = ((Component)__instance).GetComponent<ZNetView>();
					if ((Object)(object)nview == (Object)null || nview.GetZDO() == null)
					{
						Debug.LogWarning((object)("[BulkSmelt] FuelPatch: no valid ZDO on " + ((Object)__instance).name + " - letting vanilla handle it."));
						return true;
					}
					int num = BulkInvoke(__instance, __originalMethod, user, () => nview.GetZDO().GetFloat("fuel", 0f) < (float)limit);
					if (num > 0)
					{
						((Character)user).Message((MessageType)1, $"Bulk added: {num} fuel", 0, (Sprite)null, false);
					}
				}
				catch (Exception arg)
				{
					Debug.LogError((object)$"[BulkSmelt] FuelPatch error: {arg}");
				}
				finally
				{
					_isProcessing = false;
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(Smelter), "OnAddOre")]
		private static class OrePatch
		{
			private static bool Prefix(Smelter __instance, Humanoid user, MethodBase __originalMethod)
			{
				if (!ShouldBulk((Component)(object)__instance))
				{
					return true;
				}
				_isProcessing = true;
				try
				{
					int limit = 0;
					List<string> list = new List<string>();
					if (__instance.m_conversion != null)
					{
						foreach (ItemConversion item in __instance.m_conversion)
						{
							object obj;
							if (item == null)
							{
								obj = null;
							}
							else
							{
								ItemDrop obj2 = item.m_from;
								obj = ((obj2 != null) ? ((Object)obj2).name : null);
							}
							string text = (string)obj;
							if (text != null)
							{
								list.Add(text);
								if (ItemConfigs.TryGetValue(text, out var value))
								{
									limit = value.Value;
									break;
								}
							}
						}
						if (limit <= 0)
						{
							Debug.Log((object)("[BulkSmelt] OrePatch: no config match on " + ((Object)__instance).name + " for prefabs [" + string.Join(", ", list) + "] - using station max."));
						}
					}
					if (limit <= 0)
					{
						limit = __instance.m_maxOre;
					}
					ZNetView nview = ((Component)__instance).GetComponent<ZNetView>();
					if ((Object)(object)nview == (Object)null || nview.GetZDO() == null)
					{
						Debug.LogWarning((object)("[BulkSmelt] OrePatch: no valid ZDO on " + ((Object)__instance).name + " - letting vanilla handle it."));
						return true;
					}
					int num = BulkInvoke(__instance, __originalMethod, user, () => nview.GetZDO().GetInt("queued", 0) < limit);
					if (num > 0)
					{
						((Character)user).Message((MessageType)1, $"Bulk inserted: {num} items", 0, (Sprite)null, false);
					}
				}
				catch (Exception arg)
				{
					Debug.LogError((object)$"[BulkSmelt] OrePatch error: {arg}");
				}
				finally
				{
					_isProcessing = false;
				}
				return false;
			}
		}

		public static ConfigEntry<bool> ModEnabled;

		public static ConfigEntry<KeyboardShortcut> ToggleKey;

		private static readonly KeyboardShortcut FillShortcut = new KeyboardShortcut((KeyCode)101, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 });

		public static ConfigEntry<int> MaxWood;

		public static ConfigEntry<int> MaxCoal;

		public static ConfigEntry<int> MaxSoftTissue;

		public static Dictionary<string, ConfigEntry<int>> ItemConfigs = new Dictionary<string, ConfigEntry<int>>();

		private static bool _isProcessing = false;

		private void Awake()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			InitConfigs();
			Harmony val = new Harmony("ChillCodeClub.BulkSmelt");
			try
			{
				val.PatchAll();
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"[BulkSmelt] PatchAll threw: {arg}");
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"BulkSmelt 3.0.4 loaded.");
			foreach (MethodBase patchedMethod in val.GetPatchedMethods())
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("[BulkSmelt] Patched: " + patchedMethod.DeclaringType?.FullName + "." + patchedMethod.Name));
			}
		}

		private void InitConfigs()
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Expected O, but got Unknown
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Expected O, but got Unknown
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Expected O, but got Unknown
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Expected O, but got Unknown
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Expected O, but got Unknown
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Expected O, but got Unknown
			string text = "0. System";
			string text2 = "1. Fuel";
			string text3 = "2. Materials";
			string text4 = "3. Farming";
			ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>(text, "Mod Enabled", true, "Enable or disable the mod");
			ToggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>(text, "Toggle Key", new KeyboardShortcut((KeyCode)0, Array.Empty<KeyCode>()), "Key to toggle mod status in-game. The bulk-fill shortcut itself is fixed to Shift+E and cannot be changed here.");
			MaxWood = ((BaseUnityPlugin)this).Config.Bind<int>(text2, "Wood_Limit", 25, new ConfigDescription("Charcoal Kiln wood limit. 0 = fill to the station's real max.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 25), Array.Empty<object>()));
			MaxCoal = ((BaseUnityPlugin)this).Config.Bind<int>(text2, "Coal_Limit", 20, new ConfigDescription("Smelter / Blast Furnace fuel (coal) limit. 0 = fill to the station's real max.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			MaxSoftTissue = ((BaseUnityPlugin)this).Config.Bind<int>(text2, "SoftTissue_Limit", 20, new ConfigDescription("Eitr Refinery Soft Tissue limit. 0 = fill to the station's real max.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			string[] array = new string[6] { "CopperOre", "TinOre", "IronScrap", "SilverOre", "BlackMetalScrap", "FlametalOre" };
			string[] array2 = array;
			foreach (string text5 in array2)
			{
				ItemConfigs[text5] = ((BaseUnityPlugin)this).Config.Bind<int>(text3, text5, 10, new ConfigDescription(text5 + " limit. 0 = fill to the station's real max.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>()));
			}
			ItemConfigs["Sap"] = ((BaseUnityPlugin)this).Config.Bind<int>(text3, "Sap", 20, new ConfigDescription("Eitr Refinery Sap limit. 0 = fill to the station's real max.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			ItemConfigs["Barley"] = ((BaseUnityPlugin)this).Config.Bind<int>(text4, "Barley", 50, new ConfigDescription("Windmill Barley limit. 0 = fill to the station's real max.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			ItemConfigs["Flax"] = ((BaseUnityPlugin)this).Config.Bind<int>(text4, "Flax", 40, new ConfigDescription("Spinning Wheel Flax limit. 0 = fill to the station's real max.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 40), Array.Empty<object>()));
		}

		private void Update()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			KeyboardShortcut value = ToggleKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				ModEnabled.Value = !ModEnabled.Value;
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, "BulkSmelt: " + (ModEnabled.Value ? "Enabled" : "Disabled"), 0, (Sprite)null, false);
				}
			}
		}

		private static int BulkInvoke(object instance, MethodBase method, Humanoid user, Func<bool> needsMore, int hardCap = 100)
		{
			if (method == null)
			{
				return 0;
			}
			ParameterInfo[] parameters = method.GetParameters();
			int num = 0;
			while (needsMore() && num < hardCap)
			{
				object[] array = new object[parameters.Length];
				for (int i = 0; i < parameters.Length; i++)
				{
					Type parameterType = parameters[i].ParameterType;
					if (typeof(Humanoid).IsAssignableFrom(parameterType))
					{
						array[i] = user;
					}
					else if (parameterType.IsValueType)
					{
						array[i] = Activator.CreateInstance(parameterType);
					}
					else
					{
						array[i] = null;
					}
				}
				bool flag;
				try
				{
					flag = (bool)method.Invoke(instance, array);
				}
				catch (Exception arg)
				{
					Debug.LogError((object)$"[BulkSmelt] Failed calling {method.DeclaringType?.Name}.{method.Name}: {arg}");
					break;
				}
				if (!flag)
				{
					break;
				}
				num++;
			}
			return num;
		}

		private static bool ShouldBulk(Component c)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (ModEnabled.Value)
			{
				KeyboardShortcut fillShortcut = FillShortcut;
				if (((KeyboardShortcut)(ref fillShortcut)).IsPressed() && !_isProcessing)
				{
					ZNetView component = c.GetComponent<ZNetView>();
					if ((Object)(object)component != (Object)null && component.IsValid() && !component.IsOwner())
					{
						component.ClaimOwnership();
					}
					return true;
				}
			}
			return false;
		}
	}
}