Decompiled source of BattlefieldAnalysisBaseDeliver v2.1.1

BattlefieldAnalysisBaseDeliver.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BattlefieldAnalysisBaseDeliver.Patches;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[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: AssemblyCompany("YourName")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("允许配送无人机从战场分析基站直接取物品")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+ec2c33da17f4f9ae6f4c489755b4340f53b3cf92")]
[assembly: AssemblyProduct("BattlefieldAnalysisBaseDeliver")]
[assembly: AssemblyTitle("BattlefieldAnalysisBaseDeliver")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BattlefieldAnalysisBaseDeliver
{
	[BepInPlugin("un1eagle.battlefieldanalysisbasedeliver", "战场分析基站配送支持", "2.1.1")]
	public class Plugin : BaseUnityPlugin
	{
		public static ManualLogSource? Log;

		public static ConfigEntry<bool> EnableDebugLog;

		public static ConfigEntry<int> BattleBaseCourierCount;

		public static ConfigEntry<float> BattleBaseCourierSpeedMultiplier;

		public static bool DebugLog()
		{
			return EnableDebugLog?.Value ?? false;
		}

		public static int GetBattleBaseCourierCount()
		{
			int num = BattleBaseCourierCount?.Value ?? 20;
			if (num < 1)
			{
				return 1;
			}
			if (num > 200)
			{
				return 200;
			}
			return num;
		}

		public static float GetBattleBaseCourierSpeedMultiplier()
		{
			float num = BattleBaseCourierSpeedMultiplier?.Value ?? 2f;
			if (num < 0.1f)
			{
				return 0.1f;
			}
			if (num > 10f)
			{
				return 10f;
			}
			return num;
		}

		private void Awake()
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Expected O, but got Unknown
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Expected O, but got Unknown
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Expected O, but got Unknown
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Expected O, but got Unknown
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Expected O, but got Unknown
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Expected O, but got Unknown
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Expected O, but got Unknown
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_034d: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Log.LogInfo((object)"[战场分析基站配送支持] 正在加载... (GUID: un1eagle.battlefieldanalysisbasedeliver)");
			EnableDebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EnableDebugLog", false, "为 true 时在日志中输出详细的调试信息,用于排查问题。正常使用时建议设置为 false。");
			BattleBaseCourierCount = ((BaseUnityPlugin)this).Config.Bind<int>("General", "BattleBaseCourierCount", 20, new ConfigDescription("每个战场基站的无人机总数(1~200,默认 20)。修改后需重新进入存档或重新加载星球后生效。", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 200), Array.Empty<object>()));
			BattleBaseCourierSpeedMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("General", "BattleBaseCourierSpeedMultiplier", 2f, new ConfigDescription("基站无人机速度倍率(在游戏物流速度基础上的倍数,0.1~10,默认 2.0)。", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>()));
			Harmony val = new Harmony("un1eagle.battlefieldanalysisbasedeliver");
			MethodInfo methodInfo = AccessTools.Method(typeof(PlanetFactory), "Init", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(PlanetFactory_Init_Patch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ManualLogSource? log = Log;
				if (log != null)
				{
					log.LogInfo((object)"[战场分析基站配送支持] ✓ PlanetFactory.Init 补丁已应用");
				}
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(PlanetFactory), "Import", (Type[])null, (Type[])null);
			if (methodInfo2 != null)
			{
				val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(PlanetFactory_Import_Patch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ManualLogSource? log2 = Log;
				if (log2 != null)
				{
					log2.LogInfo((object)"[战场分析基站配送支持] ✓ PlanetFactory.Import 补丁已应用(清理旧虚拟配送器)");
				}
			}
			MethodInfo methodInfo3 = AccessTools.Method(typeof(PlanetFactory), "Free", (Type[])null, (Type[])null);
			if (methodInfo3 != null)
			{
				val.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(PlanetFactory_Free_Patch), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ManualLogSource? log3 = Log;
				if (log3 != null)
				{
					log3.LogInfo((object)"[战场分析基站配送支持] ✓ PlanetFactory.Free 补丁已应用");
				}
			}
			MethodInfo methodInfo4 = AccessTools.Method(typeof(BattleBaseComponent), "InternalUpdate", (Type[])null, (Type[])null);
			if (methodInfo4 != null)
			{
				val.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, new HarmonyMethod(typeof(BattleBaseComponent_InternalUpdate_Patch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ManualLogSource? log4 = Log;
				if (log4 != null)
				{
					log4.LogInfo((object)"[战场分析基站配送支持] ✓ BattleBaseComponent.InternalUpdate 补丁已应用(核心逻辑)");
				}
			}
			else
			{
				ManualLogSource? log5 = Log;
				if (log5 != null)
				{
					log5.LogWarning((object)"[战场分析基站配送支持] ⚠ 未找到 BattleBaseComponent.InternalUpdate 方法!");
				}
			}
			MethodInfo methodInfo5 = AccessTools.Method(typeof(LogisticCourierRenderer), "Update", (Type[])null, (Type[])null);
			if (methodInfo5 != null)
			{
				val.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, new HarmonyMethod(typeof(LogisticCourierRenderer_Update_Patch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ManualLogSource? log6 = Log;
				if (log6 != null)
				{
					log6.LogInfo((object)"[战场分析基站配送支持] ✓ LogisticCourierRenderer.Update 补丁已应用(无人机可见)");
				}
			}
			else
			{
				ManualLogSource? log7 = Log;
				if (log7 != null)
				{
					log7.LogWarning((object)"[战场分析基站配送支持] ⚠ 未找到 LogisticCourierRenderer.Update 方法!");
				}
			}
			MethodInfo methodInfo6 = AccessTools.Method(typeof(GameData), "Export", (Type[])null, (Type[])null);
			if (methodInfo6 != null)
			{
				val.Patch((MethodBase)methodInfo6, new HarmonyMethod(typeof(GameData_Export_Patch), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ManualLogSource? log8 = Log;
				if (log8 != null)
				{
					log8.LogInfo((object)"[战场分析基站配送支持] ✓ GameData.Export 补丁已应用(存档安全)");
				}
			}
			else
			{
				ManualLogSource? log9 = Log;
				if (log9 != null)
				{
					log9.LogWarning((object)"[战场分析基站配送支持] ⚠ 未找到 GameData.Export 方法!");
				}
			}
			MethodInfo methodInfo7 = AccessTools.Method(typeof(GameData), "Import", (Type[])null, (Type[])null);
			if (methodInfo7 != null)
			{
				val.Patch((MethodBase)methodInfo7, (HarmonyMethod)null, new HarmonyMethod(typeof(GameData_Import_Patch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ManualLogSource? log10 = Log;
				if (log10 != null)
				{
					log10.LogInfo((object)"[战场分析基站配送支持] ✓ GameData.Import 补丁已应用(自动重新派遣)");
				}
			}
			else
			{
				ManualLogSource? log11 = Log;
				if (log11 != null)
				{
					log11.LogWarning((object)"[战场分析基站配送支持] ⚠ 未找到 GameData.Import 方法!");
				}
			}
			ManualLogSource? log12 = Log;
			if (log12 != null)
			{
				log12.LogInfo((object)"[战场分析基站配送支持] ========================================");
			}
			ManualLogSource? log13 = Log;
			if (log13 != null)
			{
				log13.LogInfo((object)"[战场分析基站配送支持] ✅ 加载完成!基站直接派遣方案");
			}
			ManualLogSource? log14 = Log;
			if (log14 != null)
			{
				log14.LogInfo((object)string.Format("[{0}] \ud83d\udce6 战场基站无人机数量: {1},速度倍率: {2}(可在配置中修改)", "战场分析基站配送支持", GetBattleBaseCourierCount(), GetBattleBaseCourierSpeedMultiplier()));
			}
			ManualLogSource? log15 = Log;
			if (log15 != null)
			{
				log15.LogInfo((object)"[战场分析基站配送支持] \ud83d\ude80 无需虚拟配送器,性能优化");
			}
			ManualLogSource? log16 = Log;
			if (log16 != null)
			{
				log16.LogInfo((object)"[战场分析基站配送支持] \ud83d\udcbe 存档安全,自动兼容旧方案");
			}
			ManualLogSource? log17 = Log;
			if (log17 != null)
			{
				log17.LogInfo((object)"[战场分析基站配送支持] ========================================");
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "un1eagle.battlefieldanalysisbasedeliver";

		public const string PLUGIN_NAME = "战场分析基站配送支持";

		public const string PLUGIN_VERSION = "2.1.1";
	}
}
namespace BattlefieldAnalysisBaseDeliver.Patches
{
	[HarmonyPatch(typeof(BattleBaseComponent), "InternalUpdate")]
	public static class BattleBaseComponent_InternalUpdate_Patch
	{
		private const int STATION_ENDID_OFFSET = 20000;

		[HarmonyPostfix]
		private static void Postfix(BattleBaseComponent __instance, PlanetFactory factory)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (__instance == null || factory == null || __instance.id <= 0 || __instance.entityId <= 0)
				{
					return;
				}
				int id = __instance.id;
				BaseLogisticSystem orCreate = BattleBaseLogisticsManager.GetOrCreate(factory.planetId, id);
				UpdateCouriers(orCreate, __instance, factory);
				DispatchContext dispatchContext = BattleBaseLogisticsManager.TryGetDispatchContext(orCreate, __instance, factory, __instance.entityId);
				if (dispatchContext == null)
				{
					return;
				}
				int num = 0;
				foreach (DispenserDemand demand in dispatchContext.Demands)
				{
					if (orCreate.idleCount > 0)
					{
						if (DispatchCourier(orCreate, __instance, factory, demand, dispatchContext.BasePosition, dispatchContext.CurrentInventory))
						{
							num++;
						}
						continue;
					}
					break;
				}
				if (num > 0 && Plugin.DebugLog())
				{
					ManualLogSource? log = Plugin.Log;
					if (log != null)
					{
						log.LogInfo((object)string.Format("[{0}] \ud83d\udce6 基站[{1}] 共派遣 {2} 个无人机,剩余空闲={3}", "战场分析基站配送支持", id, num, orCreate.idleCount));
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)("[战场分析基站配送支持] BattleBaseComponent.InternalUpdate 异常: " + ex.Message + "\n" + ex.StackTrace));
				}
			}
		}

		private static bool DispatchCourier(BaseLogisticSystem logistics, BattleBaseComponent battleBase, PlanetFactory factory, DispenserDemand demand, Vector3 basePosition, Dictionary<int, int> currentInventory)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: 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_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: 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_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: 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_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: 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)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: 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)
			try
			{
				int itemId = demand.itemId;
				int num = 100;
				if (demand.IsMechaSlot && demand.needCount > 0 && demand.needCount < num)
				{
					num = demand.needCount;
				}
				int num2 = (currentInventory.ContainsKey(itemId) ? currentInventory[itemId] : 0);
				int actualCount = 0;
				int inc = 0;
				if (!TakeItemFromBase(battleBase, itemId, num, out actualCount, out inc))
				{
					return false;
				}
				if (actualCount <= 0)
				{
					return false;
				}
				int num3 = num2 - actualCount;
				Vector3 position = demand.position;
				float num4 = Vector3.Distance(basePosition, position);
				int num5 = -1;
				for (int i = 0; i < logistics.couriers.Length; i++)
				{
					if (logistics.couriers[i].maxt <= 0f)
					{
						num5 = i;
						break;
					}
				}
				if (num5 < 0)
				{
					ReturnItemToBase(battleBase, itemId, actualCount, inc);
					return false;
				}
				int endId = (demand.IsMechaSlot ? (-(demand.slotIndex + 1)) : (demand.IsStationTower ? (20000 + demand.stationId) : demand.dispenserId));
				float maxt = num4;
				Vector3 begin = basePosition;
				Vector3 end = position;
				if (demand.IsMechaSlot)
				{
					begin = basePosition;
					end = basePosition;
					maxt = 1f;
				}
				logistics.couriers[num5] = new CourierData
				{
					begin = begin,
					end = end,
					endId = endId,
					direction = 1f,
					maxt = maxt,
					t = 0f,
					itemId = itemId,
					itemCount = actualCount,
					inc = inc,
					gene = num5
				};
				logistics.idleCount--;
				logistics.workingCount++;
				if (Plugin.DebugLog())
				{
					string itemName = GetItemName(itemId);
					string text = (demand.IsMechaSlot ? $"机甲槽位[{demand.slotIndex}]" : (demand.IsStationTower ? $"物流塔[{demand.stationId}]" : $"配送器[{demand.dispenserId}]"));
					ManualLogSource? log = Plugin.Log;
					if (log != null)
					{
						log.LogInfo((object)string.Format("[{0}] \ud83d\ude80 派遣无人机: 基站[{1}] → {2} 物品={3}(ID:{4}) 派遣={5} 剩余={6} 紧急度={7:F2}", "战场分析基站配送支持", battleBase.id, text, itemName, itemId, actualCount, num3, demand.urgency));
					}
				}
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource? log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)("[战场分析基站配送支持] DispatchCourier 异常: " + ex.Message));
				}
				return false;
			}
		}

		private static void UpdateCouriers(BaseLogisticSystem logistics, BattleBaseComponent battleBase, PlanetFactory factory)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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_00ae: 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_04e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f3: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (logistics.workingCount <= 0)
				{
					return;
				}
				float logisticCourierSpeedModified = GameMain.history.logisticCourierSpeedModified;
				logisticCourierSpeedModified *= Plugin.GetBattleBaseCourierSpeedMultiplier();
				float num = logisticCourierSpeedModified * (1f / 60f);
				Vector3 pos = factory.entityPool[battleBase.entityId].pos;
				Vector3? val = ((GameMain.mainPlayer != null) ? new Vector3?(GameMain.mainPlayer.position) : null);
				for (int i = 0; i < logistics.couriers.Length; i++)
				{
					ref CourierData reference = ref logistics.couriers[i];
					if (reference.maxt <= 0f)
					{
						continue;
					}
					if (reference.endId < 0 && reference.direction > 0f && val.HasValue)
					{
						UpdateCourierToMecha(ref reference, pos, val.Value, logisticCourierSpeedModified);
					}
					else
					{
						reference.t += num * reference.direction;
					}
					if (reference.direction > 0f && reference.t >= reference.maxt)
					{
						reference.t = reference.maxt;
						bool flag;
						if (reference.endId < 0)
						{
							int num2 = -(reference.endId + 1);
							flag = DeliverToMecha(num2, reference.itemId, reference.itemCount, reference.inc);
							if (Plugin.DebugLog() && flag)
							{
								string itemName = GetItemName(reference.itemId);
								ManualLogSource? log = Plugin.Log;
								if (log != null)
								{
									log.LogInfo((object)string.Format("[{0}] \ud83d\udcec 送货成功: 机甲槽位[{1}] 物品={2}(ID:{3})x{4}", "战场分析基站配送支持", num2, itemName, reference.itemId, reference.itemCount));
								}
							}
						}
						else if (reference.endId >= 20000)
						{
							int num3 = reference.endId - 20000;
							flag = DeliverToStation(factory, num3, reference.itemId, reference.itemCount, reference.inc);
							if (Plugin.DebugLog() && flag)
							{
								string itemName2 = GetItemName(reference.itemId);
								ManualLogSource? log2 = Plugin.Log;
								if (log2 != null)
								{
									log2.LogInfo((object)string.Format("[{0}] \ud83d\udcec 送货成功: 物流塔[{1}] 物品={2}(ID:{3})x{4}", "战场分析基站配送支持", num3, itemName2, reference.itemId, reference.itemCount));
								}
							}
						}
						else
						{
							flag = DeliverToDispenser(factory, reference.endId, reference.itemId, reference.itemCount, reference.inc);
							if (Plugin.DebugLog() && flag)
							{
								string itemName3 = GetItemName(reference.itemId);
								ManualLogSource? log3 = Plugin.Log;
								if (log3 != null)
								{
									log3.LogInfo((object)string.Format("[{0}] \ud83d\udcec 送货成功: 配送器[{1}] 物品={2}(ID:{3})x{4}", "战场分析基站配送支持", reference.endId, itemName3, reference.itemId, reference.itemCount));
								}
							}
						}
						if (flag)
						{
							reference.itemId = 0;
							reference.itemCount = 0;
							reference.inc = 0;
						}
						else if (Plugin.DebugLog())
						{
							string itemName4 = GetItemName(reference.itemId);
							string text = ((reference.endId < 0) ? $"机甲槽位[{-reference.endId - 1}]" : ((reference.endId >= 20000) ? $"物流塔[{reference.endId - 20000}]" : $"配送器[{reference.endId}]"));
							ManualLogSource? log4 = Plugin.Log;
							if (log4 != null)
							{
								log4.LogWarning((object)string.Format("[{0}] ⚠\ufe0f 送货失败: {1} 物品={2}(ID:{3})x{4},将返还到基站", "战场分析基站配送支持", text, itemName4, reference.itemId, reference.itemCount));
							}
						}
						reference.direction = -1f;
					}
					else
					{
						if (!(reference.direction < 0f) || !(reference.t <= 0f))
						{
							continue;
						}
						reference.t = 0f;
						if (reference.itemId > 0 && reference.itemCount > 0)
						{
							ReturnItemToBase(battleBase, reference.itemId, reference.itemCount, reference.inc);
							if (Plugin.DebugLog())
							{
								string itemName5 = GetItemName(reference.itemId);
								ManualLogSource? log5 = Plugin.Log;
								if (log5 != null)
								{
									log5.LogInfo((object)string.Format("[{0}] \ud83d\udce6 返还物品: 基站[{1}] 物品={2}(ID:{3})x{4}", "战场分析基站配送支持", battleBase.id, itemName5, reference.itemId, reference.itemCount));
								}
							}
						}
						reference.maxt = 0f;
						reference.begin = Vector3.zero;
						reference.end = Vector3.zero;
						reference.endId = 0;
						reference.direction = 0f;
						reference.itemId = 0;
						reference.itemCount = 0;
						reference.inc = 0;
						logistics.workingCount--;
						logistics.idleCount++;
						if (Plugin.DebugLog())
						{
							ManualLogSource? log6 = Plugin.Log;
							if (log6 != null)
							{
								log6.LogInfo((object)string.Format("[{0}] \ud83c\udfe0 无人机返回: 基站[{1}] 空闲={2}", "战场分析基站配送支持", battleBase.id, logistics.idleCount));
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log7 = Plugin.Log;
				if (log7 != null)
				{
					log7.LogError((object)("[战场分析基站配送支持] UpdateCouriers 异常: " + ex.Message));
				}
			}
		}

		private static void UpdateCourierToMecha(ref CourierData courier, Vector3 basePos, Vector3 playerPos, float courierSpeed)
		{
			//IL_0001: 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)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: 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_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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_0089: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: 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_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: 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)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: 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_0111: 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)
			//IL_011e: 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_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: 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_014f: 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_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: 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_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: 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_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: 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_02c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_031f: Unknown result type (might be due to invalid IL or missing references)
			Vector3 end = courier.end;
			float num = playerPos.x - end.x;
			float num2 = playerPos.y - end.y;
			float num3 = playerPos.z - end.z;
			float num4 = (float)Math.Sqrt(num * num + num2 * num2 + num3 * num3);
			float num5 = (float)Math.Sqrt((playerPos.x - basePos.x) * (playerPos.x - basePos.x) + (playerPos.y - basePos.y) * (playerPos.y - basePos.y) + (playerPos.z - basePos.z) * (playerPos.z - basePos.z));
			float num6 = (float)Math.Sqrt(end.x * end.x + end.y * end.y + end.z * end.z);
			float num7 = (float)Math.Sqrt(playerPos.x * playerPos.x + playerPos.y * playerPos.y + playerPos.z * playerPos.z);
			if (num4 < 1.4f)
			{
				double num8 = Math.Sqrt(basePos.x * basePos.x + basePos.y * basePos.y + basePos.z * basePos.z);
				double num9 = Math.Sqrt(playerPos.x * playerPos.x + playerPos.y * playerPos.y + playerPos.z * playerPos.z);
				double num10 = (double)(basePos.x * playerPos.x + basePos.y * playerPos.y + basePos.z * playerPos.z) / (num8 * num9);
				if (num10 < -1.0)
				{
					num10 = -1.0;
				}
				else if (num10 > 1.0)
				{
					num10 = 1.0;
				}
				courier.begin = basePos;
				courier.maxt = (float)(Math.Acos(num10) * ((num8 + num9) * 0.5));
				courier.maxt = (float)Math.Sqrt((double)(courier.maxt * courier.maxt) + (num8 - num9) * (num8 - num9));
				courier.t = courier.maxt;
				return;
			}
			courier.begin = end;
			float num11 = courierSpeed * (1f / 60f) / num4;
			if (num11 > 1f)
			{
				num11 = 1f;
			}
			float num12 = num * num11;
			float num13 = num2 * num11;
			float num14 = num3 * num11;
			float num15 = num4 / courierSpeed;
			if (num15 < 0.03333333f)
			{
				num15 = 0.03333333f;
			}
			float num16 = (num7 - num6) / num15 * (1f / 60f);
			end.x += num12;
			end.y += num13;
			end.z += num14;
			float num17 = (float)Math.Sqrt(end.x * end.x + end.y * end.y + end.z * end.z);
			if (num17 > 1E-05f)
			{
				float num18 = (num6 + num16) / num17;
				end.x *= num18;
				end.y *= num18;
				end.z *= num18;
			}
			courier.end = end;
			if (num5 > courier.maxt)
			{
				courier.maxt = num5;
			}
			courier.t = num4;
			if (courier.t >= courier.maxt * 0.99f)
			{
				courier.t = courier.maxt * 0.99f;
			}
		}

		private static bool TakeItemFromBase(BattleBaseComponent battleBase, int itemId, int maxCount, out int actualCount, out int inc)
		{
			actualCount = 0;
			inc = 0;
			try
			{
				if (battleBase.storage == null)
				{
					return false;
				}
				MethodInfo method = ((object)battleBase.storage).GetType().GetMethod("TakeItem", BindingFlags.Instance | BindingFlags.Public);
				if (method == null)
				{
					return false;
				}
				object[] array = new object[3] { itemId, maxCount, 0 };
				object obj = method.Invoke(battleBase.storage, array);
				if (obj == null)
				{
					return false;
				}
				actualCount = (int)obj;
				inc = (int)array[2];
				return actualCount > 0;
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] TakeItemFromBase 异常: " + ex.Message));
				}
				return false;
			}
		}

		private static void ReturnItemToBase(BattleBaseComponent battleBase, int itemId, int count, int inc)
		{
			try
			{
				if (battleBase.storage != null)
				{
					MethodInfo method = ((object)battleBase.storage).GetType().GetMethod("AddItem", BindingFlags.Instance | BindingFlags.Public, null, new Type[5]
					{
						typeof(int),
						typeof(int),
						typeof(int),
						typeof(int).MakeByRefType(),
						typeof(bool)
					}, null);
					if (!(method == null))
					{
						object[] parameters = new object[5] { itemId, count, inc, 0, false };
						method.Invoke(battleBase.storage, parameters);
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] ReturnItemToBase 异常: " + ex.Message));
				}
			}
		}

		private static bool DeliverToMecha(int slotIndex, int itemId, int count, int inc)
		{
			try
			{
				Player mainPlayer = GameMain.mainPlayer;
				if (((mainPlayer != null) ? mainPlayer.packageUtility : null) == null)
				{
					return false;
				}
				if (itemId <= 0 || count <= 0 || itemId == 1099)
				{
					return false;
				}
				int num = default(int);
				int num2 = mainPlayer.packageUtility.AddItemToAllPackages(itemId, count, slotIndex, inc, ref num, 0);
				if (num2 > 0)
				{
					mainPlayer.NotifyReplenishPreferred(itemId, num2);
					return true;
				}
				return false;
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] DeliverToMecha 异常: " + ex.Message + "\n" + ex.StackTrace));
				}
				return false;
			}
		}

		private static bool DeliverToStation(PlanetFactory factory, int stationId, int itemId, int count, int inc)
		{
			try
			{
				if (factory?.transport == null)
				{
					return false;
				}
				if (stationId <= 0)
				{
					return false;
				}
				StationComponent stationComponent = factory.transport.GetStationComponent(stationId);
				if (stationComponent == null || stationComponent.id != stationId)
				{
					return false;
				}
				return stationComponent.AddItem(itemId, count, inc) > 0;
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] DeliverToStation 异常: " + ex.Message + "\n" + ex.StackTrace));
				}
				return false;
			}
		}

		private static bool DeliverToDispenser(PlanetFactory factory, int dispenserId, int itemId, int count, int inc)
		{
			try
			{
				if (factory?.transport == null)
				{
					if (Plugin.DebugLog())
					{
						ManualLogSource? log = Plugin.Log;
						if (log != null)
						{
							log.LogWarning((object)"[战场分析基站配送支持] 送货失败: factory.transport 为 null");
						}
					}
					return false;
				}
				FieldInfo field = ((object)factory.transport).GetType().GetField("dispenserPool", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field == null)
				{
					if (Plugin.DebugLog())
					{
						ManualLogSource? log2 = Plugin.Log;
						if (log2 != null)
						{
							log2.LogWarning((object)"[战场分析基站配送支持] 送货失败: dispenserPoolField 为 null");
						}
					}
					return false;
				}
				Array array = field.GetValue(factory.transport) as Array;
				if (array == null || dispenserId <= 0 || dispenserId >= array.Length)
				{
					if (Plugin.DebugLog())
					{
						ManualLogSource? log3 = Plugin.Log;
						if (log3 != null)
						{
							log3.LogWarning((object)string.Format("[{0}] 送货失败: dispenserId={1} 无效(范围: 1-{2})", "战场分析基站配送支持", dispenserId, array?.Length ?? 0));
						}
					}
					return false;
				}
				object? value = array.GetValue(dispenserId);
				DispenserComponent val = (DispenserComponent)((value is DispenserComponent) ? value : null);
				if (val == null || val.id != dispenserId)
				{
					if (Plugin.DebugLog())
					{
						ManualLogSource? log4 = Plugin.Log;
						if (log4 != null)
						{
							log4.LogWarning((object)string.Format("[{0}] 送货失败: dispenser[{1}] 为 null 或 id 不匹配", "战场分析基站配送支持", dispenserId));
						}
					}
					return false;
				}
				if (val.storage?.bottomStorage == null)
				{
					if (Plugin.DebugLog())
					{
						ManualLogSource? log5 = Plugin.Log;
						if (log5 != null)
						{
							log5.LogWarning((object)string.Format("[{0}] 送货失败: dispenser[{1}].storage.bottomStorage 为 null", "战场分析基站配送支持", dispenserId));
						}
					}
					return false;
				}
				FieldInfo field2 = ((object)val.storage.bottomStorage).GetType().GetField("id");
				if (field2 == null)
				{
					if (Plugin.DebugLog())
					{
						ManualLogSource? log6 = Plugin.Log;
						if (log6 != null)
						{
							log6.LogWarning((object)"[战场分析基站配送支持] 送货失败: storageIdField 为 null");
						}
					}
					return false;
				}
				int num = (int)field2.GetValue(val.storage.bottomStorage);
				int num2 = default(int);
				int num3 = factory.InsertIntoStorage(num, itemId, count, inc, ref num2, true);
				int num4 = count - num3;
				if (num4 > 0)
				{
					FieldInfo field3 = ((object)val).GetType().GetField("holdupPackage", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					FieldInfo field4 = ((object)val).GetType().GetField("holdupItemCount", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (field3 != null && field4 != null)
					{
						Array array2 = field3.GetValue(val) as Array;
						int num5 = (int)field4.GetValue(val);
						if (array2 != null && num5 < array2.Length)
						{
							bool flag = false;
							for (int i = 0; i < num5; i++)
							{
								object value2 = array2.GetValue(i);
								if (value2 == null)
								{
									continue;
								}
								FieldInfo field5 = value2.GetType().GetField("itemId");
								if (!(field5 != null) || (int)field5.GetValue(value2) != itemId)
								{
									continue;
								}
								FieldInfo field6 = value2.GetType().GetField("count");
								FieldInfo field7 = value2.GetType().GetField("inc");
								if (!(field6 != null) || !(field7 != null))
								{
									continue;
								}
								int num6 = (int)field6.GetValue(value2);
								int num7 = (int)field7.GetValue(value2);
								field6.SetValue(value2, num6 + num4);
								field7.SetValue(value2, num7 + num2);
								array2.SetValue(value2, i);
								flag = true;
								if (Plugin.DebugLog())
								{
									string itemName = GetItemName(itemId);
									ManualLogSource? log7 = Plugin.Log;
									if (log7 != null)
									{
										log7.LogInfo((object)string.Format("[{0}] \ud83d\udce6 送货到缓存区: 配送器[{1}] 物品={2}(ID:{3}) 直接插入={4} 缓存={5}", "战场分析基站配送支持", dispenserId, itemName, itemId, num3, num4));
									}
								}
								break;
							}
							if (!flag)
							{
								Type elementType = array2.GetType().GetElementType();
								if (elementType != null)
								{
									object obj = Activator.CreateInstance(elementType);
									FieldInfo field8 = obj.GetType().GetField("itemId");
									FieldInfo field9 = obj.GetType().GetField("count");
									FieldInfo field10 = obj.GetType().GetField("inc");
									if (field8 != null && field9 != null && field10 != null)
									{
										field8.SetValue(obj, itemId);
										field9.SetValue(obj, num4);
										field10.SetValue(obj, num2);
										array2.SetValue(obj, num5);
										field4.SetValue(val, num5 + 1);
										if (Plugin.DebugLog())
										{
											string itemName2 = GetItemName(itemId);
											ManualLogSource? log8 = Plugin.Log;
											if (log8 != null)
											{
												log8.LogInfo((object)string.Format("[{0}] \ud83d\udce6 送货到缓存区(新增): 配送器[{1}] 物品={2}(ID:{3}) 直接插入={4} 缓存={5}", "战场分析基站配送支持", dispenserId, itemName2, itemId, num3, num4));
											}
										}
									}
								}
							}
						}
					}
				}
				else if (Plugin.DebugLog())
				{
					string itemName3 = GetItemName(itemId);
					ManualLogSource? log9 = Plugin.Log;
					if (log9 != null)
					{
						log9.LogInfo((object)string.Format("[{0}] \ud83d\udcec 送货成功(直接插入): 配送器[{1}] 物品={2}(ID:{3})x{4}", "战场分析基站配送支持", dispenserId, itemName3, itemId, count));
					}
				}
				val.pulseSignal = 2;
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource? log10 = Plugin.Log;
				if (log10 != null)
				{
					log10.LogError((object)("[战场分析基站配送支持] DeliverToDispenser 异常: " + ex.Message + "\n" + ex.StackTrace));
				}
				return false;
			}
		}

		private static string GetItemName(int itemId)
		{
			try
			{
				ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(itemId);
				if (val != null && !string.IsNullOrEmpty(((Proto)val).name))
				{
					return Localization.Translate(((Proto)val).name);
				}
			}
			catch
			{
			}
			return $"item_{itemId}";
		}
	}
	public class BaseLogisticSystem
	{
		public int battleBaseId;

		public int planetId;

		public CourierData[] couriers = (CourierData[])(object)new CourierData[20];

		public int idleCount = 20;

		public int workingCount;

		public Dictionary<int, int> lastInventory = new Dictionary<int, int>();

		public int cooldownCounter;

		public const int DISPATCH_INTERVAL = 60;

		public int CourierCapacity
		{
			get
			{
				CourierData[] array = couriers;
				if (array == null)
				{
					return 0;
				}
				return array.Length;
			}
		}
	}
	public class DispenserDemand
	{
		public int dispenserId;

		public int entityId;

		public int storageId;

		public int itemId;

		public int currentStock;

		public int maxStock;

		public float urgency;

		public Vector3 position;

		public float distance;

		public bool IsMechaSlot;

		public int slotIndex;

		public int needCount;

		public bool IsStationTower;

		public int stationId;
	}
	public class DispatchContext
	{
		public List<DispenserDemand> Demands;

		public Dictionary<int, int> CurrentInventory;

		public Vector3 BasePosition;

		public DispatchContext(List<DispenserDemand> demands, Dictionary<int, int> currentInventory, Vector3 basePosition)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			Demands = demands;
			CurrentInventory = currentInventory;
			BasePosition = basePosition;
		}
	}
	public static class BattleBaseLogisticsManager
	{
		private static Dictionary<int, Dictionary<int, BaseLogisticSystem>> _systems = new Dictionary<int, Dictionary<int, BaseLogisticSystem>>();

		private static object _lock = new object();

		public static BaseLogisticSystem GetOrCreate(int planetId, int battleBaseId)
		{
			lock (_lock)
			{
				if (!_systems.ContainsKey(planetId))
				{
					_systems[planetId] = new Dictionary<int, BaseLogisticSystem>();
				}
				if (!_systems[planetId].ContainsKey(battleBaseId))
				{
					int battleBaseCourierCount = Plugin.GetBattleBaseCourierCount();
					_systems[planetId][battleBaseId] = new BaseLogisticSystem
					{
						battleBaseId = battleBaseId,
						planetId = planetId,
						couriers = (CourierData[])(object)new CourierData[battleBaseCourierCount],
						idleCount = battleBaseCourierCount,
						workingCount = 0
					};
				}
				return _systems[planetId][battleBaseId];
			}
		}

		public static IEnumerable<BaseLogisticSystem> GetAllForPlanet(int planetId)
		{
			lock (_lock)
			{
				if (_systems.TryGetValue(planetId, out Dictionary<int, BaseLogisticSystem> value))
				{
					return value.Values.ToList();
				}
				return Enumerable.Empty<BaseLogisticSystem>();
			}
		}

		public static void Clear(int planetId)
		{
			lock (_lock)
			{
				_systems.Remove(planetId);
				if (Plugin.DebugLog())
				{
					ManualLogSource? log = Plugin.Log;
					if (log != null)
					{
						log.LogInfo((object)string.Format("[{0}] 清理基站物流系统:行星[{1}]", "战场分析基站配送支持", planetId));
					}
				}
			}
		}

		public static void ClearAll()
		{
			lock (_lock)
			{
				_systems.Clear();
				if (Plugin.DebugLog())
				{
					ManualLogSource? log = Plugin.Log;
					if (log != null)
					{
						log.LogInfo((object)"[战场分析基站配送支持] 清理所有基站物流系统");
					}
				}
			}
		}

		public static bool HasInventoryChanged(BaseLogisticSystem logistics, Dictionary<int, int> currentInventory)
		{
			if (logistics.lastInventory.Count != currentInventory.Count)
			{
				return true;
			}
			foreach (KeyValuePair<int, int> item in currentInventory)
			{
				if (!logistics.lastInventory.TryGetValue(item.Key, out var value) || value != item.Value)
				{
					return true;
				}
			}
			return false;
		}

		public static List<DispenserDemand> ScanDispenserDemands(PlanetFactory factory, Vector3 basePosition, Dictionary<int, int> baseInventory)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Invalid comparison between Unknown and I4
			//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_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: 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_0171: 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_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			List<DispenserDemand> list = new List<DispenserDemand>();
			try
			{
				if (factory == null)
				{
					return list;
				}
				PlanetTransport transport = factory.transport;
				if (transport == null)
				{
					return list;
				}
				FieldInfo field = ((object)transport).GetType().GetField("dispenserPool", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				FieldInfo field2 = ((object)transport).GetType().GetField("dispenserCursor", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field == null || field2 == null)
				{
					return list;
				}
				Array array = field.GetValue(transport) as Array;
				object value = field2.GetValue(transport);
				if (array == null || value == null)
				{
					return list;
				}
				int num = Convert.ToInt32(value);
				for (int i = 1; i < num && i < array.Length; i++)
				{
					object value2 = array.GetValue(i);
					if (value2 == null)
					{
						continue;
					}
					DispenserComponent val = (DispenserComponent)((value2 is DispenserComponent) ? value2 : null);
					if (val == null || val.id != i || (int)val.storageMode != 2 || val.filter <= 0 || !baseInventory.ContainsKey(val.filter) || baseInventory[val.filter] <= 0)
					{
						continue;
					}
					int dispenserStock = GetDispenserStock(val, val.filter);
					int dispenserMaxStock = GetDispenserMaxStock(val);
					if (dispenserMaxStock > 0 && (float)dispenserStock / (float)dispenserMaxStock > 0.8f)
					{
						continue;
					}
					Vector3 val2 = Vector3.zero;
					EntityData[] entityPool = factory.entityPool;
					if (val.entityId > 0 && entityPool != null && val.entityId < entityPool.Length)
					{
						EntityData val3 = entityPool[val.entityId];
						if (val3.id > 0)
						{
							val2 = val3.pos;
						}
					}
					float distance = Vector3.Distance(basePosition, val2);
					float urgency = ((dispenserMaxStock > 0) ? ((float)dispenserStock / (float)dispenserMaxStock) : 1f);
					int storageId = 0;
					if (val.storage?.bottomStorage != null)
					{
						FieldInfo field3 = ((object)val.storage.bottomStorage).GetType().GetField("id");
						if (field3 != null)
						{
							storageId = (int)field3.GetValue(val.storage.bottomStorage);
						}
					}
					list.Add(new DispenserDemand
					{
						dispenserId = val.id,
						entityId = val.entityId,
						storageId = storageId,
						itemId = val.filter,
						currentStock = dispenserStock,
						maxStock = dispenserMaxStock,
						urgency = urgency,
						position = val2,
						distance = distance
					});
				}
				list.Sort(delegate(DispenserDemand a, DispenserDemand b)
				{
					int num2 = a.urgency.CompareTo(b.urgency);
					return (num2 != 0) ? num2 : a.distance.CompareTo(b.distance);
				});
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] ScanDispenserDemands 异常: " + ex.Message));
				}
			}
			return list;
		}

		public static List<DispenserDemand> ScanStationDemands(PlanetFactory factory, Vector3 basePosition, Dictionary<int, int> baseInventory)
		{
			//IL_0090: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: 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_00ac: Invalid comparison between Unknown and I4
			//IL_00b1: 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_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: 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_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: 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_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: 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_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//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)
			List<DispenserDemand> list = new List<DispenserDemand>();
			try
			{
				if (factory == null)
				{
					return list;
				}
				PlanetTransport transport = factory.transport;
				if (transport == null)
				{
					return list;
				}
				StationComponent[] stationPool = transport.stationPool;
				if (stationPool == null)
				{
					return list;
				}
				int stationCursor = transport.stationCursor;
				EntityData[] entityPool = factory.entityPool;
				if (entityPool == null)
				{
					return list;
				}
				for (int i = 1; i < stationCursor && i < stationPool.Length; i++)
				{
					StationComponent val = stationPool[i];
					if (val == null || val.id != i || val.storage == null)
					{
						continue;
					}
					for (int j = 0; j < val.storage.Length; j++)
					{
						StationStore val2 = val.storage[j];
						if (val2.itemId <= 0 || (int)val2.localLogic != 2)
						{
							continue;
						}
						int num = val2.count + val2.localOrder;
						if (num >= val2.max || val2.max - num <= 0 || !baseInventory.ContainsKey(val2.itemId) || baseInventory[val2.itemId] <= 0)
						{
							continue;
						}
						Vector3 val3 = Vector3.zero;
						if (val.entityId > 0 && val.entityId < entityPool.Length)
						{
							EntityData val4 = entityPool[val.entityId];
							if (val4.id > 0)
							{
								val3 = val4.pos;
							}
						}
						float distance = Vector3.Distance(basePosition, val3);
						float urgency = ((val2.max > 0) ? ((float)num / (float)val2.max) : 1f);
						list.Add(new DispenserDemand
						{
							IsStationTower = true,
							stationId = val.id,
							dispenserId = 0,
							entityId = val.entityId,
							storageId = 0,
							itemId = val2.itemId,
							currentStock = num,
							maxStock = val2.max,
							urgency = urgency,
							position = val3,
							distance = distance
						});
					}
				}
				list.Sort(delegate(DispenserDemand a, DispenserDemand b)
				{
					int num2 = a.urgency.CompareTo(b.urgency);
					return (num2 != 0) ? num2 : a.distance.CompareTo(b.distance);
				});
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] ScanStationDemands 异常: " + ex.Message));
				}
			}
			return list;
		}

		public static List<DispenserDemand> ScanMechaDemands(PlanetFactory factory, Vector3 basePosition, Dictionary<int, int> baseInventory)
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: 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_01fd: Unknown result type (might be due to invalid IL or missing references)
			List<DispenserDemand> list = new List<DispenserDemand>();
			try
			{
				if (factory == null)
				{
					return list;
				}
				Player mainPlayer = GameMain.mainPlayer;
				if (mainPlayer == null || !mainPlayer.isAlive || mainPlayer.sailing)
				{
					return list;
				}
				DeliveryPackage deliveryPackage = mainPlayer.deliveryPackage;
				PlayerPackageUtility packageUtility = mainPlayer.packageUtility;
				if (deliveryPackage == null || packageUtility == null)
				{
					return list;
				}
				if (!deliveryPackage.unlockedAndEnabled)
				{
					return list;
				}
				PlanetData planet = factory.planet;
				if (planet == null || GameMain.localPlanet != planet || !planet.loaded || !planet.factoryLoaded)
				{
					return list;
				}
				GRID[] grids = deliveryPackage.grids;
				if (grids == null)
				{
					return list;
				}
				Vector3 position = mainPlayer.position;
				if (((Vector3)(ref position)).sqrMagnitude < 0.01f)
				{
					return list;
				}
				float distance = Vector3.Distance(basePosition, position);
				for (int i = 0; i < deliveryPackage.gridLength; i++)
				{
					if (!deliveryPackage.IsGridActive(i) || grids[i].itemId <= 0)
					{
						continue;
					}
					int itemId = grids[i].itemId;
					if (itemId == 1099 || !baseInventory.ContainsKey(itemId) || baseInventory[itemId] <= 0)
					{
						continue;
					}
					int num = grids[i].count + packageUtility.GetPackageItemCountIncludeHandItem(itemId);
					int clampedRequireCount = ((GRID)(ref grids[i])).clampedRequireCount;
					if (num < clampedRequireCount && ((GRID)(ref grids[i])).stackSizeModified - grids[i].count + packageUtility.GetPackageItemCapacity(itemId) > 0)
					{
						int num2 = clampedRequireCount - num;
						if (num2 > 0)
						{
							float urgency = ((clampedRequireCount > 0) ? ((float)num / (float)clampedRequireCount) : 1f);
							list.Add(new DispenserDemand
							{
								IsMechaSlot = true,
								slotIndex = i,
								needCount = num2,
								dispenserId = 0,
								entityId = 0,
								storageId = 0,
								itemId = itemId,
								currentStock = num,
								maxStock = clampedRequireCount,
								urgency = urgency,
								position = position,
								distance = distance
							});
						}
					}
				}
				list.Sort(delegate(DispenserDemand a, DispenserDemand b)
				{
					int num3 = a.urgency.CompareTo(b.urgency);
					return (num3 != 0) ? num3 : a.distance.CompareTo(b.distance);
				});
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] ScanMechaDemands 异常: " + ex.Message));
				}
			}
			return list;
		}

		public static DispatchContext? TryGetDispatchContext(BaseLogisticSystem logistics, object battleBase, PlanetFactory factory, int entityId)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if (logistics == null || battleBase == null || factory == null)
			{
				return null;
			}
			logistics.cooldownCounter++;
			if (logistics.cooldownCounter < 60)
			{
				return null;
			}
			logistics.cooldownCounter = 0;
			Dictionary<int, int> baseInventory = GetBaseInventory(battleBase);
			if (!HasInventoryChanged(logistics, baseInventory) && (logistics.idleCount <= 0 || baseInventory.Count == 0))
			{
				return null;
			}
			if (logistics.idleCount <= 0)
			{
				return null;
			}
			Vector3 basePosition = Vector3.zero;
			if (entityId >= 0 && factory.entityPool != null && entityId < factory.entityPool.Length)
			{
				basePosition = factory.entityPool[entityId].pos;
			}
			List<DispenserDemand> list = ScanMechaDemands(factory, basePosition, baseInventory);
			List<DispenserDemand> list2 = ScanStationDemands(factory, basePosition, baseInventory);
			List<DispenserDemand> list3 = ScanDispenserDemands(factory, basePosition, baseInventory);
			List<DispenserDemand> list4 = new List<DispenserDemand>(list.Count + list2.Count + list3.Count);
			list4.AddRange(list);
			list4.AddRange(list2);
			list4.AddRange(list3);
			list4.Sort(delegate(DispenserDemand a, DispenserDemand b)
			{
				int num = ((!a.IsMechaSlot) ? (a.IsStationTower ? 1 : 2) : 0);
				int value = ((!b.IsMechaSlot) ? (b.IsStationTower ? 1 : 2) : 0);
				int num2 = num.CompareTo(value);
				if (num2 != 0)
				{
					return num2;
				}
				int num3 = a.urgency.CompareTo(b.urgency);
				return (num3 != 0) ? num3 : a.distance.CompareTo(b.distance);
			});
			if (list4.Count == 0)
			{
				logistics.lastInventory = new Dictionary<int, int>(baseInventory);
				return null;
			}
			return new DispatchContext(list4, baseInventory, basePosition);
		}

		private static int GetDispenserStock(DispenserComponent dispenser, int itemId)
		{
			try
			{
				if (dispenser.storage?.bottomStorage == null)
				{
					return 0;
				}
				StorageComponent bottomStorage = dispenser.storage.bottomStorage;
				if (!(((object)bottomStorage).GetType().GetField("grids")?.GetValue(bottomStorage) is Array array))
				{
					return 0;
				}
				int num = 0;
				for (int i = 0; i < array.Length; i++)
				{
					object value = array.GetValue(i);
					if (value != null)
					{
						FieldInfo field = value.GetType().GetField("itemId");
						FieldInfo field2 = value.GetType().GetField("count");
						int num2 = ((field != null) ? ((int)field.GetValue(value)) : 0);
						int num3 = ((field2 != null) ? ((int)field2.GetValue(value)) : 0);
						if (num2 == itemId)
						{
							num += num3;
						}
					}
				}
				return num;
			}
			catch
			{
				return 0;
			}
		}

		private static int GetDispenserMaxStock(DispenserComponent dispenser)
		{
			try
			{
				if (dispenser.storage?.bottomStorage == null)
				{
					return 0;
				}
				StorageComponent bottomStorage = dispenser.storage.bottomStorage;
				if (!(((object)bottomStorage).GetType().GetField("grids")?.GetValue(bottomStorage) is Array array))
				{
					return 0;
				}
				return array.Length * 1000;
			}
			catch
			{
				return 0;
			}
		}

		public static Dictionary<int, int> GetBaseInventory(object battleBase)
		{
			Dictionary<int, int> dictionary = new Dictionary<int, int>();
			try
			{
				object obj = battleBase.GetType().GetField("storage")?.GetValue(battleBase);
				if (obj == null)
				{
					return dictionary;
				}
				if (!(obj.GetType().GetField("grids")?.GetValue(obj) is Array array))
				{
					return dictionary;
				}
				for (int i = 0; i < array.Length; i++)
				{
					object value = array.GetValue(i);
					if (value == null)
					{
						continue;
					}
					FieldInfo field = value.GetType().GetField("itemId");
					FieldInfo field2 = value.GetType().GetField("count");
					int num = ((field != null) ? ((int)field.GetValue(value)) : 0);
					int num2 = ((field2 != null) ? ((int)field2.GetValue(value)) : 0);
					if (num > 0 && num2 > 0)
					{
						if (!dictionary.ContainsKey(num))
						{
							dictionary[num] = 0;
						}
						dictionary[num] += num2;
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] GetBaseInventory 异常: " + ex.Message));
				}
			}
			return dictionary;
		}
	}
	[HarmonyPatch(typeof(GameData), "Export")]
	public static class GameData_Export_Patch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: 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)
			try
			{
				if (Plugin.DebugLog())
				{
					ManualLogSource? log = Plugin.Log;
					if (log != null)
					{
						log.LogInfo((object)"[战场分析基站配送支持] \ud83d\udcbe 存档开始:返还所有基站在途物品");
					}
				}
				int num = 0;
				int num2 = 0;
				if (GameMain.data?.factories == null)
				{
					return;
				}
				PlanetFactory[] factories = GameMain.data.factories;
				foreach (PlanetFactory val in factories)
				{
					if (val == null)
					{
						continue;
					}
					foreach (BaseLogisticSystem item in BattleBaseLogisticsManager.GetAllForPlanet(val.planetId))
					{
						if (item.couriers == null)
						{
							continue;
						}
						for (int j = 0; j < item.couriers.Length; j++)
						{
							ref CourierData reference = ref item.couriers[j];
							if (reference.maxt <= 0f)
							{
								continue;
							}
							num2++;
							bool flag = false;
							if (reference.itemId > 0 && reference.itemCount > 0)
							{
								if (ReturnItemToBase(val, item.battleBaseId, reference.itemId, reference.itemCount, reference.inc))
								{
									num++;
									flag = true;
									if (Plugin.DebugLog())
									{
										string itemName = GetItemName(reference.itemId);
										ManualLogSource? log2 = Plugin.Log;
										if (log2 != null)
										{
											log2.LogInfo((object)string.Format("[{0}] \ud83d\udce6 返还物品: 基站[{1}] 物品={2}(ID:{3})x{4}", "战场分析基站配送支持", item.battleBaseId, itemName, reference.itemId, reference.itemCount));
										}
									}
								}
								else
								{
									ManualLogSource? log3 = Plugin.Log;
									if (log3 != null)
									{
										log3.LogWarning((object)string.Format("[{0}] ⚠\ufe0f 存档返还失败: 基站[{1}] 物品(ID:{2})x{3} 未写入基站,可能丢失", "战场分析基站配送支持", item.battleBaseId, reference.itemId, reference.itemCount));
									}
								}
							}
							reference.maxt = 0f;
							reference.begin = Vector3.zero;
							reference.end = Vector3.zero;
							reference.endId = 0;
							reference.direction = 0f;
							reference.t = 0f;
							if (reference.itemId <= 0 || reference.itemCount <= 0 || flag)
							{
								reference.itemId = 0;
								reference.itemCount = 0;
								reference.inc = 0;
							}
						}
						item.workingCount = 0;
						CourierData[] couriers = item.couriers;
						item.idleCount = ((couriers != null) ? couriers.Length : 20);
					}
				}
				if (Plugin.DebugLog())
				{
					ManualLogSource? log4 = Plugin.Log;
					if (log4 != null)
					{
						log4.LogInfo((object)string.Format("[{0}] ✅ 存档准备完成:回收 {1} 个无人机,返还 {2} 批物品", "战场分析基站配送支持", num2, num));
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log5 = Plugin.Log;
				if (log5 != null)
				{
					log5.LogError((object)("[战场分析基站配送支持] GameData.Export Prefix 异常: " + ex.Message));
				}
			}
		}

		private static bool ReturnItemToBase(PlanetFactory factory, int battleBaseId, int itemId, int count, int inc)
		{
			try
			{
				DefenseSystem val = factory?.defenseSystem;
				if (val == null)
				{
					return false;
				}
				FieldInfo field = ((object)val).GetType().GetField("battleBases", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field == null)
				{
					return false;
				}
				object value = field.GetValue(val);
				if (value == null)
				{
					return false;
				}
				FieldInfo field2 = value.GetType().GetField("buffer", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field2 == null)
				{
					return false;
				}
				if (!(field2.GetValue(value) is Array array) || battleBaseId <= 0 || battleBaseId >= array.Length)
				{
					return false;
				}
				object value2 = array.GetValue(battleBaseId);
				if (value2 == null)
				{
					return false;
				}
				object obj = value2.GetType().GetField("storage")?.GetValue(value2);
				if (obj == null)
				{
					return false;
				}
				MethodInfo method = obj.GetType().GetMethod("AddItem", BindingFlags.Instance | BindingFlags.Public, null, new Type[5]
				{
					typeof(int),
					typeof(int),
					typeof(int),
					typeof(int).MakeByRefType(),
					typeof(bool)
				}, null);
				if (method == null)
				{
					return false;
				}
				object[] parameters = new object[5] { itemId, count, inc, 0, false };
				method.Invoke(obj, parameters);
				return true;
			}
			catch
			{
				return false;
			}
		}

		private static string GetItemName(int itemId)
		{
			try
			{
				ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(itemId);
				if (val != null && !string.IsNullOrEmpty(((Proto)val).name))
				{
					return Localization.Translate(((Proto)val).name);
				}
			}
			catch
			{
			}
			return $"item_{itemId}";
		}
	}
	[HarmonyPatch(typeof(GameData), "Import")]
	public static class GameData_Import_Patch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			try
			{
				if (Plugin.DebugLog())
				{
					ManualLogSource? log = Plugin.Log;
					if (log != null)
					{
						log.LogInfo((object)"[战场分析基站配送支持] \ud83d\udcc2 存档加载完成:基站将自动重新派遣无人机");
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)("[战场分析基站配送支持] GameData.Import Postfix 异常: " + ex.Message));
				}
			}
		}

		private static string GetItemName(int itemId)
		{
			try
			{
				ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(itemId);
				if (val != null && !string.IsNullOrEmpty(((Proto)val).name))
				{
					return Localization.Translate(((Proto)val).name);
				}
			}
			catch
			{
			}
			return $"item_{itemId}";
		}
	}
	[HarmonyPatch(typeof(LogisticCourierRenderer), "Update")]
	public static class LogisticCourierRenderer_Update_Patch
	{
		[HarmonyPostfix]
		private static void Postfix(LogisticCourierRenderer __instance)
		{
			//IL_01cf: 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)
			try
			{
				if (__instance == null)
				{
					return;
				}
				FieldInfo field = typeof(LogisticCourierRenderer).GetField("transport", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field == null)
				{
					return;
				}
				object? value = field.GetValue(__instance);
				PlanetTransport val = (PlanetTransport)((value is PlanetTransport) ? value : null);
				if (val?.factory == null)
				{
					return;
				}
				int planetId = val.factory.planetId;
				FieldInfo field2 = typeof(LogisticCourierRenderer).GetField("courierCount", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field2 == null)
				{
					return;
				}
				int num = (int)field2.GetValue(__instance);
				FieldInfo field3 = typeof(LogisticCourierRenderer).GetField("couriersArr", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field3 == null)
				{
					return;
				}
				CourierData[] array = field3.GetValue(__instance) as CourierData[];
				IEnumerable<BaseLogisticSystem> allForPlanet = BattleBaseLogisticsManager.GetAllForPlanet(planetId);
				if (array == null)
				{
					bool flag = false;
					foreach (BaseLogisticSystem item in allForPlanet)
					{
						for (int i = 0; i < item.couriers.Length; i++)
						{
							if (item.couriers[i].maxt > 0f)
							{
								flag = true;
								break;
							}
						}
						if (flag)
						{
							break;
						}
					}
					if (!flag)
					{
						return;
					}
					ExpandCouriersArray(__instance);
					array = field3.GetValue(__instance) as CourierData[];
					if (array == null)
					{
						return;
					}
				}
				int num2 = 0;
				foreach (BaseLogisticSystem item2 in allForPlanet)
				{
					for (int j = 0; j < item2.couriers.Length; j++)
					{
						ref CourierData reference = ref item2.couriers[j];
						if (reference.maxt <= 0f)
						{
							continue;
						}
						num2++;
						if (array == null || num >= array.Length)
						{
							ExpandCouriersArray(__instance);
							array = field3.GetValue(__instance) as CourierData[];
							if (array == null)
							{
								break;
							}
						}
						array[num] = reference;
						num++;
					}
				}
				field2.SetValue(__instance, num);
				UpdateBuffer(__instance, num);
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] LogisticCourierRenderer.Update Postfix 异常: " + ex.Message));
				}
			}
		}

		private static void ExpandCouriersArray(LogisticCourierRenderer renderer)
		{
			try
			{
				MethodInfo method = typeof(LogisticCourierRenderer).GetMethod("Expand2x", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (method != null)
				{
					method.Invoke(renderer, null);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] ExpandCouriersArray 异常: " + ex.Message));
				}
			}
		}

		private static void UpdateBuffer(LogisticCourierRenderer renderer, int count)
		{
			try
			{
				FieldInfo field = typeof(LogisticCourierRenderer).GetField("couriersBuffer", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				FieldInfo field2 = typeof(LogisticCourierRenderer).GetField("couriersArr", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (!(field == null) && !(field2 == null))
				{
					object? value = field.GetValue(renderer);
					ComputeBuffer val = (ComputeBuffer)((value is ComputeBuffer) ? value : null);
					CourierData[] array = field2.GetValue(renderer) as CourierData[];
					if (val != null && array != null && count > 0)
					{
						val.SetData((Array)array, 0, 0, count);
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] UpdateBuffer 异常: " + ex.Message));
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlanetFactory), "Init")]
	public static class PlanetFactory_Init_Patch
	{
		[HarmonyPostfix]
		private static void Postfix(PlanetFactory __instance)
		{
			try
			{
				if (__instance != null && Plugin.DebugLog())
				{
					ManualLogSource? log = Plugin.Log;
					if (log != null)
					{
						log.LogInfo((object)string.Format("[{0}] 星球工厂初始化:行星[{1}]", "战场分析基站配送支持", __instance.planetId));
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)("[战场分析基站配送支持] PlanetFactory.Init Postfix 异常: " + ex.Message));
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlanetFactory), "Free")]
	public static class PlanetFactory_Free_Patch
	{
		[HarmonyPrefix]
		private static void Prefix(PlanetFactory __instance)
		{
			try
			{
				if (__instance != null)
				{
					BattleBaseLogisticsManager.Clear(__instance.planetId);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)("[战场分析基站配送支持] PlanetFactory.Free Prefix 异常: " + ex.Message));
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlanetFactory), "Import")]
	public static class PlanetFactory_Import_Patch
	{
		[HarmonyPostfix]
		private static void Postfix(PlanetFactory __instance)
		{
			try
			{
				if (__instance == null)
				{
					return;
				}
				CleanupVirtualDispensers(__instance);
				if (Plugin.DebugLog())
				{
					ManualLogSource? log = Plugin.Log;
					if (log != null)
					{
						log.LogInfo((object)string.Format("[{0}] 存档加载完成:行星[{1}]", "战场分析基站配送支持", __instance.planetId));
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)("[战场分析基站配送支持] PlanetFactory.Import Postfix 异常: " + ex.Message));
				}
			}
		}

		private static void CleanupVirtualDispensers(PlanetFactory factory)
		{
			try
			{
				if (factory?.transport == null)
				{
					return;
				}
				FieldInfo field = ((object)factory.transport).GetType().GetField("dispenserPool", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				FieldInfo field2 = ((object)factory.transport).GetType().GetField("dispenserCursor", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field == null || field2 == null)
				{
					return;
				}
				Array array = field.GetValue(factory.transport) as Array;
				object value = field2.GetValue(factory.transport);
				if (array == null || value == null)
				{
					return;
				}
				int num = Convert.ToInt32(value);
				HashSet<int> battleBaseEntityIds = GetBattleBaseEntityIds(factory);
				if (battleBaseEntityIds.Count == 0)
				{
					return;
				}
				int num2 = 0;
				for (int i = 1; i < num && i < array.Length; i++)
				{
					object value2 = array.GetValue(i);
					if (value2 == null)
					{
						continue;
					}
					DispenserComponent val = (DispenserComponent)((value2 is DispenserComponent) ? value2 : null);
					if (val == null || val.id != i || !battleBaseEntityIds.Contains(val.entityId))
					{
						continue;
					}
					array.SetValue(null, i);
					num2++;
					if (Plugin.DebugLog())
					{
						ManualLogSource? log = Plugin.Log;
						if (log != null)
						{
							log.LogInfo((object)string.Format("[{0}] \ud83e\uddf9 清理虚拟配送器[{1}]:entityId={2}", "战场分析基站配送支持", i, val.entityId));
						}
					}
				}
				if (num2 > 0)
				{
					ManualLogSource? log2 = Plugin.Log;
					if (log2 != null)
					{
						log2.LogInfo((object)string.Format("[{0}] ✅ 清理完成:删除 {1} 个旧虚拟配送器,存档已兼容新方案", "战场分析基站配送支持", num2));
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log3 = Plugin.Log;
				if (log3 != null)
				{
					log3.LogError((object)("[战场分析基站配送支持] CleanupVirtualDispensers 异常: " + ex.Message));
				}
			}
		}

		private static HashSet<int> GetBattleBaseEntityIds(PlanetFactory factory)
		{
			HashSet<int> hashSet = new HashSet<int>();
			try
			{
				DefenseSystem val = factory?.defenseSystem;
				if (val == null)
				{
					return hashSet;
				}
				FieldInfo field = ((object)val).GetType().GetField("battleBases", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field == null)
				{
					return hashSet;
				}
				object value = field.GetValue(val);
				if (value == null)
				{
					return hashSet;
				}
				FieldInfo field2 = value.GetType().GetField("buffer", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field2 == null)
				{
					return hashSet;
				}
				if (!(field2.GetValue(value) is Array array))
				{
					return hashSet;
				}
				for (int i = 1; i < array.Length; i++)
				{
					object value2 = array.GetValue(i);
					if (value2 == null)
					{
						continue;
					}
					FieldInfo field3 = value2.GetType().GetField("entityId");
					if (!(field3 == null))
					{
						int num = (int)field3.GetValue(value2);
						if (num > 0)
						{
							hashSet.Add(num);
						}
					}
				}
			}
			catch
			{
			}
			return hashSet;
		}
	}
}