Decompiled source of DeliverySlotsTweaks v1.5.5

DeliverySlotsTweaks.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using NebulaAPI;
using NebulaAPI.GameState;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("starfi5h.plugin.DeliverySlotsTweaks")]
[assembly: AssemblyProduct("DeliverySlotsTweaks")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.5.0")]
[module: UnverifiableCode]
namespace DeliverySlotsTweaks;

public class Compatibility
{
	public static class CheatEnabler_Patch
	{
		public const string GUID = "org.soardev.cheatenabler";

		public static void Init(Harmony harmony)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			if (!Chainloader.PluginInfos.TryGetValue("org.soardev.cheatenabler", out var value))
			{
				return;
			}
			try
			{
				Assembly assembly = ((object)value.Instance).GetType().Assembly;
				Type type = assembly.GetType("CheatEnabler.FactoryPatch+ArchitectMode");
				harmony.Patch((MethodBase)AccessTools.Method(type, "Enable", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(CheatEnabler_Patch), "ArchitectModeValueChanged_Postfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				type = assembly.GetType("CheatEnabler.FactoryPatch");
				DeliveryPackagePatch.architectMode = ((ConfigEntry<bool>)AccessTools.Field(type, "ArchitectModeEnabled").GetValue(null)).Value;
				Plugin.Log.LogDebug((object)("CheatEnabler ArchitectModeEnabled: " + DeliveryPackagePatch.architectMode));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)"CheatEnabler compatibility failed! Last working version: 2.3.7");
				Plugin.Log.LogWarning((object)ex);
			}
		}

		internal static void ArchitectModeValueChanged_Postfix(bool enable)
		{
			if (enable)
			{
				DeliveryPackagePatch.architectMode = true;
			}
			else
			{
				DeliveryPackagePatch.architectMode = false;
			}
		}
	}

	public static class Auxilaryfunction_Patch
	{
		public const string GUID = "cn.blacksnipe.dsp.Auxilaryfunction";

		public static void Init(Harmony harmony)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			try
			{
				if (Chainloader.PluginInfos.TryGetValue("cn.blacksnipe.dsp.Auxilaryfunction", out var value))
				{
					Type type = ((object)value.Instance).GetType().Assembly.GetType("Auxilaryfunction.Auxilaryfunction");
					harmony.Patch((MethodBase)AccessTools.Method(type, "AutoMovetounbuilt", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(DeliveryPackagePatch).GetMethod("UIBuildMenu_Transpiler")), (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)"Auxilaryfunction compatibility failed! Last working version: 2.5.1");
				Plugin.Log.LogWarning((object)ex);
			}
		}
	}

	public static class Multfunction_mod_Patch
	{
		public const string GUID = "cn.blacksnipe.dsp.Multfuntion_mod";

		private static ConfigEntry<bool> architectMode;

		public static void Init(Harmony harmony)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			try
			{
				if (Chainloader.PluginInfos.TryGetValue("cn.blacksnipe.dsp.Multfuntion_mod", out var value))
				{
					Type type = ((object)value.Instance).GetType().Assembly.GetType("Multifunction_mod.GUIDraw");
					harmony.Patch((MethodBase)AccessTools.Method(type, "BuildPannel", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Multfunction_mod_Patch).GetMethod("BuildPannel_Postfix")), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					architectMode = (ConfigEntry<bool>)AccessTools.Field(AccessTools.TypeByName("Multifunction_mod.Multifunction"), "ArchitectMode").GetValue(null);
					DeliveryPackagePatch.architectMode = architectMode.Value;
					Plugin.Log.LogDebug((object)("Multfunction_mod ArchitectModeEnabled: " + DeliveryPackagePatch.architectMode));
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)"Multfunction_mod compatibility failed! Last working version: 3.1.7");
				Plugin.Log.LogWarning((object)ex);
			}
		}

		public static void BuildPannel_Postfix()
		{
			DeliveryPackagePatch.architectMode = architectMode.Value;
		}
	}

	public static class Nebula_Patch
	{
		public const string GUID = "dsp.nebula-multiplayer";

		private static bool IsPatched;

		public static bool IsActive { get; private set; }

		public static void Init(Harmony harmony)
		{
			try
			{
				if (Chainloader.PluginInfos.TryGetValue("dsp.nebula-multiplayer", out var _))
				{
					Patch(harmony);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)"Nebula compatibility failed!");
				Plugin.Log.LogWarning((object)ex);
			}
		}

		public static bool IsOthers()
		{
			IFactoryManager factories = NebulaModAPI.MultiplayerSession.Factories;
			if (factories.IsIncomingRequest.Value)
			{
				return factories.PacketAuthor != NebulaModAPI.MultiplayerSession.LocalPlayer.Id;
			}
			return false;
		}

		private static void Patch(Harmony harmony)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			if (NebulaModAPI.NebulaIsInstalled && !IsPatched)
			{
				NebulaModAPI.OnMultiplayerGameStarted = (Action)Delegate.Combine(NebulaModAPI.OnMultiplayerGameStarted, new Action(OnMultiplayerGameStarted));
				NebulaModAPI.OnMultiplayerGameEnded = (Action)Delegate.Combine(NebulaModAPI.OnMultiplayerGameEnded, new Action(OnMultiplayerGameEnded));
				Type type = AccessTools.TypeByName("NebulaWorld.SimulatedWorld");
				harmony.Patch((MethodBase)AccessTools.Method(type, "SetupInitialPlayerState", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(Plugin), "ApplyConfigs", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				IsPatched = true;
			}
		}

		private static void OnMultiplayerGameStarted()
		{
			IsActive = NebulaModAPI.IsMultiplayerActive;
		}

		private static void OnMultiplayerGameEnded()
		{
			IsActive = false;
		}
	}

	public static class RebindBuildBar_Patch
	{
		public const string GUID = "org.kremnev8.plugin.RebindBuildBar";

		public static void Init(Harmony harmony)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			try
			{
				if (Chainloader.PluginInfos.TryGetValue("org.kremnev8.plugin.RebindBuildBar", out var value))
				{
					Type type = ((object)value.Instance).GetType().Assembly.GetType("RebindBuildBar.Patches");
					harmony.Patch((MethodBase)AccessTools.Method(type, "EnableButton", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(DeliveryPackagePatch).GetMethod("UIBuildMenu_Transpiler")), (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)"RebindBuildBar compatibility failed! Last working version: 1.0.0");
				Plugin.Log.LogWarning((object)ex);
			}
		}
	}

	public static class UnlimitedFoundations_Patch
	{
		public const string GUID1 = "com.aekoch.mods.dsp.UnlimitedFoundations";

		public const string GUID2 = "com.tinysquid.infinitefoundations";

		public static void Init(Harmony harmony)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			try
			{
				if (Chainloader.PluginInfos.ContainsKey("com.aekoch.mods.dsp.UnlimitedFoundations") || Chainloader.PluginInfos.ContainsKey("com.tinysquid.infinitefoundations"))
				{
					harmony.Patch((MethodBase)AccessTools.Method(typeof(DeliveryPackagePatch), "GetItemCount", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(UnlimitedFoundations_Patch).GetMethod("GetItemCount_Postfix")), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)"UnlimitedFoundations compatibility failed!");
				Plugin.Log.LogWarning((object)ex);
			}
		}

		public static void GetItemCount_Postfix(int itemId, ref int __result)
		{
			if (itemId == 1131)
			{
				__result = 9999;
			}
		}
	}

	public static void Init(Harmony harmony)
	{
		CheatEnabler_Patch.Init(harmony);
		Multfunction_mod_Patch.Init(harmony);
		RebindBuildBar_Patch.Init(harmony);
		UnlimitedFoundations_Patch.Init(harmony);
		Nebula_Patch.Init(harmony);
	}
}
public class DeliveryPackagePatch
{
	public static bool architectMode = false;

	public static int maxDeliveryGridIndex = 0;

	private static readonly Dictionary<int, int> packageItemCount = new Dictionary<int, int>();

	private static readonly Dictionary<int, int> deliveryItemCount = new Dictionary<int, int>();

	private static readonly Dictionary<int, int> deliveryGridindex = new Dictionary<int, int>();

	public static void Count(StorageComponent package)
	{
		packageItemCount.Clear();
		GRID[] grids = package.grids;
		int num = ((package.size < grids.Length) ? package.size : grids.Length);
		for (int i = 0; i < num; i++)
		{
			int itemId = grids[i].itemId;
			if (itemId > 0)
			{
				if (packageItemCount.ContainsKey(itemId))
				{
					packageItemCount[itemId] += grids[i].count;
				}
				else
				{
					packageItemCount.Add(itemId, grids[i].count);
				}
			}
		}
	}

	public static void Count(DeliveryPackage package)
	{
		deliveryItemCount.Clear();
		deliveryGridindex.Clear();
		GRID[] grids = package.grids;
		for (int i = 0; i <= maxDeliveryGridIndex; i++)
		{
			int itemId = grids[i].itemId;
			if (itemId > 0)
			{
				deliveryItemCount.Add(itemId, grids[i].count);
				deliveryGridindex.Add(itemId, i);
			}
		}
	}

	public static int GetItemCount(StorageComponent _, int itemId)
	{
		if (architectMode)
		{
			return 999;
		}
		packageItemCount.TryGetValue(itemId, out var value);
		deliveryItemCount.TryGetValue(itemId, out var value2);
		return value + value2;
	}

	public static int GetItemCountDummy(StorageComponent _, int itemId)
	{
		return 999;
	}

	public static int TakeItem(StorageComponent storage, int itemId, int count, out int inc)
	{
		if (deliveryGridindex.TryGetValue(itemId, out var value))
		{
			GameMain.mainPlayer.packageUtility.TakeItemFromAllPackages(value, ref itemId, ref count, ref inc, false);
			return count;
		}
		return storage.TakeItem(itemId, count, ref inc);
	}

	public static void TakeTailItems(StorageComponent storage, ref int itemId, ref int count, out int inc, bool _)
	{
		if (architectMode)
		{
			inc = 0;
			return;
		}
		if (Compatibility.Nebula_Patch.IsActive && Compatibility.Nebula_Patch.IsOthers())
		{
			inc = 0;
			return;
		}
		if (deliveryGridindex.TryGetValue(itemId, out var value))
		{
			GameMain.mainPlayer.packageUtility.TakeItemFromAllPackages(value, ref itemId, ref count, ref inc, false);
			if (packageItemCount.ContainsKey(itemId))
			{
				int num = packageItemCount[itemId] - count;
				packageItemCount[itemId] = num;
				if (num == 0)
				{
					packageItemCount.Remove(itemId);
				}
			}
			else if (deliveryItemCount.ContainsKey(itemId))
			{
				int num2 = deliveryItemCount[itemId] - count;
				deliveryItemCount[itemId] = num2;
				if (num2 == 0)
				{
					deliveryItemCount.Remove(itemId);
				}
			}
			return;
		}
		storage.TakeTailItems(ref itemId, ref count, ref inc, false);
		if (packageItemCount.ContainsKey(itemId))
		{
			int num3 = packageItemCount[itemId] - count;
			packageItemCount[itemId] = num3;
			if (num3 == 0)
			{
				packageItemCount.Remove(itemId);
			}
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Mecha), "GameTick")]
	public static void Prepare(Mecha __instance, long time)
	{
		if (__instance?.player != null && __instance.player == GameMain.mainPlayer)
		{
			Count(__instance.player.package);
			Count(__instance.player.deliveryPackage);
			if (time % 30 == 0L && Plugin.AutoRefillWarper.Value)
			{
				TryReillWarper(__instance);
			}
		}
	}

	private static void TryReillWarper(Mecha mecha)
	{
		if (!mecha.HasWarper())
		{
			int itemId = 1210;
			int count = 1;
			if (GetItemCount(null, itemId) > 0)
			{
				TakeTailItems(mecha.player.package, ref itemId, ref count, out var inc, _: false);
				int num = default(int);
				mecha.warpStorage.AddItem(itemId, count, inc, ref num, false);
			}
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(StorageComponent), "Sort")]
	public static void Sort_Prefix(StorageComponent __instance)
	{
		if (!Plugin.SortToDelieverySlots.Value)
		{
			return;
		}
		Player mainPlayer = GameMain.mainPlayer;
		if (__instance != ((mainPlayer != null) ? mainPlayer.package : null))
		{
			return;
		}
		GRID[] grids = __instance.grids;
		DeliveryPackage deliveryPackage = GameMain.mainPlayer.deliveryPackage;
		int inc = default(int);
		for (int num = ((__instance.size < __instance.grids.Length) ? __instance.size : __instance.grids.Length) - 1; num > 0; num--)
		{
			ref GRID reference = ref grids[num];
			int itemId = reference.itemId;
			if (itemId > 0 && deliveryGridindex.ContainsKey(itemId))
			{
				int num2 = deliveryPackage.AddItem(deliveryGridindex[itemId], itemId, reference.count, reference.inc, ref inc);
				reference.count -= num2;
				reference.inc = inc;
			}
		}
	}

	[HarmonyTranspiler]
	[HarmonyPatch(typeof(ConstructionModuleComponent), "PlaceItems")]
	public static IEnumerable<CodeInstruction> PlaceItems_Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Expected O, but got Unknown
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Expected O, but got Unknown
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a0: Expected O, but got Unknown
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Expected O, but got Unknown
		//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Expected O, but got Unknown
		//IL_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Expected O, but got Unknown
		//IL_0100: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Expected O, but got Unknown
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_012d: Expected O, but got Unknown
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0141: Expected O, but got Unknown
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0155: Expected O, but got Unknown
		//IL_0163: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Expected O, but got Unknown
		//IL_0177: Unknown result type (might be due to invalid IL or missing references)
		//IL_017d: Expected O, but got Unknown
		//IL_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a5: Expected O, but got Unknown
		try
		{
			CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null);
			val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[5]
			{
				new CodeMatch((OpCode?)OpCodes.Br, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(ConstructionModuleComponent), "entityId"), (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldc_I4_0, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ble, (object)null, (string)null)
			}).Insert((CodeInstruction[])(object)new CodeInstruction[4]
			{
				new CodeInstruction(OpCodes.Ldarg_0, (object)null),
				new CodeInstruction(OpCodes.Ldarg_2, (object)null),
				new CodeInstruction(OpCodes.Ldloca_S, (object)(byte)0),
				new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(DeliveryPackagePatch), "AddConstructableCountsInStorage", (Type[])null, (Type[])null))
			});
			val.MatchForward(true, (CodeMatch[])(object)new CodeMatch[7]
			{
				new CodeMatch((OpCode?)OpCodes.Ldarg_2, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Callvirt, (object)AccessTools.DeclaredPropertyGetter(typeof(Player), "package"), (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldloca_S, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldloca_S, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldloca_S, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldc_I4_0, (object)null, (string)null),
				new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Callvirt && ((MethodInfo)i.operand).Name == "TakeTailItems"), (string)null)
			}).Repeat((Action<CodeMatcher>)delegate(CodeMatcher matcher)
			{
				matcher.SetAndAdvance(OpCodes.Call, (object)AccessTools.Method(typeof(DeliveryPackagePatch), "TakeTailItems", (Type[])null, (Type[])null));
			}, (Action<string>)null);
			return val.InstructionEnumeration();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)"Transpiler PlaceItems error");
			Plugin.Log.LogWarning((object)ex);
			return instructions;
		}
	}

	private static void AddConstructableCountsInStorage(ConstructionModuleComponent constructionModule, Player player, ref int num)
	{
		if (((player != null) ? player.deliveryPackage : null) == null)
		{
			return;
		}
		ConstructableCount[] constructableCountsInStorage = constructionModule.constructableCountsInStorage;
		GRID[] grids = player.deliveryPackage.grids;
		for (int i = 0; i <= maxDeliveryGridIndex; i++)
		{
			int itemId = grids[i].itemId;
			if (itemId > 0 && ItemProto.constructableIdHash.Contains(itemId))
			{
				int count = grids[i].count;
				int num2 = ItemProto.constructableIndiceById[itemId];
				constructableCountsInStorage[num2].haveCount += count;
				num += count;
			}
		}
	}

	[HarmonyTranspiler]
	[HarmonyPatch(typeof(MechaForge), "TryAddTask")]
	[HarmonyPatch(typeof(MechaForge), "TryTaskWithTestPackage")]
	public static IEnumerable<CodeInstruction> TryAddTask_Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		try
		{
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Call && ((MethodInfo)i.operand).Name == "TryAddTaskIterate"), (string)null)
			}).SetAndAdvance(OpCodes.Call, (object)AccessTools.Method(typeof(DeliveryPackagePatch), "TryAddTaskIterate", (Type[])null, (Type[])null)).InstructionEnumeration();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)"Transpiler TryAddTask error");
			Plugin.Log.LogWarning((object)ex);
			return instructions;
		}
	}

	public static bool TryAddTaskIterate(MechaForge mechaForge, RecipeProto recipe, int count)
	{
		Count(mechaForge.player.deliveryPackage);
		foreach (KeyValuePair<int, int> item in deliveryItemCount)
		{
			mechaForge._test_pack.Alter(item.Key, item.Value);
		}
		return mechaForge.TryAddTaskIterate(recipe, count);
	}

	[HarmonyTranspiler]
	[HarmonyPatch(typeof(MechaForge), "AddTaskIterate")]
	[HarmonyPatch(typeof(Mecha), "AutoReplenishAmmo")]
	public static IEnumerable<CodeInstruction> TakeItem_Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		try
		{
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Callvirt && ((MethodInfo)i.operand).Name == "TakeItem"), (string)null)
			}).Repeat((Action<CodeMatcher>)delegate(CodeMatcher matcher)
			{
				matcher.SetAndAdvance(OpCodes.Call, (object)AccessTools.Method(typeof(DeliveryPackagePatch), "TakeItem", (Type[])null, (Type[])null));
			}, (Action<string>)null).InstructionEnumeration();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)"Transpiler StorageComponent.TakeItem error");
			Plugin.Log.LogWarning((object)ex);
			return instructions;
		}
	}

	[HarmonyTranspiler]
	[HarmonyPatch(typeof(BuildTool_Reform), "ReformAction")]
	[HarmonyPatch(typeof(BuildTool_Reform), "RemoveBasePit")]
	[HarmonyPatch(typeof(PlanetFactory), "EntityAutoReplenishIfNeeded")]
	[HarmonyPatch(typeof(PlanetFactory), "StationAutoReplenishIfNeeded")]
	[HarmonyPatch(typeof(PlayerAction_Inspect), "GameTick")]
	[HarmonyPatch(typeof(UIBlueprintInspector), "OnPlayerPackageChange")]
	[HarmonyPatch(typeof(UIBlueprintInspector), "SetComponentItem")]
	[HarmonyPatch(typeof(UIBuildMenu), "_OnUpdate")]
	[HarmonyPatch(typeof(UIBuildMenu), "OnChildButtonClick")]
	[HarmonyPatch(typeof(UIHandTip), "_OnUpdate")]
	[HarmonyPatch(typeof(UIRemoveBasePitButton), "_OnUpdate")]
	[HarmonyPatch(typeof(UITurretWindow), "OnHandFillAmmoButtonClick")]
	public static IEnumerable<CodeInstruction> UIBuildMenu_Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		try
		{
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Callvirt && ((MethodInfo)i.operand).Name == "GetItemCount"), (string)null)
			}).Repeat((Action<CodeMatcher>)delegate(CodeMatcher matcher)
			{
				matcher.SetAndAdvance(OpCodes.Call, (object)AccessTools.Method(typeof(DeliveryPackagePatch), "GetItemCount", (Type[])null, (Type[])null));
			}, (Action<string>)null).InstructionEnumeration();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)"Transpiler UIBuildMenu._OnUpdate error");
			Plugin.Log.LogWarning((object)ex);
			return instructions;
		}
	}

	[HarmonyTranspiler]
	[HarmonyAfter(new string[] { "dsp.nebula-multiplayer" })]
	[HarmonyPatch(typeof(BuildTool_Click), "CreatePrebuilds")]
	[HarmonyPatch(typeof(BuildTool_Path), "CreatePrebuilds")]
	[HarmonyPatch(typeof(BuildTool_Addon), "CreatePrebuilds")]
	[HarmonyPatch(typeof(BuildTool_Inserter), "CreatePrebuilds")]
	[HarmonyPatch(typeof(BuildTool_BlueprintPaste), "CreatePrebuilds")]
	[HarmonyPatch(typeof(BuildTool_Reform), "ReformAction")]
	[HarmonyPatch(typeof(BuildTool_Reform), "RemoveBasePit")]
	[HarmonyPatch(typeof(PlanetFactory), "EntityAutoReplenishIfNeeded")]
	[HarmonyPatch(typeof(PlanetFactory), "StationAutoReplenishIfNeeded")]
	[HarmonyPatch(typeof(Player), "TakeItemFromPlayer")]
	[HarmonyPatch(typeof(PlayerAction_Build), "DoUpgradeObject")]
	[HarmonyPatch(typeof(PlayerAction_Inspect), "GameTick")]
	[HarmonyPatch(typeof(UITurretWindow), "OnHandFillAmmoButtonClick")]
	public static IEnumerable<CodeInstruction> CheckBuildConditions_Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Expected O, but got Unknown
		try
		{
			int num = 1;
			if (__originalMethod.Name == "StationAutoReplenishIfNeeded")
			{
				num = 2;
			}
			else if (__originalMethod.Name == "EntityAutoReplenishIfNeeded")
			{
				num = 3;
			}
			CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null).End();
			for (int j = 0; j < num; j++)
			{
				val.MatchBack(false, (CodeMatch[])(object)new CodeMatch[1]
				{
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Callvirt && ((MethodInfo)i.operand).Name == "TakeTailItems"), (string)null)
				}).SetAndAdvance(OpCodes.Call, (object)AccessTools.Method(typeof(DeliveryPackagePatch), "TakeTailItems", (Type[])null, (Type[])null));
			}
			return val.InstructionEnumeration();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)"Transpiler CreatePrebuilds error");
			Plugin.Log.LogWarning((object)ex);
			return instructions;
		}
	}

	[HarmonyTranspiler]
	[HarmonyPatch(typeof(PlayerAction_Build), "GameTick")]
	public static IEnumerable<CodeInstruction> PlayerAction_Build_Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		try
		{
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Callvirt && ((MethodInfo)i.operand).Name == "_GameTick"), (string)null)
			}).SetAndAdvance(OpCodes.Call, (object)AccessTools.Method(typeof(DeliveryPackagePatch), "BuildTool_GameTick", (Type[])null, (Type[])null)).InstructionEnumeration();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)"Transpiler PlayerAction_Build.GameTick error");
			Plugin.Log.LogWarning((object)ex);
			return instructions;
		}
	}

	public static void BuildTool_GameTick(BuildTool @this, long time)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Expected O, but got Unknown
		if (@this.active)
		{
			@this.mouseRay = @this.mainCamera.ScreenPointToRay(Input.mousePosition);
			@this.SetFactoryReferences();
			int num = @this.player.package.size + maxDeliveryGridIndex + 1;
			if (@this.tmpPackage == null)
			{
				@this.tmpPackage = new StorageComponent(num);
			}
			if (@this.tmpPackage.size != num)
			{
				@this.tmpPackage.SetSize(num);
			}
			Array.Copy(@this.player.package.grids, @this.tmpPackage.grids, @this.player.package.size);
			GRID[] grids = @this.player.deliveryPackage.grids;
			for (int i = @this.player.package.size; i < num; i++)
			{
				ref GRID reference = ref grids[i - @this.player.package.size];
				@this.tmpPackage.grids[i].itemId = reference.itemId;
				@this.tmpPackage.grids[i].count = reference.count;
			}
			@this.tmpInhandId = @this.player.inhandItemId;
			@this.tmpInhandCount = @this.player.inhandItemCount;
			try
			{
				@this._OnTick(time);
			}
			catch (Exception ex)
			{
				Debug.LogError((object)ex);
			}
			@this.frame++;
		}
	}
}
public class PlayerPackagePatch
{
	private static int packageStacksize = 1000;

	private static int packageStackMultiplier = 1;

	public static void OnConfigChange()
	{
		packageStackMultiplier = 1;
		if (Plugin.PlayerPackageStackSize.Value > 0)
		{
			packageStacksize = Plugin.PlayerPackageStackSize.Value;
			Plugin.Log.LogDebug((object)("PlayerPackage stack count:" + packageStacksize));
			if (GameMain.mainPlayer == null)
			{
				return;
			}
			GRID[] grids = GameMain.mainPlayer.package.grids;
			for (int i = 0; i < GameMain.mainPlayer.package.size; i++)
			{
				if (grids[i].filter > 0)
				{
					grids[i].stackSize = packageStacksize;
				}
			}
		}
		else
		{
			if (Plugin.PlayerPackageStackMultiplier.Value <= 0)
			{
				return;
			}
			packageStackMultiplier = Plugin.PlayerPackageStackMultiplier.Value;
			Plugin.Log.LogDebug((object)("PlayerPackage stack multiplier:" + packageStackMultiplier));
			if (GameMain.mainPlayer == null)
			{
				return;
			}
			GRID[] grids2 = GameMain.mainPlayer.package.grids;
			for (int j = 0; j < GameMain.mainPlayer.package.size; j++)
			{
				int filter = grids2[j].filter;
				if (filter > 0 && filter < StorageComponent.itemStackCount.Length)
				{
					grids2[j].stackSize = StorageComponent.itemStackCount[filter] * packageStackMultiplier;
				}
			}
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(StorageComponent), "SetFilter")]
	public static void OverwritePlayerPackageStacksize2(StorageComponent __instance, int gridIndex, int filterId)
	{
		if (filterId > 0 && IsPlayerStorage(__instance))
		{
			if (Plugin.PlayerPackageStackSize.Value > 0)
			{
				__instance.grids[gridIndex].stackSize = packageStacksize;
			}
			else
			{
				__instance.grids[gridIndex].stackSize = StorageComponent.itemStackCount[filterId] * packageStackMultiplier;
			}
		}
	}

	[HarmonyTranspiler]
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	[HarmonyPatch(typeof(StorageComponent), "AddItemStacked")]
	[HarmonyPatch(typeof(StorageComponent), "Sort")]
	[HarmonyPatch(typeof(StorageComponent), "AddItemForSort")]
	private static IEnumerable<CodeInstruction> OverwritePlayerPackageStacksize(IEnumerable<CodeInstruction> instructions, ILGenerator il)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Expected O, but got Unknown
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		//IL_0166: Expected O, but got Unknown
		//IL_0183: Unknown result type (might be due to invalid IL or missing references)
		//IL_0189: Expected O, but got Unknown
		//IL_0196: Unknown result type (might be due to invalid IL or missing references)
		//IL_019c: Expected O, but got Unknown
		//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bd: Expected O, but got Unknown
		//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cb: Expected O, but got Unknown
		//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Expected O, but got Unknown
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Expected O, but got Unknown
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Expected O, but got Unknown
		//IL_010c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0112: Expected O, but got Unknown
		//IL_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0133: Expected O, but got Unknown
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_0146: Expected O, but got Unknown
		CodeMatcher val = new CodeMatcher(instructions, il);
		Label label = default(Label);
		val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
		{
			new CodeMatch((OpCode?)OpCodes.Ldsfld, (object)AccessTools.Field(typeof(StorageComponent), "itemStackCount"), (string)null)
		}).Advance(1).CreateLabelAt(val.Pos, ref label);
		int pos = val.Pos;
		Label label2 = default(Label);
		val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
		{
			new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => CodeInstructionExtensions.IsStloc(i, (LocalBuilder)null)), (string)null)
		}).CreateLabelAt(val.Pos, ref label2);
		if (Plugin.PlayerPackageStackSize.Value > 0)
		{
			val.Advance(pos - val.Pos);
			val.Insert((CodeInstruction[])(object)new CodeInstruction[6]
			{
				new CodeInstruction(OpCodes.Ldarg_0, (object)null),
				new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(PlayerPackagePatch), "IsPlayerStorage", (Type[])null, (Type[])null)),
				new CodeInstruction(OpCodes.Brfalse_S, (object)label),
				new CodeInstruction(OpCodes.Pop, (object)null),
				new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(PlayerPackagePatch), "packageStacksize")),
				new CodeInstruction(OpCodes.Br_S, (object)label2)
			});
		}
		else
		{
			val.Insert((CodeInstruction[])(object)new CodeInstruction[5]
			{
				new CodeInstruction(OpCodes.Ldarg_0, (object)null),
				new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(PlayerPackagePatch), "IsPlayerStorage", (Type[])null, (Type[])null)),
				new CodeInstruction(OpCodes.Brfalse_S, (object)label2),
				new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(PlayerPackagePatch), "packageStackMultiplier")),
				new CodeInstruction(OpCodes.Mul, (object)null)
			});
		}
		return val.Instructions();
	}

	public static bool IsPlayerStorage(StorageComponent storageComponent)
	{
		if (storageComponent != GameMain.mainPlayer.package)
		{
			return storageComponent == GameMain.mainPlayer.mecha.reactorStorage;
		}
		return true;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PackageStatistics), "Count")]
	private static bool CountOverwrite(PackageStatistics __instance, StorageComponent package)
	{
		if (!IsPlayerStorage(package))
		{
			return true;
		}
		__instance.itemBundle.Clear();
		ref GRID[] grids = ref package.grids;
		int num = 0;
		if (packageStackMultiplier > 1)
		{
			int[] itemStackCount = StorageComponent.itemStackCount;
			for (int i = 0; i < package.size; i++)
			{
				int itemId = grids[i].itemId;
				if (itemId > 0)
				{
					__instance.itemBundle.Add(itemId, grids[i].count, itemStackCount[itemId] * packageStackMultiplier - grids[i].count);
				}
				else
				{
					num++;
				}
			}
			if (num > 0)
			{
				int[] itemIds = ItemProto.itemIds;
				int num2 = itemIds.Length;
				for (int j = 0; j < num2; j++)
				{
					__instance.itemBundle.Add(itemIds[j], 0, itemStackCount[itemIds[j]] * packageStackMultiplier * num);
				}
			}
		}
		else
		{
			for (int k = 0; k < package.size; k++)
			{
				int itemId2 = grids[k].itemId;
				if (itemId2 > 0)
				{
					__instance.itemBundle.Add(itemId2, grids[k].count, packageStacksize - grids[k].count);
				}
				else
				{
					num++;
				}
			}
			if (num > 0)
			{
				int[] itemIds2 = ItemProto.itemIds;
				for (int l = 0; l < itemIds2.Length; l++)
				{
					__instance.itemBundle.Add(itemIds2[l], 0, packageStacksize * num);
				}
			}
		}
		return false;
	}
}
[BepInPlugin("starfi5h.plugin.DeliverySlotsTweaks", "DeliverySlotsTweaks", "1.5.5")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Plugin : BaseUnityPlugin
{
	public const string GUID = "starfi5h.plugin.DeliverySlotsTweaks";

	public const string NAME = "DeliverySlotsTweaks";

	public const string VERSION = "1.5.5";

	public static Plugin Instance;

	public static ManualLogSource Log;

	public static ConfigEntry<bool> UseLogisticSlots;

	public static ConfigEntry<bool> AutoRefillFuel;

	public static ConfigEntry<bool> AutoRefillWarper;

	public static ConfigEntry<int> ColCount;

	public static ConfigEntry<int> StackSizeMultiplier;

	public static ConfigEntry<bool> DeliveryFirst;

	public static ConfigEntry<int> PlayerPackageStackSize;

	public static ConfigEntry<int> PlayerPackageStackMultiplier;

	public static ConfigEntry<bool> SortToDelieverySlots;

	public static ConfigEntry<bool> EnableArchitectMode;

	public static ConfigEntry<bool> EnableFastReplicator;

	private Harmony harmony;

	public void Start()
	{
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Expected O, but got Unknown
		//IL_0188: Unknown result type (might be due to invalid IL or missing references)
		//IL_0192: Expected O, but got Unknown
		//IL_0219: Unknown result type (might be due to invalid IL or missing references)
		//IL_0225: Expected O, but got Unknown
		//IL_025a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0266: Expected O, but got Unknown
		UseLogisticSlots = ((BaseUnityPlugin)this).Config.Bind<bool>("DeliveryPackage", "UseLogisticSlots", true, "Let replicator and build tools use items in logistic slots.\n使手动制造和建筑工具可以使用物流清单内的物品");
		AutoRefillFuel = ((BaseUnityPlugin)this).Config.Bind<bool>("DeliveryPackage", "AutoRefillFuel", false, "Allow fuel chamber to also take from logistics slots.\n自动补充燃料时也会使用物流清单内的物品");
		AutoRefillWarper = ((BaseUnityPlugin)this).Config.Bind<bool>("DeliveryPackage", "AutoRefillWarper", false, "Auto refill space warper from inventory and logistics slots.\n从背包和物流清单自动补充翘曲器");
		ColCount = ((BaseUnityPlugin)this).Config.Bind<int>("DeliveryPackage", "ColCount", 0, new ConfigDescription("NoChange:0 TechMax:3 Limit:5\n物流清单容量-列(不改:0 原版科技:3 最高上限:5)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 5), Array.Empty<object>()));
		StackSizeMultiplier = ((BaseUnityPlugin)this).Config.Bind<int>("DeliveryPackage", "StackSizeMultiplier", 0, "NoChange:0 TechMax:10\n物流清单物品堆叠倍率(不改:0 原版科技:10)");
		DeliveryFirst = ((BaseUnityPlugin)this).Config.Bind<bool>("DeliveryPackage", "DeliveryFirst", true, "When logistic bots send items to mecha, send them to delivery slots first.\n配送机会优先将物品送入物流清单的栏位");
		SortToDelieverySlots = ((BaseUnityPlugin)this).Config.Bind<bool>("DeliveryPackage", "SortToDelieverySlots", false, "When sorting inventory, send them to delivery slots first.\n整理背包时会先将物品送入物流清单的栏位");
		PlayerPackageStackSize = ((BaseUnityPlugin)this).Config.Bind<int>("PlayerPackage", "StackSize", 0, "Overwrite stack size in inventory. NoChange:0\n统一修改玩家背包中的物品堆疊上限(每件物品皆相同)(不改:0)");
		PlayerPackageStackMultiplier = ((BaseUnityPlugin)this).Config.Bind<int>("PlayerPackage", "StackMultiplier", 0, "Apply multiplier for stack size in inventory. NoChange:0\n修改玩家背包中的物品堆疊倍率(不改:0)");
		EnableArchitectMode = ((BaseUnityPlugin)this).Config.Bind<bool>("BuildTool", "EnableArchitectMode", false, "Build without requirement of items (infinite buildings)\n建筑师模式:建造无需物品");
		EnableFastReplicator = ((BaseUnityPlugin)this).Config.Bind<bool>("BuildTool", "EnableFastReplicator", true, "Right click on hotbar to queue the building in replicator\n右键单击快捷栏中的建筑可直接在合成器排程制造");
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		harmony = new Harmony("starfi5h.plugin.DeliverySlotsTweaks");
		Compatibility.Init(harmony);
		harmony.PatchAll(typeof(Plugin));
		if (UseLogisticSlots.Value)
		{
			harmony.PatchAll(typeof(DeliveryPackagePatch));
			if (AutoRefillFuel.Value)
			{
				harmony.Patch((MethodBase)AccessTools.Method(typeof(Mecha), "AutoReplenishFuel", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(DeliveryPackagePatch), "TakeItem_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(Mecha), "AutoReplenishFuelAll", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(DeliveryPackagePatch), "TakeItem_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}
		StackSizeMultiplier.Value = Math.Min(StackSizeMultiplier.Value, 1000000);
		PlayerPackageStackSize.Value = Math.Min(PlayerPackageStackSize.Value, 1000000000);
		PlayerPackageStackMultiplier.Value = Math.Min(PlayerPackageStackMultiplier.Value, 1000000);
		if (PlayerPackageStackSize.Value > 0 || PlayerPackageStackMultiplier.Value > 0)
		{
			harmony.PatchAll(typeof(PlayerPackagePatch));
		}
		if (EnableFastReplicator.Value)
		{
			harmony.PatchAll(typeof(UIBuildMenuPatch));
		}
	}

	public void OnDestroy()
	{
		harmony.UnpatchSelf();
		harmony = null;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(UIOptionWindow), "OnApplyClick")]
	internal static void OnApplyClick()
	{
		((BaseUnityPlugin)Instance).Config.Reload();
		ApplyConfigs();
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(Player), "Import")]
	[HarmonyPatch(typeof(Player), "SetForNewGame")]
	internal static void ApplyConfigs()
	{
		ParameterOverwrite();
		PlayerPackagePatch.OnConfigChange();
		Player mainPlayer = GameMain.mainPlayer;
		SetMaxDeliveryGridIndex((mainPlayer != null) ? mainPlayer.deliveryPackage : null);
		DeliveryPackagePatch.architectMode = EnableArchitectMode.Value;
	}

	[HarmonyPostfix]
	[HarmonyPriority(500)]
	[HarmonyPatch(typeof(GameHistoryData), "UnlockTechFunction")]
	private static void ParameterOverwrite()
	{
		DeliveryPackage deliveryPackage = GameMain.mainPlayer.deliveryPackage;
		if (ColCount.Value > 0 && ColCount.Value <= 5 && deliveryPackage.colCount != ColCount.Value)
		{
			deliveryPackage.colCount = ColCount.Value;
			GameMain.mainPlayer.deliveryPackage.NotifySizeChange();
		}
		if (StackSizeMultiplier.Value > 0)
		{
			deliveryPackage.stackSizeMultiplier = StackSizeMultiplier.Value;
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(DeliveryPackage), "NotifySizeChange")]
	private static void SetMaxDeliveryGridIndex(DeliveryPackage __instance)
	{
		if (!UseLogisticSlots.Value || __instance == null)
		{
			return;
		}
		Player mainPlayer = GameMain.mainPlayer;
		if (__instance != ((mainPlayer != null) ? mainPlayer.deliveryPackage : null))
		{
			return;
		}
		DeliveryPackagePatch.maxDeliveryGridIndex = 0;
		for (int num = __instance.gridLength - 1; num >= 0; num--)
		{
			if (__instance.IsGridActive(num))
			{
				DeliveryPackagePatch.maxDeliveryGridIndex = num;
				break;
			}
		}
		Log.LogDebug((object)$"DeliveryPackage:{__instance.rowCount}x{__instance.colCount} stack:{__instance.stackSizeMultiplier} maxIndex:{DeliveryPackagePatch.maxDeliveryGridIndex}");
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PlayerPackageUtility), "AddItemToAllPackages")]
	private static void AddItemToAllPackages(ref bool deliveryFirst)
	{
		deliveryFirst = DeliveryFirst.Value;
	}
}
public class UIBuildMenuPatch
{
	private static bool Initialized;

	[HarmonyPostfix]
	[HarmonyPatch(typeof(UIBuildMenu), "_OnRegEvent")]
	public static void AddEvents(UIBuildMenu __instance)
	{
		if (Initialized)
		{
			return;
		}
		Initialized = true;
		for (int i = 0; i < __instance.childButtons.Length; i++)
		{
			UIButton val = __instance.childButtons[i];
			if (!((Object)(object)val == (Object)null))
			{
				val.data = i;
				val.onRightClick += OnChildButtonRightClick;
			}
		}
	}

	private static void OnChildButtonRightClick(int index)
	{
		UIBuildMenu buildMenu = UIRoot.instance.uiGame.buildMenu;
		if (UIBuildMenu.protos[buildMenu.currentCategory, index] != null)
		{
			int iD = ((Proto)UIBuildMenu.protos[buildMenu.currentCategory, index]).ID;
			ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(iD);
			if (val != null && val.maincraft != null)
			{
				TryReplicateItem(val);
			}
		}
	}

	private static void TryReplicateItem(ItemProto itemProto)
	{
		RecipeProto maincraft = itemProto.maincraft;
		if (maincraft == null)
		{
			return;
		}
		int iD = ((Proto)maincraft).ID;
		int num = 1;
		if (!maincraft.Handcraft)
		{
			UIRealtimeTip.Popup(Localization.Translate("该配方") + maincraft.madeFromString + Localization.Translate("生产"), true, 0);
			return;
		}
		if (!GameMain.history.RecipeUnlocked(iD))
		{
			UIRealtimeTip.Popup(Localization.Translate("配方未解锁"), true, 0);
			return;
		}
		MechaForge forge = GameMain.mainPlayer.mecha.forge;
		int num2 = forge.PredictTaskCount(iD, 99);
		if (num > num2)
		{
			num = num2;
		}
		if (num == 0)
		{
			UIRealtimeTip.Popup(Localization.Translate("材料不足"), true, 0);
			return;
		}
		if (forge.AddTask(iD, num) == null)
		{
			UIRealtimeTip.Popup(Localization.Translate("材料不足"), true, 0);
			return;
		}
		GameMain.history.RegFeatureKey(1000104);
		int num3 = 0;
		if (maincraft.ResultCounts != null && maincraft.ResultCounts.Length != 0)
		{
			num3 = maincraft.ResultCounts[0];
		}
		UIRealtimeTip.Popup(string.Format(Localization.Translate("Crafting {0} [{1}]"), ((Proto)itemProto).name, num3), false, 0);
	}
}