Decompiled source of BuildToolOpt v1.0.9

BuildToolOpt.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
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.Logging;
using HarmonyLib;
using UnityEngine;

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

public class BuildTool_Inserter_Patch
{
	[HarmonyTranspiler]
	[HarmonyAfter(new string[] { "com.hetima.dsp.LongSorter" })]
	[HarmonyPatch(typeof(BuildTool_Inserter), "DeterminePreviews")]
	public static IEnumerable<CodeInstruction> DeterminePreviews_Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0002: 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_0022: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Expected O, but got Unknown
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Expected O, but got Unknown
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Expected O, but got Unknown
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Expected O, but got Unknown
		try
		{
			CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[4]
			{
				new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(BuildTool_Inserter), "startObjectId"), (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldc_I4_0, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ble, (object)null, (string)null)
			});
			for (int i = 0; i < 6; i++)
			{
				val.SetAndAdvance(OpCodes.Nop, (object)null);
			}
			val.RemoveInstructions(2).Insert((CodeInstruction[])(object)new CodeInstruction[2]
			{
				new CodeInstruction(OpCodes.Ldarg_0, (object)null),
				new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(BuildTool_Inserter_Patch), "AddPrebuildBeltSlot", (Type[])null, (Type[])null))
			});
			val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(BuildTool), "ObjectIsBelt", (Type[])null, (Type[])null), (string)null)
			}).Repeat((Action<CodeMatcher>)delegate(CodeMatcher matcher)
			{
				matcher.SetAndAdvance(OpCodes.Call, (object)AccessTools.Method(typeof(BuildTool_Inserter_Patch), "ObjectIsBeltEntity", (Type[])null, (Type[])null));
			}, (Action<string>)null);
			return val.InstructionEnumeration();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)"Transpiler BuildTool_Inserter.DeterminePreviews error");
			Plugin.Log.LogWarning((object)ex);
			return instructions;
		}
	}

	private static bool ObjectIsBeltEntity(BuildTool_Inserter @this, int objId)
	{
		if (objId <= 0)
		{
			return false;
		}
		return ((BuildTool)@this).factory.entityPool[objId].beltId > 0;
	}

	private static void AddPrebuildBeltSlot(BuildTool_Inserter @this)
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		if (@this.startObjectId < 0 && ((BuildTool)@this).ObjectIsBelt(@this.startObjectId))
		{
			Pose[] belt_slots = @this.belt_slots;
			SlotPoint item = default(SlotPoint);
			for (int i = 0; i < belt_slots.Length; i++)
			{
				Pose val = belt_slots[i];
				item.objId = @this.startObjectId;
				ref PrebuildData reference = ref ((BuildTool)@this).factory.prebuildPool[-@this.startObjectId];
				item.pose = ((Pose)(ref val)).GetTransformedBy(new Pose(reference.pos, reference.rot));
				item.slotIdx = -1;
				@this.startSlots.Add(item);
			}
		}
		if (@this.castObjectId < 0 && ((BuildTool)@this).ObjectIsBelt(@this.castObjectId))
		{
			Pose[] belt_slots = @this.belt_slots;
			SlotPoint item2 = default(SlotPoint);
			for (int i = 0; i < belt_slots.Length; i++)
			{
				Pose val2 = belt_slots[i];
				item2.objId = @this.castObjectId;
				ref PrebuildData reference2 = ref ((BuildTool)@this).factory.prebuildPool[-@this.castObjectId];
				item2.pose = ((Pose)(ref val2)).GetTransformedBy(new Pose(reference2.pos, reference2.rot));
				item2.slotIdx = -1;
				@this.endSlots.Add(item2);
			}
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(BuildTool_Inserter), "CheckBuildConditions")]
	public static void BuildTool_Inserter_CheckBuildConditions_Postfix(BuildTool_Inserter __instance, ref bool __result)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Invalid comparison between Unknown and I4
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		if (__result || ((BuildTool)__instance).buildPreviews.Count != 1)
		{
			return;
		}
		BuildPreview val = ((BuildTool)__instance).buildPreviews[0];
		if ((int)val.condition == 34 && (val.inputObjId < 0 || val.outputObjId < 0))
		{
			__result = true;
			val.condition = (EBuildCondition)0;
			((BuildTool)__instance).actionBuild.model.cursorText = val.conditionText;
			((BuildTool)__instance).actionBuild.model.cursorState = 0;
			if (!VFInput.onGUI)
			{
				UICursor.SetCursor((ECursor)0);
			}
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(BuildTool_Inserter), "DeterminePreviews")]
	public static void PrebuildCorrection(BuildTool_Inserter __instance)
	{
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Invalid comparison between Unknown and I4
		//IL_0290: Unknown result type (might be due to invalid IL or missing references)
		//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_02be: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_028a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0190: Unknown result type (might be due to invalid IL or missing references)
		//IL_0195: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01da: Unknown result type (might be due to invalid IL or missing references)
		//IL_01df: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fb: 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_0241: Unknown result type (might be due to invalid IL or missing references)
		//IL_0246: Unknown result type (might be due to invalid IL or missing references)
		//IL_0250: Unknown result type (might be due to invalid IL or missing references)
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_025a: Unknown result type (might be due to invalid IL or missing references)
		//IL_025f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0269: Unknown result type (might be due to invalid IL or missing references)
		//IL_027a: Unknown result type (might be due to invalid IL or missing references)
		//IL_027f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		//IL_010c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0134: Unknown result type (might be due to invalid IL or missing references)
		//IL_0139: Unknown result type (might be due to invalid IL or missing references)
		//IL_013e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_015e: Unknown result type (might be due to invalid IL or missing references)
		if (((BuildTool)__instance).buildPreviews.Count != 1 || (__instance.startObjectId >= 0 && __instance.castObjectId >= 0))
		{
			return;
		}
		bool flag = __instance.startObjectId < 0 && ((BuildTool)__instance).ObjectIsBelt(__instance.startObjectId);
		bool flag2 = __instance.castObjectId < 0 && ((BuildTool)__instance).ObjectIsBelt(__instance.castObjectId);
		BuildPreview val = ((BuildTool)__instance).buildPreviews[0];
		if ((int)val.condition == 15)
		{
			if (flag && !flag2 && __instance.endSlots.Count > 0)
			{
				Vector3 position = __instance.startSlots[0].pose.position;
				List<SlotPoint> endSlots = __instance.endSlots;
				int index = 0;
				float num = float.MaxValue;
				for (int i = 0; i < endSlots.Count; i++)
				{
					float num2 = Vector3.SqrMagnitude(endSlots[i].pose.position - position);
					if (num2 < num)
					{
						num = num2;
						index = i;
					}
				}
				val.lpos2 = endSlots[index].pose.position;
				val.lrot2 = endSlots[index].pose.rotation * Quaternion.Euler(0f, 180f, 0f);
				val.outputToSlot = endSlots[index].slotIdx;
				val.lrot = val.lrot2;
			}
			if (!flag && flag2 && __instance.startSlots.Count > 0)
			{
				Vector3 position2 = __instance.endSlots[0].pose.position;
				List<SlotPoint> startSlots = __instance.startSlots;
				int index2 = 0;
				float num3 = float.MaxValue;
				for (int j = 0; j < startSlots.Count; j++)
				{
					float num4 = Vector3.SqrMagnitude(startSlots[j].pose.position - position2);
					Vector3 val2 = position2 - startSlots[j].pose.position;
					SlotPoint val3 = startSlots[j];
					float num5 = Vector3.Angle(val2, ((Pose)(ref val3.pose)).forward);
					if (num4 < num3 && num5 < 40f)
					{
						num3 = num4;
						index2 = j;
					}
				}
				val.lpos = startSlots[index2].pose.position;
				val.lrot = startSlots[index2].pose.rotation;
				val.inputFromSlot = startSlots[index2].slotIdx;
				val.lrot2 = val.lrot;
			}
			_ = flag && flag2;
			val.condition = (EBuildCondition)0;
		}
		if ((int)val.condition == 0)
		{
			UIInserterBuildTip inserterBuildTip = __instance.uiGame.inserterBuildTip;
			Vector3 val4 = val.lpos2 - val.lpos;
			inserterBuildTip.direction = ((Vector3)(ref val4)).normalized;
			inserterBuildTip.position = (val.lpos + val.lpos2) * 0.5f;
			inserterBuildTip.position1 = val.lpos;
			inserterBuildTip.position2 = val.lpos2;
			if (flag && !flag2)
			{
				inserterBuildTip.input = true;
				inserterBuildTip.output = false;
				inserterBuildTip.outputBelt = true;
				inserterBuildTip.inputBelt = false;
			}
			if (!flag && flag2)
			{
				inserterBuildTip.output = true;
				inserterBuildTip.input = false;
				inserterBuildTip.inputBelt = true;
				inserterBuildTip.outputBelt = false;
			}
		}
	}
}
public class BuildTool_Patch
{
	public static int GetItemCountDummy(StorageComponent _, int itemId)
	{
		return 999;
	}

	[HarmonyTranspiler]
	[HarmonyPatch(typeof(UIBuildMenu), "OnChildButtonClick")]
	public static IEnumerable<CodeInstruction> OnBuildingButtonClick_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(BuildTool_Patch), "GetItemCountDummy", (Type[])null, (Type[])null));
			}, (Action<string>)null).InstructionEnumeration();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)"Transpiler UIBuildMenu.OnChildButtonClick error");
			Plugin.Log.LogWarning((object)ex);
			return instructions;
		}
	}

	[HarmonyTranspiler]
	[HarmonyAfter(new string[] { "dsp.nebula-multiplayer" })]
	[HarmonyPriority(200)]
	[HarmonyPatch(typeof(BuildTool_Click), "CheckBuildConditions")]
	[HarmonyPatch(typeof(BuildTool_Inserter), "CheckBuildConditions")]
	[HarmonyPatch(typeof(BuildTool_Addon), "CheckBuildConditions")]
	[HarmonyPatch(typeof(BuildTool_Path), "CheckBuildConditions")]
	public static IEnumerable<CodeInstruction> CheckBuildConditions_Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0002: 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_0022: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Expected O, but got Unknown
		try
		{
			CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[2]
			{
				new CodeMatch((OpCode?)OpCodes.Ldc_I4_2, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Stfld, (object)AccessTools.Field(typeof(BuildPreview), "condition"), (string)null)
			});
			if (val.IsInvalid)
			{
				Plugin.Log.LogWarning((object)"Can't find EBuildCondition.NotEnoughItem");
				return instructions;
			}
			val.Advance(-1).SetAndAdvance(OpCodes.Nop, (object)null).SetAndAdvance(OpCodes.Nop, (object)null)
				.SetAndAdvance(OpCodes.Nop, (object)null);
			if (val.Opcode == OpCodes.Br)
			{
				val.RemoveInstruction();
			}
			return val.InstructionEnumeration();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)"Transpiler BuildTool.CheckBuildConditions error");
			Plugin.Log.LogWarning((object)ex);
			return instructions;
		}
	}

	[HarmonyTranspiler]
	[HarmonyAfter(new string[] { "dsp.nebula-multiplayer" })]
	[HarmonyPriority(200)]
	[HarmonyPatch(typeof(BuildTool_Click), "CreatePrebuilds")]
	[HarmonyPatch(typeof(BuildTool_Inserter), "CreatePrebuilds")]
	[HarmonyPatch(typeof(BuildTool_Addon), "CreatePrebuilds")]
	[HarmonyPatch(typeof(BuildTool_Path), "CreatePrebuilds")]
	public static IEnumerable<CodeInstruction> CreatePrebuilds_Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Expected O, but got Unknown
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Expected O, but got Unknown
		//IL_01de: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e4: Expected O, but got Unknown
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Expected O, but got Unknown
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_015b: Expected O, but got Unknown
		//IL_0194: Unknown result type (might be due to invalid IL or missing references)
		//IL_019e: Expected O, but got Unknown
		try
		{
			CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null).MatchForward(true, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Callvirt, (object)AccessTools.Method(typeof(PlanetFactory), "AddPrebuildDataWithComponents", (Type[])null, (Type[])null), (string)null)
			});
			if (!val.IsInvalid)
			{
				List<CodeInstruction> list = val.InstructionsInRange(val.Pos - 4, val.Pos + 2);
				switch (__originalMethod.DeclaringType.Name)
				{
				case "BuildTool_Click":
					ToLdloca(list[3]);
					list[4] = new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(BuildTool_Patch), "AddPrebuildData_Click", (Type[])null, (Type[])null));
					break;
				case "BuildTool_Inserter":
					ToLdloca(list[3]);
					list[4] = new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(BuildTool_Patch), "AddPrebuildData_Inserter", (Type[])null, (Type[])null));
					list.Insert(0, list[0]);
					break;
				case "BuildTool_Path":
					ToLdloca(list[3]);
					list[4] = new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(BuildTool_Patch), "AddPrebuildData_Addon", (Type[])null, (Type[])null));
					list.Insert(0, list[0]);
					break;
				case "BuildTool_Addon":
					ToLdloca(list[3]);
					list[4] = new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(BuildTool_Patch), "AddPrebuildData_Path", (Type[])null, (Type[])null));
					list.RemoveAt(2);
					list.Insert(0, list[0]);
					break;
				}
				val.MatchForward(true, (CodeMatch[])(object)new CodeMatch[1]
				{
					new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(Assert), "CannotBeReached", (Type[])null, (Type[])null), (string)null)
				}).Advance(1);
				do
				{
					val.RemoveInstruction();
				}
				while (!(val.Opcode == OpCodes.Call) || !(((MethodInfo)val.Operand).Name == "Popup"));
				val.RemoveInstruction();
				val.Insert((IEnumerable<CodeInstruction>)list);
			}
			if (Plugin.EnableRemoveGC)
			{
				val.End();
				for (int i = 0; i < 5; i++)
				{
					val.Advance(-1);
					if (val.Opcode == OpCodes.Call && ((MethodInfo)val.Operand).Name == "Collect")
					{
						val.SetOpcodeAndAdvance(OpCodes.Nop);
						break;
					}
				}
			}
			return val.InstructionEnumeration();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)"Transpiler CreatePrebuilds error");
			Plugin.Log.LogWarning((object)ex);
			return instructions;
		}
	}

	private static void ToLdloca(CodeInstruction code)
	{
		if (code.opcode == OpCodes.Ldloc_3)
		{
			code.operand = (sbyte)3;
		}
		else if (code.opcode == OpCodes.Ldloc_2)
		{
			code.operand = (sbyte)2;
		}
		else if (code.opcode == OpCodes.Ldloc_1)
		{
			code.operand = (sbyte)1;
		}
		else if (code.opcode == OpCodes.Ldloc_0)
		{
			code.operand = (sbyte)0;
		}
		code.opcode = OpCodes.Ldloca_S;
	}

	public static int AddPrebuildData_Click(PlanetFactory factory, ref PrebuildData prebuildData)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		prebuildData.itemRequired = 1;
		return factory.AddPrebuildDataWithComponents(prebuildData);
	}

	public static int AddPrebuildData_Inserter(BuildPreview buildPreview, PlanetFactory factory, ref PrebuildData prebuildData)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		if (buildPreview.coverObjId != 0)
		{
			return 0;
		}
		prebuildData.itemRequired = 1;
		return factory.AddPrebuildDataWithComponents(prebuildData);
	}

	public static int AddPrebuildData_Addon(BuildPreview buildPreview, PlanetFactory factory, ref PrebuildData prebuildData)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		prebuildData.itemRequired = 1;
		int num = factory.AddPrebuildDataWithComponents(prebuildData);
		if (num != 0 && (buildPreview.desc.isSpraycoster || buildPreview.desc.isDispenser || buildPreview.desc.isTurret))
		{
			if (buildPreview.outputObjId != 0)
			{
				factory.WriteObjectConn(buildPreview.objId, buildPreview.outputFromSlot, true, buildPreview.outputObjId, buildPreview.outputToSlot);
			}
			else if (buildPreview.output != null)
			{
				factory.WriteObjectConn(buildPreview.objId, buildPreview.outputFromSlot, true, buildPreview.output.objId, buildPreview.outputToSlot);
			}
			if (buildPreview.inputObjId != 0)
			{
				factory.WriteObjectConn(buildPreview.objId, buildPreview.inputToSlot, false, buildPreview.inputObjId, buildPreview.inputFromSlot);
				return num;
			}
			if (buildPreview.input != null)
			{
				factory.WriteObjectConn(buildPreview.objId, buildPreview.inputToSlot, false, buildPreview.input.objId, buildPreview.inputFromSlot);
			}
		}
		return num;
	}

	public static int AddPrebuildData_Path(BuildPreview buildPreview, BuildTool_Path @this, ref PrebuildData prebuildData)
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
		if (buildPreview.coverObjId != 0 && !buildPreview.willRemoveCover)
		{
			UIRealtimeTip.Popup(Localization.Translate("物品不足"), true, 1);
			return 0;
		}
		prebuildData.itemRequired = 1;
		int result = 0;
		PlanetFactory factory = ((BuildTool)@this).factory;
		if (buildPreview.coverObjId == 0)
		{
			result = factory.AddPrebuildDataWithComponents(prebuildData);
		}
		else if (buildPreview.willRemoveCover)
		{
			int coverObjId = buildPreview.coverObjId;
			bool flag = default(bool);
			if (ObjectIsBelt(factory, coverObjId))
			{
				int num = default(int);
				int num2 = default(int);
				for (int i = 0; i < 4; i++)
				{
					factory.ReadObjectConn(coverObjId, i, ref flag, ref num, ref num2);
					int num3 = num;
					if (num3 == 0 || !ObjectIsBelt(factory, num3))
					{
						continue;
					}
					bool flag2 = false;
					for (int j = 0; j < 2; j++)
					{
						factory.ReadObjectConn(num3, j, ref flag, ref num, ref num2);
						if (num != 0)
						{
							bool num4 = ObjectIsBelt(factory, num);
							bool flag3 = ObjectIsInserter(factory, num);
							if (!num4 && !flag3)
							{
								flag2 = true;
								break;
							}
						}
					}
					if (flag2)
					{
						@this.tmp_links.Add(num3);
					}
				}
			}
			if (buildPreview.coverObjId > 0)
			{
				Array.Copy(factory.entityConnPool, buildPreview.coverObjId * 16, @this.tmp_conn, 0, 16);
				int num5 = default(int);
				int num6 = default(int);
				for (int k = 0; k < 16; k++)
				{
					factory.ReadObjectConn(buildPreview.coverObjId, k, ref flag, ref num5, ref num6);
					if (num5 > 0)
					{
						factory.ApplyEntityDisconnection(num5, buildPreview.coverObjId, num6, k);
					}
				}
				Array.Clear(((BuildTool)@this).factory.entityConnPool, buildPreview.coverObjId * 16, 16);
			}
			else
			{
				Array.Copy(factory.prebuildConnPool, -buildPreview.coverObjId * 16, @this.tmp_conn, 0, 16);
				Array.Clear(factory.prebuildConnPool, -buildPreview.coverObjId * 16, 16);
			}
			result = factory.AddPrebuildDataWithComponents(prebuildData);
			if (buildPreview.objId > 0)
			{
				Array.Copy(@this.tmp_conn, 0, factory.entityConnPool, buildPreview.objId * 16, 16);
			}
			else
			{
				Array.Copy(@this.tmp_conn, 0, factory.prebuildConnPool, -buildPreview.objId * 16, 16);
			}
			factory.EnsureObjectConn(buildPreview.objId);
		}
		else
		{
			buildPreview.objId = buildPreview.coverObjId;
		}
		return result;
	}

	private static bool ObjectIsBelt(PlanetFactory factory, int objId)
	{
		if (objId == 0)
		{
			return false;
		}
		if (objId > 0)
		{
			return factory.entityPool[objId].beltId > 0;
		}
		return ((ProtoSet<ItemProto>)(object)LDB.items).Select((int)factory.prebuildPool[-objId].protoId)?.prefabDesc.isBelt ?? false;
	}

	private static bool ObjectIsInserter(PlanetFactory factory, int objId)
	{
		if (objId == 0)
		{
			return false;
		}
		if (objId > 0)
		{
			return factory.entityPool[objId].inserterId > 0;
		}
		return ((ProtoSet<ItemProto>)(object)LDB.items).Select((int)factory.prebuildPool[-objId].protoId)?.prefabDesc.isInserter ?? false;
	}
}
public class Compatibility
{
	public static class Nebula_Patch
	{
		public const string GUID = "dsp.nebula-multiplayer";

		public static void Init()
		{
			if (Chainloader.PluginInfos.TryGetValue("dsp.nebula-multiplayer", out var _))
			{
				Plugin.EnableReplaceStation = false;
				Plugin.EnableHologram = false;
				Plugin.EnableStationBuildOptimize = false;
				Plugin.Log.LogDebug((object)"Nebula: Disable replace station and hologram function");
			}
		}
	}

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

		public static void Init(Harmony harmony)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			if (!Chainloader.PluginInfos.TryGetValue("org.soardev.cheatenabler", out var value))
			{
				return;
			}
			try
			{
				Type type = ((object)value.Instance).GetType().Assembly.GetType("CheatEnabler.Patches.FactoryPatch");
				harmony.Patch((MethodBase)AccessTools.Method(type, "ArrivePlanet", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(CheatEnabler_Patch), "ArrivePlanet_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)"CheatEnabler compatibility failed! Last working version: 2.3.26");
				Plugin.Log.LogWarning((object)ex);
			}
		}

		internal static bool ArrivePlanet_Prefix()
		{
			return !ReplaceStationLogic.IsReplacing;
		}
	}

	public static void Init(Harmony harmony)
	{
		Nebula_Patch.Init();
		CheatEnabler_Patch.Init(harmony);
	}
}
internal static class GalacticTransport_Patch
{
	[HarmonyPrefix]
	[HarmonyPatch(typeof(GalacticTransport), "RefreshTraffic")]
	public static bool RefreshTraffic_Prefix(GalacticTransport __instance, int keyStationGId)
	{
		if (keyStationGId == 0)
		{
			return true;
		}
		if (keyStationGId > __instance.stationPool.Length || __instance.stationPool[keyStationGId] == null)
		{
			return true;
		}
		Plugin.Log.LogDebug((object)("GalacticTransport.RefreshTraffic key gid = " + keyStationGId));
		StationComponent val = __instance.stationPool[keyStationGId];
		int[] remotePairOffsets = val.remotePairOffsets;
		int num = ((remotePairOffsets != null) ? remotePairOffsets[6] : 0);
		HashSet<int> hashSet = ClearOtherStationRemotePairs(__instance.stationPool, val);
		val.ClearRemotePairs();
		AddRemotePairs(val, __instance);
		int[] remotePairOffsets2 = val.remotePairOffsets;
		int num2 = ((remotePairOffsets2 != null) ? remotePairOffsets2[6] : 0);
		Plugin.Log.LogDebug((object)$"Related station count = {hashSet.Count}. RemotePairs count {num} => {num2}");
		int logisticShipCarries = GameMain.history.logisticShipCarries;
		UpdateShipStatus(val, __instance, keyStationGId, logisticShipCarries);
		foreach (int item in hashSet)
		{
			UpdateShipStatus(__instance.stationPool[item], __instance, keyStationGId, logisticShipCarries);
		}
		__instance.remotePairCount = 0;
		for (int i = 1; i < __instance.stationCursor; i++)
		{
			if (__instance.stationPool[i] != null && __instance.stationPool[i].gid == i)
			{
				__instance.remotePairCount += __instance.stationPool[i].remotePairTotalCount;
			}
		}
		__instance.remotePairCount /= 2;
		return false;
	}

	public static HashSet<int> ClearOtherStationRemotePairs(StationComponent[] stationPool, StationComponent station)
	{
		HashSet<int> hashSet = new HashSet<int>();
		if (station.remotePairOffsets == null)
		{
			return hashSet;
		}
		if (station.remotePairs == null)
		{
			station.SetRemotePairCapacity(128);
		}
		int num = 0;
		for (int i = 0; i < station.remotePairOffsets[6]; i++)
		{
			ref SupplyDemandPair reference = ref station.remotePairs[i];
			int num2 = ((reference.supplyId != station.gid) ? reference.supplyId : reference.demandId);
			if (num2 != 0)
			{
				hashSet.Add(num2);
			}
			num++;
		}
		int num3 = 0;
		foreach (int item in hashSet)
		{
			num3 += ClearStationRemotePairs(stationPool[item], station.gid);
		}
		if (num3 != num)
		{
			Plugin.Log.LogWarning((object)$"RemotePairs mismatch! local:{num} remote:{num3}");
		}
		return hashSet;
	}

	public static int ClearStationRemotePairs(StationComponent station, int keyStationGId)
	{
		int num = 0;
		int num2 = 6;
		for (int num3 = station.remotePairOffsets[6] - 1; num3 >= 0; num3--)
		{
			ref SupplyDemandPair reference = ref station.remotePairs[num3];
			if (reference.demandId == keyStationGId || reference.supplyId == keyStationGId)
			{
				while (num3 < station.remotePairOffsets[num2 - 1] && num2 != 1)
				{
					num2--;
				}
				if (num3 < station.remotePairOffsets[6] - 1)
				{
					Array.Copy(station.remotePairs, num3 + 1, station.remotePairs, num3, station.remotePairOffsets[6] - num3 - 1);
				}
				for (int i = num2; i <= 6; i++)
				{
					station.remotePairOffsets[i]--;
				}
				num++;
			}
		}
		return num;
	}

	public static void AddRemotePairs(StationComponent @this, GalacticTransport galacticTransport)
	{
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Invalid comparison between Unknown and I4
		//IL_0296: Unknown result type (might be due to invalid IL or missing references)
		//IL_029c: Invalid comparison between Unknown and I4
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Invalid comparison between Unknown and I4
		//IL_031a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0320: Invalid comparison between Unknown and I4
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_010c: Invalid comparison between Unknown and I4
		//IL_0372: Unknown result type (might be due to invalid IL or missing references)
		//IL_0378: Invalid comparison between Unknown and I4
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Invalid comparison between Unknown and I4
		//IL_037b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0381: Invalid comparison between Unknown and I4
		int num = @this.storage.Length;
		StationComponent[] stationPool = galacticTransport.stationPool;
		int stationCursor = galacticTransport.stationCursor;
		for (int i = 0; i < num; i++)
		{
			if ((int)@this.storage[i].remoteLogic == 1)
			{
				int itemId = @this.storage[i].itemId;
				for (int j = 1; j < stationCursor; j++)
				{
					if (stationPool[j] == null || stationPool[j].gid != j || stationPool[j].planetId == @this.planetId)
					{
						continue;
					}
					StationStore[] storage = stationPool[j].storage;
					for (int k = 0; k < storage.Length; k++)
					{
						if (itemId != storage[k].itemId || (int)storage[k].remoteLogic != 2)
						{
							continue;
						}
						int planetId = @this.planetId;
						int planetId2 = stationPool[j].planetId;
						int num2 = planetId / 100 * 100;
						int num3 = planetId2 / 100 * 100;
						if (!galacticTransport.IsAstro2AstroBanExist(planetId, planetId2, itemId) && !galacticTransport.IsAstro2AstroBanExist(num2, num3, itemId))
						{
							bool flag = (int)stationPool[j].routePriority == 4 || (int)@this.routePriority == 4;
							if (!flag)
							{
								@this.AddRemotePair(@this.gid, i, j, k);
								stationPool[j].AddRemotePair(@this.gid, i, j, k);
							}
							bool flag2 = false;
							if (galacticTransport.IsStation2StationRouteExist(@this.gid, stationPool[j].gid))
							{
								@this.AddRouteRemotePair(@this.gid, i, j, k, 2);
								stationPool[j].AddRouteRemotePair(@this.gid, i, j, k, 2);
								flag2 = true;
							}
							if (galacticTransport.IsAstro2AstroRouteEnable(planetId, planetId2, itemId))
							{
								@this.AddRouteRemotePair(@this.gid, i, j, k, 3);
								stationPool[j].AddRouteRemotePair(@this.gid, i, j, k, 3);
								flag2 = true;
							}
							if (galacticTransport.IsAstro2AstroRouteEnable(num2, num3, itemId))
							{
								@this.AddRouteRemotePair(@this.gid, i, j, k, 4);
								stationPool[j].AddRouteRemotePair(@this.gid, i, j, k, 4);
								flag2 = true;
							}
							if ((@this.remoteGroupMask & stationPool[j].remoteGroupMask) > 0)
							{
								@this.AddRouteRemotePair(@this.gid, i, j, k, 5);
								stationPool[j].AddRouteRemotePair(@this.gid, i, j, k, 5);
								flag2 = true;
							}
							if (!flag2 && !flag)
							{
								@this.AddRouteRemotePair(@this.gid, i, j, k, 6);
								stationPool[j].AddRouteRemotePair(@this.gid, i, j, k, 6);
							}
						}
					}
				}
			}
			else
			{
				if ((int)@this.storage[i].remoteLogic != 2)
				{
					continue;
				}
				int itemId2 = @this.storage[i].itemId;
				for (int l = 1; l < stationCursor; l++)
				{
					if (stationPool[l] == null || stationPool[l].gid != l || stationPool[l].planetId == @this.planetId)
					{
						continue;
					}
					StationStore[] storage2 = stationPool[l].storage;
					for (int m = 0; m < storage2.Length; m++)
					{
						if (itemId2 != storage2[m].itemId || (int)storage2[m].remoteLogic != 1)
						{
							continue;
						}
						int planetId3 = @this.planetId;
						int planetId4 = stationPool[l].planetId;
						int num4 = planetId3 / 100 * 100;
						int num5 = planetId4 / 100 * 100;
						if (!galacticTransport.IsAstro2AstroBanExist(planetId3, planetId4, itemId2) && !galacticTransport.IsAstro2AstroBanExist(num4, num5, itemId2))
						{
							bool flag3 = (int)stationPool[l].routePriority == 4 || (int)@this.routePriority == 4;
							if (!flag3)
							{
								@this.AddRemotePair(l, m, @this.gid, i);
								stationPool[l].AddRemotePair(l, m, @this.gid, i);
							}
							bool flag4 = false;
							if (galacticTransport.IsStation2StationRouteExist(@this.gid, stationPool[l].gid))
							{
								@this.AddRouteRemotePair(l, m, @this.gid, i, 2);
								stationPool[l].AddRouteRemotePair(l, m, @this.gid, i, 2);
								flag4 = true;
							}
							if (galacticTransport.IsAstro2AstroRouteEnable(planetId3, planetId4, itemId2))
							{
								@this.AddRouteRemotePair(l, m, @this.gid, i, 3);
								stationPool[l].AddRouteRemotePair(l, m, @this.gid, i, 3);
								flag4 = true;
							}
							if (galacticTransport.IsAstro2AstroRouteEnable(num4, num5, itemId2))
							{
								@this.AddRouteRemotePair(l, m, @this.gid, i, 4);
								stationPool[l].AddRouteRemotePair(l, m, @this.gid, i, 4);
								flag4 = true;
							}
							if ((@this.remoteGroupMask & stationPool[l].remoteGroupMask) > 0)
							{
								@this.AddRouteRemotePair(l, m, @this.gid, i, 5);
								stationPool[l].AddRouteRemotePair(l, m, @this.gid, i, 5);
								flag4 = true;
							}
							if (!flag4 && !flag3)
							{
								@this.AddRouteRemotePair(l, m, @this.gid, i, 6);
								stationPool[l].AddRouteRemotePair(l, m, @this.gid, i, 6);
							}
						}
					}
				}
			}
		}
	}

	public static void UpdateShipStatus(StationComponent @this, GalacticTransport galacticTransport, int keyStationGId, int shipCarries)
	{
		//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0205: Invalid comparison between Unknown and I4
		//IL_03e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0401: Unknown result type (might be due to invalid IL or missing references)
		//IL_040b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0410: Unknown result type (might be due to invalid IL or missing references)
		//IL_0415: Unknown result type (might be due to invalid IL or missing references)
		//IL_041a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0ac7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0acd: Invalid comparison between Unknown and I4
		StationComponent[] stationPool = galacticTransport.stationPool;
		if (keyStationGId <= 0)
		{
			return;
		}
		for (int i = 0; i < @this.workShipCount; i++)
		{
			StationComponent val = stationPool[@this.workShipDatas[i].otherGId];
			StationStore[] array = val?.storage;
			if (keyStationGId == @this.gid)
			{
				if (@this.workShipDatas[i].itemCount == 0 && @this.workShipDatas[i].direction > 0 && @this.workShipDatas[i].otherGId > 0)
				{
					int itemId = @this.workShipDatas[i].itemId;
					if (@this.HasRemoteDemand(itemId, -10000000) == -1)
					{
						if (@this.workShipOrders[i].itemId > 0)
						{
							if (@this.storage[@this.workShipOrders[i].thisIndex].itemId == @this.workShipOrders[i].itemId)
							{
								StationStore[] storage = @this.storage;
								int thisIndex = @this.workShipOrders[i].thisIndex;
								storage[thisIndex].remoteOrder = storage[thisIndex].remoteOrder - @this.workShipOrders[i].thisOrdered;
							}
							if (array != null && array[@this.workShipOrders[i].otherIndex].itemId == @this.workShipOrders[i].itemId)
							{
								StationStore[] array2 = array;
								int otherIndex = @this.workShipOrders[i].otherIndex;
								array2[otherIndex].remoteOrder = array2[otherIndex].remoteOrder - @this.workShipOrders[i].otherOrdered;
							}
							((RemoteLogisticOrder)(ref @this.workShipOrders[i])).ClearThis();
							((RemoteLogisticOrder)(ref @this.workShipOrders[i])).ClearOther();
						}
						@this.workShipDatas[i].itemId = 0;
						for (int j = 0; j < @this.storage.Length; j++)
						{
							if ((int)@this.storage[j].remoteLogic == 2)
							{
								int num = val.HasRemoteSupply(@this.storage[j].itemId, 1);
								if (num >= 0 && ((StationStore)(ref @this.storage[j])).remoteDemandCount > 0)
								{
									@this.workShipDatas[i].itemId = @this.storage[j].itemId;
									@this.workShipDatas[i].direction = 1;
									@this.workShipOrders[i].itemId = @this.workShipDatas[i].itemId;
									@this.workShipOrders[i].otherStationGId = @this.workShipDatas[i].otherGId;
									@this.workShipOrders[i].thisIndex = j;
									@this.workShipOrders[i].otherIndex = num;
									@this.workShipOrders[i].thisOrdered = shipCarries;
									@this.workShipOrders[i].otherOrdered = -shipCarries;
									StationStore[] storage2 = @this.storage;
									int num2 = j;
									storage2[num2].remoteOrder = storage2[num2].remoteOrder + shipCarries;
									StationStore[] array3 = array;
									int num3 = num;
									array3[num3].remoteOrder = array3[num3].remoteOrder - shipCarries;
									break;
								}
							}
						}
						if (@this.workShipDatas[i].itemId == 0)
						{
							@this.workShipDatas[i].otherGId = 0;
							@this.workShipDatas[i].direction = -1;
							if (@this.workShipDatas[i].stage == -1)
							{
								@this.workShipDatas[i].pPosTemp = VectorLF3.op_Implicit(@this.shipDiskPos[@this.workShipDatas[i].shipIndex] + ((Vector3)(ref @this.shipDiskPos[@this.workShipDatas[i].shipIndex])).normalized * 25f);
							}
						}
					}
				}
				if (@this.workShipDatas[i].itemCount != 0 && @this.workShipDatas[i].direction < 0)
				{
					int itemId2 = @this.workShipDatas[i].itemId;
					if (@this.HasRemoteDemand(itemId2, -10000000) == -1 && @this.workShipOrders[i].itemId > 0)
					{
						if (@this.storage[@this.workShipOrders[i].thisIndex].itemId == @this.workShipOrders[i].itemId)
						{
							StationStore[] storage3 = @this.storage;
							int thisIndex2 = @this.workShipOrders[i].thisIndex;
							storage3[thisIndex2].remoteOrder = storage3[thisIndex2].remoteOrder - @this.workShipOrders[i].thisOrdered;
						}
						if (array != null && array[@this.workShipOrders[i].otherIndex].itemId == @this.workShipOrders[i].itemId)
						{
							StationStore[] array4 = array;
							int otherIndex2 = @this.workShipOrders[i].otherIndex;
							array4[otherIndex2].remoteOrder = array4[otherIndex2].remoteOrder - @this.workShipOrders[i].otherOrdered;
						}
						((RemoteLogisticOrder)(ref @this.workShipOrders[i])).ClearThis();
						((RemoteLogisticOrder)(ref @this.workShipOrders[i])).ClearOther();
						@this.workShipOrders[i].itemId = itemId2;
					}
				}
			}
			if (keyStationGId != @this.workShipDatas[i].otherGId)
			{
				continue;
			}
			if ((stationPool[@this.workShipDatas[i].otherGId] == null || stationPool[@this.workShipDatas[i].otherGId].gid == 0) && @this.workShipDatas[i].direction > 0)
			{
				if (@this.workShipOrders[i].itemId > 0)
				{
					if (@this.storage[@this.workShipOrders[i].thisIndex].itemId == @this.workShipOrders[i].itemId)
					{
						StationStore[] storage4 = @this.storage;
						int thisIndex3 = @this.workShipOrders[i].thisIndex;
						storage4[thisIndex3].remoteOrder = storage4[thisIndex3].remoteOrder - @this.workShipOrders[i].thisOrdered;
					}
					((RemoteLogisticOrder)(ref @this.workShipOrders[i])).ClearThis();
					((RemoteLogisticOrder)(ref @this.workShipOrders[i])).ClearOther();
				}
				@this.workShipDatas[i].otherGId = 0;
				@this.workShipDatas[i].direction = -1;
			}
			else if ((stationPool[@this.workShipDatas[i].otherGId] == null || stationPool[@this.workShipDatas[i].otherGId].gid == 0) && @this.workShipDatas[i].direction < 0)
			{
				@this.workShipDatas[i].otherGId = 0;
				@this.workShipDatas[i].direction = -1;
			}
			else if (@this.workShipDatas[i].itemCount > 0 && @this.workShipDatas[i].direction > 0 && @this.workShipDatas[i].otherGId > 0)
			{
				if (val.HasRemoteDemand(@this.workShipDatas[i].itemId, 0) != -1)
				{
					continue;
				}
				if (@this.workShipOrders[i].itemId > 0)
				{
					if (@this.storage[@this.workShipOrders[i].thisIndex].itemId == @this.workShipOrders[i].itemId)
					{
						StationStore[] storage5 = @this.storage;
						int thisIndex4 = @this.workShipOrders[i].thisIndex;
						storage5[thisIndex4].remoteOrder = storage5[thisIndex4].remoteOrder - @this.workShipOrders[i].thisOrdered;
					}
					if (array[@this.workShipOrders[i].otherIndex].itemId == @this.workShipOrders[i].itemId)
					{
						StationStore[] array5 = array;
						int otherIndex3 = @this.workShipOrders[i].otherIndex;
						array5[otherIndex3].remoteOrder = array5[otherIndex3].remoteOrder - @this.workShipOrders[i].otherOrdered;
					}
					((RemoteLogisticOrder)(ref @this.workShipOrders[i])).ClearThis();
					((RemoteLogisticOrder)(ref @this.workShipOrders[i])).ClearOther();
				}
				@this.workShipDatas[i].otherGId = 0;
				@this.workShipDatas[i].direction = -1;
			}
			else
			{
				if (@this.workShipDatas[i].itemCount != 0 || @this.workShipDatas[i].direction <= 0 || @this.workShipDatas[i].otherGId <= 0)
				{
					continue;
				}
				int itemId3 = @this.workShipDatas[i].itemId;
				if (val.HasRemoteSupply(itemId3, 0) != -1)
				{
					continue;
				}
				if (@this.workShipOrders[i].itemId > 0)
				{
					if (@this.storage[@this.workShipOrders[i].thisIndex].itemId == @this.workShipOrders[i].itemId)
					{
						StationStore[] storage6 = @this.storage;
						int thisIndex5 = @this.workShipOrders[i].thisIndex;
						storage6[thisIndex5].remoteOrder = storage6[thisIndex5].remoteOrder - @this.workShipOrders[i].thisOrdered;
					}
					if (array[@this.workShipOrders[i].otherIndex].itemId == @this.workShipOrders[i].itemId)
					{
						StationStore[] array6 = array;
						int otherIndex4 = @this.workShipOrders[i].otherIndex;
						array6[otherIndex4].remoteOrder = array6[otherIndex4].remoteOrder - @this.workShipOrders[i].otherOrdered;
					}
					((RemoteLogisticOrder)(ref @this.workShipOrders[i])).ClearThis();
					((RemoteLogisticOrder)(ref @this.workShipOrders[i])).ClearOther();
				}
				@this.workShipDatas[i].itemId = 0;
				for (int k = 0; k < @this.storage.Length; k++)
				{
					if ((int)@this.storage[k].remoteLogic == 2)
					{
						int num4 = val.HasRemoteSupply(@this.storage[k].itemId, 1);
						if (num4 >= 0 && ((StationStore)(ref @this.storage[k])).remoteDemandCount > 0)
						{
							@this.workShipDatas[i].itemId = @this.storage[k].itemId;
							@this.workShipDatas[i].direction = 1;
							@this.workShipOrders[i].itemId = @this.workShipDatas[i].itemId;
							@this.workShipOrders[i].otherStationGId = @this.workShipDatas[i].otherGId;
							@this.workShipOrders[i].thisIndex = k;
							@this.workShipOrders[i].otherIndex = num4;
							@this.workShipOrders[i].thisOrdered = shipCarries;
							@this.workShipOrders[i].otherOrdered = -shipCarries;
							StationStore[] storage7 = @this.storage;
							int num5 = k;
							storage7[num5].remoteOrder = storage7[num5].remoteOrder + shipCarries;
							StationStore[] array7 = array;
							int num6 = num4;
							array7[num6].remoteOrder = array7[num6].remoteOrder - shipCarries;
							break;
						}
					}
				}
				if (@this.workShipDatas[i].itemId == 0)
				{
					@this.workShipDatas[i].otherGId = 0;
					@this.workShipDatas[i].direction = -1;
				}
			}
		}
	}
}
internal class PlayerController_Patch
{
	private static int clipboardLength;

	private static int hashCode;

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PlayerController), "UpdateCommandState")]
	public static void UpdateCommandState_Prefix(PlayerController __instance)
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Invalid comparison between Unknown and I4
		//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Expected O, but got Unknown
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		if (!VFInput.readyToBuild || !VFInput._pasteBlueprintKey || !VFInput.inScreen || GameMain.history.blueprintLimit <= 0 || ((int)__instance.actionBuild.blueprintMode == 1 && !BlueprintData.IsNullOrEmpty(__instance.actionBuild.blueprintCopyTool.blueprint)))
		{
			return;
		}
		string systemCopyBuffer = GUIUtility.systemCopyBuffer;
		if (clipboardLength == systemCopyBuffer?.Length && hashCode == systemCopyBuffer?.GetHashCode())
		{
			return;
		}
		if (string.IsNullOrEmpty(systemCopyBuffer))
		{
			clipboardLength = 0;
			hashCode = 0;
			return;
		}
		clipboardLength = systemCopyBuffer.Length;
		hashCode = systemCopyBuffer.GetHashCode();
		BlueprintData val = new BlueprintData();
		val.FromBase64String(systemCopyBuffer);
		if (val.isValid)
		{
			__instance.actionBuild.blueprintClipboard = val;
			UIRealtimeTip.Popup($"Parse {clipboardLength:N0} from clipboard!", false, 0);
		}
	}
}
[BepInPlugin("starfi5h.plugin.BuildToolOpt", "BuildToolOpt", "1.0.9")]
public class Plugin : BaseUnityPlugin
{
	public const string GUID = "starfi5h.plugin.BuildToolOpt";

	public const string NAME = "BuildToolOpt";

	public const string VERSION = "1.0.9";

	public static ManualLogSource Log;

	private static Harmony harmony;

	public static bool EnableRemoveGC = true;

	public static bool EnableGCwhenPause = false;

	public static bool EnableReplaceStation = true;

	public static bool EnableHologram = false;

	public static bool EnableStationBuildOptimize = false;

	public static bool EnableUIBlueprintOpt = true;

	public static bool EnableClipboardPaste = true;

	public void Start()
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d8: Expected O, but got Unknown
		//IL_020b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0218: Expected O, but got Unknown
		//IL_026f: Unknown result type (might be due to invalid IL or missing references)
		//IL_027c: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		harmony = new Harmony("starfi5h.plugin.BuildToolOpt");
		EnableRemoveGC = ((BaseUnityPlugin)this).Config.Bind<bool>("BuildTool", "RemoveGC", true, "Remove c# garbage collection of build tools to reduce lag\n移除建筑工具的强制内存回收以减少铺设时卡顿").Value;
		EnableGCwhenPause = ((BaseUnityPlugin)this).Config.Bind<bool>("BuildTool", "GC when pause", false, "Trigger garbage collection when game pause (esc menu). Enable this option if memory usage grow rapidly.\n在游戏暂停时(Esc)回收内存。当内存占用快速增长时可启用此选项手动释放").Value;
		EnableReplaceStation = ((BaseUnityPlugin)this).Config.Bind<bool>("BuildTool", "ReplaceStation", true, "Directly replace old station with new one in hand\n可直接替换物流塔").Value;
		EnableHologram = ((BaseUnityPlugin)this).Config.Bind<bool>("BuildTool", "EnableHologram", false, "Place white holograms when lacking of item\n即使物品不足也可以放置建筑虚影").Value;
		EnableStationBuildOptimize = ((BaseUnityPlugin)this).Config.Bind<bool>("BuildTool", "EnableStationBuildOptimize", false, "Optimize RefreshTraffic to reduce lag when placing stations (experimental)\n优化RefreshTraffic以减少放置物流塔的卡顿 (实验性)").Value;
		EnableUIBlueprintOpt = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "UIBlueprintOpt", true, "Optimize blueprint UI to reduce lag time\n优化蓝图UI减少卡顿").Value;
		EnableClipboardPaste = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "ClipboardPaste", true, "Directly parse blueprint data from clipboard when Ctrl + V\n热键粘贴蓝图时,直接读取剪切板").Value;
		Compatibility.Init(harmony);
		if (EnableReplaceStation)
		{
			harmony.PatchAll(typeof(ReplaceStationLogic));
		}
		if (EnableUIBlueprintOpt)
		{
			harmony.PatchAll(typeof(UIBlueprint_Patch));
		}
		if (EnableHologram)
		{
			harmony.PatchAll(typeof(BuildTool_Patch));
			harmony.PatchAll(typeof(BuildTool_Inserter_Patch));
			if (EnableRemoveGC)
			{
				harmony.Patch((MethodBase)AccessTools.Method(typeof(BuildTool_BlueprintPaste), "CreatePrebuilds", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(RemoveGC_Patch), "RemoveGC_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(DSPGame), "EndGame", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(RemoveGC_Patch), "GCCollect", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}
		else if (EnableRemoveGC)
		{
			harmony.PatchAll(typeof(RemoveGC_Patch));
		}
		if (EnableGCwhenPause)
		{
			harmony.Patch((MethodBase)AccessTools.Method(typeof(GameMain), "Pause", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(RemoveGC_Patch), "GCCollect", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		if (EnableClipboardPaste)
		{
			harmony.PatchAll(typeof(PlayerController_Patch));
		}
		if (EnableStationBuildOptimize)
		{
			harmony.PatchAll(typeof(GalacticTransport_Patch));
		}
	}

	public void OnDestroy()
	{
		harmony.UnpatchSelf();
		harmony = null;
	}
}
public static class RemoveGC_Patch
{
	[HarmonyTranspiler]
	[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")]
	public static IEnumerable<CodeInstruction> RemoveGC_Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null).End();
		for (int i = 0; i < 5; i++)
		{
			val.Advance(-1);
			if (val.Opcode == OpCodes.Call && ((MethodInfo)val.Operand).Name == "Collect")
			{
				val.SetOpcodeAndAdvance(OpCodes.Nop);
				break;
			}
		}
		return val.InstructionEnumeration();
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(DSPGame), "EndGame")]
	public static void GCCollect()
	{
		GC.Collect();
	}
}
internal class ReplaceStationLogic
{
	private struct StationState
	{
		public long energy;

		public int warperCount;

		public int droneCount;

		public int shipCount;

		public StationStore[] storage;
	}

	private static int stationId;

	public static bool IsReplacing { get; private set; }

	[HarmonyPostfix]
	[HarmonyPatch(typeof(BuildTool_Click), "CheckBuildConditions")]
	public static void BuildTool_Click_CheckBuildConditions_Postfix(BuildTool_Click __instance, ref bool __result)
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Invalid comparison between Unknown and I4
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		stationId = 0;
		if (((BuildTool)__instance).buildPreviews.Count != 1)
		{
			return;
		}
		BuildPreview val = ((BuildTool)__instance).buildPreviews[0];
		if (!val.desc.isStation || (int)val.condition != 34 || val.desc.isVeinCollector || val.desc.isCollectStation)
		{
			return;
		}
		int overlapStationEntityId = GetOverlapStationEntityId(__instance);
		if (overlapStationEntityId > 0)
		{
			ref EntityData reference = ref ((BuildTool)__instance).factory.entityPool[overlapStationEntityId];
			stationId = reference.stationId;
			val.lpos = reference.pos;
			val.lrot = reference.rot;
			val.condition = (EBuildCondition)0;
			if (!VFInput.onGUI)
			{
				UICursor.SetCursor((ECursor)0);
			}
			__result = true;
			EBuildCondition realStationCondition = GetRealStationCondition(__instance, val);
			((BuildTool)__instance).actionBuild.model.cursorState = (((int)realStationCondition != 0) ? (-1) : 0);
			((BuildTool)__instance).actionBuild.model.cursorText = BuildPreview.GetConditionText(realStationCondition);
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(BuildTool_Click), "ConfirmOperation")]
	public static void ConfirmOperation_Postfix(BuildTool_Click __instance, ref bool __result)
	{
		if (__result && stationId > 0)
		{
			ReplaceStation(__instance, stationId);
			__result = false;
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(PlanetTransport), "TakeBackItems_Station")]
	public static void TakeBackItems_Station(PlanetTransport __instance, int stationId, ref bool __runOriginal)
	{
		__runOriginal = !IsReplacing;
		if (__runOriginal || stationId == 0)
		{
			return;
		}
		StationComponent stationComponent = __instance.GetStationComponent(stationId);
		if (stationComponent == null || stationComponent.id != stationId)
		{
			return;
		}
		StationStore[] storage = stationComponent.storage;
		int num = ((storage != null) ? storage.Length : 0);
		for (int i = 0; i < num; i++)
		{
			if (stationComponent.storage[i].count > 0 && stationComponent.storage[i].itemId > 0)
			{
				stationComponent.storage[i].count = 0;
				stationComponent.storage[i].inc = 0;
			}
		}
		stationComponent.idleDroneCount = 0;
		stationComponent.idleShipCount = 0;
		stationComponent.warperCount = 0;
		Plugin.Log.LogDebug((object)"TakeBackItems_Station");
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(UIItemup), "Up")]
	private static void Up()
	{
		Plugin.Log.LogDebug((object)Environment.StackTrace);
	}

	private static int GetOverlapStationEntityId(BuildTool_Click tool)
	{
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		PlanetPhysics physics = ((BuildTool)tool).player.planetData.physics;
		ColliderData val = default(ColliderData);
		for (int i = 0; (Object)(object)BuildTool._tmp_cols[i] != (Object)null; i++)
		{
			if (physics.GetColliderData(BuildTool._tmp_cols[i], ref val) && (int)((ColliderData)(ref val)).objType == 0 && ((BuildTool)tool).factory.entityPool[((ColliderData)(ref val)).objId].stationId > 0)
			{
				return ((ColliderData)(ref val)).objId;
			}
		}
		return 0;
	}

	private static EBuildCondition GetRealStationCondition(BuildTool_Click tool, BuildPreview buildPreview)
	{
		//IL_00a6: 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_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0183: Unknown result type (might be due to invalid IL or missing references)
		//IL_0188: Unknown result type (might be due to invalid IL or missing references)
		StationComponent[] stationPool = ((BuildTool)tool).factory.transport.stationPool;
		int stationCursor = ((BuildTool)tool).factory.transport.stationCursor;
		PrebuildData[] prebuildPool = ((BuildTool)tool).factory.prebuildPool;
		int prebuildCursor = ((BuildTool)tool).factory.prebuildCursor;
		EntityData[] entityPool = ((BuildTool)tool).factory.entityPool;
		float num = 225f;
		float num2 = 841f;
		Vector3 val;
		for (int i = 1; i < stationCursor; i++)
		{
			if (i == stationId || stationPool[i] == null || stationPool[i].id != i)
			{
				continue;
			}
			float num3 = ((stationPool[i].isStellar || buildPreview.desc.isStellarStation) ? num2 : num);
			val = entityPool[stationPool[i].entityId].pos - buildPreview.lpos;
			if (((Vector3)(ref val)).sqrMagnitude < num3)
			{
				if (!stationPool[i].isVeinCollector)
				{
					return (EBuildCondition)8;
				}
				return (EBuildCondition)11;
			}
		}
		for (int j = 1; j < prebuildCursor; j++)
		{
			if (prebuildPool[j].id != j)
			{
				continue;
			}
			ItemProto val2 = ((ProtoSet<ItemProto>)(object)LDB.items).Select((int)prebuildPool[j].protoId);
			if (val2 == null || !val2.prefabDesc.isStation)
			{
				continue;
			}
			float num4 = ((val2.prefabDesc.isStellarStation || buildPreview.desc.isStellarStation) ? num2 : num);
			if (buildPreview.desc.isVeinCollector && val2.prefabDesc.isVeinCollector)
			{
				num4 = 0f;
			}
			val = prebuildPool[j].pos - buildPreview.lpos;
			if (((Vector3)(ref val)).sqrMagnitude < num4)
			{
				if (!val2.prefabDesc.isVeinCollector)
				{
					return (EBuildCondition)8;
				}
				return (EBuildCondition)11;
			}
		}
		return (EBuildCondition)0;
	}

	public static void ReplaceStation(BuildTool_Click tool, int stationId)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: 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)
		IsReplacing = true;
		StationComponent val = ((BuildTool)tool).factory.transport.stationPool[stationId];
		BuildingParameters val2 = default(BuildingParameters);
		((BuildingParameters)(ref val2)).CopyFromFactoryObject(val.entityId, ((BuildTool)tool).factory, true, false);
		SlotData[] slots = val.slots;
		SaveState(val, out var state);
		((BuildTool)tool).actionBuild.DoDismantleObject(val.entityId);
		((BuildTool)tool).buildPreviews[0].parameters = val2.parameters;
		((BuildTool)tool).buildPreviews[0].paramCount = val2.parameters.Length;
		tool.CreatePrebuilds();
		int objId = ((BuildTool)tool).buildPreviews[0].objId;
		ReconnectBelts(((BuildTool)tool).factory, objId, slots);
		stationId = ((BuildTool)tool).factory.transport.stationCursor;
		if (((BuildTool)tool).factory.transport.stationRecycleCursor > 0)
		{
			stationId = ((BuildTool)tool).factory.transport.stationRecycle[((BuildTool)tool).factory.transport.stationRecycleCursor - 1];
		}
		((BuildTool)tool).factory.BuildFinally(((BuildTool)tool).player, -objId, true, true);
		LoadState(((BuildTool)tool).factory.transport.stationPool[stationId], in state);
		IsReplacing = false;
	}

	private static void ReconnectBelts(PlanetFactory factory, int objId, SlotData[] slots)
	{
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Invalid comparison between Unknown and I4
		for (int i = 0; i < slots.Length; i++)
		{
			if (slots[i].beltId > 0)
			{
				int entityId = factory.cargoTraffic.beltPool[slots[i].beltId].entityId;
				if ((int)slots[i].dir == 1)
				{
					factory.WriteObjectConn(objId, i, true, entityId, 1);
				}
				else
				{
					factory.WriteObjectConn(objId, i, false, entityId, 0);
				}
			}
		}
	}

	private static void SaveState(StationComponent station, out StationState state)
	{
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		state = default(StationState);
		state.energy = station.energy;
		state.warperCount = station.warperCount;
		state.droneCount = station.idleDroneCount + station.workDroneCount;
		state.shipCount = station.idleShipCount + station.workShipCount;
		state.storage = (StationStore[])(object)new StationStore[station.storage.Length];
		for (int i = 0; i < station.storage.Length; i++)
		{
			state.storage[i] = station.storage[i];
		}
	}

	private static void LoadState(StationComponent station, in StationState state)
	{
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_0146: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		station.energy = state.energy;
		int warperCount = station.warperCount;
		station.warperCount = Math.Min(state.warperCount, station.warperMaxCount);
		RefundItem(1210, state.warperCount - station.warperMaxCount + warperCount, 0, station.entityId);
		warperCount = station.idleDroneCount;
		station.idleDroneCount = Math.Min(state.droneCount, station.workDroneDatas.Length);
		RefundItem(5001, state.droneCount - station.workDroneDatas.Length + warperCount, 0, station.entityId);
		warperCount = station.idleShipCount;
		station.idleShipCount = Math.Min(state.shipCount, station.workShipDatas.Length);
		RefundItem(5002, state.shipCount - station.workShipDatas.Length + warperCount, 0, station.entityId);
		int num = Math.Min(station.storage.Length, state.storage.Length);
		for (int i = 0; i < num; i++)
		{
			station.storage[i].count = state.storage[i].count;
			station.storage[i].inc = state.storage[i].inc;
		}
		for (int j = num; j < state.storage.Length; j++)
		{
			StationStore val = state.storage[j];
			RefundItem(val.itemId, val.count, val.inc, station.entityId);
		}
	}

	private static void RefundItem(int itemId, int count, int inc, int objId)
	{
		if (count > 0)
		{
			GameMain.mainPlayer.TryAddItemToPackage(itemId, count, inc, true, objId, false);
			UIItemup.Up(itemId, count);
		}
	}
}
internal class UIBlueprint_Patch
{
	[HarmonyPrefix]
	[HarmonyPatch(typeof(BlueprintData), "Clone")]
	public static bool BlueprintData_Clone(BlueprintData __instance, ref BlueprintData __result)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		__result = new BlueprintData();
		__result.HeaderFromBase64String(__instance.headerStr);
		using (MemoryStream memoryStream = new MemoryStream())
		{
			using BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
			__instance.Export(binaryWriter);
			binaryWriter.Flush();
			memoryStream.Position = 0L;
			using BinaryReader binaryReader = new BinaryReader(memoryStream);
			__result.Import(binaryReader);
		}
		if (!__result.isValid)
		{
			Plugin.Log.LogWarning((object)"BlueprintData Clone is invalid!");
			__result = null;
		}
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPriority(200)]
	[HarmonyPatch(typeof(UIBlueprintFileItem), "OnThisClick")]
	public static bool UIBlueprintFileItem_OnThisClick(UIBlueprintFileItem __instance)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		if (__instance.time - __instance.lastClickTime < 0.5f * Time.timeScale)
		{
			VFAudio.Create("ui-click-0", (Transform)null, Vector3.zero, true, 1, -1, -1L);
			((ManualBehaviour)__instance.browser.inspector)._Close();
			((ManualBehaviour)__instance.browser.boolInspector)._Close();
			__instance.lastClickTime = -1f;
			__instance.OnThisDoubleClick();
			return false;
		}
		return true;
	}

	[HarmonyPrefix]
	[HarmonyPriority(200)]
	[HarmonyPatch(typeof(UIBlueprintInspector), "_OnOpen")]
	public static bool UIBlueprintInspector_OnOpen(UIBlueprintInspector __instance)
	{
		__instance.player.package.onStorageChange += __instance.OnPlayerPackageChange;
		__instance.Refresh(false, true, false, false);
		__instance.shareLengthText.text = "";
		__instance.shareCodeText.text = "";
		string text = GameConfig.blueprintFolder + __instance.newPath + ".txt";
		if (File.Exists(text))
		{
			try
			{
				FileInfo fileInfo = new FileInfo(text);
				__instance.shareLengthText.text = string.Format(Localization.Translate("几字节"), fileInfo.Length);
				char[] array = new char[256];
				using (StreamReader streamReader = new StreamReader(text))
				{
					streamReader.ReadBlock(array, 0, array.Length);
				}
				__instance.shareCodeText.text = new string(array);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("UIBlueprintInspector_OnOpen: " + ex));
			}
		}
		return false;
	}
}