Decompiled source of TowerFactory v1.4.3

TowerFactory.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using BepInEx;
using BepInEx.Logging;
using CatAPI;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal static class PluginInfo
{
	public const string PLUGIN_GUID = "com.yummi.dsp.towerfactory";

	public const string PLUGIN_NAME = "TowerFactory";

	public const string PLUGIN_VERSION = "1.4.2";
}
namespace TowerFactory
{
	[HarmonyPatch(typeof(DysonSwarm), "AddSolarSail")]
	public static class DysonSwarmCapPatch
	{
		public const int MaxSwarmSailCount = 10000;

		[HarmonyPrefix]
		[Guard("f4cdd480508157f8")]
		public static bool Prefix(DysonSwarm __instance, ref int __result)
		{
			if (__instance.sailCount >= 10000)
			{
				__result = 0;
				return false;
			}
			return true;
		}
	}
	internal class ItemAmounts
	{
		public readonly int[] ids;

		public readonly int[] counts;

		public ItemAmounts(IDictionary<int, int> amounts)
		{
			ids = amounts.Keys.ToArray();
			counts = ids.Select((int id) => amounts[id]).ToArray();
		}

		public static ItemAmounts Of(int[] ids, int[] counts)
		{
			Dictionary<int, int> dictionary = new Dictionary<int, int>();
			for (int i = 0; i < ids.Length; i++)
			{
				dictionary.TryGetValue(ids[i], out var value);
				dictionary[ids[i]] = value + counts[i];
			}
			return new ItemAmounts(dictionary);
		}

		public void Register(int[] register, int times)
		{
			lock (register)
			{
				for (int i = 0; i < ids.Length; i++)
				{
					register[ids[i]] += counts[i] * times;
				}
			}
		}
	}
	internal class PseudoRecipe
	{
		public string name;

		public ERecipeType buildingType;

		public int[] ingredients;

		public int[] ingredientCounts;

		public Dictionary<int, int> outputs;

		public ItemAmounts produced;

		public ItemAmounts consumed;

		public int ticks;
	}
	internal static class PseudoRecipes
	{
		private const int Coal = 1006;

		private const int CrudeOil = 1007;

		private const int FireIce = 1011;

		private const int OpticalGrating = 1014;

		private const int Graphite = 1109;

		private const int RefinedOil = 1114;

		private const int TitaniumCrystal = 1118;

		private const int Hydrogen = 1120;

		private const int Antimatter = 1122;

		private const int Graphene = 1123;

		private const int Casimir = 1126;

		private const int CriticalPhoton = 1208;

		private const int AntimatterFuelRod = 1803;

		private const int EnergyMatrix = 6002;

		private static readonly Lazy<List<PseudoRecipe>> all = new Lazy<List<PseudoRecipe>>(Build);

		public static List<PseudoRecipe> All => all.Value;

		private static List<PseudoRecipe> Build()
		{
			List<PseudoRecipe> list = new List<PseudoRecipe>();
			RecipeProto item = Find((ERecipeType)3, new int[1] { 1007 }, 1114);
			RecipeProto item2 = Find((ERecipeType)3, new int[2] { 1114, 1120 }, 1109);
			RecipeProto item3 = FindReformedRefinement();
			RecipeProto item4 = Find((ERecipeType)15, new int[2] { 1109, 1120 }, 6002);
			RecipeProto grapheneRecipe = Find((ERecipeType)2, new int[1] { 1011 }, 1123);
			RecipeProto target = Find((ERecipeType)4, new int[3] { 1118, 1123, 1120 }, 1126);
			RecipeProto target2 = Find((ERecipeType)4, new int[3] { 1014, 1123, 1120 }, 1126);
			RecipeProto massEnergy = Find((ERecipeType)5, new int[1] { 1208 }, 1122);
			RecipeProto fuelRod = FindByResult((ERecipeType)4, 1803);
			Add(list, "能量矩阵(原油+石墨)", (ERecipeType)3, new int[2] { 1007, 1109 }, (item, 2), (item2, 4), (item4, 3));
			Add(list, "X 射线裂解(净)", (ERecipeType)3, new int[1] { 1114 }, (item2, 1));
			Add(list, "精炼油(原油+煤)", (ERecipeType)3, new int[2] { 1007, 1006 }, (item, 1), (item3, 1));
			Add(list, "精炼油(氢+煤)", (ERecipeType)3, new int[2] { 1120, 1006 }, (item3, 1));
			AddGrapheneSwap(list, "卡西米尔晶体(可燃冰)", target, grapheneRecipe);
			AddGrapheneSwap(list, "卡西米尔晶体(光栅石+可燃冰)", target2, grapheneRecipe);
			AddAntimatterFuelRodPhotonSwap(list, "反物质燃料棒(光子)", massEnergy, fuelRod);
			return list;
		}

		private static void AddAntimatterFuelRodPhotonSwap(List<PseudoRecipe> list, string name, RecipeProto massEnergy, RecipeProto fuelRod)
		{
			if (massEnergy == null || fuelRod == null)
			{
				TowerFactory.Log.LogWarning((object)("伪配方 " + name + " 未启用:找不到对应的真实配方"));
				return;
			}
			int num = fuelRod.ItemCounts[Array.IndexOf(fuelRod.Items, 1122)];
			int num2 = massEnergy.ResultCounts[Array.IndexOf(massEnergy.Results, 1122)];
			if (num <= 0 || num2 <= 0 || num % num2 != 0)
			{
				TowerFactory.Log.LogWarning((object)("伪配方 " + name + " 未启用:反物质数量无法对齐质能储存配方"));
				return;
			}
			int item = num / num2;
			List<int> list2 = new List<int> { 1208 };
			int[] items = fuelRod.Items;
			foreach (int num3 in items)
			{
				if (num3 != 1122 && num3 != 1120)
				{
					list2.Add(num3);
				}
			}
			Add(list, name, (ERecipeType)5, list2.ToArray(), (massEnergy, item), (fuelRod, 1));
		}

		private static void AddGrapheneSwap(List<PseudoRecipe> list, string name, RecipeProto target, RecipeProto grapheneRecipe)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			if (target == null || grapheneRecipe == null)
			{
				TowerFactory.Log.LogWarning((object)("伪配方 " + name + " 未启用:找不到对应的真实配方"));
				return;
			}
			int num = target.ItemCounts[Array.IndexOf(target.Items, 1123)];
			int num2 = grapheneRecipe.ResultCounts[Array.IndexOf(grapheneRecipe.Results, 1123)];
			int num3 = num / Gcd(num, num2) * num2;
			int[] ingredientOrder = target.Items.Select((int id) => (id != 1123) ? id : 1011).ToArray();
			Add(list, name, target.Type, ingredientOrder, (grapheneRecipe, num3 / num2), (target, num3 / num));
		}

		private static void Add(List<PseudoRecipe> list, string name, ERecipeType buildingType, int[] ingredientOrder, params (RecipeProto recipe, int times)[] steps)
		{
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			if (steps.Any(((RecipeProto recipe, int times) step) => step.recipe == null))
			{
				TowerFactory.Log.LogWarning((object)("伪配方 " + name + " 未启用:找不到对应的真实配方"));
				return;
			}
			Dictionary<int, int> dictionary = new Dictionary<int, int>();
			Dictionary<int, int> dictionary2 = new Dictionary<int, int>();
			int num = 0;
			for (int num2 = 0; num2 < steps.Length; num2++)
			{
				var (val, num3) = steps[num2];
				Accumulate(dictionary, val.Results, val.ResultCounts, num3);
				Accumulate(dictionary2, val.Items, val.ItemCounts, num3);
				num += val.TimeSpend * num3;
			}
			Dictionary<int, int> net = new Dictionary<int, int>(dictionary);
			foreach (KeyValuePair<int, int> item in dictionary2)
			{
				net.TryGetValue(item.Key, out var value);
				net[item.Key] = value - item.Value;
			}
			List<int> list2 = (from pair in net
				where pair.Value < 0
				select pair.Key).ToList();
			if (list2.Count != ingredientOrder.Length || !ingredientOrder.All(list2.Contains))
			{
				string text = string.Join("、", list2.Select((int id) => $"{id}×{-net[id]}"));
				TowerFactory.Log.LogWarning((object)("伪配方 " + name + " 未启用:按真实配方算出的净原料为 " + text + ",与设计不符"));
				return;
			}
			PseudoRecipe pseudo = new PseudoRecipe
			{
				name = name,
				buildingType = buildingType,
				ingredients = ingredientOrder,
				ingredientCounts = ingredientOrder.Select((int id) => -net[id]).ToArray(),
				outputs = net.Where((KeyValuePair<int, int> pair) => pair.Value > 0).ToDictionary((KeyValuePair<int, int> pair) => pair.Key, (KeyValuePair<int, int> pair) => pair.Value),
				produced = new ItemAmounts(dictionary),
				consumed = new ItemAmounts(dictionary2),
				ticks = Math.Max(num, 1)
			};
			list.Add(pseudo);
			string text2 = string.Join(" + ", pseudo.ingredients.Select((int id, int i) => $"{pseudo.ingredientCounts[i]} {ItemName(id)}"));
			string text3 = string.Join(" + ", pseudo.outputs.Select((KeyValuePair<int, int> pair) => $"{pair.Value} {ItemName(pair.Key)}"));
			TowerFactory.Log.LogInfo((object)$"伪配方 {name}:{text2} → {text3},{(double)num / 60.0:0.##} 秒");
		}

		private static void Accumulate(Dictionary<int, int> target, int[] ids, int[] counts, int times)
		{
			for (int i = 0; i < ids.Length; i++)
			{
				target.TryGetValue(ids[i], out var value);
				target[ids[i]] = value + counts[i] * times;
			}
		}

		private static RecipeProto FindReformedRefinement()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Invalid comparison between Unknown and I4
			RecipeProto[] dataArray = ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray;
			foreach (RecipeProto val in dataArray)
			{
				if (val != null && (int)val.Type == 3 && RecipeResultCount(val, 1114) == 3 && RecipeItemCount(val, 1114) == 2 && RecipeItemCount(val, 1120) == 1 && RecipeItemCount(val, 1006) == 1)
				{
					return val;
				}
			}
			return null;
		}

		private static int RecipeItemCount(RecipeProto recipe, int itemId)
		{
			int num = 0;
			for (int i = 0; i < recipe.Items.Length; i++)
			{
				if (recipe.Items[i] == itemId)
				{
					num += recipe.ItemCounts[i];
				}
			}
			return num;
		}

		private static int RecipeResultCount(RecipeProto recipe, int itemId)
		{
			int num = 0;
			for (int i = 0; i < recipe.Results.Length; i++)
			{
				if (recipe.Results[i] == itemId)
				{
					num += recipe.ResultCounts[i];
				}
			}
			return num;
		}

		private static RecipeProto Find(ERecipeType type, int[] items, int result)
		{
			//IL_002c: 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)
			RecipeProto[] dataArray = ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray;
			foreach (RecipeProto recipe in dataArray)
			{
				if (recipe != null && recipe.Type == type && Array.IndexOf(recipe.Results, result) >= 0 && recipe.Items.Length == items.Length && items.All((int id) => Array.IndexOf(recipe.Items, id) >= 0))
				{
					return recipe;
				}
			}
			return null;
		}

		private static RecipeProto FindByResult(ERecipeType type, int result)
		{
			//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)
			RecipeProto[] dataArray = ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray;
			foreach (RecipeProto val in dataArray)
			{
				if (val != null && val.Type == type && Array.IndexOf(val.Results, result) >= 0)
				{
					return val;
				}
			}
			return null;
		}

		private static int Gcd(int a, int b)
		{
			while (b != 0)
			{
				int num = b;
				b = a % b;
				a = num;
			}
			return a;
		}

		private static string ItemName(int itemId)
		{
			ItemProto obj = ((ProtoSet<ItemProto>)(object)LDB.items).Select(itemId);
			return ((obj != null) ? ((Proto)obj).name : null) ?? itemId.ToString();
		}
	}
	[HarmonyPatch]
	public class StationProductionPatch
	{
		private enum PlanKind
		{
			Recipe,
			Miner,
			Gamma,
			Dyson,
			TechResearch
		}

		private class Plan
		{
			public PlanKind kind;

			public string description;

			public int[] items;

			public int[] itemCounts;

			public int resultId;

			public int resultCount;

			public double recipeTicks;

			public ItemAmounts statProduced;

			public ItemAmounts statConsumed;

			public int[] outputSlots;

			public int outputMultiplier;

			public double minerTicksPerItem;

			public double itemsPerMinutePerBuilding;

			public double photonTicks;

			public long photonHeat;

			public int dysonBulletId;

			public bool dysonCellPoints;

			public int buildingSlotIndex;

			public int minBuildingCount;
		}

		private class State
		{
			public int[] signature = Array.Empty<int>();

			public Plan plan;

			public int stableTicks;

			public bool active;

			public double progress;

			public long energyBuffer;

			public int revalidateGeneration;
		}

		private const int ActivateDelayTicks = 60;

		private const int CycleDivisor = 10;

		private const int FirstIngredientSlot = 2;

		private const int TechResearchMatrixFirstSlot = 1;

		private const string SlotsNotEnoughMessage = "原料格子不够,请安装 BigTower";

		private const double OilExtractorTicksPerItem = 60.0;

		private const double VeinMinerItemsPerMinutePerBuilding = 180.0;

		private const double AdvancedVeinMinerItemsPerMinutePerBuilding = 900.0;

		private const double GameTicksPerMinute = 3600.0;

		private const int AssemblerSelfProductMinBuildings = 100;

		private const double FractionatorTicksPerItem = 300.0;

		private const float GammaPhotonModeMultiplier = 8f;

		private const float GammaFullWarmupMultiplier = 2.5f;

		private const float GammaFullWarmupLossFactor = 0.6f;

		private const double TechResearchTicksPerCycle = 600.0;

		private const int MatrixPointPerItem = 3600;

		private static readonly int[] ResearchMatrixIds = new int[6] { 6001, 6002, 6003, 6004, 6005, 6006 };

		private static readonly ConditionalWeakTable<StationComponent, State> states = new ConditionalWeakTable<StationComponent, State>();

		private static int stationPlanRevalidateGeneration;

		private static int SplitInc(ref int count, ref int inc, int take)
		{
			if (count == 0)
			{
				return 0;
			}
			int num = inc / count;
			int num2 = inc - num * count;
			count -= take;
			num2 -= count;
			int num3 = ((num2 > 0) ? (num * take + num2) : (num * take));
			inc -= num3;
			return num3;
		}

		internal static void InvalidateAllStationPlans()
		{
			stationPlanRevalidateGeneration++;
		}

		internal static string Tr(string zh, string en)
		{
			if (!Localization.isZHCN)
			{
				return en;
			}
			return zh;
		}

		private static bool IsSelfAssemblerInSlot2(StationStore[] storage)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Invalid comparison between Unknown and I4
			if (storage == null || storage.Length < 2 || storage[0].itemId > 0 || storage[1].itemId <= 0)
			{
				return false;
			}
			PrefabDesc val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(storage[1].itemId)?.prefabDesc;
			if (val != null && val.isAssembler)
			{
				return (int)val.assemblerRecipeType == 4;
			}
			return false;
		}

		private static Plan MatchSelfAssemblerTowerPlan(StationStore[] storage, out string reason)
		{
			int itemId = storage[1].itemId;
			Plan plan = MatchRecipePlan(storage, (ERecipeType)4, itemId, out reason);
			if (plan == null)
			{
				return null;
			}
			plan.buildingSlotIndex = 1;
			plan.minBuildingCount = 100;
			plan.description += Tr("(自产制造台)", " (self-assembler tower)");
			return plan;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlanetTransport), "GameTick")]
		[Guard("d51c267cb7ae3cf0")]
		public static void PlanetTransport_GameTick_Postfix(PlanetTransport __instance)
		{
			PlanetFactory factory = __instance.factory;
			FactoryProductionStat val = GameMain.statistics.production.factoryStatPool[factory.index];
			StationComponent[] stationPool = __instance.stationPool;
			for (int i = 1; i < __instance.stationCursor; i++)
			{
				StationComponent val2 = stationPool[i];
				if (val2 != null && val2.id == i && !val2.isCollector && !val2.isVeinCollector)
				{
					Tick(factory, val2, val.productRegister, val.consumeRegister);
				}
			}
		}

		private static void Tick(PlanetFactory factory, StationComponent station, int[] productRegister, int[] consumeRegister)
		{
			StationStore[] storage = station.storage;
			if (storage == null)
			{
				return;
			}
			State orCreateValue = states.GetOrCreateValue(station);
			if (orCreateValue.revalidateGeneration != stationPlanRevalidateGeneration)
			{
				orCreateValue.revalidateGeneration = stationPlanRevalidateGeneration;
				orCreateValue.signature = Array.Empty<int>();
			}
			else if (orCreateValue.plan == null && StorageMightBeTowerFactory(station, storage) && (GameMain.gameTick + station.id) % 60 == 0L)
			{
				string reason;
				Plan plan = MatchPlan(factory, station, out reason);
				if (plan != null)
				{
					orCreateValue.signature = BuildSignature(storage);
					orCreateValue.plan = plan;
					orCreateValue.stableTicks = 0;
					orCreateValue.active = false;
					orCreateValue.progress = 0.0;
					orCreateValue.energyBuffer = 0L;
					LogMatch(factory, station, null, plan, reason);
				}
			}
			if (!SignatureEquals(orCreateValue.signature, storage))
			{
				Plan plan2 = orCreateValue.plan;
				orCreateValue.signature = BuildSignature(storage);
				orCreateValue.plan = MatchPlan(factory, station, out var reason2);
				orCreateValue.stableTicks = 0;
				orCreateValue.active = false;
				orCreateValue.progress = 0.0;
				orCreateValue.energyBuffer = 0L;
				LogMatch(factory, station, plan2, orCreateValue.plan, reason2);
			}
			Plan plan3 = orCreateValue.plan;
			if (plan3 == null)
			{
				return;
			}
			if (!orCreateValue.active)
			{
				if (++orCreateValue.stableTicks < 60)
				{
					return;
				}
				orCreateValue.active = true;
				TowerFactory.Log.LogInfo((object)(StationLabel(factory, station) + " 塔厂开始生产:" + plan3.description));
			}
			int num = storage[plan3.buildingSlotIndex].count;
			if (num <= 0)
			{
				if (plan3.minBuildingCount <= 0)
				{
					return;
				}
				num = plan3.minBuildingCount;
			}
			else if (plan3.minBuildingCount > 0)
			{
				num = Math.Max(num, plan3.minBuildingCount);
			}
			int num2 = (num + 10 - 1) / 10;
			if (plan3.kind == PlanKind.Miner && plan3.itemsPerMinutePerBuilding > 0.0)
			{
				float miningSpeedScale = GameMain.history.miningSpeedScale;
				if (!(miningSpeedScale <= 0f))
				{
					orCreateValue.progress += (double)num * plan3.itemsPerMinutePerBuilding * (double)miningSpeedScale / 3600.0;
					int num3 = (int)orCreateValue.progress;
					if (num3 > 0)
					{
						orCreateValue.progress -= num3;
						CraftMiner(station, plan3, num3, productRegister);
					}
				}
				return;
			}
			double period = GetPeriod(plan3);
			if (period <= 0.0)
			{
				return;
			}
			if (plan3.kind == PlanKind.Gamma)
			{
				DrawGammaEnergy(factory, orCreateValue, plan3, num2, num);
			}
			double num4;
			if (plan3.kind == PlanKind.TechResearch || (plan3.kind == PlanKind.Dyson && plan3.dysonCellPoints))
			{
				orCreateValue.progress += 10.0;
				num4 = period;
			}
			else
			{
				orCreateValue.progress += num;
				num4 = period * (double)num2;
			}
			while (orCreateValue.progress >= num4)
			{
				orCreateValue.progress -= num4;
				switch (plan3.kind)
				{
				case PlanKind.Recipe:
					CraftRecipe(station, plan3, num2, productRegister, consumeRegister);
					break;
				case PlanKind.Miner:
					CraftMiner(station, plan3, num2 * plan3.outputMultiplier, productRegister);
					break;
				case PlanKind.Gamma:
					CraftGamma(station, orCreateValue, plan3, num2, productRegister);
					break;
				case PlanKind.Dyson:
					CraftDyson(factory, station, plan3, num2, num, consumeRegister);
					break;
				case PlanKind.TechResearch:
					TechHashMainThreadPatch.EnqueueTechCraft(factory, station, num);
					break;
				}
			}
		}

		private static double GetPeriod(Plan plan)
		{
			switch (plan.kind)
			{
			case PlanKind.Recipe:
				return plan.recipeTicks;
			case PlanKind.Miner:
			{
				float miningSpeedScale = GameMain.history.miningSpeedScale;
				if (!(miningSpeedScale > 0f))
				{
					return 0.0;
				}
				return plan.minerTicksPerItem / (double)miningSpeedScale;
			}
			case PlanKind.Gamma:
				return plan.photonTicks;
			case PlanKind.Dyson:
				if (!plan.dysonCellPoints)
				{
					return plan.recipeTicks;
				}
				return 10.0;
			case PlanKind.TechResearch:
				return plan.recipeTicks;
			default:
				return 0.0;
			}
		}

		private static bool IsResearchMatrix(int itemId)
		{
			for (int i = 0; i < ResearchMatrixIds.Length; i++)
			{
				if (ResearchMatrixIds[i] == itemId)
				{
					return true;
				}
			}
			return false;
		}

		private static bool IsUniverseMatrixOnlyTech(TechProto tech)
		{
			if (tech?.Items == null || tech.Items.Length == 0)
			{
				return false;
			}
			for (int i = 0; i < tech.Items.Length; i++)
			{
				if (tech.Items[i] != 6006)
				{
					return false;
				}
			}
			return true;
		}

		private static bool TryGetCurrentLabTech(out TechProto tech, out TechState state)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			tech = null;
			state = default(TechState);
			GameHistoryData history = GameMain.history;
			int currentTech = history.currentTech;
			if (currentTech <= 0)
			{
				return false;
			}
			tech = ((ProtoSet<TechProto>)(object)LDB.techs).Select(currentTech);
			if (tech == null || !tech.IsLabTech || (tech.PropertyOverrideItems != null && tech.PropertyOverrideItems.Length != 0))
			{
				return false;
			}
			if (!history.techStates.TryGetValue(currentTech, out state) || state.unlocked)
			{
				return false;
			}
			return true;
		}

		private static int CountMatrixInStation(StationStore[] storage, int matrixId, int firstSlot = 2)
		{
			int num = 0;
			for (int i = firstSlot; i < storage.Length; i++)
			{
				if (storage[i].itemId == matrixId)
				{
					num += storage[i].count;
				}
			}
			return num;
		}

		private static int CountTechResearchMatrix(StationStore[] storage, int matrixId)
		{
			return CountMatrixInStation(storage, matrixId, 1);
		}

		private static bool LabStorageIsResearchFeed(StationStore[] storage)
		{
			if (storage[1].itemId <= 0)
			{
				return true;
			}
			if (!IsResearchMatrix(storage[1].itemId))
			{
				return false;
			}
			for (int i = 2; i < storage.Length; i++)
			{
				int itemId = storage[i].itemId;
				if (itemId > 0 && !IsResearchMatrix(itemId))
				{
					return false;
				}
			}
			return true;
		}

		private static bool TryComputeMatrixNeeds(TechProto tech, long remainingHash, int[] countsOut)
		{
			Array.Clear(countsOut, 0, countsOut.Length);
			if (remainingHash <= 0 || tech.Items == null)
			{
				return false;
			}
			for (int i = 0; i < tech.Items.Length; i++)
			{
				int value = tech.Items[i];
				int num = Array.IndexOf(ResearchMatrixIds, value);
				if (num < 0)
				{
					return false;
				}
				countsOut[num] = (int)(remainingHash * tech.ItemPoints[i] / 3600);
			}
			return true;
		}

		private static bool StationHasMatrices(StationStore[] storage, TechProto tech, long remainingHash)
		{
			int[] array = new int[ResearchMatrixIds.Length];
			if (!TryComputeMatrixNeeds(tech, remainingHash, array))
			{
				return false;
			}
			for (int i = 0; i < ResearchMatrixIds.Length; i++)
			{
				if (array[i] > 0 && CountTechResearchMatrix(storage, ResearchMatrixIds[i]) < array[i])
				{
					return false;
				}
			}
			return array.Any((int n) => n > 0);
		}

		private static void RegisterResearchMatrixConsumptionTotal(PlanetFactory factory, int matrixId, int amount)
		{
			if (factory == null || matrixId <= 0 || amount <= 0)
			{
				return;
			}
			ProductionStatistics val = GameMain.statistics?.production;
			if (val != null)
			{
				FactoryProductionStat obj = val.factoryStatPool[factory.index];
				if (obj != null)
				{
					obj.AddConsumptionToTotalArray(matrixId, amount);
				}
			}
		}

		private static bool TryConsumeMatricesFromStation(PlanetFactory factory, StationStore[] storage, TechProto tech, long remainingHash)
		{
			int[] array = new int[ResearchMatrixIds.Length];
			if (!TryComputeMatrixNeeds(tech, remainingHash, array))
			{
				return false;
			}
			for (int i = 0; i < ResearchMatrixIds.Length; i++)
			{
				if (array[i] > 0 && CountTechResearchMatrix(storage, ResearchMatrixIds[i]) < array[i])
				{
					return false;
				}
			}
			for (int j = 0; j < ResearchMatrixIds.Length; j++)
			{
				int num = ResearchMatrixIds[j];
				int num2 = array[j];
				if (num2 <= 0)
				{
					continue;
				}
				for (int k = 1; k < storage.Length; k++)
				{
					if (num2 <= 0)
					{
						break;
					}
					ref StationStore reference = ref storage[k];
					if (reference.itemId == num)
					{
						int num3 = Math.Min(num2, reference.count);
						SplitInc(ref reference.count, ref reference.inc, num3);
						num2 -= num3;
					}
				}
				if (num2 > 0)
				{
					return false;
				}
				RegisterResearchMatrixConsumptionTotal(factory, num, array[j]);
			}
			return true;
		}

		private static int MatrixCostForHash(TechProto tech, long hashAmount)
		{
			if (hashAmount <= 0 || tech.Items == null || tech.Items.Length == 0)
			{
				return 0;
			}
			long num = hashAmount * tech.ItemPoints[0] / 3600;
			if (num <= 0 && hashAmount > 0)
			{
				num = 1L;
			}
			return (int)Math.Min(num, 2147483647L);
		}

		private static bool TryConsumeMatrixAmount(PlanetFactory factory, StationStore[] storage, int matrixId, int amount, int firstSlot = 2)
		{
			if (amount <= 0 || CountMatrixInStation(storage, matrixId, firstSlot) < amount)
			{
				return false;
			}
			int num = amount;
			for (int i = firstSlot; i < storage.Length; i++)
			{
				if (num <= 0)
				{
					break;
				}
				ref StationStore reference = ref storage[i];
				if (reference.itemId == matrixId)
				{
					int num2 = Math.Min(num, reference.count);
					SplitInc(ref reference.count, ref reference.inc, num2);
					num -= num2;
				}
			}
			if (num > 0)
			{
				return false;
			}
			RegisterResearchMatrixConsumptionTotal(factory, matrixId, amount);
			return true;
		}

		internal static void RunTechResearchOnMainThread(PlanetFactory factory, StationComponent station, int buildingCount)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			StationStore[] storage = station.storage;
			lock (storage)
			{
				lock (GameMain.history)
				{
					if (!TryGetCurrentLabTech(out var tech, out var state))
					{
						return;
					}
					if (IsUniverseMatrixOnlyTech(tech))
					{
						CraftUniverseMatrixResearch(factory, storage, tech, buildingCount);
						return;
					}
					while (TryGetCurrentLabTech(out tech, out state) && !IsUniverseMatrixOnlyTech(tech))
					{
						long num = state.hashNeeded - state.hashUploaded;
						if (num <= 0 || !StationHasMatrices(storage, tech, num) || !TryConsumeMatricesFromStation(factory, storage, tech, num))
						{
							break;
						}
						GameMain.history.AddTechHash(num);
					}
				}
			}
		}

		private static long HashFromUniverseMatrixCount(TechProto tech, int matrixCount)
		{
			if (matrixCount <= 0 || tech.ItemPoints == null || tech.ItemPoints.Length == 0)
			{
				return 0L;
			}
			int num = tech.ItemPoints[0];
			if (num <= 0)
			{
				return matrixCount;
			}
			return (long)matrixCount * 3600L / num;
		}

		private static void CraftUniverseMatrixResearch(PlanetFactory factory, StationStore[] storage, TechProto tech, int buildingCount)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!GameMain.history.techStates.TryGetValue(GameMain.history.currentTech, out var value))
			{
				return;
			}
			long num = value.hashNeeded - value.hashUploaded;
			if (num <= 0 || buildingCount <= 0)
			{
				return;
			}
			int num2 = Math.Min(buildingCount, CountTechResearchMatrix(storage, 6006));
			if (num2 > 0)
			{
				long num3 = HashFromUniverseMatrixCount(tech, num2);
				if (num3 <= 0)
				{
					num3 = num2;
				}
				if (num3 > num)
				{
					int num4 = tech.ItemPoints[0];
					num2 = (int)((num4 > 0) ? ((num * num4 + 3600 - 1) / 3600) : Math.Min(num, num2));
					num2 = Math.Max(1, Math.Min(num2, Math.Min(buildingCount, CountTechResearchMatrix(storage, 6006))));
					num3 = Math.Min(HashFromUniverseMatrixCount(tech, num2), num);
				}
				if (num3 > 0 && TryConsumeMatrixAmount(factory, storage, 6006, num2, 1))
				{
					GameMain.history.AddTechHash(num3);
				}
			}
		}

		private static bool SphereHasStructureWork(DysonSphere sphere)
		{
			return sphere.GetAutoNodeCount() > 0;
		}

		private static bool NodeReadyForCellConstruction(DysonNode node)
		{
			if (node != null)
			{
				return node.sp == node.spMax;
			}
			return false;
		}

		private static bool SphereHasCellWork(DysonSphere sphere)
		{
			for (int i = 1; i < sphere.layersIdBased.Length; i++)
			{
				DysonSphereLayer val = sphere.layersIdBased[i];
				if (val == null || val.id != i)
				{
					continue;
				}
				for (int j = 1; j < val.nodeCursor; j++)
				{
					DysonNode val2 = val.nodePool[j];
					if (val2 != null && val2.id == j && NodeReadyForCellConstruction(val2) && val2.cpReqOrder > 0)
					{
						return true;
					}
				}
			}
			return false;
		}

		private static int TryConstructCellPointWave(DysonSphere sphere, int maxOps)
		{
			if (maxOps <= 0)
			{
				return 0;
			}
			int num = 0;
			for (int i = 1; i < sphere.layersIdBased.Length; i++)
			{
				DysonSphereLayer val = sphere.layersIdBased[i];
				if (val == null || val.id != i)
				{
					continue;
				}
				for (int j = 1; j < val.nodeCursor; j++)
				{
					if (num >= maxOps)
					{
						return num;
					}
					DysonNode val2 = val.nodePool[j];
					if (val2 == null || val2.id != j || !NodeReadyForCellConstruction(val2) || val2.cpReqOrder <= 0)
					{
						continue;
					}
					val2.cpOrdered++;
					if (val2.ConstructCp() == null)
					{
						continue;
					}
					sphere.needRecalculatePower = true;
					int[] productRegister = sphere.productRegister;
					if (productRegister != null)
					{
						lock (productRegister)
						{
							productRegister[11903]++;
						}
					}
					num++;
				}
			}
			return num;
		}

		private static bool TryConstructStructurePoint(DysonSphere sphere, int autoNodeIndex)
		{
			if (sphere.GetAutoNodeCount() <= 0)
			{
				return false;
			}
			DysonNode autoDysonNode = sphere.GetAutoDysonNode(autoNodeIndex);
			sphere.OrderConstructSp(autoDysonNode);
			object obj = autoDysonNode.ConstructSp();
			if (obj == null)
			{
				return false;
			}
			sphere.needRecalculatePower = true;
			DysonNode val = (DysonNode)((obj is DysonNode) ? obj : null);
			if (val != null)
			{
				sphere.UpdateProgress(val);
			}
			else
			{
				DysonFrame val2 = (DysonFrame)((obj is DysonFrame) ? obj : null);
				if (val2 != null)
				{
					sphere.UpdateProgress(val2);
				}
			}
			int[] productRegister = sphere.productRegister;
			if (productRegister != null)
			{
				lock (productRegister)
				{
					productRegister[11902]++;
				}
			}
			return true;
		}

		private static void CraftDyson(PlanetFactory factory, StationComponent station, Plan plan, int batch, int buildingCount, int[] consumeRegister)
		{
			DysonSphere dysonSphere = factory.dysonSphere;
			if (dysonSphere == null)
			{
				return;
			}
			StationStore[] storage = station.storage;
			int i = 0;
			int count;
			lock (storage)
			{
				if (storage[1].itemId != plan.dysonBulletId || storage[1].count <= 0)
				{
					return;
				}
				count = storage[1].count;
			}
			lock (dysonSphere.dysonSphere_mx)
			{
				if (plan.dysonCellPoints)
				{
					int num;
					for (; i < count; i += num)
					{
						if (!SphereHasCellWork(dysonSphere))
						{
							break;
						}
						num = TryConstructCellPointWave(dysonSphere, count - i);
						if (num <= 0)
						{
							break;
						}
					}
				}
				else
				{
					int num2 = Math.Min(batch, count);
					for (int j = 0; j < num2; j++)
					{
						if (!TryConstructStructurePoint(dysonSphere, station.id + i))
						{
							break;
						}
						i++;
					}
				}
			}
			if (i <= 0)
			{
				return;
			}
			lock (storage)
			{
				int num3 = Math.Min(i, storage[1].count);
				if (num3 <= 0)
				{
					return;
				}
				SplitInc(ref storage[1].count, ref storage[1].inc, num3);
				i = num3;
			}
			plan.statConsumed.Register(consumeRegister, i);
		}

		private static void CraftRecipe(StationComponent station, Plan plan, int batch, int[] productRegister, int[] consumeRegister)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			StationStore[] storage = station.storage;
			int[] items = plan.items;
			int[] itemCounts = plan.itemCounts;
			int resultCount = plan.resultCount;
			lock (storage)
			{
				int val = batch;
				for (int i = 0; i < items.Length; i++)
				{
					val = Math.Min(val, storage[2 + i].count / itemCounts[i]);
				}
				ref StationStore reference = ref storage[1];
				if (reference.itemId != 0 && reference.itemId != plan.resultId)
				{
					return;
				}
				val = Math.Min(val, FreeSpace(reference) / resultCount);
				if (val > 0)
				{
					for (int j = 0; j < items.Length; j++)
					{
						ref StationStore reference2 = ref storage[2 + j];
						SplitInc(ref reference2.count, ref reference2.inc, val * itemCounts[j]);
					}
					if (reference.itemId == 0)
					{
						reference.itemId = plan.resultId;
					}
					reference.count += val * resultCount;
					plan.statConsumed.Register(consumeRegister, val);
					plan.statProduced.Register(productRegister, val);
				}
			}
		}

		private static void CraftMiner(StationComponent station, Plan plan, int itemCount, int[] productRegister)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			StationStore[] storage = station.storage;
			lock (storage)
			{
				int[] outputSlots = plan.outputSlots;
				foreach (int num in outputSlots)
				{
					int num2 = Math.Min(itemCount, FreeSpace(storage[num]));
					if (num2 > 0)
					{
						storage[num].count += num2;
						lock (productRegister)
						{
							productRegister[storage[num].itemId] += num2;
						}
					}
				}
			}
		}

		private static long EnergyPerPhoton(Plan plan)
		{
			float num = 1f - GameMain.history.solarEnergyLossRate * 0.6f;
			if (!(num > 0f))
			{
				return 0L;
			}
			return (long)((float)plan.photonHeat / num);
		}

		private static void DrawGammaEnergy(PlanetFactory factory, State state, Plan plan, int batch, int buildingCount)
		{
			DysonSphere dysonSphere = factory.dysonSphere;
			long num = EnergyPerPhoton(plan);
			if (dysonSphere == null || num <= 0)
			{
				return;
			}
			long num2 = batch * num;
			long num3 = Math.Min((long)((double)buildingCount * (double)num / plan.photonTicks) + 1, num2 - state.energyBuffer);
			if (num3 <= 0)
			{
				return;
			}
			long num4;
			long num5;
			do
			{
				num4 = Interlocked.Read(in dysonSphere.energyReqCurrentTick);
				long val = dysonSphere.energyGenCurrentTick - num4;
				num5 = Math.Min(num3, val);
				if (num5 <= 0)
				{
					return;
				}
			}
			while (Interlocked.CompareExchange(ref dysonSphere.energyReqCurrentTick, num4 + num5, num4) != num4);
			state.energyBuffer += num5;
		}

		private static void CraftGamma(StationComponent station, State state, Plan plan, int batch, int[] productRegister)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			long num = EnergyPerPhoton(plan);
			if (num <= 0)
			{
				return;
			}
			StationStore[] storage = station.storage;
			lock (storage)
			{
				int num2 = (int)Math.Min(Math.Min(batch, FreeSpace(storage[1])), state.energyBuffer / num);
				if (num2 <= 0)
				{
					return;
				}
				state.energyBuffer -= num2 * num;
				storage[1].count += num2;
				lock (productRegister)
				{
					productRegister[storage[1].itemId] += num2;
				}
			}
		}

		private static int FreeSpace(StationStore store)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			int num = store.max - store.count;
			if (num <= 0)
			{
				return 0;
			}
			return num;
		}

		private static bool StorageMightBeTowerFactory(StationComponent station, StationStore[] storage)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Invalid comparison between Unknown and I4
			//IL_007a: 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_009d: Invalid comparison between Unknown and I4
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Invalid comparison between Unknown and I4
			if (storage == null || storage.Length < 2)
			{
				return false;
			}
			if (IsSelfAssemblerInSlot2(storage))
			{
				return true;
			}
			if (storage[0].itemId <= 0 || storage[0].count <= 0)
			{
				return false;
			}
			PrefabDesc val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(storage[0].itemId)?.prefabDesc;
			if (val == null)
			{
				return false;
			}
			if ((int)storage[0].localLogic != 0 || (station.isStellar && (int)storage[0].remoteLogic != 0))
			{
				return false;
			}
			bool flag = (int)val.minerType == 2 || val.isVeinCollector;
			bool flag2 = (int)val.minerType == 1;
			bool flag3 = (int)val.minerType == 3;
			if (!(val.isAssembler || val.isLab || val.isFractionator || flag || flag2 || flag3) && !val.gammaRayReceiver && !val.isPowerExchanger && !val.isEjector)
			{
				return val.isSilo;
			}
			return true;
		}

		private static Plan MatchPlan(PlanetFactory factory, StationComponent station, out string reason)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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_005f: Invalid comparison between Unknown and I4
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Invalid comparison between Unknown and I4
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Invalid comparison between Unknown and I4
			//IL_00c6: 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_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			reason = null;
			StationStore[] storage = station.storage;
			if (storage.Length < 2)
			{
				return null;
			}
			if (IsSelfAssemblerInSlot2(storage))
			{
				return MatchSelfAssemblerTowerPlan(storage, out reason);
			}
			StationStore val = storage[0];
			PrefabDesc val2 = ((val.itemId <= 0) ? null : ((ProtoSet<ItemProto>)(object)LDB.items).Select(val.itemId)?.prefabDesc);
			if (val2 == null)
			{
				return null;
			}
			bool flag = (int)val2.minerType == 2 || val2.isVeinCollector;
			bool flag2 = (int)val2.minerType == 1;
			bool flag3 = (int)val2.minerType == 3;
			if (!val2.isAssembler && !val2.isLab && !val2.isFractionator && !flag && !flag2 && !flag3 && !val2.gammaRayReceiver && !val2.isPowerExchanger && !val2.isEjector && !val2.isSilo)
			{
				return null;
			}
			if ((int)val.localLogic != 0 || (station.isStellar && (int)val.remoteLogic != 0))
			{
				reason = "第一格设置了需求或供应";
				return null;
			}
			if (val2.isEjector || val2.isSilo)
			{
				return MatchDysonPlan(factory, storage, val2, out reason);
			}
			if (val2.isLab && LabStorageIsResearchFeed(storage))
			{
				return MatchTechResearchPlan(storage, out reason);
			}
			int itemId = storage[1].itemId;
			if (itemId <= 0)
			{
				reason = Tr("第二格为空", "Slot 2 is empty");
				return null;
			}
			if (val2.isAssembler)
			{
				return MatchRecipePlan(storage, val2.assemblerRecipeType, itemId, out reason);
			}
			if (val2.isLab)
			{
				return MatchRecipePlan(storage, (ERecipeType)15, storage[1].itemId, out reason);
			}
			if (val2.isFractionator)
			{
				return MatchFractionatorPlan(storage, out reason);
			}
			if (flag)
			{
				return MatchMinerPlan(factory, storage, val2.isVeinCollector, out reason);
			}
			if (flag2)
			{
				return MatchPumpPlan(factory, storage, val2, out reason);
			}
			if (flag3)
			{
				return MatchOilExtractorPlan(factory, storage, out reason);
			}
			if (val2.isPowerExchanger)
			{
				return MatchExchangerPlan(storage, val2, out reason);
			}
			return MatchGammaPlan(factory, storage, val2, out reason);
		}

		private static Plan MatchRecipePlan(StationStore[] storage, ERecipeType recipeType, int productId, out string reason)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			reason = null;
			bool flag = false;
			bool flag2 = false;
			foreach (PseudoRecipe item in PseudoRecipes.All)
			{
				if (item.buildingType == recipeType && item.outputs.TryGetValue(productId, out var value))
				{
					flag = true;
					flag2 |= FitsSlotCount(storage, item.ingredients);
					if (SlotsMatch(storage, item.ingredients))
					{
						return new Plan
						{
							kind = PlanKind.Recipe,
							description = "伪配方 " + item.name,
							items = item.ingredients,
							itemCounts = item.ingredientCounts,
							resultId = productId,
							resultCount = value,
							recipeTicks = item.ticks,
							statProduced = item.produced,
							statConsumed = item.consumed
						};
					}
				}
			}
			RecipeProto[] dataArray = ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray;
			foreach (RecipeProto val in dataArray)
			{
				if (val == null || val.Type != recipeType)
				{
					continue;
				}
				int num = Array.IndexOf(val.Results, productId);
				if (num >= 0)
				{
					flag = true;
					flag2 |= FitsSlotCount(storage, val.Items);
					if (SlotsMatch(storage, val.Items))
					{
						return new Plan
						{
							kind = PlanKind.Recipe,
							description = "配方 " + ((Proto)val).name,
							items = val.Items,
							itemCounts = val.ItemCounts,
							resultId = productId,
							resultCount = val.ResultCounts[num],
							recipeTicks = Math.Max(val.TimeSpend, 1),
							statProduced = ItemAmounts.Of(val.Results, val.ResultCounts),
							statConsumed = ItemAmounts.Of(val.Items, val.ItemCounts)
						};
					}
				}
			}
			if (!flag)
			{
				reason = "第二格 " + ItemName(productId) + " 不是该建筑能生产的产品";
			}
			else if (!flag2)
			{
				reason = "原料格子不够,请安装 BigTower";
			}
			else
			{
				reason = "第三格起的原料与配方顺序不符";
			}
			return null;
		}

		private static bool FitsSlotCount(StationStore[] storage, int[] ingredients)
		{
			return 2 + ingredients.Length <= storage.Length;
		}

		private static Plan MatchTechResearchPlan(StationStore[] storage, out string reason)
		{
			reason = null;
			for (int i = 1; i < storage.Length; i++)
			{
				int itemId = storage[i].itemId;
				if (itemId > 0 && !IsResearchMatrix(itemId))
				{
					reason = Tr($"第 {i + 1} 格 {ItemName(itemId)} 不是研究矩阵(6001–6006)", $"Slot {i + 1} {ItemName(itemId)} is not a research matrix (6001–6006)");
					return null;
				}
			}
			return new Plan
			{
				kind = PlanKind.TechResearch,
				description = Tr("矩阵研究塔(第二格起放矩阵,队列当前科技)", "Matrix research tower (matrices from slot 2, UI queue head)"),
				recipeTicks = 600.0
			};
		}

		private static Plan MatchDysonPlan(PlanetFactory factory, StationStore[] storage, PrefabDesc prefabDesc, out string reason)
		{
			reason = null;
			bool isEjector = prefabDesc.isEjector;
			int num = (isEjector ? prefabDesc.ejectorBulletId : prefabDesc.siloBulletId);
			if (num <= 0)
			{
				reason = Tr("建筑弹药配置无效", "Invalid ammo config on building");
				return null;
			}
			if (storage[1].itemId != num)
			{
				reason = Tr("第二格应为 " + ItemName(num), "Slot 2 must hold " + ItemName(num));
				return null;
			}
			if (factory.dysonSphere == null)
			{
				reason = Tr("本恒星系无戴森球", "No Dyson sphere in this star system");
				return null;
			}
			int val = (isEjector ? (prefabDesc.ejectorChargeFrame + prefabDesc.ejectorColdFrame) : (prefabDesc.siloChargeFrame + prefabDesc.siloColdFrame));
			val = Math.Max(val, 1);
			string text = (isEjector ? Tr("弹射器直建细胞点(每帧全节点满速)", "Ejector direct cell points (max speed, all nodes each wave)") : Tr("发射井直建结构点", "Silo direct structure points"));
			Plan plan = new Plan();
			plan.kind = PlanKind.Dyson;
			plan.dysonCellPoints = isEjector;
			plan.description = (isEjector ? text : $"{text},单座每 {(double)val / 60.0:0.##} 秒 1 点");
			plan.dysonBulletId = num;
			plan.recipeTicks = val;
			plan.statConsumed = ItemAmounts.Of(new int[1] { num }, new int[1] { 1 });
			return plan;
		}

		private static Plan MatchFractionatorPlan(StationStore[] storage, out string reason)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Invalid comparison between Unknown and I4
			reason = null;
			if (storage.Length <= 2)
			{
				reason = "格子不够";
				return null;
			}
			int itemId = storage[1].itemId;
			int itemId2 = storage[2].itemId;
			RecipeProto[] dataArray = ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray;
			foreach (RecipeProto val in dataArray)
			{
				if (val != null && (int)val.Type == 8 && val.Results.Length != 0 && val.Results[0] == itemId && val.Items.Length != 0 && val.Items[0] == itemId2)
				{
					Plan plan = new Plan();
					plan.kind = PlanKind.Recipe;
					plan.description = "分馏 " + ItemName(itemId2) + " → " + ItemName(itemId);
					plan.items = new int[1] { itemId2 };
					plan.itemCounts = new int[1] { 1 };
					plan.resultId = itemId;
					plan.resultCount = 1;
					plan.recipeTicks = 300.0;
					plan.statProduced = ItemAmounts.Of(new int[1] { itemId }, new int[1] { 1 });
					plan.statConsumed = ItemAmounts.Of(new int[1] { itemId2 }, new int[1] { 1 });
					return plan;
				}
			}
			reason = "第二格/第三格不是分馏配方的产品/原料";
			return null;
		}

		public static bool TryAutoFill(PlanetTransport transport, StationComponent station, out string message)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			Player mainPlayer = GameMain.mainPlayer;
			if (mainPlayer == null)
			{
				message = Tr("需要玩家", "Player required");
				return false;
			}
			if (!TryPrepareAutoFillStation(transport, station, mainPlayer, out var prepNotes, out message))
			{
				return false;
			}
			int[] array = SuggestIngredients(station, out message);
			if (array == null)
			{
				return false;
			}
			ELogisticStorage val = (ELogisticStorage)(station.isStellar ? 2 : 0);
			for (int i = 0; i < array.Length; i++)
			{
				transport.SetStationStorage(station.id, 2 + i, array[i], int.MaxValue, (ELogisticStorage)2, val, mainPlayer);
			}
			string text = string.Join(Tr("、", ", "), array.Select(ItemName));
			string text2 = Tr("已填入原料:" + text, "Ingredients filled: " + text);
			message = ((prepNotes.Count > 0) ? (string.Join(Tr(";", "; "), prepNotes) + Tr(";", "; ") + text2) : text2);
			TowerFactory.Log.LogInfo((object)(StationLabel(transport.factory, station) + " " + message));
			return true;
		}

		private static bool TryPrepareAutoFillStation(PlanetTransport transport, StationComponent station, Player player, out List<string> prepNotes, out string message)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Invalid comparison between Unknown and I4
			prepNotes = new List<string>();
			message = null;
			StationStore[] array = station?.storage;
			if (array == null || array.Length == 0)
			{
				message = Tr("这座塔不能做塔厂", "This station can't be a tower factory");
				return false;
			}
			ref StationStore reference = ref array[0];
			if ((int)reference.localLogic != 0 || (station.isStellar && (int)reference.remoteLogic > 0))
			{
				int num = ((reference.max > 0) ? reference.max : int.MaxValue);
				transport.SetStationStorage(station.id, 0, reference.itemId, num, (ELogisticStorage)0, (ELogisticStorage)0, player);
				prepNotes.Add(Tr("第一格已改为仓储", "Slot 1 set to Storage"));
			}
			if (reference.itemId <= 0)
			{
				if (IsSelfAssemblerInSlot2(array))
				{
					return true;
				}
				int itemId = array[1].itemId;
				if (itemId <= 0)
				{
					message = Tr("第一格为空时请先在第二格放产品", "With slot 1 empty, put the product in slot 2 first");
					return false;
				}
				if (!TryResolveAutoFillBuildingItem(array, itemId, out var buildingItemId))
				{
					message = Tr("无法根据第二格产品识别生产建筑", "Can't infer a production building from the product in slot 2");
					return false;
				}
				int num2 = ((reference.max > 0) ? reference.max : int.MaxValue);
				transport.SetStationStorage(station.id, 0, buildingItemId, num2, (ELogisticStorage)0, (ELogisticStorage)0, player);
				prepNotes.Add(Tr("第一格已识别为 " + ItemName(buildingItemId), "Slot 1 set to " + ItemName(buildingItemId)));
			}
			return true;
		}

		private static bool TryResolveAutoFillBuildingItem(StationStore[] storage, int productId, out int buildingItemId)
		{
			buildingItemId = 0;
			for (int i = 2; i < storage.Length; i++)
			{
				int itemId = storage[i].itemId;
				if (itemId > 0 && ProductionBuildingCanMakeProduct(itemId, productId))
				{
					buildingItemId = itemId;
					return true;
				}
			}
			List<int> list = new List<int>();
			ItemProto[] dataArray = ((ProtoSet<ItemProto>)(object)LDB.items).dataArray;
			if (dataArray == null)
			{
				return false;
			}
			foreach (ItemProto val in dataArray)
			{
				if (val != null && ProductionBuildingCanMakeProduct(((Proto)val).ID, productId))
				{
					list.Add(((Proto)val).ID);
				}
			}
			if (list.Count == 0)
			{
				return false;
			}
			list.Sort();
			buildingItemId = list[0];
			return true;
		}

		private static bool ProductionBuildingCanMakeProduct(int buildingItemId, int productId)
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			PrefabDesc val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(buildingItemId)?.prefabDesc;
			if (val == null)
			{
				return false;
			}
			if (val.isPowerExchanger)
			{
				if (val.fullId == productId)
				{
					return val.emptyId > 0;
				}
				return false;
			}
			if (val.isFractionator)
			{
				return ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray.Any((RecipeProto recipe) => recipe != null && (int)recipe.Type == 8 && recipe.Results.Length != 0 && recipe.Results[0] == productId && recipe.Items.Length != 0);
			}
			if (val.isLab)
			{
				return ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray.Any((RecipeProto recipe) => recipe != null && (int)recipe.Type == 15 && recipe.Results.Length != 0 && Array.IndexOf(recipe.Results, productId) >= 0);
			}
			if (val.isAssembler)
			{
				ERecipeType recipeType = val.assemblerRecipeType;
				if (PseudoRecipes.All.Any((PseudoRecipe pseudo) => pseudo.buildingType == recipeType && pseudo.outputs.ContainsKey(productId)))
				{
					return true;
				}
				return ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray.Any((RecipeProto recipe) => recipe != null && recipe.Type == recipeType && Array.IndexOf(recipe.Results, productId) >= 0);
			}
			return false;
		}

		private static int[] SuggestIngredients(StationComponent station, out string reason)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Invalid comparison between Unknown and I4
			StationStore[] storage = station?.storage;
			if (storage == null || station.isCollector || station.isVeinCollector || storage.Length <= 2)
			{
				reason = Tr("这座塔不能做塔厂", "This station can't be a tower factory");
				return null;
			}
			StationStore val = storage[0];
			int num = (IsSelfAssemblerInSlot2(storage) ? storage[1].itemId : val.itemId);
			int productId = storage[1].itemId;
			PrefabDesc val2 = ((num <= 0) ? null : ((ProtoSet<ItemProto>)(object)LDB.items).Select(num)?.prefabDesc);
			if (val2 == null || (!val2.isAssembler && !val2.isLab && !val2.isFractionator && !val2.isPowerExchanger))
			{
				reason = Tr("第一格需要是有配方的生产建筑", "Slot 1 must be a production building that uses recipes");
				return null;
			}
			if (productId <= 0)
			{
				reason = Tr("第二格需要放产品", "Slot 2 must hold the product");
				return null;
			}
			for (int i = 2; i < storage.Length; i++)
			{
				if (storage[i].itemId != 0)
				{
					reason = Tr("第三格起需要全部为空", "Slot 3 and later must all be empty");
					return null;
				}
			}
			List<int[]> list = new List<int[]>();
			if (val2.isPowerExchanger)
			{
				if (productId == val2.fullId && val2.emptyId > 0)
				{
					list.Add(new int[1] { val2.emptyId });
				}
			}
			else if (val2.isFractionator)
			{
				RecipeProto[] dataArray = ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray;
				foreach (RecipeProto val3 in dataArray)
				{
					if (val3 != null && (int)val3.Type == 8 && val3.Results.Length != 0 && val3.Results[0] == productId && val3.Items.Length != 0)
					{
						list.Add(new int[1] { val3.Items[0] });
					}
				}
			}
			else
			{
				ERecipeType recipeType = (ERecipeType)((!val2.isAssembler) ? 15 : ((int)val2.assemblerRecipeType));
				list.AddRange(from pseudo in PseudoRecipes.All
					where pseudo.buildingType == recipeType && pseudo.outputs.ContainsKey(productId)
					select pseudo.ingredients);
				list.AddRange(from recipe in ((ProtoSet<RecipeProto>)(object)LDB.recipes).dataArray
					where recipe != null && recipe.Type == recipeType && Array.IndexOf(recipe.Results, productId) >= 0
					select recipe.Items);
			}
			if (list.Count == 0)
			{
				reason = Tr(ItemName(productId) + " 不是该建筑能生产的产品", ItemName(productId) + " can't be produced by this building");
				return null;
			}
			if (!list.Any((int[] ingredients) => FitsSlotCount(storage, ingredients)))
			{
				reason = Tr("原料格子不够,请安装 BigTower", "Not enough slots for the ingredients. Please install BigTower");
				return null;
			}
			foreach (int[] item in list)
			{
				if (FitsSlotCount(storage, item) && item.Distinct().Count() == item.Length && !item.Contains(num) && !item.Contains(productId))
				{
					reason = null;
					return item;
				}
			}
			reason = Tr("放得下的配方里,原料与塔里已有物品重复", "Every recipe that fits has an ingredient that duplicates an item already in the station");
			return null;
		}

		private static Plan MatchExchangerPlan(StationStore[] storage, PrefabDesc prefabDesc, out string reason)
		{
			reason = null;
			if (storage.Length <= 2)
			{
				reason = "原料格子不够,请安装 BigTower";
				return null;
			}
			if (storage[1].itemId != prefabDesc.fullId || storage[2].itemId != prefabDesc.emptyId)
			{
				reason = "第二格应为 " + ItemName(prefabDesc.fullId) + ",第三格应为 " + ItemName(prefabDesc.emptyId);
				return null;
			}
			if (prefabDesc.exchangeEnergyPerTick <= 0 || prefabDesc.maxExcEnergy <= 0)
			{
				reason = "能量枢纽功率数据异常";
				return null;
			}
			double num = (double)prefabDesc.maxExcEnergy / (double)prefabDesc.exchangeEnergyPerTick;
			Plan plan = new Plan();
			plan.kind = PlanKind.Recipe;
			plan.description = $"充电 {ItemName(prefabDesc.emptyId)} → {ItemName(prefabDesc.fullId)},单座每 {num / 60.0:0.##} 秒 1 个";
			plan.items = new int[1] { prefabDesc.emptyId };
			plan.itemCounts = new int[1] { 1 };
			plan.resultId = prefabDesc.fullId;
			plan.resultCount = 1;
			plan.recipeTicks = num;
			plan.statProduced = ItemAmounts.Of(new int[1] { prefabDesc.fullId }, new int[1] { 1 });
			plan.statConsumed = ItemAmounts.Of(new int[1] { prefabDesc.emptyId }, new int[1] { 1 });
			return plan;
		}

		private static bool SlotsMatch(StationStore[] storage, int[] ingredients)
		{
			if (2 + ingredients.Length > storage.Length)
			{
				return false;
			}
			for (int i = 0; i < ingredients.Length; i++)
			{
				if (storage[2 + i].itemId != ingredients[i])
				{
					return false;
				}
			}
			return true;
		}

		private static Plan MatchMinerPlan(PlanetFactory factory, StationStore[] storage, bool isAdvanced, out string reason)
		{
			reason = null;
			int num = ((!isAdvanced) ? 1 : (storage.Length - 1));
			List<int> list = new List<int>();
			List<string> list2 = new List<string>();
			List<string> list3 = new List<string>();
			for (int i = 1; i <= num; i++)
			{
				int itemId = storage[i].itemId;
				if (itemId > 0)
				{
					string text = null;
					if (!IsMineral(itemId))
					{
						text = $"第 {i + 1} 格 {ItemName(itemId)} 不是采矿机能采的矿物";
					}
					else if (!PlanetHasMineral(factory.planet, itemId))
					{
						text = $"本行星没有第 {i + 1} 格 {ItemName(itemId)} 的矿簇";
					}
					if (text != null)
					{
						list3.Add(text);
						continue;
					}
					list.Add(i);
					list2.Add(ItemName(itemId));
				}
			}
			if (list.Count == 0)
			{
				reason = ((list3.Count > 0) ? string.Join(";", list3) : "第二格为空");
				return null;
			}
			string text2 = ((list3.Count > 0) ? (";跳过:" + string.Join(";", list3)) : "");
			return new Plan
			{
				kind = PlanKind.Miner,
				description = (isAdvanced ? "大型采矿" : "采矿") + " " + string.Join("、", list2) + text2,
				outputSlots = list.ToArray(),
				itemsPerMinutePerBuilding = (isAdvanced ? 900.0 : 180.0)
			};
		}

		private static Plan MatchPumpPlan(PlanetFactory factory, StationStore[] storage, PrefabDesc prefabDesc, out string reason)
		{
			reason = null;
			int num = factory.planet?.waterItemId ?? 0;
			if (num <= 0)
			{
				reason = "本行星没有可抽取的海洋";
				return null;
			}
			if (storage[1].itemId != num)
			{
				reason = "第二格应为本行星的海洋物品 " + ItemName(num);
				return null;
			}
			if (prefabDesc.minerPeriod <= 0)
			{
				reason = "抽水机速度数据异常";
				return null;
			}
			Plan plan = new Plan();
			plan.kind = PlanKind.Miner;
			plan.description = "抽取 " + ItemName(num);
			plan.outputSlots = new int[1] { 1 };
			plan.outputMultiplier = 1;
			plan.minerTicksPerItem = (double)prefabDesc.minerPeriod / 10000.0;
			return plan;
		}

		private static Plan MatchOilExtractorPlan(PlanetFactory factory, StationStore[] storage, out string reason)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Invalid comparison between Unknown and I4
			reason = null;
			int itemId = storage[1].itemId;
			if ((int)LDB.veins.GetVeinTypeByItemId(itemId) != 7)
			{
				reason = "第二格 " + ItemName(itemId) + " 不是原油";
				return null;
			}
			if (!PlanetHasMineral(factory.planet, itemId))
			{
				reason = "本行星没有油井";
				return null;
			}
			Plan plan = new Plan();
			plan.kind = PlanKind.Miner;
			plan.description = "萃取 " + ItemName(itemId);
			plan.outputSlots = new int[1] { 1 };
			plan.outputMultiplier = 1;
			plan.minerTicksPerItem = 60.0;
			return plan;
		}

		private static bool IsMineral(int itemId)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			EVeinType veinTypeByItemId = LDB.veins.GetVeinTypeByItemId(itemId);
			if ((int)veinTypeByItemId != 0)
			{
				return (int)veinTypeByItemId != 7;
			}
			return false;
		}

		private static bool PlanetHasMineral(PlanetData planet, int itemId)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			EVeinType veinTypeByItemId = LDB.veins.GetVeinTypeByItemId(itemId);
			VeinGroup[] array = ((planet != null) ? planet.runtimeVeinGroups : null);
			if (array == null)
			{
				return false;
			}
			VeinGroup[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				VeinGroup val = array2[i];
				if (val.type == veinTypeByItemId && !((VeinGroup)(ref val)).isEmpty)
				{
					return true;
				}
			}
			return false;
		}

		private static Plan MatchGammaPlan(PlanetFactory factory, StationStore[] storage, PrefabDesc prefabDesc, out string reason)
		{
			reason = null;
			if (storage[1].itemId != prefabDesc.powerProductId || prefabDesc.powerProductHeat <= 0)
			{
				reason = "第二格应为 " + ItemName(prefabDesc.powerProductId);
				return null;
			}
			float num = (float)prefabDesc.genEnergyPerTick * 8f * 2.5f;
			if (num <= 0f)
			{
				reason = "射线接收站功率数据异常";
				return null;
			}
			if (factory.dysonSphere == null)
			{
				reason = "本星系没有戴森球";
				return null;
			}
			Plan plan = new Plan
			{
				kind = PlanKind.Gamma,
				photonTicks = (double)prefabDesc.powerProductHeat / (double)num,
				photonHeat = prefabDesc.powerProductHeat
			};
			plan.description = $"临界光子,单座每 {plan.photonTicks / 60.0:0.##} 秒 1 个,每个耗能 {(double)prefabDesc.powerProductHeat / 1000000.0:0.##} MJ";
			return plan;
		}

		private static void LogMatch(PlanetFactory factory, StationComponent station, Plan previous, Plan plan, string reason)
		{
			if (plan != null)
			{
				TowerFactory.Log.LogInfo((object)$"{StationLabel(factory, station)} 识别为塔厂({plan.description}),{1} 秒后生效");
			}
			else if (reason != null)
			{
				TowerFactory.Log.LogInfo((object)(StationLabel(factory, station) + " 未成为塔厂:" + reason));
			}
			else if (previous != null)
			{
				TowerFactory.Log.LogInfo((object)(StationLabel(factory, station) + " 不再是塔厂"));
			}
		}

		private static string StationLabel(PlanetFactory factory, StationComponent station)
		{
			PlanetData planet = factory.planet;
			return $"[{((planet != null) ? planet.displayName : null)} 站点 #{station.id}]";
		}

		private static string ItemName(int itemId)
		{
			ItemProto obj = ((ProtoSet<ItemProto>)(object)LDB.items).Select(itemId);
			return ((obj != null) ? ((Proto)obj).name : null) ?? itemId.ToString();
		}

		private static int[] BuildSignature(StationStore[] storage)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected I4, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected I4, but got Unknown
			int[] array = new int[storage.Length * 3];
			for (int i = 0; i < storage.Length; i++)
			{
				array[i * 3] = storage[i].itemId;
				array[i * 3 + 1] = (int)storage[i].localLogic;
				array[i * 3 + 2] = (int)storage[i].remoteLogic;
			}
			return array;
		}

		private static bool SignatureEquals(int[] signature, StationStore[] storage)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Invalid comparison between I4 and Unknown
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Invalid comparison between I4 and Unknown
			if (signature.Length != storage.Length * 3)
			{
				return false;
			}
			for (int i = 0; i < storage.Length; i++)
			{
				if (signature[i * 3] != storage[i].itemId || signature[i * 3 + 1] != (int)storage[i].localLogic || signature[i * 3 + 2] != (int)storage[i].remoteLogic)
				{
					return false;
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(GameMain), "Begin")]
	public static class StationTowerRevalidatePatch
	{
		[HarmonyPostfix]
		[Guard("fc4688b51c514392")]
		public static void Begin_Postfix()
		{
			StationProductionPatch.InvalidateAllStationPlans();
			ManualLogSource log = TowerFactory.Log;
			if (log != null)
			{
				log.LogInfo((object)"塔厂:已请求进档后全站重新识别");
			}
		}
	}
	public static class TechHashMainThreadPatch
	{
		private readonly struct PendingTechCraft
		{
			public readonly PlanetFactory factory;

			public readonly StationComponent station;

			public readonly int buildingCount;

			public PendingTechCraft(PlanetFactory factory, StationComponent station, int buildingCount)
			{
				this.factory = factory;
				this.station = station;
				this.buildingCount = buildingCount;
			}
		}

		private static readonly ConcurrentQueue<PendingTechCraft> pendingCrafts = new ConcurrentQueue<PendingTechCraft>();

		internal static void EnqueueTechCraft(PlanetFactory factory, StationComponent station, int buildingCount)
		{
			if (factory != null && station != null && buildingCount > 0)
			{
				pendingCrafts.Enqueue(new PendingTechCraft(factory, station, buildingCount));
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameMain), "Update")]
		[Guard("381b98d1af328905")]
		public static void GameMain_Update_Postfix()
		{
			PendingTechCraft result;
			while (pendingCrafts.TryDequeue(out result))
			{
				StationProductionPatch.RunTechResearchOnMainThread(result.factory, result.station, result.buildingCount);
			}
		}
	}
	[HarmonyPatch(typeof(GameHistoryData))]
	public static class TechStationGiftPatch
	{
		private const int PlanetaryLogisticsStationItemId = 2103;

		private const int DefaultStationGiftCount = 1;

		private const int BonusStationGiftCount = 3;

		private const int FeatureKeyBase = 99001000;

		private static readonly int[] BonusGiftTechIds = new int[5] { 1001, 1201, 1002, 1401, 1601 };

		[HarmonyPostfix]
		[HarmonyPatch("NotifyTechUnlock")]
		[Guard("69c5bc40ce9ed7f5")]
		public static void NotifyTechUnlock_Postfix(GameHistoryData __instance, int _techId, int _level, bool _unlockedDirect)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (__instance != null && __instance.techStates.TryGetValue(_techId, out var value) && value.unlocked)
			{
				int num = 99001000 + _techId;
				if (!__instance.HasFeatureKey(num) && CanDeliverItemsToPlayer())
				{
					int num2 = ((!IsBonusGiftTech(_techId)) ? 1 : 3);
					__instance.RegFeatureKey(num);
					__instance.GainTechAwards(2103, num2);
					TechProto obj = ((ProtoSet<TechProto>)(object)LDB.techs).Select(_techId);
					string arg = ((obj != null) ? ((Proto)obj).name : null) ?? _techId.ToString();
					TowerFactory.Log.LogInfo((object)$"科技 {arg} 已解锁:赠送 {num2} 个行星内物流运输塔(未解锁物流科技配方)");
				}
			}
		}

		private static bool CanDeliverItemsToPlayer()
		{
			Player mainPlayer = GameMain.mainPlayer;
			if (mainPlayer != null)
			{
				return mainPlayer.package != null;
			}
			return false;
		}

		private static bool IsBonusGiftTech(int techId)
		{
			int[] bonusGiftTechIds = BonusGiftTechIds;
			for (int i = 0; i < bonusGiftTechIds.Length; i++)
			{
				if (bonusGiftTechIds[i] == techId)
				{
					return true;
				}
			}
			return false;
		}
	}
	[BepInPlugin("com.yummi.dsp.towerfactory", "塔厂 (Tower Factory)", "1.4.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class TowerFactory : BaseUnityPlugin
	{
		public const string PLUGIN_GUID = "com.yummi.dsp.towerfactory";

		public const string PLUGIN_NAME = "塔厂 (Tower Factory)";

		public const string PLUGIN_VERSION = "1.4.3";

		private static readonly Harmony harmony = new Harmony("com.yummi.dsp.towerfactory");

		private static readonly PatchOptions HarnessOptions = new PatchOptions
		{
			ModName = "TowerFactory"
		};

		internal static ManualLogSource Log;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			Harness.PatchAll(harmony, typeof(StationProductionPatch), HarnessOptions);
			Harness.PatchAll(harmony, typeof(UIStationWindowPatch), HarnessOptions);
			Harness.PatchAll(harmony, typeof(TechStationGiftPatch), HarnessOptions);
			Harness.PatchAll(harmony, typeof(DysonSwarmCapPatch), HarnessOptions);
			Harness.PatchAll(harmony, typeof(StationTowerRevalidatePatch), HarnessOptions);
			Harness.PatchAll(harmony, typeof(TechHashMainThreadPatch), HarnessOptions);
			Log.LogInfo((object)"塔厂 (Tower Factory) v1.4.3 已加载");
		}

		private void OnDestroy()
		{
			harmony.UnpatchSelf();
		}
	}
	[HarmonyPatch(typeof(UIStationWindow))]
	public static class UIStationWindowPatch
	{
		private sealed class AutoFillButtonHost : MonoBehaviour
		{
			public UIStationWindow window;

			public void OnClick()
			{
				OnAutoFillClick(window);
			}
		}

		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__9_0;

			internal void <CreateButton>b__9_0()
			{
				_buttonHost.OnClick();
			}
		}

		private static Button _autoFillButton;

		private static Text _autoFillText;

		private static AutoFillButtonHost _buttonHost;

		[HarmonyPostfix]
		[HarmonyPatch("_OnOpen")]
		[Guard("12e97c0fdc1081fd")]
		public static void OnOpen_Postfix(UIStationWindow __instance)
		{
			EnsureButton(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("OnStationIdChange")]
		[Guard("a94c837d579532f7")]
		public static void OnStationIdChange_Postfix(UIStationWindow __instance)
		{
			EnsureButton(__instance);
			if (!((Object)(object)_autoFillButton == (Object)null))
			{
				StationComponent station = GetStation(__instance);
				bool flag = ((ManualBehaviour)__instance).active && station != null && !station.isCollector && !station.isVeinCollector;
				((Component)_autoFillButton).gameObject.SetActive(flag);
				if (flag)
				{
					UpdateButtonText();
				}
			}
		}

		private static void UpdateButtonText()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_005a: 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)
			string text = StationProductionPatch.Tr("塔厂:填原料", "Fill Ingredients");
			if (!(_autoFillText.text == text))
			{
				_autoFillText.text = text;
				RectTransform val = (RectTransform)((Component)_autoFillButton).transform;
				val.sizeDelta = new Vector2(Mathf.Max(100f, _autoFillText.preferredWidth + 16f), val.sizeDelta.y);
			}
		}

		private static StationComponent GetStation(UIStationWindow window)
		{
			PlanetTransport val = window.transport ?? window.factory?.transport;
			int stationId = window.stationId;
			if (val == null || stationId <= 0 || stationId >= val.stationCursor)
			{
				return null;
			}
			StationComponent val2 = val.stationPool[stationId];
			if (val2 == null || val2.id != stationId)
			{
				return null;
			}
			return val2;
		}

		private static void EnsureButton(UIStationWindow window)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			if ((Object)(object)window == (Object)null || (Object)(object)window.windowTrans == (Object)null)
			{
				return;
			}
			if ((Object)(object)_autoFillButton == (Object)null)
			{
				CreateButton(window);
			}
			if (!((Object)(object)_autoFillButton == (Object)null))
			{
				PlaceInTabRow(window, (RectTransform)((Component)_autoFillButton).transform);
				((Component)_autoFillButton).transform.SetAsLastSibling();
				_buttonHost = ((Component)_autoFillButton).GetComponent<AutoFillButtonHost>();
				if ((Object)(object)_buttonHost == (Object)null)
				{
					_buttonHost = ((Component)_autoFillButton).gameObject.AddComponent<AutoFillButtonHost>();
				}
				_buttonHost.window = window;
			}
		}

		private static void PlaceInTabRow(UIStationWindow window, RectTransform btnRect)
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: 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_0050: 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_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: 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_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			RectTransform controlPanelBtnRt = window.controlPanelBtnRt;
			RectTransform val = (RectTransform)(((Object)(object)controlPanelBtnRt != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
			if ((Object)(object)val == (Object)null)
			{
				val = window.windowTrans;
				if ((Object)(object)((Transform)btnRect).parent != (Object)(object)val)
				{
					((Transform)btnRect).SetParent((Transform)(object)val, false);
				}
				btnRect.anchorMin = new Vector2(1f, 1f);
				btnRect.anchorMax = new Vector2(1f, 1f);
				btnRect.pivot = new Vector2(1f, 1f);
				btnRect.anchoredPosition = new Vector2(-20f, -36f);
				return;
			}
			if ((Object)(object)((Transform)btnRect).parent != (Object)(object)val)
			{
				((Transform)btnRect).SetParent((Transform)(object)val, false);
			}
			btnRect.anchorMin = new Vector2(1f, controlPanelBtnRt.anchorMin.y);
			btnRect.anchorMax = new Vector2(1f, controlPanelBtnRt.anchorMax.y);
			btnRect.pivot = new Vector2(1f, controlPanelBtnRt.pivot.y);
			Rect rect = controlPanelBtnRt.rect;
			float num;
			if (!(((Rect)(ref rect)).height > 1f))
			{
				num = 22f;
			}
			else
			{
				rect = controlPanelBtnRt.rect;
				num = ((Rect)(ref rect)).height;
			}
			float y = btnRect.sizeDelta.y;
			float num2 = (num - y) * (0.5f - controlPanelBtnRt.pivot.y);
			RectTransform obj = val;
			RectTransform windowTrans = window.windowTrans;
			rect = window.windowTrans.rect;
			Vector3 val2 = ((Transform)obj).InverseTransformPoint(((Transform)windowTrans).TransformPoint(new Vector3(((Rect)(ref rect)).xMax, 0f, 0f)));
			float num3 = val2.x - 20f;
			rect = val.rect;
			btnRect.anchoredPosition = new Vector2(num3 - ((Rect)(ref rect)).xMax, controlPanelBtnRt.anchoredPosition.y + num2);
		}

		private static void CreateButton(UIStationWindow window)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: 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_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: 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_01e9: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("tower-factory-autofill");
			val.transform.SetParent((Transform)(object)window.windowTrans, false);
			RectTransform obj = val.AddComponent<RectTransform>();
			obj.anchorMin = new Vector2(1f, 1f);
			obj.anchorMax = new Vector2(1f, 1f);
			obj.pivot = new Vector2(1f, 1f);
			obj.anchoredPosition = new Vector2(-20f, -36f);
			obj.sizeDelta = new Vector2(100f, 22f);
			Image obj2 = val.AddComponent<Image>();
			((Graphic)obj2).color = new Color(0.24f, 0.55f, 0.65f, 0.9f);
			((Graphic)obj2).raycastTarget = true;
			_autoFillButton = val.AddComponent<Button>();
			ColorBlock colors = ((Selectable)_autoFillButton).colors;
			((ColorBlock)(ref colors)).highlightedColor = new Color(1.2f, 1.2f, 1.2f, 1f);
			((ColorBlock)(ref colors)).pressedColor = new Color(0.7f, 0.7f, 0.7f, 1f);
			((Selectable)_autoFillButton).colors = colors;
			_buttonHost = val.AddComponent<AutoFillButtonHost>();
			ButtonClickedEvent onClick = _autoFillButton.onClick;
			object obj3 = <>c.<>9__9_0;
			if (obj3 == null)
			{
				UnityAction val2 = delegate
				{
					_buttonHost.OnClick();
				};
				<>c.<>9__9_0 = val2;
				obj3 = (object)val2;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj3);
			GameObject val3 = new GameObject("Text");
			val3.transform.SetParent(val.transform, false);
			Text obj4 = (_autoFillText = val3.AddComponent<Text>());
			obj4.font = (((Object)(object)window.titleText != (Object)null) ? window.titleText.font : Resources.GetBuiltinResource<Font>("Arial.ttf"));
			obj4.fontSize = 14;
			obj4.alignment = (TextAnchor)4;
			((Graphic)obj4).color = Color.white;
			((Graphic)obj4).raycastTarget = false;
			RectTransform component = val3.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.offsetMin = Vector2.zero;
			component.offsetMax = Vector2.zero;
		}

		private static void RefreshStationWindow(UIStationWindow window)
		{
			if (!((Object)(object)window == (Object)null))
			{
				AccessTools.Method(typeof(UIStationWindow), "OnStationIdChange", (Type[])null, (Type[])null)?.Invoke(window, null);
			}
		}

		internal static void OnAutoFillClick(UIStationWindow window)
		{
			if ((Object)(object)window == (Object)null)
			{
				return;
			}
			PlanetTransport val = window.transport ?? window.factory?.transport;
			StationComponent station = GetStation(window);
			if (val == null || station == null)
			{
				UIRealtimeTip.Popup(StationProductionPatch.Tr("无法读取当前运输塔", "Can't read this station"), true, 0);
				return;
			}
			string message;
			bool flag = StationProductionPatch.TryAutoFill(val, station, out message);
			if (string.IsNullOrEmpty(message))
			{
				message = StationProductionPatch.Tr("填原料失败", "Failed to fill ingredients");
			}
			UIRealtimeTip.Popup(message, !flag, 0);
			RefreshStationWindow(window);
		}
	}
}